Exemplo n.º 1
0
    def test_15_new_form_list(self):
        """ por definicao, (1 2 3) == (2 3 1) == (3 1 2)"""

        a=permutation(self.sz, [1, 2, 3])
        b=permutation(self.sz, [2, 3, 1])
        c=permutation(self.sz, [3, 1, 2])

        self.assertEqual(a,b)
        self.assertEqual(b,c)
        self.assertEqual(a,c) # redundante, por transitividade
Exemplo n.º 2
0
def linkingFunc(polList, winSize):
    polyPossibles = permutation.permutation(len(polList))
    winPossibles = permutation.permutation(winSize)
    keyList = {string: [] for string in polyPossibles}
    winList = {string: [] for string in winPossibles}
    for string in winPossibles:
        strip = ""
        for i in range(len(polList)):
            strip += convolution(polList[i], string)
        keyList[strip].append(string)
        winList[string].append(strip)
#        for key in keyList.keys() :
#                if keyList[key] == [] :
#                        del keyList[i]
    return keyList, winList
Exemplo n.º 3
0
 def __init__(self, vars=None, idx=None, perm=None):
     self.vars = vars
     self.idx = idx
     if perm is None:
         self.permutation = permutation.permutation(vars, idx)
     else:
         self.permutation = perm
Exemplo n.º 4
0
 def __init__(self, vars=None, idx=None, perm=None):
     self.vars = vars
     self.idx = idx
     if perm is None:
         self.permutation = permutation.permutation(vars, idx)
     else:
         self.permutation = perm
Exemplo n.º 5
0
def main():
    # start_time = time.time()
    print("starting program")
    reader = language_model.corpusReader(
        "http://www.gutenberg.org/files/76/76-0.txt")
    lngmodel = language_model.LanguageModel(reader)
    txt = open("problemset_06_encrypted_input.txt", "r")
    msg = str(txt.read())
    txt.close()
    perm = dict()
    T = {",", ".", ":", "\n", "#", "(", ")", "!", "?", "\'", "\"", " "}
    letters = "abcdefghijklmnopqrstuvwxyz"
    for letter in letters:
        perm[letter] = letter
    for t in T:
        perm[t] = t

    p = permutation.permutation(perm)
    print("start simulated_annealing")
    sim = simulated_annealing.SimulatedAnnealing(300, 0.00001, 0.9990)
    h = sim.run(p, msg, lngmodel)
    # start_time = (time.time() - start_time)/60
    # print("exacution took: "+str(start_time))
    print(h.translate(msg))
    print(h.mapChar)
Exemplo n.º 6
0
def DriverNet(args):
    '''
    main function of DriverNet
    '''
    logger.info("Start running.")
    logger.info("Parameters: %s" %(' '.join(sys.argv)))

    ggi_matirx = args.network
    sample_mutation_matrix = args.mutation
    sample_exp_outlier = args.expression
    permutation_time = args.permutation_time
    threads = args.threads
    notPurturbGraph = args.notPurturbGraph
    purturbData = args.purturbData
    output_prefix = args.output

    edges, ggi, outlier_dict, mutation_dict = preprocess(ggi_matirx, sample_mutation_matrix, sample_exp_outlier)

    drivers, actual_events = greedy(edges, mutation_dict)
    logger.info("Driver finding done. Start significance test now.")

    random_res = permutation(ggi, outlier_dict, mutation_dict, permutation_time, threads,
                            notPurturbGraph, purturbData)
    pvalues, qvalues = compute_p(drivers, random_res)
    logger.info("Significance test done.")

    report(drivers, actual_events, pvalues, qvalues, output_prefix)
    logger.info("Writing output done. Please check %s.txt." %(output_prefix))
    logger.info("All done. Cheers.")
Exemplo n.º 7
0
 def test_30_permutate_list(self):
     perm_list = [ 0, 1 ]
     perm = permutation(self.sz,perm_list)
     a = [ i for i in range(self.sz) ]
     b = perm(a)
     self.assertEqual(b[0],1)
     self.assertEqual(b[1],0)
     self.assertTrue(all(b[i] == i for i in range(2,self.sz)))
Exemplo n.º 8
0
 def test_20_new_from_dict_2(self):
     perm_dict = { 0:1, 1:0,2:3, 3:2}
     perm = permutation(self.sz,perm_dict)
     self.assertEqual(perm[0],1)
     self.assertEqual(perm[1],0)
     self.assertEqual(perm[2],3)
     self.assertEqual(perm[3],2)
     self.assertTrue(all(perm[i] == i for i in range(4,self.sz)))
