Example #1
0
def find_NLS(fasta_object):
    # loop over NLS_list and apply brute force for each
    possible_hits = []
    for pattern in NLS_list:
        best_match = bf.brute_force(fasta_object.sequence, pattern)
        possible_hits.append(best_match)
    return (possible_hits)
def test_mt_bf(A, r):
    """
    Compare the computation of log Z and edge marginals via the matrix-tree
    theorem and brute-force search.  Warning this method is exponential in
    the number of nodes so it should only be used on small graphs.
    """

    bf = brute_force(A, r)
    [bf_lnz, bf_dr, bf_dA] = bf.lnz, bf.R, bf.M
    [mt_lnz, mt_dr, mt_dA] = mt(A, r)

    print()
    print(f'bf logZ= {bf_lnz:g}')
    print(f'mt logZ= {mt_lnz:g}')

    np.testing.assert_allclose(bf_lnz, mt_lnz)

    print('p(i = root(t))')
    print('\n'.join(f'  {x}' for x in str(mt_dr).split('\n')))

    print('p(<h,m> in t)')
    print('\n'.join(f'  {x}' for x in str(mt_dA).split('\n')))

    np.testing.assert_allclose(bf_dr, mt_dr)
    np.testing.assert_allclose(bf_dA, mt_dA)
Example #3
0
def factorize_v1(n, ini_facto=False):

    ## Version 1 of factorization algorithm
    ## 1. Set a threshold of number of digits: TH
    ## 2. Use a pre-generated list of primes. Try to divide number by these primes numbers
    ## 3. If still composite and many digits, use pollard rho
    ## 4. If still composite, finish with brute force

    prime_factors_list = list()

    if ini_facto:
        prime_factors_list, n = initial_facto(n)

    POLLARD_TH = 1e6

    if digits(n) > POLLARD_TH:
        # Pollard_rho algo
        pollard_res = pollard(n)
        # If returns false, n is prime
        if not pollard_res:
            return prime_factors_list + [n]

        [p, q] = pollard_res
        return prime_factors_list + factorize_v1(p) + factorize_v1(q)

    else:
        return prime_factors_list + brute_force(n)
Example #4
0
def factorize_v2(n, ini_facto=True):

    ## Version 1 of factorization algorithm
    ## 1. Set a threshold of number of digits: TH
    ## 2. Use a pre-generated list of primes. Try to divide number by these primes numbers
    ## 3. If still composite and many digits, use pollard rho
    ## 4. If still composite, finish with brute force

    prime_factors_list = list()
    start = time()
    print(f"Starting for {n}")
    if ini_facto:
        prime_factors_list, n = initial_facto(n)

    if n == 1:
        return prime_factors_list

    print(f"{time() - start} for initial facto. {n}")
    startp = time()
    isprime = pws_is_prime(n)
    print(f"is prime took {time() - startp}")
    if isprime:
        print(f"{n} was prime")
        print(prime_factors_list + [n])
        return prime_factors_list + [n]

    start = time()
    primes = prime_factors_list + brute_force(n)
    print(f"Brute force took {time()-start}s")
    print(f"{primes}\n\n")
    return primes
Example #5
0
def main():
    test_graph, nb_nodes, nb_edges = load_graph('specific/Gnp10_0.2.clq')

    print("\n--- GREEDY ---")
    start_time = time.time()
    gd_solution = cliques_from_list(greedy(test_graph))
    print(">>> %s seconds" % (time.time() - start_time))
    print(">>>", len(gd_solution), "cliques")
    print(">>>", gd_solution)

    print("\n--- BACKTRACK ---")
    start_time = time.time()
    cliques = [0 for x in range(test_graph.shape[0])]
    cliques[0] = 1
    bt_solution = backtrack(test_graph, cliques, 1)
    print(">>> %s seconds" % (time.time() - start_time))
    print(">>>", bt_solution[0], "cliques")
    print(">>>", bt_solution[1])

    print("\n--- BRUTE FORCE ---")
    start_time = time.time()
    bf_solution = brute_force(test_graph, cliques, 0)
    print(">>> %s seconds" % (time.time() - start_time))
    print(">>>", bf_solution[0], "cliques")
    print(">>>", bf_solution[1])
