Ejemplo n.º 1
0
    def __init__(self, id, neighs, data, variance="false"):
        """
        @type id: integer
        @param id: Id of the polygon/area

        @type neighs: list
        @param neighs: Neighborhood ids

        @type data: list.
        @param data: Data releated to the area.

        @type variance: boolean
        @keyword variance: Boolean indicating if the data have variance matrix
        """
        self.id = id
        self.neighs = neighs
        if variance == "false":
            self.data = data
        else:
            n = (npsqrt(9 + 8 * (len(data) - 1)) - 3) / 2
            self.var = npmatrix(npidentity(n))
            index = n + 1
            for i in range(int(n)):
                for j in range(i + 1):
                    self.var[i, j] = data[int(index)]
                    self.var[j, i] = data[int(index)]
                    index += 1
            self.data = data[0: int(n + 1)]
Ejemplo n.º 2
0
def possible(n, x, y, grid):
    """determina se é possível um numero n ser
    colocado na posição x y de um grid de sudoku"""
    grid = npmatrix(grid)
    if n in grid[y, :]:
        return False
    if n in grid[:, x]:
        return False
    if n in grid[y // 3 * 3:y // 3 * 3 + 3, x // 3 * 3:x // 3 * 3 + 3]:
        return False
    else:
        return True
Ejemplo n.º 3
0
def calculateCentroid(areaList):
    """
    This function return the centroid of an area list
    """
    pg = 0.0
    pk = []
    centroid = AreaCl(0, [], [])
    for area in areaList:
        pg += area.data[0]
        pk = pk + [area.data[0]]
    pkPg = npmatrix(pk).T / pg
    data = [0.0] * len(area.data)
    var = npmatrix(areaList[0].var) * 0.0
    j = 0
    for area in areaList:
        var += area.var * pow(pkPg[j, 0], 2)
        for i in range(len(area.data)):
            data[i] += area.data[i] * pkPg[j, 0]
        j += 1
    centroid.data = data
    centroid.var = var
    return centroid
Ejemplo n.º 4
0
def calculateCentroid(areaList):
    """
    This function return the centroid of an area list
    """
    pg = 0.0
    pk = []
    centroid = AreaCl(0, [], [])
    for area in areaList:
        pg += area.data[0]
        pk = pk + [area.data[0]]
    pkPg = npmatrix(pk).T / pg
    data = [0.0] * len(area.data)
    var = npmatrix(areaList[0].var) * 0.0
    j = 0
    for area in areaList:
        var += area.var * pow(pkPg[j, 0], 2)
        for i in range(len(area.data)):
            data[i] += area.data[i] * pkPg[j, 0]
        j += 1
    centroid.data = data
    centroid.var = var
    return centroid
Ejemplo n.º 5
0
def solve(_sudoku):
    """resolve um sudoku em forma de np.matrix,
    depende da funçao possible"""
    for y in range(9):
        for x in range(9):
            if _sudoku[y][x] == 0:
                for n in range(1, 10):
                    if possible(n, x, y, _sudoku):
                        _sudoku[y][x] = n
                        solve(_sudoku)
                        _sudoku[y][x] = 0
                        #print(npmatrix(_sudoku))
                return
                #print('impossible sudoku')
    print('\n')
    print('\n')
    print('\n')
    print(npmatrix(_sudoku))
    input('\nmore? ')
Ejemplo n.º 6
0
def getmatrix(block):
    """Get 1-by-n matrix corresponding to block"""
    matrix = npmatrix([[letters.index(c)] for c in block])
    return matrix
Ejemplo n.º 7
0
    blocksize = len(key)
    clean_text = cleanup(plaintext, blocksize)
    blocks_plain = [getmatrix(clean_text[i:i+blocksize]) for i in xrange(0, len(clean_text), blocksize)]
    blocks_cipher = [getblock(key*block) for block in blocks_plain]
    ciphertext = ''.join(blocks_cipher)
    return ciphertext

def decrypt(ciphertext, key):
    blocksize = len(key)
    blocks_cipher = [getmatrix(ciphertext[i:i+blocksize]) for i in xrange(0, len(ciphertext), blocksize)]
    inv_key = matrix_modinv(key, 26)
    blocks_plain = [getblock(inv_key*block) for block in blocks_cipher]
    plaintext = (''.join(blocks_plain)).lower()
    return plaintext

key = npmatrix([[6,24,1],[13,16,10],[20,17,15]]) #Key matrix

def main():
    mode, inputfile, outputfile = sys.argv[1:4]
    ifile = open(inputfile, 'r')
    ofile = open(outputfile, 'w')
    if mode=='e':
        plaintext = ifile.read()
        ciphertext = encrypt(plaintext, key) 
        ofile.write(ciphertext)
        frequencygraph.freqbars_percentage('Hill Cipher frequency graph)'.format(key), plaintext, ciphertext)
    elif mode=='d':
        ciphertext = ifile.read()
        plaintext = decrypt(ciphertext, key)
        ofile.write(plaintext)
    ifile.close()
Ejemplo n.º 8
0
def getmatrix(block):
    """Get 1-by-n matrix corresponding to block"""
    matrix = npmatrix([[letters.index(c)] for c in block])
    return matrix
Ejemplo n.º 9
0
    return ciphertext


def decrypt(ciphertext, key):
    blocksize = len(key)
    blocks_cipher = [
        getmatrix(ciphertext[i:i + blocksize])
        for i in xrange(0, len(ciphertext), blocksize)
    ]
    inv_key = matrix_modinv(key, 26)
    blocks_plain = [getblock(inv_key * block) for block in blocks_cipher]
    plaintext = (''.join(blocks_plain)).lower()
    return plaintext


key = npmatrix([[6, 24, 1], [13, 16, 10], [20, 17, 15]])  #Key matrix


def main():
    mode, inputfile, outputfile = sys.argv[1:4]
    ifile = open(inputfile, 'r')
    ofile = open(outputfile, 'w')
    if mode == 'e':
        plaintext = ifile.read()
        ciphertext = encrypt(plaintext, key)
        ofile.write(ciphertext)
        frequencygraph.freqbars_percentage(
            'Hill Cipher frequency graph)'.format(key), plaintext, ciphertext)
    elif mode == 'd':
        ciphertext = ifile.read()
        plaintext = decrypt(ciphertext, key)
Ejemplo n.º 10
0
    def __init__(self):
        self.coeffs = [(npmatrix((-1, )), npmatrix((-1, )))]
        self.rpn = [(rpncalc.RPNProgram([-1]), rpncalc.RPNProgram([-1]))]

        # In case this class is utilized by multiple threads.
        self.lock = Lock()
Ejemplo n.º 11
0
def _Del(m):
    return int0(npmatrix(diag(xrange(1, int(m)), k=1)[:-1]))
Ejemplo n.º 12
0
def _X(m):
    return int0(npmatrix(diag((1, ) * int(m), k=-1)[:, :-1]))
Ejemplo n.º 13
0
def _E(m):
    return int0(npmatrix(diag((1, ) * int(m + 1), k=0)[:, :-1]))
Ejemplo n.º 14
0
    def A(self, n, eps=0.0000001, p=16):
        # Compute matrix $\mathbf{A}_n$.

        H, W = self.DFQf.shape

        # Initialize the An matrix (as an array for now).
        An = zeros(self.R.shape, dtype=complex128)

        # First compute a partial sum for the upper triangular part.
        # Start with $m=0$

        mask = self.S < self.R

        Sum = zeros(self.R.shape, dtype=complex128)

        for m in xrange(0, p + 1, 2):
            cm_rpn, dm_rpn = self._cd[m]
            Term = self._tm(v=self.V[mask],
                            v2=self.V[mask]**2,
                            dlnr=self.dr / self.R[mask],
                            n=n,
                            n2=n**2,
                            m=m,
                            cm=cm_rpn,
                            dm=dm_rpn)

            Sum[mask] += Term
            mask[mask] *= abs(Term) >= eps
            if not mask.any():
                break

        mask = self.S < self.R

        An[mask] = 2 * self.W[mask]**n * self.Factor[mask] * Sum[mask]

        # Now to do the diagonal.
        # Since $r=s$ here, we have $q=1$, $u=\phi$, $v=-\tan\phi$,
        # and $w=1$.

        mask = self.S == self.R

        Sum = zeros(self.R.shape, dtype=complex128)

        for m in xrange(0, p + 1):
            cm_rpn, dm_rpn = self._cd[m]

            Term = self._tm(v=-tan(self.Phi),
                            v2=tan(self.Phi)**2,
                            dlnr=self.dr / self.R[mask],
                            n=n,
                            n2=n**2,
                            m=m,
                            cm=cm_rpn,
                            dm=dm_rpn)

            Sum[mask] += Term
            mask[mask] *= abs(Term) >= eps
            if not mask.any():
                break

        mask = self.S == self.R
        An[mask] = self.Factor[mask] * Sum[mask] + \
            array([1 - 1 / cos(self.Phi)] * W)

        return npmatrix(An)