Exemplo n.º 9
0
 def test_40_permutate_dict_2(self):
     perm_ = {0:1, 1:0, 2:3, 3:2}
     perm = permutation(self.sz,perm_)
     a = ['a', 'b', 'c', 'd'] 
     b = perm(a)
     self.assertEqual(b[0],'b')
     self.assertEqual(b[1],'a')
     self.assertEqual(b[2],'d')
     self.assertEqual(b[3],'c')
Exemplo n.º 10
0
    def test_50_permutate_permutation2(self):
        id = permutation(self.sz)
        perm_list = [ 0, 1 ]
        perm1 = permutation(self.sz,perm_list)

        perm_list = [ 1, 2 ]
        perm2 = permutation(self.sz,perm_list)

        perm_list = [ 0 ,2 , 1]
        perm3 = permutation(self.sz,perm_list)

        perm_list = [ 0, 1, 2 ]
        perm4 = permutation(self.sz,perm_list,complete=True)

        a = perm1(perm2)
        self.assertEqual(a, perm3)

        b = perm2(perm1)
        self.assertEqual(b, perm4)
Exemplo n.º 11
0
    def test_50_permutate_permutation3(self):
        id = permutation(self.sz)
        perm_d = {0:1,1:0,2:3,3:2}
        perm = permutation(self.sz,perm_d)

        perm_list = [ 0, 1 ]
        perm1 = permutation(self.sz,perm_list)

        perm_list = [ 2 , 3]
        perm2 = permutation(self.sz,perm_list)

        a = perm1(perm2)
        a = perm1(perm2)

        self.assertEqual(a, perm)

        b = perm2(perm1)
        self.assertEqual(b, perm)

        self.assertEqual(a,b)
Exemplo n.º 12
0
def variations(list_for_variations, k, repetition=False):
    per = []
    for c in combinations(list_for_variations, k, repetition):
        actual_permutations = permutation(c)
        if repetition:
            for x in actual_permutations:
                count = actual_permutations.count(x)
                if count > 1:
                    for y in range(count - 1):
                        actual_permutations.remove(x)
        per.extend(actual_permutations)
    return per
def frame_encryption(results, image, diffusion_matrices):
    layers = [image[:, :, 0], image[:, :, 1], image[:, :, 2]]
    encrypted_layers = []

    for layer in layers:
        i = 0
        permuted_matrix = perm.permutation(results[i], results[(i + 1) % 3],
                                           layer)
        encrypted_matrix = diff.diffusion_process(results[i],
                                                  results[(i + 1) % 3],
                                                  permuted_matrix,
                                                  diffusion_matrices[i])
        encrypted_layers.append(encrypted_matrix)
        i += 1

    return np.dstack(tuple(encrypted_layers))
Exemplo n.º 14
0
def ennet(args):
    '''
    '''
    network_file = args.network
    enhancer_file = args.enhancer
    snp_file = args.mutation
    # do some args checking here

    # preprocess
    G = preprocess.preprocess(network_file, enhancer_file)

    # escore
    G = escore.escore(snp_file, G, args.r, args.p0_meth)

    # permutation test
    G = permutation.permutation(G, args.permutation, args.threads)

    # report results
    report(G, args.output)

    logger.info('All done. Cheers')
Exemplo n.º 15
0
    def shortest_route(self):
        """Return the shortest route.

        Returns:
        shortest route
        """
        perms = permutation(self.n)
        index_min = 0
        d_min = 0
        for i in range(self.n):
            d_min += self.d[perms[0][i]][perms[0][(i + 1) % self.n]]

        for index, perm in enumerate(perms):
            d = 0
            for i in range(self.n):
                d += self.d[perm[i]][perm[(i + 1) % self.n]]
            if d < d_min:
                d_min = d
                index_min = index

        return perms[index_min]
Exemplo n.º 16
0
 def test_00_identity(self):
     id=permutation(self.sz,complete=True)
     self.assertTrue(all(id[i] == i for i in range(self.sz)))
Exemplo n.º 17
0
def final_permutation(input):
    return permutation(input, final_permutation_array)
Exemplo n.º 18
0
def parity_drop(input):
    if len(input) != 64:
        raise Exception("Wrong dimension")
    return permutation(input, parity_drop_array)
Exemplo n.º 19
0
def straight_p_box(input):
    if len(input) != 32:
        raise Exception("Wrong dimension")
    return permutation(input, straight_p_box_array)
Exemplo n.º 20
0
def initial_permutation(input):
    return permutation(input, initial_permutation_array)
Exemplo n.º 21
0
 def test_90_exception_list_size_2(self):
     perm_list = [ 0, 1 ]
     perm = permutation(self.sz,perm_list)
     a = [ i for i in range(self.sz+1) ]
     with self.assertRaises(Exception):
         perm(a)
