Beispiel #1
0
def d_hill(ciphertext, key):
    # your code here
    if len(ciphertext) == 0:
        print('Error(d_hill): invalid ciphertext')
        return ''

    new_key = ''
    if len(key) > 4:
        new_key += key[:4]
    elif len(key) == 4:
        new_key += key
    else:
        new_key += key
        counter = 0
        while len(new_key) < 4:
            new_key += key[counter]
            counter += 1

    baseString = utilities_A4.get_lower()

    key_matrix = matrix.new_matrix(2, 2, 0)
    count = 0
    for i in range(2):
        for j in range(2):
            key_matrix[i][j] = baseString.index(new_key[count].lower())
            count += 1

    if mod.gcd(matrix.det(key_matrix), 26) != 1:
        print('Error(d_hill): key is not invertible')
        return ''

    inverse_key_matrix = matrix.inverse(key_matrix, 26)

    plaintext = ''
    non_alpha = utilities_A4.get_nonalpha(ciphertext)
    blocks = utilities_A4.text_to_blocks(
        utilities_A4.remove_nonalpha(ciphertext), 2)

    for block in blocks:
        block_m = matrix.new_matrix(2, 1, 0)
        block_m[0][0] = baseString.index(block[0].lower())
        block_m[1][0] = baseString.index(block[1].lower())

        result_m = matrix.matrix_mod(matrix.mul(inverse_key_matrix, block_m),
                                     26)

        plaintext += baseString[result_m[0][0]].lower()
        plaintext += baseString[result_m[1][0]].lower()

    plaintext = utilities_A4.insert_nonalpha(plaintext, non_alpha)
    while plaintext[-1] == 'q':
        plaintext = plaintext[:-1]

    return plaintext
Beispiel #2
0
def mTMRCA_C(trees, log = None, 
             left = 0, right = math.inf, 
             gmap = Gmap(None), sft = False):
  
  N = trees.num_samples
  mtmrca_C = matrix.new_matrix(N)
  tmp = 0
  total_l = 0
  pbar = tqdm.tqdm(total = trees.num_trees, 
                   bar_format = '{l_bar}{bar:30}{r_bar}{bar:-30b}',
                   miniters = trees.num_trees // 100,
                   file = log)
  
  trees_ = trees.trees()
  if sft: next(trees_)
  
  for tree in trees_:
    pbar.update(1)
    if tree.total_branch_length == 0: continue
    l = - gmap(max(left, tree.interval[0])) + gmap(min(right, tree.interval[1]))
    if l <= 0: continue
    
    height = 0
    for c in tree.nodes():
      descendants = list(tree.samples(c))
      n = len(descendants)
      if(n == 0 or n == N): continue
      t = tree.time(tree.parent(c)) - tree.time(c)
      height = max(height, tree.time(tree.parent(c)))
      matrix.add_square(mtmrca_C, descendants, t * l)
    tmp += height * l
    total_l += l
  
  mtmrca = mat_C_to_ndarray(mtmrca_C, N)
  mtmrca = tmp - mtmrca
  mtmrca /= total_l
  pbar.close()
  return mtmrca, total_l
Beispiel #3
0
def d_type3(ciphertext):
    alpha = utilities.get_lower()
    dictList = utilities.load_dictionary('engmix.txt')

    for a in range(0, 5):
        for b in range(0, 5):
            for c in range(0, 5):
                for d in range(0, 5):
                    key_matrix = matrix.new_matrix(2, 2, 0)
                    key_matrix[0][0] = a
                    key_matrix[0][1] = b
                    key_matrix[1][0] = c
                    key_matrix[1][1] = d
                    if mod.has_mul_inv(a * d - b * c, 26):
                        key = ''
                        for i in range(2):
                            for j in range(2):
                                key += alpha[key_matrix[i][j]]
                        first = d_hill(ciphertext, key)

                        k, plain = cryptanalysis_shift(first)

                        if utilities.is_plaintext(plain, dictList, 0.70):
                            return plain, (k, key)