Example #6
0
def compare():
    # min: 1, max: 995
    start = 1
    end = 3
    p = 1
    n = 3
    dict_exp1 = {}
    dict_exp2 = {}
    dict_exp3 = {}
    dict_angles1 = {}
    dict_angles2 = {}
    dict_angles3 = {}

    for gi in range(start, end + 1):
        print(
            str(gi) + '/' + str(end) + '\t' +
            str(datetime.datetime.now().time()))
        G = nx.read_gpickle('atlas/' + str(gi) + '.gpickle')
        k = int(len(G.nodes) / 2)
        if k == 0: k = 1
        key = tuple([gi, k])

        exp, angles = brute_force(G, k, p, n)
        dict_exp1[key] = exp
        dict_angles1[key] = angles

        exp, angles = dicke_ps_ring(G, k, p, n)
        dict_exp2[key] = exp
        dict_angles2[key] = angles

        exp, angles = ring_ps_ring(G, k, p, n)
        dict_exp3[key] = exp
        dict_angles3[key] = angles

    print('Dumping pickles at: ' + str(datetime.datetime.now().time()))
    pickle.dump(dict_exp1, open('data/brute_force.exp', 'wb'))
    pickle.dump(dict_exp2, open('data/dicke_ps_ring.exp', 'wb'))
    pickle.dump(dict_exp3, open('data/ring_ps_ring.exp', 'wb'))
    pickle.dump(dict_angles1, open('data/brute_force.angles', 'wb'))
    pickle.dump(dict_angles2, open('data/dicke_ps_ring.angles', 'wb'))
    pickle.dump(dict_angles3, open('data/ring_ps_ring.angles', 'wb'))

    print('Finished at: ' + str(datetime.datetime.now().time()))
    print('dict_exp1:\n' + str(dict_exp1))
    print('dict_exp2:\n' + str(dict_exp2))
    print('dict_exp3:\n' + str(dict_exp3))
    print('dict_angles1:\n' + str(dict_angles1))
    print('dict_angles2:\n' + str(dict_angles2))
    print('dict_angles3:\n' + str(dict_angles3))
Example #7
0
def main():
    seed = int(input("Wprowadź Z: "))
    generator = RandomNumberGenerator(seed)
    taskNumber = int(input("Wprowadź rozmiar problemu: "))
    tasks = range(1, taskNumber + 1)
    nr = []
    pj = []  #czas wykonania
    wj = []  #waga/współczynnik kary
    dj = []  #żądany termin zakończenia

    for task in tasks:
        nr.append(task)
        pj.append(generator.nextInt(1, 29))

    A = 0
    for number in pj:
        A += number

    for task in tasks:
        wj.append(generator.nextInt(1, 9))
    X = 29
    #X=A
    for task in tasks:
        dj.append(generator.nextInt(1, X))

    print("\nnr:", nr)
    print("pj: ", pj)
    print("wj ", wj)
    print("dj", dj)

    witi_start = target_fun(pj, wj, dj, taskNumber)
    print(f'\nWiTi dla początkowego = {witi_start[0]}')
    print(f'C: {witi_start[2]}')
    print(f'T: {witi_start[1]}')

    witi_greedy = greedy(pj, wj, dj, taskNumber)
    print(f'\nWiTi dla Greedy algorithm = {witi_greedy[0]}')
    print(f'C: {witi_greedy[2]}')
    print(f'T: {witi_greedy[1]}')

    witi_brute_force = brute_force(pj, wj, dj, taskNumber)
    print(f'\nWiTi dla Brute Force = {witi_brute_force[0]}')
    print(f'C: {witi_brute_force[2]}')
    print(f'T: {witi_brute_force[1]}')
