-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenetic_Algorithm.py
More file actions
148 lines (112 loc) · 6.38 KB
/
Genetic_Algorithm.py
File metadata and controls
148 lines (112 loc) · 6.38 KB
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
#import functions
import numpy as np
import time
from multiprocessing import Pool
import ThreeHiggsModel_Analayse as THMA
import pandas as pd
import ast
def extract_parameters_Genetic(filename):
df = pd.read_csv(filename)
parameters = []
parameters_string = df['Parameters'].values[42501:43001]
for string_i in parameters_string:
string = string_i[1:-1]
string = string.replace('\n','')
string = string.split(' ')
parameters_i = []
for j in string:
if len(j) != 0:
parameters_i.append(ast.literal_eval(j))
parameters.append(parameters_i)
return parameters
#extract last generation
parameters_last_generation = extract_parameters_Genetic('Genetic_Roots43.csv')
def Genetic_Algorithm(num_of_parents = 500, num_iterations = 3, num_of_mutations = 1, \
parents_given = True, parents_last = parameters_last_generation, \
tolerance_avrg = 1e-5, survival_prob = 0.9,file_name = 'Genetic_Roots_Test'):
time_start = time.time()
all_minima = [np.NaN]
all_parameters = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
#select random parents
parents = []
mutation_factor = []
if parents_given is False:
time_start_generate = time.time()
for i in range(num_of_parents):
parents.append([np.random.uniform(1e4,2e5), np.random.uniform(1e4,2e5), np.random.uniform(1e4,2e5), np.random.uniform(0,7), np.random.uniform(0,7), \
np.random.uniform(0,7), np.random.uniform(-4*np.pi,4*np.pi), \
np.random.uniform(-8,4*np.pi), np.random.uniform(-8,4*np.pi), np.random.uniform(-4*np.pi,4*np.pi), np.random.uniform(-4*np.pi,8), \
np.random.uniform(-4*np.pi,8), np.random.uniform(-1.5e5,1.5e5), np.random.uniform(-0.8e5,0.25e5), np.random.uniform(-4e5,0)])
time_end_generate = time.time()
print('Time to Generate: {}'.format(time_end_generate - time_start_generate))
else:
parents = parents_last
cost_value = ['']
p = Pool(4) # this core spliting thing I have to test it more
parents_solutions = p.map(THMA.roots_Polynomial_Genetic, parents)
#update servivors
#while min(cost_value) >= tolerance: tolerance constraint
count = 0
average_cost_value =[0]
change_in_average = 0.02
standard_deviation = 0
print("here")
while count < num_iterations and abs(change_in_average) > tolerance_avrg:#number of iteration constraint
if abs(change_in_average) <= 0.1:
survival_possibility = survival_prob - 0.2
else:
survival_possibility = survival_prob
whole_generation = parents
each_new_generation = np.full((num_of_parents,15),0)
mutation_number = 0
#mutation
time_mutations_start = time.time()
while mutation_number < num_of_mutations:
for i in range(num_of_parents):
for j in range(15):
mutation_factor = np.random.uniform(-2,2)
mutation_probability = np.random.uniform(0,1)
if survival_possibility < mutation_probability:
each_new_generation[i][j] = parents[i][j]*mutation_factor
else:
each_new_generation[i][j] = parents[i][j]
whole_generation = np.concatenate((whole_generation,each_new_generation), axis=0)
mutation_number +=1
time_mutations_end = time.time()
print('Time for Mutations : {}'.format(time_mutations_end - time_mutations_start))
p2 = Pool(4) # this core spliting thing I have to test it more
time_cost_start = time.time()
children_solutions = p2.map(THMA.roots_Polynomial_Genetic, whole_generation[num_of_parents:])
generation_solutions = np.concatenate((np.array(parents_solutions), np.array(children_solutions)))
all_parameters_holder = np.concatenate((all_parameters, whole_generation), axis =0)
all_minima_holder = np.concatenate((all_minima, generation_solutions[:,1]), axis =0)
cost_value = generation_solutions[:,0]
average_cost_value.append(sum(cost_value)/len(cost_value))
standard_deviation = np.std(cost_value)
change_in_average = average_cost_value[-1]-average_cost_value[-2]
time_cost_end = time.time()
all_minima = all_minima_holder
##all_eigenvalues = all_eigenvalues_holder
all_parameters = all_parameters_holder
print('Time for Costs : {}'.format(time_cost_end - time_cost_start))
index = np.argpartition(cost_value, num_of_parents)
parents = whole_generation[index[:num_of_parents]]
parents_solutions = generation_solutions[index[:num_of_parents]]
count += 1
time_end = time.time()
#save information into csv file
print('Total Time : {}'.format(time_end-time_start))
other_info = ['Time Taken'] + [time_end - time_start] + [''] + ['Minimum Cost Function Value'] \
+ [min(cost_value)] + [''] +['Average of this generation'] + [average_cost_value[-1]] + [''] + ['Change in Average'] + [abs(change_in_average)] + [''] + \
['Standard Deviation'] + [abs(standard_deviation)] + ['']
#all_eigenvalues.pop(0)
total_length = max(len(other_info), len(all_minima))
other_info = other_info + list(np.full(total_length - len(other_info), ''))
#eigenvalues_minima_square_all_s = list(all_eigenvalues) + list(np.full(total_length - len(all_minima), ''))
minima_found_all_s = list(all_minima) + list(np.full(total_length - len(all_minima), ''))
parameters_guess_all_s = list(all_parameters) + list(np.full(total_length - len(all_minima), ''))
cost_func_value = ['']+ list(cost_value) + list(np.full(total_length - len(cost_value)-1, ''))
df = pd.DataFrame({'Parameters' : parameters_guess_all_s, 'Minima Found' : minima_found_all_s, 'Cost Function Values':cost_func_value, 'Other Info' : other_info})
df.to_csv(file_name + str(count) + '.csv', index=True)
#print(min(cost_value))
return min(cost_value)