Beispiel #4
0
def test_q4():
    print("-------------------------------------------")
    print("Testing Q4: Matrix Library")
    filename = 'q4_solution.txt'
    outFile = open(filename, 'w')
    print()

    outFile.write('1- Testing is_vector:\n')
    outFile.write('is_vector({}) =  {}\n'.format([], matrix.is_vector([])))
    outFile.write('is_vector({}) =  {}\n'.format([10], matrix.is_vector([10])))
    outFile.write('is_vector({}) =  {}\n'.format([10, 20],
                                                 matrix.is_vector([10, 20])))
    outFile.write('is_vector({}) =  {}\n'.format(10, matrix.is_vector(10)))
    outFile.write('is_vector({}) =  {}\n'.format([3, 4.5],
                                                 matrix.is_vector([3, 4.5])))
    outFile.write('is_vector({}) =  {}\n'.format([[]], matrix.is_vector([[]])))
    outFile.write('is_vector({}) =  {}\n'.format([[1, 2], [3, 4]],
                                                 matrix.is_vector([[1, 2],
                                                                   [3, 4]])))
    outFile.write('\n')

    outFile.write('2- Testing is_matrix')
    A = []
    outFile.write('is_matrix({}) =  {}\n'.format(A, matrix.is_matrix(A)))
    A = [5]
    outFile.write('is_matrix({}) =  {}\n'.format(A, matrix.is_matrix(A)))
    A = [[1, 2], [3, 4]]
    outFile.write('is_matrix({}) =  {}\n'.format(A, matrix.is_matrix(A)))
    A = [[1], [2], [3]]
    outFile.write('is_matrix({}) =  {}\n'.format(A, matrix.is_matrix(A)))
    A = [[1, 2, 3], [4, 5, 6]]
    outFile.write('is_matrix({}) =  {}\n'.format(A, matrix.is_matrix(A)))
    A = 5
    outFile.write('is_matrix({}) =  {}\n'.format(A, matrix.is_matrix(A)))
    A = [5.5]
    outFile.write('is_matrix({}) =  {}\n'.format(A, matrix.is_matrix(A)))
    A = [[1, 2, 3], [4, 5]]
    outFile.write('is_matrix({}) =  {}\n'.format(A, matrix.is_matrix(A)))
    outFile.write('\n')

    print('3- Testing print_matrix')
    A = []
    print('print_matrix({})='.format(A))
    matrix.print_matrix(A)
    A = [10, 20, 30]
    print('print_matrix({})='.format(A))
    matrix.print_matrix(A)
    A = [[10], [20], [30]]
    print('print_matrix({})='.format(A))
    matrix.print_matrix(A)
    A = [[10, 20, 30], [40, 50, 60], [70, 80, 10]]
    print('print_matrix({})='.format(A))
    matrix.print_matrix(A)
    A = [[10, 20, 30], [40, 50, 60], [70, 80]]
    print('print_matrix({})='.format(A))
    print(matrix.print_matrix(A))
    print()

    outFile.write('4/5/6- Testing size functions\n')
    A = []
    outFile.write('get_rowCount({})    =  {}\n'.format(A,
                                                       matrix.get_rowCount(A)))
    outFile.write('get_ColumnCount({}) =  {}\n'.format(
        A, matrix.get_columnCount(A)))
    outFile.write('get_size({})        =  {}\n'.format(A, matrix.get_size(A)))
    outFile.write('\n')

    A = [1, 2, 3]
    outFile.write('get_rowCount({})    =  {}\n'.format(A,
                                                       matrix.get_rowCount(A)))
    outFile.write('get_ColumnCount({}) =  {}\n'.format(
        A, matrix.get_columnCount(A)))
    outFile.write('get_size({})        =  {}\n'.format(A, matrix.get_size(A)))
    outFile.write('\n')

    A = [[1, 2], [3, 4], [5, 6]]
    outFile.write('get_rowCount({})    =  {}\n'.format(A,
                                                       matrix.get_rowCount(A)))
    outFile.write('get_ColumnCount({}) =  {}\n'.format(
        A, matrix.get_columnCount(A)))
    outFile.write('get_size({})        =  {}\n'.format(A, matrix.get_size(A)))
    outFile.write('\n')

    A = [[1, 2], [3]]
    outFile.write('get_rowCount({})    =  {}\n'.format(A,
                                                       matrix.get_rowCount(A)))
    outFile.write('get_ColumnCount({}) =  {}\n'.format(
        A, matrix.get_columnCount(A)))
    outFile.write('get_size({})        =  {}\n'.format(A, matrix.get_size(A)))
    outFile.write('\n')

    outFile.write('7- Testing is_square\n')
    A = []
    outFile.write('is_square({})    =  {}\n'.format(A, matrix.is_square(A)))
    A = [5]
    outFile.write('is_square({})    =  {}\n'.format(A, matrix.is_square(A)))
    A = [5, 6]
    outFile.write('is_square({})    =  {}\n'.format(A, matrix.is_square(A)))
    A = [[1, 2], [3, 4]]
    outFile.write('is_square({})    =  {}\n'.format(A, matrix.is_square(A)))
    A = [5.5]
    outFile.write('is_square({})    =  {}\n'.format(A, matrix.is_square(A)))
    outFile.write('\n')

    outFile.write('8/9/10- Testing getter functions\n')
    A = [[1, 2, 3], [4, 5, 6]]
    i = 0
    j = 1
    outFile.write('get_row({},{})    = {}\n'.format(A, i, matrix.get_row(A,
                                                                         i)))
    outFile.write('get_Column({},{}) = {}\n'.format(A, j,
                                                    matrix.get_column(A, j)))
    outFile.write('get_element({},{},{}) = {}\n'.format(
        A, i, j, matrix.get_element(A, i, j)))
    outFile.write('\n')

    i = 2
    j = 2
    outFile.write('get_row({},{})    = {}\n'.format(A, i, matrix.get_row(A,
                                                                         i)))
    outFile.write('get_Column({},{}) = {}\n'.format(A, j,
                                                    matrix.get_column(A, j)))
    outFile.write('get_element({},{},{}) = {}\n'.format(
        A, i, j, matrix.get_element(A, i, j)))
    outFile.write('\n')

    i = 1
    j = 3
    outFile.write('get_row({},{})    = {}\n'.format(A, i, matrix.get_row(A,
                                                                         i)))
    outFile.write('get_Column({},{}) = {}\n'.format(A, j,
                                                    matrix.get_column(A, j)))
    outFile.write('get_element({},{},{}) = {}\n'.format(
        A, i, j, matrix.get_element(A, i, j)))
    outFile.write('\n')

    A = [[1, 2, 3], []]
    outFile.write('get_row({},{})    = {}\n'.format(A, i, matrix.get_row(A,
                                                                         i)))
    outFile.write('get_Column({},{}) = {}\n'.format(A, j,
                                                    matrix.get_column(A, j)))
    outFile.write('get_element({},{},{}) = {}\n'.format(
        A, i, j, matrix.get_element(A, i, j)))
    outFile.write('\n')

    outFile.write('11- Testing new_matrix\n')
    r = 0
    c = 0
    pad = 0
    outFile.write('new_matrix({},{},{})=\n{}\n'.format(
        r, c, pad, matrix.new_matrix(r, c, pad)))
    c = 1
    outFile.write('new_matrix({},{},{})=\n{}\n'.format(
        r, c, pad, matrix.new_matrix(r, c, pad)))
    r = 1
    outFile.write('new_matrix({},{},{})=\n{}\n'.format(
        r, c, pad, matrix.new_matrix(r, c, pad)))
    r = 2
    c = 1
    outFile.write('new_matrix({},{},{})=\n{}\n'.format(
        r, c, pad, matrix.new_matrix(r, c, pad)))
    c = 2
    r = 1
    outFile.write('new_matrix({},{},{})=\n{}\n'.format(
        r, c, pad, matrix.new_matrix(r, c, pad)))
    c = 3
    r = 3
    outFile.write('new_matrix({},{},{})=\n{}\n'.format(
        r, c, pad, matrix.new_matrix(r, c, pad)))
    r = -1
    outFile.write('new_matrix({},{},{})=\n{}\n'.format(
        r, c, pad, matrix.new_matrix(r, c, pad)))
    r = 3
    c = -5
    outFile.write('new_matrix({},{},{})=\n{}\n'.format(
        r, c, pad, matrix.new_matrix(r, c, pad)))
    c = 5
    pad = 3.5
    outFile.write('new_matrix({},{},{})=\n{}\n'.format(
        r, c, pad, matrix.new_matrix(r, c, pad)))
    outFile.write('\n')

    outFile.write('12- Testing get_I\n')
    size = -1
    outFile.write('get_I({})    = {}\n'.format(size, matrix.get_I(size)))
    size = 0
    outFile.write('get_I({})    =  {}\n'.format(size, matrix.get_I(size)))
    size = 1
    outFile.write('get_I({})    =  {}\n'.format(size, matrix.get_I(size)))
    size = 2
    outFile.write('get_I({})    =  {}\n'.format(size, matrix.get_I(size)))
    size = 3
    outFile.write('get_I({})    =  {}\n'.format(size, matrix.get_I(size)))
    outFile.write('\n')

    outFile.write('13- Testing is_identity\n')
    A = [1]
    outFile.write('is_identity({}) = {}\n'.format(A, matrix.is_identity(A)))
    A = matrix.get_I(3)
    outFile.write('is_identity({}) = {}\n'.format(A, matrix.is_identity(A)))
    A = [[1, 0], [1, 1]]
    outFile.write('is_identity({}) = {}\n'.format(A, matrix.is_identity(A)))
    A = [[1, 0], [0, 1, 0]]
    outFile.write('is_identity({}) = {}\n'.format(A, matrix.is_identity(A)))
    outFile.write('\n')

    outFile.write('14- Testing scalar_mul\n')
    A = [[1, 2], [3, 4]]
    c = 10
    outFile.write('scalar_mul({},{}) = {}\n'.format(A, c,
                                                    matrix.scalar_mul(c, A)))
    A = [1, 2, 3, 4]
    outFile.write('scalar_mul({},{}) = {}\n'.format(A, c,
                                                    matrix.scalar_mul(c, A)))
    A = []
    outFile.write('scalar_mul({},{}) = {}\n'.format(A, c,
                                                    matrix.scalar_mul(c, A)))
    A = [1, 2, 3, [4]]
    outFile.write('scalar_mul({},{}) = {}\n'.format(A, c,
                                                    matrix.scalar_mul(c, A)))
    A = [[1, 2], [3, 4]]
    c = [10]
    outFile.write('scalar_mul({},{}) = {}\n'.format(A, c,
                                                    matrix.scalar_mul(c, A)))
    outFile.write('\n')

    outFile.write('15- Testing mul\n')
    A = [[1, 2], [3, 4]]
    B = [[10, 20], [30, 40]]
    outFile.write('mul({},{})=\n{}\n'.format(A, c, matrix.mul(A, B)))
    A = [[1, 2, 3], [5, 6, 7]]
    B = [[10, 20], [30, 40], [50, 60]]
    outFile.write('mul({},{})= {}\n'.format(A, c, matrix.mul(A, B)))
    A = [5]
    B = [10]
    outFile.write('mul({},{})= {}\n'.format(A, B, matrix.mul(A, B)))
    A = [0, 1, 2]
    B = [[0], [1], [2]]
    outFile.write('mul({},{})= {}\n'.format(A, B, matrix.mul(A, B)))
    A = [[0], 1]
    B = [1, 0]
    outFile.write('mul({},{})= {}\n'.format(A, B, matrix.mul(A, B)))
    A = [1, 0]
    B = [[0], 1]
    outFile.write('mul({},{})= {}\n'.format(A, B, matrix.mul(A, B)))
    A = [[1, 2, 3], [5, 6, 7]]
    B = [[10, 20], [30, 40], [50, 60]]
    outFile.write('mul({},{})= {}\n'.format(B, A, matrix.mul(B, A)))
    A = [[1, 2, 3], [5, 6, 7]]
    B = [[10, 20], [30, 40]]
    outFile.write('mul({},{})= {}\n'.format(A, B, matrix.mul(A, B)))
    outFile.write('\n')

    outFile.write('16- Testing matrix_mod\n')
    A = [[1, 2], [3, 4]]
    m = 2
    outFile.write('matrix_mod({},{})= {}\n'.format(A, m,
                                                   matrix.matrix_mod(A, m)))
    A = [1, 2, 3, 4]
    m = 2
    outFile.write('matrix_mod({},{})= {}\n'.format(A, m,
                                                   matrix.matrix_mod(A, m)))
    A = [[3], [5]]
    m = 3
    outFile.write('matrix_mod({},{})= {}\n'.format(A, m,
                                                   matrix.matrix_mod(A, m)))
    A = [[3], [5]]
    m = 0
    outFile.write('matrix_mod({},{})= {}\n'.format(A, m,
                                                   matrix.matrix_mod(A, m)))
    A = [3, [5]]
    m = 6
    outFile.write('matrix_mod({},{})= {}\n'.format(A, m,
                                                   matrix.matrix_mod(A, m)))
    outFile.write('\n')

    outFile.write('17- Testing det\n')
    A = [[1, 2], [3, 4]]
    outFile.write('det({})= {}\n'.format(A, matrix.det(A)))
    A = [10]
    outFile.write('det({})= {}\n'.format(A, matrix.det(A)))
    A = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
    outFile.write('det({})= {}\n'.format(A, matrix.det(A)))
    A = [[1, 1, 1], [2, 2]]
    outFile.write('det({})= {}\n'.format(A, matrix.det(A)))
    outFile.write('\n')

    outFile.write('18- Testing inverse\n')
    A = [[1, 4], [8, 11]]
    m = 26
    outFile.write('inverse({},{})= {}\n'.format(A, m, matrix.inverse(A, m)))
    A = [[4, 3], [1, 1]]
    m = 5
    outFile.write('inverse({},{})= {}\n'.format(A, m, matrix.inverse(A, m)))
    A = [[1, 4], [8, 10]]
    m = 26
    outFile.write('inverse({},{})= {}\n'.format(A, m, matrix.inverse(A, m)))
    A = [1, 4, 8, 10]
    m = 15
    outFile.write('inverse({},{})= {}\n'.format(A, m, matrix.inverse(A, m)))
    A = [[4, 3], [1, 1]]
    m = -5
    outFile.write('inverse({},{})= {}\n'.format(A, m, matrix.inverse(A, m)))
    A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    m = 7
    outFile.write('inverse({},{})= {}\n'.format(A, m, matrix.inverse(A, m)))
    A = [[1, 2, 3], [4, 5]]
    m = 7
    outFile.write('inverse({},{})= {}\n'.format(A, m, matrix.inverse(A, m)))

    outFile.close()
    print('Comparing q4_solution with q4_sample:')
    print(utilities_A4.compare_files('q4_solution.txt', 'q4_sample.txt'))
    print()
    print("-------------------------------------------")