Example #8
0
def DpR(points_x, points_y, seuil_recur):
    nb_points = len(points_x)

    # Si le nombre de points est inférieur au seuil de récursivité, on change
    # d'algorithme pour trouver la plus petite distance
    if nb_points <= seuil_recur:
        min_dist = brute_force(points_x)
        return min_dist

    # On divise nos points en deux groupes, en fonction de leur abscisse
    # puis on cherche récursivement le minimum dans chaque groupe
    middle = nb_points // 2
    left_group_x = points_x[:middle]
    right_group_x = points_x[middle:]

    # middle_x correspond à l'abscisse du premier point du groupe de droite
    middle_x = points_x[middle][0]

    # On sépare la liste triée selon y en deux groupes également
    left_group_y = []
    right_group_y = []
    for p in points_y:
        if p[0] < middle_x:
            left_group_y.append(p)
        else:
            right_group_y.append(p)

    # On appelle récursivement l'algo Diviser pour Régner
    min_left = DpR(left_group_x, left_group_y, seuil_recur)
    min_right = DpR(right_group_x, right_group_y, seuil_recur)
    d = min(min_left, min_right)

    # On construit une bande verticale dans laquelle les points ont une abscisse à moins
    # d'une distance d de middle_x à gauche et à droite (d = distance minimale trouvée
    # dans le groupe de gauche et dans le groupe de droite)
    strip = [p for p in points_y if abs(p[0] - middle_x) < d]
    min_strip = find_min_strip(strip, d)
    min_dist = min(d, min_strip)

    return min_dist
Example #9
0
                        default=3,
                        help="Group size to use")
    conf = parser.parse_args()

    for i in range(conf.start, conf.stop + 1):
        if conf.lex:
            start = timer()
            print("HEURISTIC - LEXOGRAPHIC:")
            lexographic(i, conf.group_size)[0].pretty_print(conf.verbose)
            end = timer()
            print("Time taken for {} students: {}".format(i, end - start))
        if conf.llu:
            start = timer()
            print("HEURISTIC - LOWEST LEAST USED")
            lowest_least_used(i, conf.group_size)[0].pretty_print(conf.verbose)
            end = timer()
            print("Time taken for {} students: {}".format(i, end - start))
        if conf.bf:
            start = timer()
            print("BRUTE-FORCE:")
            solutions = brute_force(i, conf.group_size)
            if conf.print_all:
                for solution in solutions:
                    solution.pretty_print(conf.verbose)
            else:
                solutions[0].pretty_print(conf.verbose)
            print("{} optimal solutions found of length {}".format(
                len(solutions), solutions[0].length))
            end = timer()
            print("Time taken for {} students: {}".format(i, end - start))
Example #10
0
t = time.time()

print '\nNumber of representative groups :  ', k
print 'Group size:                        ', G_size
print 'Dimension:                         ', Dimension
print 'Point_point_number:                ', N
print 'Dataset_type:                      ', dataset_name[dataset]
print 'Iterations:                        ', iteration

filename = 'E:\\datasets\\' + dataset_name[dataset] + '_' + str(Dimension) + '.txt'

print '\nConstructing DSG...',
test = DSG(filename, G_size, N)
print 'Finished'
print 'Constructing G-skyline...',
g_skyline = UWise(G_size, test)
print 'Finished   Length of G-skyline:', len(g_skyline)

[represent_skyline, time] = maximum_dominance(g_skyline, k, filename, test, N)
print '\nMaximum_dominance:   ', time
#repre_output(g_skyline, represent_skyline, 1)
#0 to output repr group, 1 to output each repr group and corresponding groups, 2 for NBA

[represent_skyline, time] = brute_force(g_skyline, G_size, Dimension, k, iteration)
print 'RG_skyline_B:        ', time
#repre_output(g_skyline, represent_skyline, 0)

