-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp_genetic.py
227 lines (171 loc) · 7.31 KB
/
app_genetic.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
from data_util import *
import json
import copy
from finder.genetic.tournament import *
from finder.genetic.elite import *
min_starting_frequencies = 3
max_starting_frequencies = 6
population_size = 8
num_elite = 1
winners_per_round = 2
max_rounds = 100
current_round = 1
num_windows = 1
def print_best_candidate(population):
best_score = None
best_candidate = None
for c in population:
c_score = c.get_composite_score()
if best_score is None or c_score < best_score:
best_score = c_score
best_candidate = c
print('\nBest candidate:')
print(best_candidate.get_formatted())
def get_normalized_probability_list(qty):
probability_list = []
for _ in range(qty):
probability_list.append(random.random())
sum_of_probabilities = sum(probability_list) * 1.5
return [p / sum_of_probabilities for p in probability_list]
target = get_random_target(
min_starting_frequencies,
max_starting_frequencies,
num_windows
)
print('Target frequencies:\n{}'.format(json.dumps(target.get_frequencies(), indent=2)))
population = get_random_population(
population_size,
min_starting_frequencies,
max_starting_frequencies,
target,
num_windows
)
target.debug_bucketed()
while True:
lowest_score = None
best_index = None
for i in range(len(population)):
combined_score = population[i].get_composite_score()
if lowest_score is None or combined_score < lowest_score:
best_index = i
lowest_score = combined_score
if current_round > max_rounds or lowest_score < 3:
break
print("\nBest candidate in round {}:\n{}".format(current_round, population[best_index].get_formatted()))
elite_indices = get_elite_indices(population, num_elite)
remaining_indices_for_tournament = [i for i in range(len(population)) if i not in elite_indices]
non_elite_surviving_indices = []
select_tournament_winners(
population,
remaining_indices_for_tournament,
non_elite_surviving_indices,
winners_per_round,
num_elite
)
all_surviving_indices = elite_indices + non_elite_surviving_indices
# randomly pair the next generation
random.shuffle(all_surviving_indices)
surviving_index_pairs = zip(all_surviving_indices[0::2], all_surviving_indices[1::2])
children = []
# Create children and calculate their fitness scores
for i1, i2 in surviving_index_pairs:
c1 = Candidate()
c2 = Candidate()
f1 = []
f2 = []
parent_frequencies = population[i1].get_frequencies() + population[i2].get_frequencies()
min_parent_freq = min([f['frequency'] for f in parent_frequencies])
max_parent_freq = max([f['frequency'] for f in parent_frequencies])
min_crossover_freq = min_parent_freq / 1.5 if min_parent_freq / 1.5 > 1.0 else 1.0
max_crossover_freq = max_parent_freq * 1.5 if max_parent_freq * 1.5 < 20000.0 else 20000.0
crossover_frequency = get_random_frequency(min_crossover_freq, max_crossover_freq)
for f in population[i1].get_frequencies():
if f['frequency'] < crossover_frequency:
f1.append(f)
else:
f2.append(f)
for f in population[i2].get_frequencies():
if f['frequency'] < crossover_frequency:
f2.append(f)
else:
f1.append(f)
c1.set_frequencies_and_calculate_scores(f1, target, num_windows)
c2.set_frequencies_and_calculate_scores(f2, target, num_windows)
children.append(c1)
children.append(c2)
# Mutation of children
for c in children:
# Adjust the number of frequencies
if c.frequency_count_score > 0 and random.random() < 0.5:
append_random_frequencies(
c.frequencies,
c.frequency_count_score
)
elif c.frequency_count_score < 0 and random.random() < 0.5:
random.shuffle(c.frequencies)
remove_frequencies(
c.frequencies,
-c.frequency_count_score if len(c.frequencies) > -c.frequency_count_score else len(c.frequencies) - 1
)
# Either add or subtract from each frequency value (with high probability)
if random.random() < 0.9:
c_frequencies = c.get_frequencies()
if c.get_too_high_score() == 0:
add_qty = len(c_frequencies)
subtract_qty = 0
elif c.get_too_low_score() == 0:
add_qty = 0
subtract_qty = len(c_frequencies)
elif len(c_frequencies) % 2 == 0:
add_qty = int(len(c_frequencies) / 2)
subtract_qty = int(len(c_frequencies) / 2)
else:
add_qty = int((len(c_frequencies) / 2) + random.random())
subtract_qty = len(c_frequencies) - add_qty
new_guess_frequencies = []
too_high_adjustments = [p * c.get_too_high_score() for p in get_normalized_probability_list(subtract_qty)]
for value in too_high_adjustments:
eligible_guess_indices = [i for i in range(len(c_frequencies)) if
c_frequencies[i]['frequency'] - value > 0]
if len(eligible_guess_indices) > 0:
subtract_index = random.randint(0, len(eligible_guess_indices) - 1)
new_guess_frequencies.append({
'type': 'sine',
'frequency': c_frequencies[eligible_guess_indices[subtract_index]]['frequency'] - value
})
del c_frequencies[eligible_guess_indices[subtract_index]]
else:
keep_index = random.randint(0, len(c_frequencies) - 1)
new_guess_frequencies.append({
'type': 'sine',
'frequency': c_frequencies[keep_index]['frequency']
})
del c_frequencies[keep_index]
too_low_adjustments = [p * c.get_too_low_score() for p in get_normalized_probability_list(add_qty)]
for value in too_low_adjustments:
add_index = random.randint(0, len(c_frequencies) - 1)
new_guess_frequencies.append({
'type': 'sine',
'frequency': c_frequencies[add_index]['frequency'] + value
})
del c_frequencies[add_index]
c.set_frequencies(new_guess_frequencies)
# Completely random mutation of each frequency value (with low probability)
for f in c.get_frequencies():
if random.random() < 0.01:
f['frequency'] = get_random_frequency(100, 2000)
c.calculate_scores(target, num_windows)
new_population = []
for i in elite_indices:
new_population.append(copy.deepcopy(population[i]))
for i in non_elite_surviving_indices:
new_population.append(copy.deepcopy(population[i]))
for c in children:
new_population.append(c)
population = new_population
current_round += 1
print_best_candidate(population)
print('\nTarget frequencies:\n{}'.format(
json.dumps(sorted(target.get_frequencies(), key=lambda x: x['frequency']), indent=2))
)
print('done after {} rounds'.format(current_round - 1))