def d_hill(ciphertext, key):
    plaintext = ''
    base = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    if len(ciphertext) == 0:
        print('Error(d_hill): invalid ciphertext')
        return plaintext

    if len(key) > 4:
        key = key[:4]

    elif len(key) < 4:
        x = len(key)
        count = 0

        while len(key) != 4:
            if count == x:
                count = 0

            key += key[count]
            count += 1

    alpha = utilities_A4.get_nonalpha(ciphertext)
    text = utilities_A4.remove_nonalpha(ciphertext)
    text = text.upper()

    if len(text) % 2 != 0:
        text += 'Q'

    indx1 = 0
    indx2 = 0
    textMatrix = matrix.new_matrix(2, int(len(text) / 2), 0)
    for i in range(len(text)):
        if i % 2 == 0:
            textMatrix[0][indx1] = base.find(text[i])
            indx1 += 1

        else:
            textMatrix[1][indx2] = base.find(text[i])
            indx2 += 1

    keyMatrix = matrix.new_matrix(2, 2, 0)
    count = 0
    for i in range(2):
        for j in range(2):
            keyMatrix[i][j] = base.find(key[count].upper())
            count += 1

    inverse = matrix.inverse(keyMatrix, 26)

    for i in range(int(len(text) / 2)):
        a = textMatrix[0][i] * inverse[0][0] + textMatrix[1][i] * inverse[0][1]
        b = textMatrix[0][i] * inverse[1][0] + textMatrix[1][i] * inverse[1][1]
        plaintext += base[a % 26]
        plaintext += base[b % 26]

    plaintext = utilities_A4.insert_nonalpha(plaintext, alpha)
    plaintext = plaintext.lower()

    while plaintext[len(plaintext) - 1] == 'q':
        plaintext = plaintext[:-1]

    return plaintext