Exemplo n.º 22
0
 def test_50_permutate_permutation(self):
     perm_list = [ 0, 1 ]
     id = permutation(self.sz)
     perm1 = permutation(self.sz,perm_list)
     a = perm1(perm1)
     self.assertEqual(a, id)
 def test_permutation_with_large_integers(self):
     assert permutation(15, 13) == 653837184000
     assert permutation(20, 10) == 670442572800
     assert permutation(25, 17) == 384702630042931200000
     assert permutation(30, 25) == 2210440498434925488635904000000
Exemplo n.º 24
0
 def __init__(self, vars, idx):
     self.vars = vars
     self.idx = idx
     self.permutation = permutation.permutation(vars, idx)
     self.pairwise_swaps = permutation.pairwise_swaps(vars, self.permutation)
Exemplo n.º 25
0
def des(plaintext_hexstr, key_hexstr, mode = 'encrypt'):
	"""Encrypt a plaintext_bin with the key_bin, Or Decrypt a cipher_bin with the key_bin
	"""
	plaintext_bin = binary.hexstr_binary(plaintext_hexstr) # get the string's 64bits binary code
	key_bin = binary.hexstr_binary(key_hexstr) # get the string's 64bits binary code
	#############################################################
	#############################################################
	# To get the turn_key 1-16
	#############################################################
	#############################################################
	# permuted choice 1
	after_permuted_choice_1 = permutation.permutation(key_bin, table.permuted_choice_1)
	#print 'After permuted choice 1 is:', binary.format(after_permuted_choice_1)
	#print 'The len of after_permuted_choice_1 is', len(after_permuted_choice_1)

	C_0 = after_permuted_choice_1[:28]
	D_0 = after_permuted_choice_1[28:]
	#print 'C_0 is: ', binary.format(C_0, 7)
	#print 'D_0 is: ', binary.format(D_0, 7)

	C_1 = C_0
	D_1 = D_0

	turn_key = []
	# get the turn_key by turn 16 times
	for times in range(16):
		# circle shift left 1 or 2 bit(s)
		C_1 = binary.circle_shift_left(C_1, table.shift_table[times])
		D_1 = binary.circle_shift_left(D_1, table.shift_table[times])

		#print 'C_1 shift left', table.shift_table[times], 'bits is: ', C_1
		#print 'D_1 shift left', table.shift_table[times], 'bits is: ', D_1

		after_permuted_choice_2 = permutation.permutation(C_1+D_1, table.permuted_choice_2) # permuted choice 2

		turn_key.append(after_permuted_choice_2)
		#print 'The turn_key[', times + 1, '] is:', binary.format(after_permuted_choice_2, 6)
		#print 'The len of after_permuted_choice_2 is:', len(after_permuted_choice_2)

	#print 'The turn key is:', turn_key
	#print len(turn_key)

	# #####################################################
	# #####################################################
	# Encrypt the Data
	# #####################################################
	# #####################################################

	# Do the initial permutation
	after_init_perm = permutation.permutation(plaintext_bin, table.initial_permutation)
	#print 'After initial permutation is:', binary.format(after_init_perm)

	L_0 = after_init_perm[:32]
	R_0 = after_init_perm[32:]
	#print 'The L_0 is:', binary.format(L_0)
	#print 'The R_0 is:', binary.format(R_0)


	R_1 = R_0

	# judging is the mode
	if mode == 'encrypt':
		range_type = range(16)
	elif mode == 'decrypt':
		range_type = range(15, -1, -1)

	# do the 16 tiems turn
	for i in range_type:
		temp = R_1
		#print 'Round:', i+1

		# Expansion R_1 from 32bits to 48bits, using the expansion table
		E = permutation.permutation(R_1, table.expansion) # now, E is 48bits
		#print 'E :', binary.format(E, 6)
		#print 'KS :', binary.format(turn_key[i], 6)

		# Xor E with turn_key[i]
		R_xor_turnkey = binary.xor_bybit(E, turn_key[i])
		#print 'E xor KS:', binary.format(R_xor_turnkey, 6)

		# S box permutation
		s_box = permutation.s_box(R_xor_turnkey)
		#print 'Sbox:', binary.format(s_box, 4)

		# P permutation
		P = permutation.permutation(s_box, table.permutation_p)
		#print 'P :', binary.format(P)

		# Xor P with L_0
		R_1 = binary.xor_bybit(L_0, P)

		L_0 = temp			# L[i] = R[i+1]
		#print 'The L[',i+1, ']:', binary.format(L_0)
		#print 'The R[',i+1,']:', binary.format(R_1)
		#print

	final = R_1 + L_0			# exchange the left 32bits with right 32bits
	#print 'R[16]L[16]:', binary.format(final)

	# do the inverse initial permutation
	output = permutation.permutation(final, table.inverse_initial_permutation)
	#print 'Output:', binary.format(output)

	# Turn binary code to hexdecimal
	output_hex = []
	for i in range(0, 64, 4):
		#print output[i:i+4]
		output_hex.append(hex(int(output[i:i+4],2))[-1])
	if mode == 'encrypt':
		#print 'The encryped hexdecimal is:', ''.join(output_hex)
		return ''.join(output_hex)
	else:
		#print 'The decrypted hexdecimal is:', ''.join(output_hex)
		#decrypt_text = binascii.a2b_hex(''.join(output_hex))
		#print 'The decrypted text is:', decrypt_text
		#return decrypt_text
		return ''.join(output_hex)
