pypharm 1.6.1__py3-none-any.whl → 1.6.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- PyPharm/__init__.py +4 -3
- PyPharm/algorithms/country_optimization.py +469 -469
- PyPharm/algorithms/country_optimization_v2.py +330 -330
- PyPharm/algorithms/country_optimization_v3.py +428 -428
- PyPharm/algorithms/genetic_optimization.py +130 -130
- PyPharm/algorithms/gold_digger_optimization.py +126 -126
- PyPharm/constants.py +80 -80
- PyPharm/country_optimization.py +470 -0
- PyPharm/country_optimization_v2.py +330 -0
- PyPharm/country_optimization_v3.py +426 -0
- PyPharm/genetic_optimization.py +130 -0
- PyPharm/gold_digger_optimization.py +127 -0
- PyPharm/models/__init__.py +3 -3
- PyPharm/models/compartment_models.py +985 -985
- PyPharm/models/pbpk.py +683 -683
- PyPharm/models.py +638 -0
- {pypharm-1.6.1.dist-info → pypharm-1.6.2.dist-info}/METADATA +11 -7
- pypharm-1.6.2.dist-info/RECORD +21 -0
- {pypharm-1.6.1.dist-info → pypharm-1.6.2.dist-info}/WHEEL +1 -1
- pypharm-1.6.1.dist-info/RECORD +0 -15
- {pypharm-1.6.1.dist-info → pypharm-1.6.2.dist-info}/top_level.txt +0 -0
|
@@ -1,428 +1,428 @@
|
|
|
1
|
-
import random
|
|
2
|
-
import numpy as np
|
|
3
|
-
import copy
|
|
4
|
-
from operator import attrgetter
|
|
5
|
-
from math import ceil, cos, sin
|
|
6
|
-
import graycode
|
|
7
|
-
|
|
8
|
-
def rand_str():
|
|
9
|
-
s = 'qwertyuiopasdfghjklzxcvbnm'
|
|
10
|
-
k = np.random.choice(len(s), 8, replace=False)
|
|
11
|
-
res = ''
|
|
12
|
-
for ki in k:
|
|
13
|
-
res += s[ki]
|
|
14
|
-
return res
|
|
15
|
-
|
|
16
|
-
def check_population(country):
|
|
17
|
-
return bool(country.population.size)
|
|
18
|
-
|
|
19
|
-
vector_check_population = np.vectorize(check_population, signature='()->()')
|
|
20
|
-
|
|
21
|
-
class Individual:
|
|
22
|
-
|
|
23
|
-
def __init__(self, gray_code, x_min, x_max, genes, function):
|
|
24
|
-
|
|
25
|
-
self.x_min = x_min
|
|
26
|
-
self.x_max = x_max
|
|
27
|
-
self.genes = genes
|
|
28
|
-
self.function = function
|
|
29
|
-
self.steps = (self.x_max - self.x_min) / (2 ** (self.genes) - 1)
|
|
30
|
-
self.gray_code = gray_code
|
|
31
|
-
self.f = self.function(self.real_x)
|
|
32
|
-
self.ep_n = 0
|
|
33
|
-
|
|
34
|
-
@property
|
|
35
|
-
def real_x(self):
|
|
36
|
-
decimal_x = []
|
|
37
|
-
gray_code = copy.deepcopy(self.gray_code)
|
|
38
|
-
for g in self.genes:
|
|
39
|
-
decimal_x.append(graycode.gray_code_to_tc(int(gray_code[:g], base=2)))
|
|
40
|
-
gray_code = gray_code[g:]
|
|
41
|
-
return self.x_min + self.steps * np.array(decimal_x)
|
|
42
|
-
|
|
43
|
-
@property
|
|
44
|
-
def decimal_x(self):
|
|
45
|
-
return (self.real_x - self.x_min) / self.steps
|
|
46
|
-
|
|
47
|
-
@classmethod
|
|
48
|
-
def generate_from_decimal(cls, decimal, x_min, x_max, genes, function):
|
|
49
|
-
gray_code = ''
|
|
50
|
-
decimal = np.clip(decimal, np.zeros(decimal.size), 2 ** (genes) - 1)
|
|
51
|
-
for i in range(len(decimal)):
|
|
52
|
-
s = '{:0' + str(genes[i]) + 'b}'
|
|
53
|
-
gray_code += s.format(graycode.tc_to_gray_code(int(decimal[i])))
|
|
54
|
-
|
|
55
|
-
return cls(gray_code, x_min, x_max, genes, function)
|
|
56
|
-
|
|
57
|
-
def mutation(self, max_mutation=1):
|
|
58
|
-
n = max(0, max_mutation - self.ep_n)
|
|
59
|
-
if n:
|
|
60
|
-
gray_code = copy.deepcopy(self.gray_code)
|
|
61
|
-
k = np.random.choice(len(gray_code), n, replace=False)
|
|
62
|
-
for ki in k:
|
|
63
|
-
b = bool(int(gray_code[ki]))
|
|
64
|
-
b = not b
|
|
65
|
-
b = str(int(b))
|
|
66
|
-
gray_code = gray_code[:ki] + b + gray_code[ki+1:]
|
|
67
|
-
return Individual(gray_code, self.x_min, self.x_max, self.genes, self.function)
|
|
68
|
-
else:
|
|
69
|
-
return self
|
|
70
|
-
|
|
71
|
-
@classmethod
|
|
72
|
-
def crossover(cls, individual1, individual2):
|
|
73
|
-
k = np.random.randint(1, len(individual1.gray_code) - 1, 2)
|
|
74
|
-
while k[0] == k[1]:
|
|
75
|
-
k = np.random.randint(1, len(individual1.gray_code) - 1, 2)
|
|
76
|
-
k = np.sort(k)
|
|
77
|
-
new_gray1 = individual1.gray_code[:k[0]] + individual2.gray_code[k[0]:k[1]] + individual1.gray_code[k[1]:]
|
|
78
|
-
new_gray2 = individual2.gray_code[:k[0]] + individual1.gray_code[k[0]:k[1]] + individual2.gray_code[k[1]:]
|
|
79
|
-
return [
|
|
80
|
-
cls(new_gray1, individual1.x_min, individual1.x_max, individual1.genes, individual1.function),
|
|
81
|
-
cls(new_gray2, individual1.x_min, individual1.x_max, individual1.genes, individual1.function),
|
|
82
|
-
]
|
|
83
|
-
|
|
84
|
-
def __lt__(self, other):
|
|
85
|
-
return self.f < other.f
|
|
86
|
-
|
|
87
|
-
def __le__(self, other):
|
|
88
|
-
return self.f <= other.f
|
|
89
|
-
|
|
90
|
-
def __gt__(self, other):
|
|
91
|
-
return self.f > other.f
|
|
92
|
-
|
|
93
|
-
def __ge__(self, other):
|
|
94
|
-
return self.f >= other.f
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
class Country:
|
|
98
|
-
|
|
99
|
-
def __init__(self, N, x_min, x_max, genes, function):
|
|
100
|
-
self.f = function
|
|
101
|
-
self.N = N
|
|
102
|
-
self.x_min = np.array(x_min)
|
|
103
|
-
self.x_max = np.array(x_max)
|
|
104
|
-
self.genes = np.array(genes)
|
|
105
|
-
self.name = rand_str()
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
local_xmin = np.random.randint(np.zeros(self.genes.size), 2 ** self.genes - 1)
|
|
109
|
-
local_xmax = np.random.randint(local_xmin, 2 ** self.genes)
|
|
110
|
-
|
|
111
|
-
self.rand_n_individual = np.vectorize(lambda x: x * self.random_individual(local_xmin, local_xmax), signature='()->(n)')
|
|
112
|
-
self.generate_population = np.vectorize(lambda decimal: Individual.generate_from_decimal(
|
|
113
|
-
decimal, self.x_min, self.x_max, self.genes, self.f), signature='(n)->()')
|
|
114
|
-
|
|
115
|
-
x = self.rand_n_individual(np.ones(self.N))
|
|
116
|
-
self.population = self.generate_population(x)
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
self.sort_population()
|
|
120
|
-
self.action = None
|
|
121
|
-
self.enemy = None
|
|
122
|
-
self.ally = None
|
|
123
|
-
|
|
124
|
-
def random_individual(self, x_min, x_max):
|
|
125
|
-
return np.random.randint(x_min, x_max)
|
|
126
|
-
|
|
127
|
-
@property
|
|
128
|
-
def best_function(self):
|
|
129
|
-
return self.population[0].f
|
|
130
|
-
|
|
131
|
-
def roulette_function(self, f_min, f_max):
|
|
132
|
-
return (f_max - self.population[0].f) / (f_max - f_min)
|
|
133
|
-
|
|
134
|
-
@property
|
|
135
|
-
def avg_function(self):
|
|
136
|
-
return sum([individual.f for individual in self.population]) / self.population.size
|
|
137
|
-
|
|
138
|
-
def sort_population(self):
|
|
139
|
-
self.population.sort()
|
|
140
|
-
|
|
141
|
-
def reproduction(self, n_min, n_max, f_min, f_max):
|
|
142
|
-
n = ceil((n_max - n_min) * (f_max - self.avg_function) / (f_max - f_min) + n_min)
|
|
143
|
-
n = np.clip(n, n_min, n_max)
|
|
144
|
-
# p2 = (1 - ti / t_max) * (self.avg_function - f_min) / (f_max - f_min)
|
|
145
|
-
new_individuals = []
|
|
146
|
-
|
|
147
|
-
for i in range(n):
|
|
148
|
-
if len(self.population) == 2 and self.population[0] == self.population[1]:
|
|
149
|
-
new_individuals.extend(Individual.crossover(self.population[0], self.population[1],
|
|
150
|
-
self.x_min, self.x_max, self.genes, self.f))
|
|
151
|
-
continue
|
|
152
|
-
k1 = random.randint(0, len(self.population) - 1)
|
|
153
|
-
individual1 = self.population[k1]
|
|
154
|
-
k2 = k1
|
|
155
|
-
while k2 == k1:
|
|
156
|
-
k2 = random.randint(0, len(self.population) - 1)
|
|
157
|
-
individual2 = self.population[k2]
|
|
158
|
-
new_individuals += Individual.crossover(individual1, individual2)
|
|
159
|
-
self.population = np.append(self.population, np.array(new_individuals))
|
|
160
|
-
self.sort_population()
|
|
161
|
-
|
|
162
|
-
def extinction(self, m_min, m_max, f_min, f_max):
|
|
163
|
-
m = int((m_max - m_min) * (self.avg_function - f_min) / (f_max - f_min) + m_min)
|
|
164
|
-
m = np.clip(m, m_min, m_max)
|
|
165
|
-
self.population = self.population[:-m]
|
|
166
|
-
|
|
167
|
-
def extinction1(self, n):
|
|
168
|
-
if self.population.size < n:
|
|
169
|
-
return n - self.population.size
|
|
170
|
-
self.population = self.population[:n]
|
|
171
|
-
return 0
|
|
172
|
-
|
|
173
|
-
def select_action(self, countries):
|
|
174
|
-
self.action = random.randint(0, 3)
|
|
175
|
-
if self.action == 1:
|
|
176
|
-
ally_list = [country for country in countries if country.action is None and country != self]
|
|
177
|
-
if ally_list:
|
|
178
|
-
self.ally = ally_list.pop(random.randint(0, len(ally_list) - 1))
|
|
179
|
-
self.ally.action = 1
|
|
180
|
-
self.ally.ally = self
|
|
181
|
-
else:
|
|
182
|
-
self.action = random.choice([0, 3])
|
|
183
|
-
if self.action == 2:
|
|
184
|
-
enemy_list = [country for country in countries if country.action is None and country != self]
|
|
185
|
-
if enemy_list:
|
|
186
|
-
self.enemy = enemy_list.pop(random.randint(0, len(enemy_list) - 1))
|
|
187
|
-
self.enemy.action = 2
|
|
188
|
-
self.enemy.enemy = self
|
|
189
|
-
else:
|
|
190
|
-
self.action = random.choice([0, 3])
|
|
191
|
-
|
|
192
|
-
def epedemic(self, elite, dead, max_mutation):
|
|
193
|
-
if max_mutation < 1:
|
|
194
|
-
max_mutation = 1
|
|
195
|
-
n_elite = ceil(elite * len(self.population))
|
|
196
|
-
n_dead = ceil(dead * len(self.population))
|
|
197
|
-
self.population = self.population[:-n_dead]
|
|
198
|
-
for i in range(n_elite, self.population.size):
|
|
199
|
-
self.population[i] = self.population[i].mutation(max_mutation)
|
|
200
|
-
self.sort_population()
|
|
201
|
-
self.action = None
|
|
202
|
-
|
|
203
|
-
# def sabotage(self, n_copy):
|
|
204
|
-
# for i in range(n_copy):
|
|
205
|
-
# self.enemy.population.append(copy.copy(self.population[0]))
|
|
206
|
-
# self.action = None
|
|
207
|
-
# self.enemy = None
|
|
208
|
-
|
|
209
|
-
def motion(self):
|
|
210
|
-
x_best = self.population[0].decimal_x
|
|
211
|
-
for i in range(1, len(self.population)):
|
|
212
|
-
self.population[i] = Individual.generate_from_decimal(
|
|
213
|
-
self.population[i].decimal_x + np.int64(random.uniform(0, 2) * (x_best - self.population[i].decimal_x)), self.x_min, self.x_max, self.genes, self.f
|
|
214
|
-
)
|
|
215
|
-
self.sort_population()
|
|
216
|
-
self.action = None
|
|
217
|
-
|
|
218
|
-
@staticmethod
|
|
219
|
-
def trade(country1, country2, k):
|
|
220
|
-
if country1.population.size <= k or country2.population.size <= k:
|
|
221
|
-
k = min(country1.population.size, country2.population.size) // 2
|
|
222
|
-
indexes1 = np.random.choice(country1.population.size, k, replace=False)
|
|
223
|
-
indexes2 = np.random.choice(country2.population.size, k, replace=False)
|
|
224
|
-
country2.population = np.concatenate([country2.population, country1.population[indexes1]])
|
|
225
|
-
country1.population = np.concatenate([country1.population, country2.population[indexes2]])
|
|
226
|
-
country1.population = np.delete(country1.population, indexes1)
|
|
227
|
-
country2.population = np.delete(country2.population, indexes2)
|
|
228
|
-
country1.sort_population()
|
|
229
|
-
country2.sort_population()
|
|
230
|
-
country1.action = None
|
|
231
|
-
country2.action = None
|
|
232
|
-
country1.ally = None
|
|
233
|
-
country2.ally = None
|
|
234
|
-
|
|
235
|
-
@staticmethod
|
|
236
|
-
def war(country1, country2, l):
|
|
237
|
-
if country1.population.size <= l or country2.population.size <= l:
|
|
238
|
-
l = min(country1.population.size, country2.population.size)
|
|
239
|
-
indexes1 = np.random.choice(country1.population.size, l, replace=False)
|
|
240
|
-
indexes2 = np.random.choice(country2.population.size, l, replace=False)
|
|
241
|
-
war_list1 = country1.population[indexes1]
|
|
242
|
-
war_list2 = country2.population[indexes2]
|
|
243
|
-
country1.population = np.delete(country1.population, indexes1)
|
|
244
|
-
country2.population = np.delete(country2.population, indexes2)
|
|
245
|
-
wins1 = np.where(war_list1 > war_list2)
|
|
246
|
-
wins2 = np.where(war_list2 > war_list2)
|
|
247
|
-
if wins1[0].size > wins2[0].size:
|
|
248
|
-
np.concatenate([country1.population, war_list1])
|
|
249
|
-
np.concatenate([country1.population, war_list2])
|
|
250
|
-
elif wins2[0].size > wins1[0].size:
|
|
251
|
-
np.concatenate([country2.population, war_list1])
|
|
252
|
-
np.concatenate([country2.population, war_list2])
|
|
253
|
-
else:
|
|
254
|
-
np.concatenate([country1.population, war_list1])
|
|
255
|
-
np.concatenate([country2.population, war_list2])
|
|
256
|
-
country1.sort_population()
|
|
257
|
-
country2.sort_population()
|
|
258
|
-
country1.action = None
|
|
259
|
-
country2.action = None
|
|
260
|
-
country1.enemy = None
|
|
261
|
-
country2.enemy = None
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
class CountriesAlgorithm:
|
|
265
|
-
|
|
266
|
-
def __init__(self, f, Xmin, Xmax, genes, M, N, n, m, k, l, ep, max_mutation, tmax, printing=False, memory_list=None):
|
|
267
|
-
self.f = f
|
|
268
|
-
self.Xmin = Xmin
|
|
269
|
-
self.Xmax = Xmax
|
|
270
|
-
self.n = n
|
|
271
|
-
self.genes = genes
|
|
272
|
-
self.m = m
|
|
273
|
-
self.k = k
|
|
274
|
-
self.M = M
|
|
275
|
-
self.N = N
|
|
276
|
-
self.l = l
|
|
277
|
-
self.ep = ep
|
|
278
|
-
self.max_mutation = max_mutation
|
|
279
|
-
self.tmax = tmax
|
|
280
|
-
self.countries = []
|
|
281
|
-
self.printing = printing
|
|
282
|
-
self.memory_list = memory_list
|
|
283
|
-
for i in range(M):
|
|
284
|
-
self.countries.append(Country(N, self.Xmin, self.Xmax, self.genes, self.f))
|
|
285
|
-
|
|
286
|
-
def start(self):
|
|
287
|
-
ti = 0
|
|
288
|
-
motion = 0
|
|
289
|
-
trade = 0
|
|
290
|
-
war = 0
|
|
291
|
-
epedemic = 0
|
|
292
|
-
if self.memory_list is not None:
|
|
293
|
-
self.memory_list[0] = False
|
|
294
|
-
while ti <= self.tmax:
|
|
295
|
-
ti += 1
|
|
296
|
-
for country in self.countries:
|
|
297
|
-
if country.action is None:
|
|
298
|
-
country.select_action(self.countries)
|
|
299
|
-
for country in self.countries:
|
|
300
|
-
if country.action == 0:
|
|
301
|
-
motion += 1
|
|
302
|
-
country.motion( )
|
|
303
|
-
elif country.action == 1:
|
|
304
|
-
trade += 1
|
|
305
|
-
Country.trade(
|
|
306
|
-
country1=country,
|
|
307
|
-
country2=country.ally,
|
|
308
|
-
k=self.k
|
|
309
|
-
)
|
|
310
|
-
elif country.action == 2:
|
|
311
|
-
war += 1
|
|
312
|
-
Country.war(
|
|
313
|
-
country1=country,
|
|
314
|
-
country2=country.enemy,
|
|
315
|
-
l=self.l
|
|
316
|
-
)
|
|
317
|
-
elif country.action == 3:
|
|
318
|
-
epedemic += 1
|
|
319
|
-
country.epedemic(
|
|
320
|
-
elite=self.ep[0],
|
|
321
|
-
dead=self.ep[1],
|
|
322
|
-
max_mutation=int((1 - ti / self.tmax) * self.max_mutation),
|
|
323
|
-
)
|
|
324
|
-
indexes = np.where(vector_check_population(self.countries) == True)
|
|
325
|
-
self.countries = [self.countries[i] for i in indexes[0]]
|
|
326
|
-
|
|
327
|
-
self.countries = sorted(self.countries, key=attrgetter('avg_function'))
|
|
328
|
-
if not self.countries:
|
|
329
|
-
break
|
|
330
|
-
f_min = self.countries[0].avg_function
|
|
331
|
-
f_max = self.countries[-1].avg_function
|
|
332
|
-
if f_min == f_max:
|
|
333
|
-
self.countries = sorted(self.countries, key=attrgetter('best_function'))
|
|
334
|
-
result = self.countries[0].population[0]
|
|
335
|
-
break
|
|
336
|
-
e_individuals = []
|
|
337
|
-
for country in self.countries:
|
|
338
|
-
if len(country.population) == 1:
|
|
339
|
-
e_individuals.append(country.population[0])
|
|
340
|
-
continue
|
|
341
|
-
if country.population.size:
|
|
342
|
-
country.reproduction(
|
|
343
|
-
n_min=self.n[0],
|
|
344
|
-
n_max=self.n[1],
|
|
345
|
-
f_min=f_min,
|
|
346
|
-
f_max=f_max
|
|
347
|
-
)
|
|
348
|
-
country.extinction(
|
|
349
|
-
m_min=self.m[0],
|
|
350
|
-
m_max=self.m[1],
|
|
351
|
-
f_min=f_min,
|
|
352
|
-
f_max=f_max
|
|
353
|
-
)
|
|
354
|
-
self.countries = [country for country in self.countries if len(country.population)]
|
|
355
|
-
# self.countries = sorted(self.countries, key=attrgetter('best_function'))
|
|
356
|
-
# f_min = self.countries[0].best_function
|
|
357
|
-
# f_max = self.countries[-1].best_function
|
|
358
|
-
# s = sum(country.roulette_function(f_min, f_max) for country in self.countries if len(country.population) > 1)
|
|
359
|
-
# self.countries.reverse()
|
|
360
|
-
# for country in self.countries:
|
|
361
|
-
# plus = 0
|
|
362
|
-
# if len(country.population) >= 1:
|
|
363
|
-
# res = country.extinction1(
|
|
364
|
-
# max(self.N // 2, ceil(country.roulette_function(f_min, f_max) / s * self.N * self.M)) + plus
|
|
365
|
-
# )
|
|
366
|
-
# if res:
|
|
367
|
-
# plus += res
|
|
368
|
-
# else:
|
|
369
|
-
# plus = 0
|
|
370
|
-
#
|
|
371
|
-
# indexes = np.where(vector_check_population(self.countries) == True)
|
|
372
|
-
# self.countries = [self.countries[i] for i in indexes[0]]
|
|
373
|
-
|
|
374
|
-
for individual in e_individuals:
|
|
375
|
-
random_country = self.countries[random.randint(0, len(self.countries) - 1)]
|
|
376
|
-
np.append(random_country.population, np.array([individual]))
|
|
377
|
-
random_country.sort_population()
|
|
378
|
-
self.countries = sorted(self.countries, key=attrgetter('best_function'))
|
|
379
|
-
if not self.countries:
|
|
380
|
-
break
|
|
381
|
-
result = self.countries[0].population[0]
|
|
382
|
-
|
|
383
|
-
if self.printing:
|
|
384
|
-
print(f"{ti}) Лучшее решение: {result.real_x} - {result.f}, Стран осталось: {len(self.countries)}, Движение/Обмен/Войны/Эпидемии: {motion}/{trade}/{war}/{epedemic}")
|
|
385
|
-
print(f"Общее количество особей: {sum([len(country.population) for country in self.countries])}")
|
|
386
|
-
print("++++++++++++++++++++++++++++++++++++++++++++++++++")
|
|
387
|
-
for i, country in enumerate(self.countries):
|
|
388
|
-
print(f'{i + 1})', country.name, len(country.population), country.best_function, country.avg_function)
|
|
389
|
-
print("++++++++++++++++++++++++++++++++++++++++++++++++++")
|
|
390
|
-
|
|
391
|
-
if self.memory_list is not None:
|
|
392
|
-
self.memory_list[0] = ti
|
|
393
|
-
for i in range(len(result.real_x)):
|
|
394
|
-
self.memory_list[i + 1] = float(result.real_x[i])
|
|
395
|
-
self.memory_list[-1] = float(result.f)
|
|
396
|
-
|
|
397
|
-
return (result.real_x, result.f, False, ti)
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
def f(x):
|
|
402
|
-
return sum([(xi ** 4 - 16 * xi ** 2 + 5 *xi) / 2 for xi in x])
|
|
403
|
-
#
|
|
404
|
-
# k = 0
|
|
405
|
-
# for i in range(100):
|
|
406
|
-
CA = CountriesAlgorithm(
|
|
407
|
-
f=f,
|
|
408
|
-
Xmin=[-5.12 for i in range(20)],
|
|
409
|
-
Xmax=[5.12 for i in range(20)],
|
|
410
|
-
genes=[16 for i in range(20)],
|
|
411
|
-
M=20,
|
|
412
|
-
N=15,
|
|
413
|
-
n=[1, 10],
|
|
414
|
-
m=[3, 8],
|
|
415
|
-
k=8,
|
|
416
|
-
l=3,
|
|
417
|
-
ep=[0.2, 0.4],
|
|
418
|
-
max_mutation=16,
|
|
419
|
-
tmax=300,
|
|
420
|
-
printing=True,
|
|
421
|
-
)
|
|
422
|
-
r = CA.start()
|
|
423
|
-
|
|
424
|
-
# print(i, r[2], r[0], r[1])
|
|
425
|
-
# if r[2]:
|
|
426
|
-
# k += 1
|
|
427
|
-
#
|
|
428
|
-
# print(k/100)
|
|
1
|
+
import random
|
|
2
|
+
import numpy as np
|
|
3
|
+
import copy
|
|
4
|
+
from operator import attrgetter
|
|
5
|
+
from math import ceil, cos, sin
|
|
6
|
+
import graycode
|
|
7
|
+
|
|
8
|
+
def rand_str():
|
|
9
|
+
s = 'qwertyuiopasdfghjklzxcvbnm'
|
|
10
|
+
k = np.random.choice(len(s), 8, replace=False)
|
|
11
|
+
res = ''
|
|
12
|
+
for ki in k:
|
|
13
|
+
res += s[ki]
|
|
14
|
+
return res
|
|
15
|
+
|
|
16
|
+
def check_population(country):
|
|
17
|
+
return bool(country.population.size)
|
|
18
|
+
|
|
19
|
+
vector_check_population = np.vectorize(check_population, signature='()->()')
|
|
20
|
+
|
|
21
|
+
class Individual:
|
|
22
|
+
|
|
23
|
+
def __init__(self, gray_code, x_min, x_max, genes, function):
|
|
24
|
+
|
|
25
|
+
self.x_min = x_min
|
|
26
|
+
self.x_max = x_max
|
|
27
|
+
self.genes = genes
|
|
28
|
+
self.function = function
|
|
29
|
+
self.steps = (self.x_max - self.x_min) / (2 ** (self.genes) - 1)
|
|
30
|
+
self.gray_code = gray_code
|
|
31
|
+
self.f = self.function(self.real_x)
|
|
32
|
+
self.ep_n = 0
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def real_x(self):
|
|
36
|
+
decimal_x = []
|
|
37
|
+
gray_code = copy.deepcopy(self.gray_code)
|
|
38
|
+
for g in self.genes:
|
|
39
|
+
decimal_x.append(graycode.gray_code_to_tc(int(gray_code[:g], base=2)))
|
|
40
|
+
gray_code = gray_code[g:]
|
|
41
|
+
return self.x_min + self.steps * np.array(decimal_x)
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def decimal_x(self):
|
|
45
|
+
return (self.real_x - self.x_min) / self.steps
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def generate_from_decimal(cls, decimal, x_min, x_max, genes, function):
|
|
49
|
+
gray_code = ''
|
|
50
|
+
decimal = np.clip(decimal, np.zeros(decimal.size), 2 ** (genes) - 1)
|
|
51
|
+
for i in range(len(decimal)):
|
|
52
|
+
s = '{:0' + str(genes[i]) + 'b}'
|
|
53
|
+
gray_code += s.format(graycode.tc_to_gray_code(int(decimal[i])))
|
|
54
|
+
|
|
55
|
+
return cls(gray_code, x_min, x_max, genes, function)
|
|
56
|
+
|
|
57
|
+
def mutation(self, max_mutation=1):
|
|
58
|
+
n = max(0, max_mutation - self.ep_n)
|
|
59
|
+
if n:
|
|
60
|
+
gray_code = copy.deepcopy(self.gray_code)
|
|
61
|
+
k = np.random.choice(len(gray_code), n, replace=False)
|
|
62
|
+
for ki in k:
|
|
63
|
+
b = bool(int(gray_code[ki]))
|
|
64
|
+
b = not b
|
|
65
|
+
b = str(int(b))
|
|
66
|
+
gray_code = gray_code[:ki] + b + gray_code[ki+1:]
|
|
67
|
+
return Individual(gray_code, self.x_min, self.x_max, self.genes, self.function)
|
|
68
|
+
else:
|
|
69
|
+
return self
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def crossover(cls, individual1, individual2):
|
|
73
|
+
k = np.random.randint(1, len(individual1.gray_code) - 1, 2)
|
|
74
|
+
while k[0] == k[1]:
|
|
75
|
+
k = np.random.randint(1, len(individual1.gray_code) - 1, 2)
|
|
76
|
+
k = np.sort(k)
|
|
77
|
+
new_gray1 = individual1.gray_code[:k[0]] + individual2.gray_code[k[0]:k[1]] + individual1.gray_code[k[1]:]
|
|
78
|
+
new_gray2 = individual2.gray_code[:k[0]] + individual1.gray_code[k[0]:k[1]] + individual2.gray_code[k[1]:]
|
|
79
|
+
return [
|
|
80
|
+
cls(new_gray1, individual1.x_min, individual1.x_max, individual1.genes, individual1.function),
|
|
81
|
+
cls(new_gray2, individual1.x_min, individual1.x_max, individual1.genes, individual1.function),
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
def __lt__(self, other):
|
|
85
|
+
return self.f < other.f
|
|
86
|
+
|
|
87
|
+
def __le__(self, other):
|
|
88
|
+
return self.f <= other.f
|
|
89
|
+
|
|
90
|
+
def __gt__(self, other):
|
|
91
|
+
return self.f > other.f
|
|
92
|
+
|
|
93
|
+
def __ge__(self, other):
|
|
94
|
+
return self.f >= other.f
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class Country:
|
|
98
|
+
|
|
99
|
+
def __init__(self, N, x_min, x_max, genes, function):
|
|
100
|
+
self.f = function
|
|
101
|
+
self.N = N
|
|
102
|
+
self.x_min = np.array(x_min)
|
|
103
|
+
self.x_max = np.array(x_max)
|
|
104
|
+
self.genes = np.array(genes)
|
|
105
|
+
self.name = rand_str()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
local_xmin = np.random.randint(np.zeros(self.genes.size), 2 ** self.genes - 1)
|
|
109
|
+
local_xmax = np.random.randint(local_xmin, 2 ** self.genes)
|
|
110
|
+
|
|
111
|
+
self.rand_n_individual = np.vectorize(lambda x: x * self.random_individual(local_xmin, local_xmax), signature='()->(n)')
|
|
112
|
+
self.generate_population = np.vectorize(lambda decimal: Individual.generate_from_decimal(
|
|
113
|
+
decimal, self.x_min, self.x_max, self.genes, self.f), signature='(n)->()')
|
|
114
|
+
|
|
115
|
+
x = self.rand_n_individual(np.ones(self.N))
|
|
116
|
+
self.population = self.generate_population(x)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
self.sort_population()
|
|
120
|
+
self.action = None
|
|
121
|
+
self.enemy = None
|
|
122
|
+
self.ally = None
|
|
123
|
+
|
|
124
|
+
def random_individual(self, x_min, x_max):
|
|
125
|
+
return np.random.randint(x_min, x_max)
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def best_function(self):
|
|
129
|
+
return self.population[0].f
|
|
130
|
+
|
|
131
|
+
def roulette_function(self, f_min, f_max):
|
|
132
|
+
return (f_max - self.population[0].f) / (f_max - f_min)
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def avg_function(self):
|
|
136
|
+
return sum([individual.f for individual in self.population]) / self.population.size
|
|
137
|
+
|
|
138
|
+
def sort_population(self):
|
|
139
|
+
self.population.sort()
|
|
140
|
+
|
|
141
|
+
def reproduction(self, n_min, n_max, f_min, f_max):
|
|
142
|
+
n = ceil((n_max - n_min) * (f_max - self.avg_function) / (f_max - f_min) + n_min)
|
|
143
|
+
n = np.clip(n, n_min, n_max)
|
|
144
|
+
# p2 = (1 - ti / t_max) * (self.avg_function - f_min) / (f_max - f_min)
|
|
145
|
+
new_individuals = []
|
|
146
|
+
|
|
147
|
+
for i in range(n):
|
|
148
|
+
if len(self.population) == 2 and self.population[0] == self.population[1]:
|
|
149
|
+
new_individuals.extend(Individual.crossover(self.population[0], self.population[1],
|
|
150
|
+
self.x_min, self.x_max, self.genes, self.f))
|
|
151
|
+
continue
|
|
152
|
+
k1 = random.randint(0, len(self.population) - 1)
|
|
153
|
+
individual1 = self.population[k1]
|
|
154
|
+
k2 = k1
|
|
155
|
+
while k2 == k1:
|
|
156
|
+
k2 = random.randint(0, len(self.population) - 1)
|
|
157
|
+
individual2 = self.population[k2]
|
|
158
|
+
new_individuals += Individual.crossover(individual1, individual2)
|
|
159
|
+
self.population = np.append(self.population, np.array(new_individuals))
|
|
160
|
+
self.sort_population()
|
|
161
|
+
|
|
162
|
+
def extinction(self, m_min, m_max, f_min, f_max):
|
|
163
|
+
m = int((m_max - m_min) * (self.avg_function - f_min) / (f_max - f_min) + m_min)
|
|
164
|
+
m = np.clip(m, m_min, m_max)
|
|
165
|
+
self.population = self.population[:-m]
|
|
166
|
+
|
|
167
|
+
def extinction1(self, n):
|
|
168
|
+
if self.population.size < n:
|
|
169
|
+
return n - self.population.size
|
|
170
|
+
self.population = self.population[:n]
|
|
171
|
+
return 0
|
|
172
|
+
|
|
173
|
+
def select_action(self, countries):
|
|
174
|
+
self.action = random.randint(0, 3)
|
|
175
|
+
if self.action == 1:
|
|
176
|
+
ally_list = [country for country in countries if country.action is None and country != self]
|
|
177
|
+
if ally_list:
|
|
178
|
+
self.ally = ally_list.pop(random.randint(0, len(ally_list) - 1))
|
|
179
|
+
self.ally.action = 1
|
|
180
|
+
self.ally.ally = self
|
|
181
|
+
else:
|
|
182
|
+
self.action = random.choice([0, 3])
|
|
183
|
+
if self.action == 2:
|
|
184
|
+
enemy_list = [country for country in countries if country.action is None and country != self]
|
|
185
|
+
if enemy_list:
|
|
186
|
+
self.enemy = enemy_list.pop(random.randint(0, len(enemy_list) - 1))
|
|
187
|
+
self.enemy.action = 2
|
|
188
|
+
self.enemy.enemy = self
|
|
189
|
+
else:
|
|
190
|
+
self.action = random.choice([0, 3])
|
|
191
|
+
|
|
192
|
+
def epedemic(self, elite, dead, max_mutation):
|
|
193
|
+
if max_mutation < 1:
|
|
194
|
+
max_mutation = 1
|
|
195
|
+
n_elite = ceil(elite * len(self.population))
|
|
196
|
+
n_dead = ceil(dead * len(self.population))
|
|
197
|
+
self.population = self.population[:-n_dead]
|
|
198
|
+
for i in range(n_elite, self.population.size):
|
|
199
|
+
self.population[i] = self.population[i].mutation(max_mutation)
|
|
200
|
+
self.sort_population()
|
|
201
|
+
self.action = None
|
|
202
|
+
|
|
203
|
+
# def sabotage(self, n_copy):
|
|
204
|
+
# for i in range(n_copy):
|
|
205
|
+
# self.enemy.population.append(copy.copy(self.population[0]))
|
|
206
|
+
# self.action = None
|
|
207
|
+
# self.enemy = None
|
|
208
|
+
|
|
209
|
+
def motion(self):
|
|
210
|
+
x_best = self.population[0].decimal_x
|
|
211
|
+
for i in range(1, len(self.population)):
|
|
212
|
+
self.population[i] = Individual.generate_from_decimal(
|
|
213
|
+
self.population[i].decimal_x + np.int64(random.uniform(0, 2) * (x_best - self.population[i].decimal_x)), self.x_min, self.x_max, self.genes, self.f
|
|
214
|
+
)
|
|
215
|
+
self.sort_population()
|
|
216
|
+
self.action = None
|
|
217
|
+
|
|
218
|
+
@staticmethod
|
|
219
|
+
def trade(country1, country2, k):
|
|
220
|
+
if country1.population.size <= k or country2.population.size <= k:
|
|
221
|
+
k = min(country1.population.size, country2.population.size) // 2
|
|
222
|
+
indexes1 = np.random.choice(country1.population.size, k, replace=False)
|
|
223
|
+
indexes2 = np.random.choice(country2.population.size, k, replace=False)
|
|
224
|
+
country2.population = np.concatenate([country2.population, country1.population[indexes1]])
|
|
225
|
+
country1.population = np.concatenate([country1.population, country2.population[indexes2]])
|
|
226
|
+
country1.population = np.delete(country1.population, indexes1)
|
|
227
|
+
country2.population = np.delete(country2.population, indexes2)
|
|
228
|
+
country1.sort_population()
|
|
229
|
+
country2.sort_population()
|
|
230
|
+
country1.action = None
|
|
231
|
+
country2.action = None
|
|
232
|
+
country1.ally = None
|
|
233
|
+
country2.ally = None
|
|
234
|
+
|
|
235
|
+
@staticmethod
|
|
236
|
+
def war(country1, country2, l):
|
|
237
|
+
if country1.population.size <= l or country2.population.size <= l:
|
|
238
|
+
l = min(country1.population.size, country2.population.size)
|
|
239
|
+
indexes1 = np.random.choice(country1.population.size, l, replace=False)
|
|
240
|
+
indexes2 = np.random.choice(country2.population.size, l, replace=False)
|
|
241
|
+
war_list1 = country1.population[indexes1]
|
|
242
|
+
war_list2 = country2.population[indexes2]
|
|
243
|
+
country1.population = np.delete(country1.population, indexes1)
|
|
244
|
+
country2.population = np.delete(country2.population, indexes2)
|
|
245
|
+
wins1 = np.where(war_list1 > war_list2)
|
|
246
|
+
wins2 = np.where(war_list2 > war_list2)
|
|
247
|
+
if wins1[0].size > wins2[0].size:
|
|
248
|
+
np.concatenate([country1.population, war_list1])
|
|
249
|
+
np.concatenate([country1.population, war_list2])
|
|
250
|
+
elif wins2[0].size > wins1[0].size:
|
|
251
|
+
np.concatenate([country2.population, war_list1])
|
|
252
|
+
np.concatenate([country2.population, war_list2])
|
|
253
|
+
else:
|
|
254
|
+
np.concatenate([country1.population, war_list1])
|
|
255
|
+
np.concatenate([country2.population, war_list2])
|
|
256
|
+
country1.sort_population()
|
|
257
|
+
country2.sort_population()
|
|
258
|
+
country1.action = None
|
|
259
|
+
country2.action = None
|
|
260
|
+
country1.enemy = None
|
|
261
|
+
country2.enemy = None
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
class CountriesAlgorithm:
|
|
265
|
+
|
|
266
|
+
def __init__(self, f, Xmin, Xmax, genes, M, N, n, m, k, l, ep, max_mutation, tmax, printing=False, memory_list=None):
|
|
267
|
+
self.f = f
|
|
268
|
+
self.Xmin = Xmin
|
|
269
|
+
self.Xmax = Xmax
|
|
270
|
+
self.n = n
|
|
271
|
+
self.genes = genes
|
|
272
|
+
self.m = m
|
|
273
|
+
self.k = k
|
|
274
|
+
self.M = M
|
|
275
|
+
self.N = N
|
|
276
|
+
self.l = l
|
|
277
|
+
self.ep = ep
|
|
278
|
+
self.max_mutation = max_mutation
|
|
279
|
+
self.tmax = tmax
|
|
280
|
+
self.countries = []
|
|
281
|
+
self.printing = printing
|
|
282
|
+
self.memory_list = memory_list
|
|
283
|
+
for i in range(M):
|
|
284
|
+
self.countries.append(Country(N, self.Xmin, self.Xmax, self.genes, self.f))
|
|
285
|
+
|
|
286
|
+
def start(self):
|
|
287
|
+
ti = 0
|
|
288
|
+
motion = 0
|
|
289
|
+
trade = 0
|
|
290
|
+
war = 0
|
|
291
|
+
epedemic = 0
|
|
292
|
+
if self.memory_list is not None:
|
|
293
|
+
self.memory_list[0] = False
|
|
294
|
+
while ti <= self.tmax:
|
|
295
|
+
ti += 1
|
|
296
|
+
for country in self.countries:
|
|
297
|
+
if country.action is None:
|
|
298
|
+
country.select_action(self.countries)
|
|
299
|
+
for country in self.countries:
|
|
300
|
+
if country.action == 0:
|
|
301
|
+
motion += 1
|
|
302
|
+
country.motion( )
|
|
303
|
+
elif country.action == 1:
|
|
304
|
+
trade += 1
|
|
305
|
+
Country.trade(
|
|
306
|
+
country1=country,
|
|
307
|
+
country2=country.ally,
|
|
308
|
+
k=self.k
|
|
309
|
+
)
|
|
310
|
+
elif country.action == 2:
|
|
311
|
+
war += 1
|
|
312
|
+
Country.war(
|
|
313
|
+
country1=country,
|
|
314
|
+
country2=country.enemy,
|
|
315
|
+
l=self.l
|
|
316
|
+
)
|
|
317
|
+
elif country.action == 3:
|
|
318
|
+
epedemic += 1
|
|
319
|
+
country.epedemic(
|
|
320
|
+
elite=self.ep[0],
|
|
321
|
+
dead=self.ep[1],
|
|
322
|
+
max_mutation=int((1 - ti / self.tmax) * self.max_mutation),
|
|
323
|
+
)
|
|
324
|
+
indexes = np.where(vector_check_population(self.countries) == True)
|
|
325
|
+
self.countries = [self.countries[i] for i in indexes[0]]
|
|
326
|
+
|
|
327
|
+
self.countries = sorted(self.countries, key=attrgetter('avg_function'))
|
|
328
|
+
if not self.countries:
|
|
329
|
+
break
|
|
330
|
+
f_min = self.countries[0].avg_function
|
|
331
|
+
f_max = self.countries[-1].avg_function
|
|
332
|
+
if f_min == f_max:
|
|
333
|
+
self.countries = sorted(self.countries, key=attrgetter('best_function'))
|
|
334
|
+
result = self.countries[0].population[0]
|
|
335
|
+
break
|
|
336
|
+
e_individuals = []
|
|
337
|
+
for country in self.countries:
|
|
338
|
+
if len(country.population) == 1:
|
|
339
|
+
e_individuals.append(country.population[0])
|
|
340
|
+
continue
|
|
341
|
+
if country.population.size:
|
|
342
|
+
country.reproduction(
|
|
343
|
+
n_min=self.n[0],
|
|
344
|
+
n_max=self.n[1],
|
|
345
|
+
f_min=f_min,
|
|
346
|
+
f_max=f_max
|
|
347
|
+
)
|
|
348
|
+
country.extinction(
|
|
349
|
+
m_min=self.m[0],
|
|
350
|
+
m_max=self.m[1],
|
|
351
|
+
f_min=f_min,
|
|
352
|
+
f_max=f_max
|
|
353
|
+
)
|
|
354
|
+
self.countries = [country for country in self.countries if len(country.population)]
|
|
355
|
+
# self.countries = sorted(self.countries, key=attrgetter('best_function'))
|
|
356
|
+
# f_min = self.countries[0].best_function
|
|
357
|
+
# f_max = self.countries[-1].best_function
|
|
358
|
+
# s = sum(country.roulette_function(f_min, f_max) for country in self.countries if len(country.population) > 1)
|
|
359
|
+
# self.countries.reverse()
|
|
360
|
+
# for country in self.countries:
|
|
361
|
+
# plus = 0
|
|
362
|
+
# if len(country.population) >= 1:
|
|
363
|
+
# res = country.extinction1(
|
|
364
|
+
# max(self.N // 2, ceil(country.roulette_function(f_min, f_max) / s * self.N * self.M)) + plus
|
|
365
|
+
# )
|
|
366
|
+
# if res:
|
|
367
|
+
# plus += res
|
|
368
|
+
# else:
|
|
369
|
+
# plus = 0
|
|
370
|
+
#
|
|
371
|
+
# indexes = np.where(vector_check_population(self.countries) == True)
|
|
372
|
+
# self.countries = [self.countries[i] for i in indexes[0]]
|
|
373
|
+
|
|
374
|
+
for individual in e_individuals:
|
|
375
|
+
random_country = self.countries[random.randint(0, len(self.countries) - 1)]
|
|
376
|
+
np.append(random_country.population, np.array([individual]))
|
|
377
|
+
random_country.sort_population()
|
|
378
|
+
self.countries = sorted(self.countries, key=attrgetter('best_function'))
|
|
379
|
+
if not self.countries:
|
|
380
|
+
break
|
|
381
|
+
result = self.countries[0].population[0]
|
|
382
|
+
|
|
383
|
+
if self.printing:
|
|
384
|
+
print(f"{ti}) Лучшее решение: {result.real_x} - {result.f}, Стран осталось: {len(self.countries)}, Движение/Обмен/Войны/Эпидемии: {motion}/{trade}/{war}/{epedemic}")
|
|
385
|
+
print(f"Общее количество особей: {sum([len(country.population) for country in self.countries])}")
|
|
386
|
+
print("++++++++++++++++++++++++++++++++++++++++++++++++++")
|
|
387
|
+
for i, country in enumerate(self.countries):
|
|
388
|
+
print(f'{i + 1})', country.name, len(country.population), country.best_function, country.avg_function)
|
|
389
|
+
print("++++++++++++++++++++++++++++++++++++++++++++++++++")
|
|
390
|
+
|
|
391
|
+
if self.memory_list is not None:
|
|
392
|
+
self.memory_list[0] = ti
|
|
393
|
+
for i in range(len(result.real_x)):
|
|
394
|
+
self.memory_list[i + 1] = float(result.real_x[i])
|
|
395
|
+
self.memory_list[-1] = float(result.f)
|
|
396
|
+
|
|
397
|
+
return (result.real_x, result.f, False, ti)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def f(x):
|
|
402
|
+
return sum([(xi ** 4 - 16 * xi ** 2 + 5 *xi) / 2 for xi in x])
|
|
403
|
+
#
|
|
404
|
+
# k = 0
|
|
405
|
+
# for i in range(100):
|
|
406
|
+
CA = CountriesAlgorithm(
|
|
407
|
+
f=f,
|
|
408
|
+
Xmin=[-5.12 for i in range(20)],
|
|
409
|
+
Xmax=[5.12 for i in range(20)],
|
|
410
|
+
genes=[16 for i in range(20)],
|
|
411
|
+
M=20,
|
|
412
|
+
N=15,
|
|
413
|
+
n=[1, 10],
|
|
414
|
+
m=[3, 8],
|
|
415
|
+
k=8,
|
|
416
|
+
l=3,
|
|
417
|
+
ep=[0.2, 0.4],
|
|
418
|
+
max_mutation=16,
|
|
419
|
+
tmax=300,
|
|
420
|
+
printing=True,
|
|
421
|
+
)
|
|
422
|
+
r = CA.start()
|
|
423
|
+
|
|
424
|
+
# print(i, r[2], r[0], r[1])
|
|
425
|
+
# if r[2]:
|
|
426
|
+
# k += 1
|
|
427
|
+
#
|
|
428
|
+
# print(k/100)
|