Beispiel #6
0
def new_zbuffer(width=XRES, height=YRES):
    return new_matrix(width, height, float("-inf"))
Beispiel #7
0
def varGRM_C(trees, log = None, 
             rlim = 0, alim = math.inf, 
             left = 0, right = math.inf, 
             gmap = Gmap(None), g = (lambda x: 1/(x*(1-x))), 
             var = True, sft = False):
  
  N = trees.num_samples
  egrm_C = matrix.new_matrix(N)
  if var:
    egrm2_C = matrix.new_matrix(N)
    tmp1 = np.zeros(N)
    tmp2 = 0
  
  total_mu = 0
  pbar = tqdm.tqdm(total = trees.num_trees, 
                   bar_format = '{l_bar}{bar:30}{r_bar}{bar:-30b}',
                   miniters = trees.num_trees // 100,
                   file = log)
  
  trees_ = trees.trees()
  if sft: next(trees_)
  
  for tree in trees_:
    pbar.update(1)
    if tree.total_branch_length == 0: continue
    l = - gmap(max(left, tree.interval[0])) + gmap(min(right, tree.interval[1]))
    if l <= 0: continue
    
    for c in tree.nodes():
      descendants = list(tree.samples(c))
      n = len(descendants)
      if(n == 0 or n == N): continue
      t = max(0, min(alim, tree.time(tree.parent(c))) - max(rlim, tree.time(c)))
      mu = l * t * 1e-8
      p = float(n/N)
      matrix.add_square(egrm_C, descendants, mu * g(p))
      if var:
        matrix.add_square(egrm2_C, descendants, mu * np.power(g(p), 2) * np.power((1 - 2*p), 2))
        tmp1[descendants] += mu * np.power(g(p), 2) * (np.power(p, 2) - 2 * np.power(p, 3))
        tmp2 += mu * np.power(g(p), 2) * np.power(p, 4)
      total_mu += mu
  
  egrm = mat_C_to_ndarray(egrm_C, N)
  if var:
    egrm2 = mat_C_to_ndarray(egrm2_C, N) 
  
  egrm /= total_mu
  if var:
    egrm2 /= total_mu
    tmp1 /= total_mu
    tmp2 /= total_mu
  
  egrm -= egrm.mean(axis = 0)
  egrm -= egrm.mean(axis = 1, keepdims=True)
  if var:
    e = np.reciprocal((lambda x:x[x!=0])(np.random.poisson(lam=total_mu, size=10000)).astype("float")).mean()
    vargrm = e * (egrm2 + np.tile(tmp1, (N, 1)) + np.tile(tmp1, (N, 1)).transpose() + tmp2 - np.power(egrm, 2))
  else:
    vargrm = None
  
  pbar.close()
  return egrm, vargrm, total_mu