-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhill-climbin.py
80 lines (67 loc) · 3 KB
/
hill-climbin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import common
import random
maximum_restarts = 50
def calculate_minimum_hamming_distance(motif, string):
string_motifs = common.get_nth_substrings(
common.input_motif_length, string)
error = common.input_motif_length
for substring in string_motifs:
substring_error = common.calculate_hamming_distance(substring, motif)
if substring_error < error:
error = substring_error
return error
def calculate_fitness_score(motif):
fitness_score = 0
valid = True
for string in common.input_strings:
string_score = calculate_minimum_hamming_distance(motif, string)
if string_score > common.input_hamming_distance:
valid = False
fitness_score += string_score
return fitness_score, valid
def check_motif_fitness_score_and_validation(motif):
motif_is_valid_for_all_strings_inputs = True
this_motif_fitness_score, is_motif_valid = calculate_fitness_score(motif)
next_motif = motif
for i in range(0, maximum_restarts):
print(motif)
adjecent_motif = common.generate_adjecent_motif(motif)
print(adjecent_motif)
adjecent_motif_fitness_score, adjecent_valid = calculate_fitness_score(
adjecent_motif)
print('Adjecent motif fitness score:', adjecent_motif_fitness_score)
if adjecent_motif_fitness_score < this_motif_fitness_score:
print(adjecent_motif + ' is better than ' + next_motif + ' with ' +
str(this_motif_fitness_score - adjecent_motif_fitness_score) + ' scores.')
next_motif = adjecent_motif
break
if next_motif == motif:
return motif, this_motif_fitness_score, is_motif_valid
else:
print('Going to adjecent motif.\n\n')
return check_motif_fitness_score_and_validation(next_motif)
def start_hill_climbing():
answers = []
for i in range(0, maximum_restarts):
motif, fitness, is_valid = check_motif_fitness_score_and_validation(
common.generate_random_potential_motif())
if is_valid == True:
if not motif in answers:
print('\n')
answers.append(motif)
common.print_success(
motif + ' is a discovered motif with score of ' + map_fitness_to_number(fitness))
else:
common.print_warning(motif + ' is not a motif because of ' +
map_fitness_to_number(fitness) + ' fitness score.')
if len(answers) > 0:
common.print_success(str(len(answers)) + ' motif(s) with length of ' +
str(common.input_motif_length) + ' motifs were discovered.')
else:
common.print_error('No motifs with length of ' +
str(common.input_motif_length) + ' were found.')
def map_fitness_to_number(fitness):
return str(int((common.input_motif_length * len(common.input_strings)) - (fitness / (len(common.input_strings) + 1))))
st = common.start_time()
start_hill_climbing()
common.end_time(st)