Exemplo n.º 26
0
 def test_80_expand(self):
     id = permutation(self.sz)
     id.expand()
     for i in range(id.maxsize):
         self.assertTrue(id.permutation.has_key(i),msg='{} should be present '.format(i))
         self.assertEqual(id.permutation[i],i)
Exemplo n.º 27
0
 def test_80_collapse(self):
     id = permutation(self.sz,complete=True)
     id.collapse()
     for i in range(id.maxsize):
         self.assertFalse(id.permutation.has_key(i),msg='{} should not be present '.format(i))
 def test_permutation_with_small_integers(self):
     # permutation should return the product n*(n-1)*...*(n-m+1) for n >= m > 0
     assert permutation(10, 0) == 1  # base case
     assert permutation(10, 1) == 10  # base case
     assert permutation(10, 2) == 10*9
     assert permutation(10, 3) == 10*9*8
     assert permutation(10, 4) == 10*9*8*7
     assert permutation(10, 5) == 10*9*8*7*6
     assert permutation(10, 6) == 10*9*8*7*6*5
     assert permutation(10, 7) == 10*9*8*7*6*5*4
     assert permutation(10, 8) == 10*9*8*7*6*5*4*3
     assert permutation(10, 9) == 10*9*8*7*6*5*4*3*2
     assert permutation(10, 10) == 10*9*8*7*6*5*4*3*2*1
Exemplo n.º 29
0
 def test_10_new_from_list(self):
     perm_list = [ 0, 1 ]
     perm = permutation(self.sz,perm_list)
     self.assertEqual(perm[0],1)
     self.assertEqual(perm[1],0)
     self.assertTrue(all(perm[i] == i for i in range(2,self.sz)))
Exemplo n.º 30
0
def compression_p_box(input):
    return permutation(input, key_compression_array)
Exemplo n.º 31
0
 def test_20_new_from_dict_1(self):
     perm_dict = { 0:1, 1:0,}
     perm = permutation(self.sz,perm_dict)
     self.assertEqual(perm[0],1)
     self.assertEqual(perm[1],0)
     self.assertTrue(all(perm[i] == i for i in range(2,self.sz)))
Exemplo n.º 32
0
import permutation


def answer(coins, amount):
    total = 0
    for i in range(0, len(coins)):
        total += amount // coins[i]
        if amount >= coins[i]:
            amount = amount % coins[i]
            #print(f'i: {i}, coin selected: {coins[i]}, total coins: {total} , remaining amount: {amount}')
        if amount == 0:
            return total
    return -1


array = [8, 5, 3]
amount = 18
coin_lists = permutation.permutation(array)
outputs = []
for coins in coin_lists:
    outputs.append(answer(coins, amount))

print(outputs)
 def test_permutation_with_negative_integers_m(self):
     # permutation should raise a ValueError for n < 0
     with self.assertRaises(ValueError, msg='function undefined for m < 0'):
         permutation(1, -1)
         permutation(5, -5)
Exemplo n.º 34
0
def expansion_p_box(input):
    if len(input) != 32:
        raise Exception("Wrong dimension")

    return permutation(input, expansion_p_box_array)
 def test_permutation_with_integers_m_larger_than_integers_n(self):
     # permutation should raise a ValueError for n < 0
     with self.assertRaises(ValueError, msg='function undefined for n <= m'):
         permutation(4, 5)
         permutation(3, 7)
 def test_permutation_with_floating_point_numbers(self):
     # permutation should raise a ValueError for non-integer n
     with self.assertRaises(ValueError, msg='function undefined for float'):
         permutation(2.0, 1)
         permutation(3.14159, 3)
         permutation(9, 3.14159)
Exemplo n.º 37
0
 def __init__(self, vars, idx):
     self.vars = vars
     self.idx = idx
     self.permutation = permutation.permutation(vars, idx)
     self.pairwise_swaps = permutation.pairwise_swaps(
         vars, self.permutation)
Exemplo n.º 38
0
def image_encrypt(src_img, key):
    chen_system = chaosSystem3d(key)
    per_img = permutation(src_img, chen_system)
    cipher = diffusion(per_img, chen_system)
    return cipher