[represent_skyline, time] = g_clustering(g_skyline, G_size, Dimension, k, iteration)
print 'RG_skyline:          ', time
#repre_output(g_skyline, represent_skyline, 1)
Example #11
0
        txt = file.read()
    pattern = "ATTCGGGTGGCATCCTCCGGAGAGAGAGAGAGGAAGGAG"

    lst_alg_for_plot = ["DFA", "brute force", "KMP", "BMH", "BM"]
    lst_time_for_plot = []

    #DFA
    start_time = time.time()
    DFA_match(pattern, txt)
    end_time = time.time()
    lst_time_for_plot.append(end_time-start_time)
    print(f"DFA done :{end_time-start_time}")

    #BRUTE FORCE
    start_time = time.time()
    brute_force(pattern, txt)
    end_time = time.time()
    lst_time_for_plot.append(end_time-start_time)
    print(f"BRUTE FORCE done :{end_time - start_time}")

    #KMP
    start_time = time.time()
    KMP_search(pattern, txt)
    end_time = time.time()
    lst_time_for_plot.append(end_time-start_time)
    print(f"KMP done :{end_time - start_time}")

    #BMH
    start_time = time.time()
    BMH_search(pattern, txt)
    end_time = time.time()
    print(f"\nWhich algoritm would you like to use?\n\
        Type A for a brute force algorithm\n\
        Type B for a random algorithm that will run 10.000 times and saves the best result\n\
        Type C for a greedy algorithm followed by a hillclimber\n\
        Type D for a hillclimber algorithm on a random solution\n\
        Type E or a simulated annealing algorithm on a random solution")

    while True:
        answer = str(input())
        if answer == 'A':
            print(
                "\nWARNING: This algorithm might take weeks to run.\nAre you sure you want to run a brute force algorithm?"
            )
            answer = str(input("Type Y or N\n"))
            if answer == 'Y':
                results = brute_force(smartgrid)
                algorithm = "brute_force"
                break
            elif answer == 'N':
                print("Choose B, C, D or E")
        if answer == 'B':
            results = random_solution(smartgrid, count)
            algorithm = "random"
            break
        if answer == 'C':
            results = greedy(smartgrid)
            results = add_missing_houses(smartgrid, results)
            results = hillclimber_determined(smartgrid, results)
            algorithm = "greedy_hillclimber"
            break
        if answer == 'D':
              + "\tAll lowercase values have been converted to UPPERCASE\n"
              + "\tand all non alphabetic characters have been removed including spaces and newlines\n")

    secret_message_sanitized = string_tools.string_to_num_list(
        secret_message_sanitized, 'A')
    secret_key_sanitized = string_tools.string_to_num_list(
        secret_key_sanitized, 'A')

    cipher_text = vigenere.encrypt(
        secret_message_sanitized, secret_key_sanitized)

    keylengths = ci_keylength(cipher_text, 1, 9)

    # print("\nStarting PSO and Brute force threads on key length(s): " + str(keylengths))
    # print("and cipher text\n" + str(cipher_text) + "\n")

    pso_thread = []
    brute_thread = []

    for i, keylength in enumerate(keylengths):
        pso_thread.append(pso(cipher_text, len(secret_key_sanitized),
                              200, 200, 26, 1, 10, 1, 2.05, 2.05, queue.Queue()))
        brute_thread.append(brute_force(
            cipher_text, keylength, secret_message_sanitized))

        print("\nStarting PSO and Brute force threads on key length " +
              str(keylength) + "\n")

        brute_thread[i].start()
        pso_thread[i].start()
def exp_bf(A):
  """Brute force
  """

  U, s, V = brute_force(A)
Example #15
0
 def test_actual(self):
     # brute force the thing
     [pk] = list(brute_force((29815, n), CIPHER, 'h'))
     message = decrypt((pk, n), CIPHER)
     self.assertTrue(message.startswith('h'))
def brute_time(puzzle):
    start = time.time()
    puzzle = brute_force(puzzle, len(puzzle))
    end = time.time()
    return (end - start)