beecolpy 2.3.3__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.
- beecolpy/__init__.py +2 -0
- beecolpy/beecolpy.py +1078 -0
- beecolpy/tests/__init__.py +0 -0
- beecolpy/tests/test_beecolpy.py +423 -0
- beecolpy-2.3.3.dist-info/METADATA +548 -0
- beecolpy-2.3.3.dist-info/RECORD +9 -0
- beecolpy-2.3.3.dist-info/WHEEL +5 -0
- beecolpy-2.3.3.dist-info/licenses/LICENSE.md +21 -0
- beecolpy-2.3.3.dist-info/top_level.txt +1 -0
beecolpy/beecolpy.py
ADDED
|
@@ -0,0 +1,1078 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
'''
|
|
3
|
+
+----------------------------------------------------------------------+
|
|
4
|
+
|
|
5
|
+
Samuel C P Oliveira
|
|
6
|
+
samuelcpoliveira@gmail.com
|
|
7
|
+
Artificial Bee Colony Optimization
|
|
8
|
+
This project is licensed under the MIT License.
|
|
9
|
+
|
|
10
|
+
+----------------------------------------------------------------------+
|
|
11
|
+
|
|
12
|
+
Bibliography
|
|
13
|
+
------------
|
|
14
|
+
|
|
15
|
+
[1] Karaboga, D. and Basturk, B., 2007
|
|
16
|
+
A powerful and efficient algorithm for numerical function
|
|
17
|
+
optimization: artificial bee colony (ABC) algorithm. Journal
|
|
18
|
+
of global optimization, 39(3), pp.459-471.
|
|
19
|
+
DOI: https://doi.org/10.1007/s10898-007-9149-x
|
|
20
|
+
|
|
21
|
+
[2] Liu, T., Zhang, L. and Zhang, J., 2013
|
|
22
|
+
Study of binary artificial bee colony algorithm based on
|
|
23
|
+
particle swarm optimization. Journal of Computational
|
|
24
|
+
Information Systems, 9(16), pp.6459-6466.
|
|
25
|
+
Link: https://api.semanticscholar.org/CorpusID:8789571
|
|
26
|
+
|
|
27
|
+
[3] Anuar, S., Selamat, A. and Sallehuddin, R., 2016
|
|
28
|
+
A modified scout bee for artificial bee colony algorithm and
|
|
29
|
+
its performance on optimization problems. Journal of King Saud
|
|
30
|
+
University-Computer and Information Sciences, 28(4),
|
|
31
|
+
pp.395-406.
|
|
32
|
+
DOI: https://doi.org/10.1016/j.jksuci.2016.03.001
|
|
33
|
+
|
|
34
|
+
[4] Kennedy, J. and Eberhart, R.C., 1997
|
|
35
|
+
A discrete binary version of the particle swarm algorithm.
|
|
36
|
+
In 1997 IEEE International conference on systems, man, and
|
|
37
|
+
cybernetics. Computational cybernetics and simulation
|
|
38
|
+
(Vol. 5, pp. 4104-4108). IEEE.
|
|
39
|
+
DOI: https://doi.org/10.1109/ICSMC.1997.637339
|
|
40
|
+
|
|
41
|
+
[5] Pampará, G. and Engelbrecht, A.P., 2011
|
|
42
|
+
Binary artificial bee colony optimization. In 2011 IEEE
|
|
43
|
+
Symposium on Swarm Intelligence (pp. 1-8). IEEE.
|
|
44
|
+
DOI: https://doi.org/10.1109/SIS.2011.5952562
|
|
45
|
+
|
|
46
|
+
[6] Mirjalili, S., Hashim, S., Taherzadeh, G., Mirjalili, S.Z.
|
|
47
|
+
and Salehi, S., 2011
|
|
48
|
+
A study of different transfer functions for binary version
|
|
49
|
+
of particle swarm optimization. In International Conference
|
|
50
|
+
on Genetic and Evolutionary Methods (Vol. 1, No. 1, pp. 2-7).
|
|
51
|
+
Link: http://hdl.handle.net/10072/48831
|
|
52
|
+
|
|
53
|
+
[7] Huang, S.C., 2015
|
|
54
|
+
Polygonal approximation using an artificial bee colony
|
|
55
|
+
algorithm. Mathematical Problems in Engineering, 2015.
|
|
56
|
+
DOI: https://doi.org/10.1155/2015/375926
|
|
57
|
+
|
|
58
|
+
+----------------------------------------------------------------------+
|
|
59
|
+
'''
|
|
60
|
+
import numpy as np
|
|
61
|
+
import random as rng
|
|
62
|
+
import warnings as wrn
|
|
63
|
+
from collections import Counter
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class abc:
|
|
67
|
+
'''
|
|
68
|
+
Class that applies Artificial Bee Colony (ABC) algorithm to find
|
|
69
|
+
minimum or maximum of a function that's receive a vector of floats
|
|
70
|
+
as input and returns a float as output.
|
|
71
|
+
|
|
72
|
+
https://en.wikipedia.org/wiki/Artificial_bee_colony_algorithm
|
|
73
|
+
|
|
74
|
+
Parameters
|
|
75
|
+
----------
|
|
76
|
+
function : Name
|
|
77
|
+
A name of a function to minimize/maximize.
|
|
78
|
+
Example: if the function is:
|
|
79
|
+
def my_func(x): return x[0]**2 + x[1]**2 + 5*x[1]
|
|
80
|
+
|
|
81
|
+
Use "my_func" as parameter.
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
boundaries : List of Tuples
|
|
85
|
+
A list of tuples containing the lower and upper boundaries of
|
|
86
|
+
each dimension of function domain.
|
|
87
|
+
|
|
88
|
+
Obs.: The number of boundaries determines the dimension of
|
|
89
|
+
function.
|
|
90
|
+
|
|
91
|
+
Example: A function F(x1, x2) = y with:
|
|
92
|
+
(-5 <= x1 <= 5) and (-20 <= x2 <= 20) have the boundaries:
|
|
93
|
+
[(-5,5), (-20,20)]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
[colony_size] : Int --optional-- (default: 40)
|
|
97
|
+
A value that determines the number of bees in algorithm. Half
|
|
98
|
+
of this amount determines the number of points analyzed (food
|
|
99
|
+
sources).
|
|
100
|
+
|
|
101
|
+
According articles, half of this number determines the amount
|
|
102
|
+
of Employed bees and other half is Onlooker bees.
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
[scouts] : Float --optional-- (default: 0.5)
|
|
106
|
+
Determines the limit of tries for scout bee discard a food
|
|
107
|
+
source and replace for a new one.
|
|
108
|
+
- If scouts = 0 :
|
|
109
|
+
Scout_limit = colony_size * dimension
|
|
110
|
+
|
|
111
|
+
- If scouts = (0 to 1) :
|
|
112
|
+
Scout_limit = colony_size * dimension * scouts
|
|
113
|
+
Obs.: scouts = 0.5 is used in [3] as benchmark.
|
|
114
|
+
|
|
115
|
+
- If scouts >= 1 :
|
|
116
|
+
Scout_limit = scouts
|
|
117
|
+
|
|
118
|
+
Obs.: Scout_limit is rounded down in all cases.
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
[iterations] : Int --optional-- (default: 50)
|
|
122
|
+
The number of iterations executed by algorithm.
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
[min_max] : String --optional-- (default: 'min')
|
|
126
|
+
Determines if algorithm will minimize or maximize the function.
|
|
127
|
+
- If min_max = 'min' : (default)
|
|
128
|
+
Locate the minimum of function.
|
|
129
|
+
|
|
130
|
+
- If min_max = 'max' :
|
|
131
|
+
Locate the maximum of function.
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
[nan_protection] : Boolean --optional-- (default: True)
|
|
135
|
+
If true, re-generate food sources that get NaN value as cost
|
|
136
|
+
during initialization or during scout events. This option
|
|
137
|
+
usually helps the algorithm stability because, in rare cases,
|
|
138
|
+
NaN values can lock the algorithm in a infinite loop.
|
|
139
|
+
|
|
140
|
+
Obs.: NaN protection can drastically increases calculation
|
|
141
|
+
time if analysed function has too many values of domain
|
|
142
|
+
returning NaN.
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
[log_agents] : Boolean --optional-- (default: False)
|
|
146
|
+
If true, beecolpy will register, before each iteration, the
|
|
147
|
+
position of each food source. Useful to debug but, if there a
|
|
148
|
+
high amount of food sources and/or iterations, this option
|
|
149
|
+
drastically increases memory usage.
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
[seed] : Int --optional-- (default: None)
|
|
153
|
+
If defined as an int, set the seed used in all random process.
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
Methods
|
|
157
|
+
----------
|
|
158
|
+
fit()
|
|
159
|
+
Execute the algorithm with defined parameters.
|
|
160
|
+
|
|
161
|
+
Obs.: Returns a list with values found as minimum/maximum
|
|
162
|
+
coordinate.
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
get_solution()
|
|
166
|
+
Returns the value obtained after fit() the method.
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
get_status()
|
|
170
|
+
Returns a tuple with:
|
|
171
|
+
- Number of complete iterations executed
|
|
172
|
+
- Number of scout events during iterations
|
|
173
|
+
- Number of times that NaN protection was activated
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
get_agents()
|
|
177
|
+
Returns a list with the position of each food source during
|
|
178
|
+
each iteration if "log_agents = True".
|
|
179
|
+
|
|
180
|
+
Parameters
|
|
181
|
+
----------
|
|
182
|
+
[reset_agents] : bool --optional-- (default: False)
|
|
183
|
+
If true, the food source position log will be cleaned in
|
|
184
|
+
next fit().
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
Bibliography
|
|
188
|
+
----------
|
|
189
|
+
[1] Karaboga, D. and Basturk, B., 2007
|
|
190
|
+
A powerful and efficient algorithm for numerical function
|
|
191
|
+
optimization: artificial bee colony (ABC) algorithm. Journal
|
|
192
|
+
of global optimization, 39(3), pp.459-471.
|
|
193
|
+
DOI: https://doi.org/10.1007/s10898-007-9149-x
|
|
194
|
+
|
|
195
|
+
[2] Liu, T., Zhang, L. and Zhang, J., 2013
|
|
196
|
+
Study of binary artificial bee colony algorithm based on
|
|
197
|
+
particle swarm optimization. Journal of Computational
|
|
198
|
+
Information Systems, 9(16), pp.6459-6466.
|
|
199
|
+
Link: https://api.semanticscholar.org/CorpusID:8789571
|
|
200
|
+
|
|
201
|
+
[3] Anuar, S., Selamat, A. and Sallehuddin, R., 2016
|
|
202
|
+
A modified scout bee for artificial bee colony algorithm and
|
|
203
|
+
its performance on optimization problems. Journal of King Saud
|
|
204
|
+
University-Computer and Information Sciences, 28(4),
|
|
205
|
+
pp.395-406.
|
|
206
|
+
DOI: https://doi.org/10.1016/j.jksuci.2016.03.001
|
|
207
|
+
|
|
208
|
+
'''
|
|
209
|
+
def __init__(self,
|
|
210
|
+
function,
|
|
211
|
+
boundaries,
|
|
212
|
+
colony_size: int=40,
|
|
213
|
+
scouts: float=0.5,
|
|
214
|
+
iterations: int=50,
|
|
215
|
+
min_max: str='min',
|
|
216
|
+
nan_protection: bool=True,
|
|
217
|
+
log_agents: bool=False,
|
|
218
|
+
seed: int=None):
|
|
219
|
+
|
|
220
|
+
self.boundaries = boundaries
|
|
221
|
+
self.min_max_selector = min_max
|
|
222
|
+
self.cost_function = function
|
|
223
|
+
self.nan_protection = nan_protection
|
|
224
|
+
self.log_agents = log_agents
|
|
225
|
+
self.reset_agents = False
|
|
226
|
+
self.seed = seed
|
|
227
|
+
|
|
228
|
+
self.max_iterations = int(max([iterations, 1]))
|
|
229
|
+
if (iterations < 1):
|
|
230
|
+
warn_message = 'Using the minimun value of iterations = 1'
|
|
231
|
+
wrn.warn(warn_message, RuntimeWarning)
|
|
232
|
+
|
|
233
|
+
self.employed_onlookers_count = int(max([(colony_size/2), 2]))
|
|
234
|
+
if (colony_size < 4):
|
|
235
|
+
warn_message = 'Using the minimun value of colony_size = 4'
|
|
236
|
+
wrn.warn(warn_message, RuntimeWarning)
|
|
237
|
+
|
|
238
|
+
if (scouts <= 0):
|
|
239
|
+
self.scout_limit = int(self.employed_onlookers_count * len(self.boundaries))
|
|
240
|
+
if (scouts < 0):
|
|
241
|
+
warn_message = 'Negative scout count given, using default scout ' \
|
|
242
|
+
'count: colony_size * dimension = ' + str(self.scout_limit)
|
|
243
|
+
wrn.warn(warn_message, RuntimeWarning)
|
|
244
|
+
elif (scouts < 1):
|
|
245
|
+
self.scout_limit = int(self.employed_onlookers_count * len(self.boundaries) * scouts)
|
|
246
|
+
else:
|
|
247
|
+
self.scout_limit = int(scouts)
|
|
248
|
+
|
|
249
|
+
self.scout_status = 0
|
|
250
|
+
self.iteration_status = 0
|
|
251
|
+
self.nan_status = 0
|
|
252
|
+
|
|
253
|
+
if (self.seed is not None):
|
|
254
|
+
rng.seed(self.seed)
|
|
255
|
+
|
|
256
|
+
self.foods = [None] * self.employed_onlookers_count
|
|
257
|
+
for i in range(len(self.foods)):
|
|
258
|
+
_ABC_engine(self).generate_food_source(i)
|
|
259
|
+
|
|
260
|
+
try:
|
|
261
|
+
self.best_food_source = self.foods[np.nanargmax([food.fit for food in self.foods])]
|
|
262
|
+
except:
|
|
263
|
+
self.best_food_source = self.foods[0]
|
|
264
|
+
warn_message = 'All food sources\'s fit resulted in NaN and beecolpy can got stuck ' \
|
|
265
|
+
'in an infinite loop during fit(). Enable nan_protection to prevent this.'
|
|
266
|
+
wrn.warn(warn_message, RuntimeWarning)
|
|
267
|
+
|
|
268
|
+
self.agents = []
|
|
269
|
+
if self.log_agents:
|
|
270
|
+
self.agents.append([food.position for food in self.foods])
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def fit(self):
|
|
274
|
+
'''
|
|
275
|
+
Execute the algorithm with defined parameters.
|
|
276
|
+
|
|
277
|
+
Obs.: Returns a list with values found as minimum/maximum
|
|
278
|
+
coordinate.
|
|
279
|
+
'''
|
|
280
|
+
if (self.seed is not None):
|
|
281
|
+
rng.seed(self.seed)
|
|
282
|
+
|
|
283
|
+
if self.reset_agents:
|
|
284
|
+
self.agents = []
|
|
285
|
+
if self.log_agents:
|
|
286
|
+
self.agents.append([food.position for food in self.foods])
|
|
287
|
+
self.reset_agents = False
|
|
288
|
+
|
|
289
|
+
for _ in range(self.max_iterations):
|
|
290
|
+
#--> Employer bee phase <--
|
|
291
|
+
#Generate and evaluate a neighbor point to every food source
|
|
292
|
+
_ABC_engine(self).employer_bee_phase()
|
|
293
|
+
|
|
294
|
+
#--> Onlooker bee phase <--
|
|
295
|
+
#Based in probability, generate a neighbor point and evaluate again some food sources
|
|
296
|
+
#Same food source can be evaluated multiple times
|
|
297
|
+
_ABC_engine(self).onlooker_bee_phase()
|
|
298
|
+
|
|
299
|
+
#--> Memorize best solution <--
|
|
300
|
+
_ABC_engine(self).memorize_best_solution()
|
|
301
|
+
|
|
302
|
+
#--> Scout bee phase <--
|
|
303
|
+
#Generate up to one new food source that does not improve over scout_limit evaluation tries
|
|
304
|
+
_ABC_engine(self).scout_bee_phase()
|
|
305
|
+
|
|
306
|
+
#Update iteration status
|
|
307
|
+
self.iteration_status += 1
|
|
308
|
+
if self.log_agents:
|
|
309
|
+
self.agents.append([food.position for food in self.foods])
|
|
310
|
+
|
|
311
|
+
return self.best_food_source.position
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def get_agents(self, reset_agents: bool=False):
|
|
315
|
+
'''
|
|
316
|
+
Returns a list with the position of each food source during
|
|
317
|
+
each iteration.
|
|
318
|
+
|
|
319
|
+
Parameters
|
|
320
|
+
----------
|
|
321
|
+
[reset_agents] : bool --optional-- (default: False)
|
|
322
|
+
If true, the food source position log will be cleaned in
|
|
323
|
+
next fit().
|
|
324
|
+
'''
|
|
325
|
+
assert self.log_agents, 'Food source logging disabled.'
|
|
326
|
+
self.reset_agents = reset_agents
|
|
327
|
+
return self.agents
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def get_solution(self):
|
|
331
|
+
'''
|
|
332
|
+
Returns the value obtained after fit() the method.
|
|
333
|
+
|
|
334
|
+
'''
|
|
335
|
+
assert (self.iteration_status > 0), 'fit() not executed yet!'
|
|
336
|
+
return self.best_food_source.position
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def get_status(self):
|
|
340
|
+
'''
|
|
341
|
+
Returns a tuple with:
|
|
342
|
+
- Number of complete iterations executed
|
|
343
|
+
- Number of scout events during iterations
|
|
344
|
+
- Number of times that NaN protection was activated
|
|
345
|
+
'''
|
|
346
|
+
return self.iteration_status, \
|
|
347
|
+
self.scout_status, \
|
|
348
|
+
self.nan_status
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
class bin_abc:
|
|
354
|
+
'''
|
|
355
|
+
Class that applies Artificial Bee Colony in a binary domain
|
|
356
|
+
function to find minimum or maximum of a function that's receive
|
|
357
|
+
the number of bits as input and returns a vector of bits as output.
|
|
358
|
+
|
|
359
|
+
There two methods in this solver:
|
|
360
|
+
- Angle Modulated Artificial Bee Colony (AMABC [5]): (default)
|
|
361
|
+
A deterministic based solver. Ideal to solve general
|
|
362
|
+
problems represented by a bit list.
|
|
363
|
+
|
|
364
|
+
- Binary Artificial Bee Colony (BABC [5], based in BPSO [4]):
|
|
365
|
+
A stochastic based solver. Ideal to solve problems
|
|
366
|
+
represented by a bit list that have random elements
|
|
367
|
+
applied to each iteration.
|
|
368
|
+
- To solve very noisy problems, using the default
|
|
369
|
+
result format ("best" result format) usually have
|
|
370
|
+
good results.
|
|
371
|
+
|
|
372
|
+
- To solve problems with great random components
|
|
373
|
+
applied to each iteration, geting the most frequent
|
|
374
|
+
bit ("average" result format) will have good results.
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
Parameters
|
|
378
|
+
----------
|
|
379
|
+
function : Name
|
|
380
|
+
A name of a function to minimize/maximize.
|
|
381
|
+
|
|
382
|
+
Example: if the function is:
|
|
383
|
+
def my_func(x): return x[0] or (x[1] and x[2])
|
|
384
|
+
|
|
385
|
+
Use "my_func" as parameter.
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
-=x=--=x=--=x=--=x=--=x=-
|
|
389
|
+
|
|
390
|
+
Just one of these parameters are mandatory. If you don't know
|
|
391
|
+
exactly how binary solvers work, just inform the number of bits
|
|
392
|
+
(bits_count) and the default boundaries will be used. These
|
|
393
|
+
boundaries usually are enough to solve most problems.
|
|
394
|
+
|
|
395
|
+
bits_count : Int
|
|
396
|
+
The number of bits that compose the output vector.
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
boundaries : List of Tuples
|
|
400
|
+
A list of tuples containing the lower and upper boundaries
|
|
401
|
+
that will be applied over sigmoid or angle modulation function
|
|
402
|
+
to determine the probability to bit become 1.
|
|
403
|
+
|
|
404
|
+
Example: A function F(b1, b2) = y with:
|
|
405
|
+
(-5 <= b1 <= 5) and (-20 <= b2 <= 20) have the boundaries:
|
|
406
|
+
[(-5,5), (-20,20)]
|
|
407
|
+
|
|
408
|
+
Obs.:
|
|
409
|
+
- If boundaries are set:
|
|
410
|
+
boundaries take the priority over the bits_count.
|
|
411
|
+
|
|
412
|
+
- If boundaries are not set:
|
|
413
|
+
boundaries became (-2,2) to each bit in AMABC method or
|
|
414
|
+
(-10,10) to each bit in BABC method.
|
|
415
|
+
|
|
416
|
+
-=x=--=x=--=x=--=x=--=x=-
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
[method] : String --optional-- (default: 'am')
|
|
420
|
+
Select the applied solver:
|
|
421
|
+
- If method = 'am' : (default)
|
|
422
|
+
Applied Angle Modulated ABC (AMABC).
|
|
423
|
+
|
|
424
|
+
- If method = 'bin' :
|
|
425
|
+
Applied Binary ABC (BABC).
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
[colony_size] : Int --optional-- (default: 40)
|
|
429
|
+
A value that determines the number of bees in algorithm. Half
|
|
430
|
+
of this amount determines the number of points analyzed
|
|
431
|
+
(food sources).
|
|
432
|
+
|
|
433
|
+
According articles, half of this number determines the amount
|
|
434
|
+
of Employed bees and other half is Onlooker bees.
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
[scouts] : Float --optional-- (default: 0.5)
|
|
438
|
+
Determines the limit of tries for scout bee discard a food
|
|
439
|
+
source and replace for a new one.
|
|
440
|
+
- If scouts = 0 :
|
|
441
|
+
Scout_limit = colony_size * dimension
|
|
442
|
+
|
|
443
|
+
- If scouts = (0 to 1) :
|
|
444
|
+
Scout_limit = colony_size * dimension * scouts
|
|
445
|
+
Obs.: scouts = 0.5 is used in [3] as benchmark.
|
|
446
|
+
|
|
447
|
+
- If scouts >= 1 :
|
|
448
|
+
Scout_limit = scouts
|
|
449
|
+
|
|
450
|
+
Obs.1: Scout_limit is rounded down in all cases.
|
|
451
|
+
|
|
452
|
+
Obs.2: In Binary form, the scouts tends to be more relevant
|
|
453
|
+
than in continuous form. If your problem are badly solved,
|
|
454
|
+
try to reduce the scouts value.
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
[iterations] : Int --optional-- (default: 50)
|
|
458
|
+
The number of iterations executed by algorithm.
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
[min_max] : String --optional-- (default: 'min')
|
|
462
|
+
Determines if algorithm will minimize or maximize the function.
|
|
463
|
+
- If min_max = 'min' : (default)
|
|
464
|
+
Locate the minimum of function.
|
|
465
|
+
|
|
466
|
+
- If min_max = 'max' :
|
|
467
|
+
Locate the maximum of function.
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
[nan_protection] : Boolean or Int --optional--
|
|
471
|
+
(default (boolean): True)
|
|
472
|
+
With "method='am'", this variable are used as a boolean.
|
|
473
|
+
|
|
474
|
+
With "method='bin'", this variable determines the number of
|
|
475
|
+
times the function are recalculated when it returns a NaN.
|
|
476
|
+
(default (int): 3)
|
|
477
|
+
|
|
478
|
+
If true or greater than 0, re-generate food sources that get
|
|
479
|
+
NaN value as cost during initialization or during scout
|
|
480
|
+
events. This option usually helps the algorithm stability
|
|
481
|
+
because, in rare cases, NaN values can lock the algorithm in
|
|
482
|
+
a infinite loop.
|
|
483
|
+
|
|
484
|
+
Obs.: NaN protection can drastically increases calculation
|
|
485
|
+
time if analysed function has too many values of domain
|
|
486
|
+
returning NaN.
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
[transfer_function] : String --optional-- (default: 'sigmoid')
|
|
490
|
+
Only used with "method='bin'". Defines the transfer function
|
|
491
|
+
used to calculate the probability for each bit becomes '1'.
|
|
492
|
+
|
|
493
|
+
The possibilities are explained on article [6]:
|
|
494
|
+
- If transfer_function = 'sigmoid' : (default)
|
|
495
|
+
S(x) = 1/(1 + exp(-x))
|
|
496
|
+
|
|
497
|
+
- If transfer_function = 'sigmoid-2x' :
|
|
498
|
+
S(x) = 1/(1 + exp(-2*x))
|
|
499
|
+
|
|
500
|
+
- If transfer_function = 'sigmoid-x/2' :
|
|
501
|
+
S(x) = 1/(1 + exp(-x/2))
|
|
502
|
+
|
|
503
|
+
- If transfer_function = 'sigmoid-x/3' :
|
|
504
|
+
S(x) = 1/(1 + exp(-x/3))
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
[result_format] : String --optional-- (default: 'best')
|
|
508
|
+
Only used with "method='bin'". In a stochastic method, the
|
|
509
|
+
result vector are represented by a probability vector with
|
|
510
|
+
the probability of each bit becomes "True". This property
|
|
511
|
+
determines how output bit vector will be estimated.
|
|
512
|
+
- If result_format = 'average' :
|
|
513
|
+
Returns the most frequent bit vector after
|
|
514
|
+
"best_model_iterations" simulations of the probability
|
|
515
|
+
vector. This approach is ideal to solve problems with
|
|
516
|
+
highly random elements.
|
|
517
|
+
Obs.: To use this method efficiently, use high
|
|
518
|
+
values in "best_model_iterations". Usually values
|
|
519
|
+
greater than 100 have better results.
|
|
520
|
+
|
|
521
|
+
- If result_format = 'best' : (default)
|
|
522
|
+
Returns the best result after "best_model_iterations"
|
|
523
|
+
simulations of the probability vector. This approach is
|
|
524
|
+
useful to solve highly noisy problems.
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
[best_model_iterations] : int --optional--
|
|
528
|
+
(default: iterations count)
|
|
529
|
+
Only used with "method='bin'". Due stochastic aspect of
|
|
530
|
+
Binary form of particle based metaheuristic, after execution
|
|
531
|
+
of ABC, the cost function will be calculated
|
|
532
|
+
"best_model_iterations" times and the "best" or the "most
|
|
533
|
+
frequent" result will be returned.
|
|
534
|
+
- If best_model_iterations = 0 : (default)
|
|
535
|
+
Tries "iterations" times.
|
|
536
|
+
|
|
537
|
+
- If best_model_iterations = N :
|
|
538
|
+
Tries "N" times.
|
|
539
|
+
|
|
540
|
+
Obs.: If "best_model_iterations" (or "iterations") is even,
|
|
541
|
+
then "best_model_iterations" is increased by one.
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
[log_agents] : Boolean --optional-- (default: False)
|
|
545
|
+
If true, beecolpy will register, before each iteration, the
|
|
546
|
+
position of each food source. Useful to debug but, if there a
|
|
547
|
+
high amount of food sources and/or iterations, this option
|
|
548
|
+
drastically increases memory usage.
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
[seed] : Int --optional-- (default: None)
|
|
552
|
+
If defined as an int, set the seed used in all random process.
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
Methods
|
|
556
|
+
----------
|
|
557
|
+
fit()
|
|
558
|
+
Execute the algorithm with defined parameters.
|
|
559
|
+
|
|
560
|
+
Obs.: Returns a list with values found as minimum/maximum
|
|
561
|
+
coordinate.
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
get_solution()
|
|
565
|
+
Returns the value obtained after fit() the method.
|
|
566
|
+
|
|
567
|
+
Parameters
|
|
568
|
+
----------
|
|
569
|
+
[probability_vector] : bool --optional-- (default: False)
|
|
570
|
+
Only used with "method='bin'". Returns the vector with
|
|
571
|
+
probability of each bit becomes "True". Useful to use
|
|
572
|
+
probability as component of stopping criteria or to
|
|
573
|
+
evaluate solution stability.
|
|
574
|
+
- If probability_vector = True :
|
|
575
|
+
"get_solution" returns a vector with the
|
|
576
|
+
probability of each bit becomes "True".
|
|
577
|
+
|
|
578
|
+
- If probability_vector = False: (default)
|
|
579
|
+
"get_solution" returns the solution bit vector.
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
get_status()
|
|
583
|
+
Returns a tuple with:
|
|
584
|
+
- Number of complete iterations executed
|
|
585
|
+
- Number of scout events during iterations
|
|
586
|
+
- Number of times that NaN protection was activated
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
get_agents()
|
|
590
|
+
Returns a list with the position of each food source during
|
|
591
|
+
each iteration if "log_agents = True".
|
|
592
|
+
|
|
593
|
+
Obs.: In binary form, this method returns the position of
|
|
594
|
+
each food source after transformation "binary -> continuous".
|
|
595
|
+
I.e. returns the values applied on angle modulation function
|
|
596
|
+
in AMABC or the values applied on transfer function in BABC.
|
|
597
|
+
|
|
598
|
+
Parameters
|
|
599
|
+
----------
|
|
600
|
+
[reset_agents] : bool --optional-- (default: False)
|
|
601
|
+
If true, the food source position log will be cleaned in
|
|
602
|
+
next fit().
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
Bibliography
|
|
606
|
+
----------
|
|
607
|
+
[1] Karaboga, D. and Basturk, B., 2007
|
|
608
|
+
A powerful and efficient algorithm for numerical function
|
|
609
|
+
optimization: artificial bee colony (ABC) algorithm. Journal
|
|
610
|
+
of global optimization, 39(3), pp.459-471.
|
|
611
|
+
DOI: https://doi.org/10.1007/s10898-007-9149-x
|
|
612
|
+
|
|
613
|
+
[2] Liu, T., Zhang, L. and Zhang, J., 2013
|
|
614
|
+
Study of binary artificial bee colony algorithm based on
|
|
615
|
+
particle swarm optimization. Journal of Computational
|
|
616
|
+
Information Systems, 9(16), pp.6459-6466.
|
|
617
|
+
Link: https://api.semanticscholar.org/CorpusID:8789571
|
|
618
|
+
|
|
619
|
+
[3] Anuar, S., Selamat, A. and Sallehuddin, R., 2016
|
|
620
|
+
A modified scout bee for artificial bee colony algorithm and
|
|
621
|
+
its performance on optimization problems. Journal of King Saud
|
|
622
|
+
University-Computer and Information Sciences, 28(4),
|
|
623
|
+
pp.395-406.
|
|
624
|
+
DOI: https://doi.org/10.1016/j.jksuci.2016.03.001
|
|
625
|
+
|
|
626
|
+
[4] Kennedy, J. and Eberhart, R.C., 1997
|
|
627
|
+
A discrete binary version of the particle swarm algorithm.
|
|
628
|
+
In 1997 IEEE International conference on systems, man, and
|
|
629
|
+
cybernetics. Computational cybernetics and simulation
|
|
630
|
+
(Vol. 5, pp. 4104-4108). IEEE.
|
|
631
|
+
DOI: https://doi.org/10.1109/ICSMC.1997.637339
|
|
632
|
+
|
|
633
|
+
[5] Pampará, G. and Engelbrecht, A.P., 2011
|
|
634
|
+
Binary artificial bee colony optimization. In 2011 IEEE
|
|
635
|
+
Symposium on Swarm Intelligence (pp. 1-8). IEEE.
|
|
636
|
+
DOI: https://doi.org/10.1109/SIS.2011.5952562
|
|
637
|
+
|
|
638
|
+
[6] Mirjalili, S., Hashim, S., Taherzadeh, G., Mirjalili, S.Z.
|
|
639
|
+
and Salehi, S., 2011
|
|
640
|
+
A study of different transfer functions for binary version
|
|
641
|
+
of particle swarm optimization. In International Conference
|
|
642
|
+
on Genetic and Evolutionary Methods (Vol. 1, No. 1, pp. 2-7).
|
|
643
|
+
Link: http://hdl.handle.net/10072/48831
|
|
644
|
+
|
|
645
|
+
[7] Huang, S.C., 2015
|
|
646
|
+
Polygonal approximation using an artificial bee colony
|
|
647
|
+
algorithm. Mathematical Problems in Engineering, 2015.
|
|
648
|
+
DOI: https://doi.org/10.1155/2015/375926
|
|
649
|
+
|
|
650
|
+
'''
|
|
651
|
+
def __init__(self,
|
|
652
|
+
function,
|
|
653
|
+
bits_count: int=0,
|
|
654
|
+
boundaries: list=[],
|
|
655
|
+
colony_size: int=40,
|
|
656
|
+
scouts: float=0.5,
|
|
657
|
+
iterations: int=50,
|
|
658
|
+
min_max: str='min',
|
|
659
|
+
method: str='am',
|
|
660
|
+
nan_protection: bool=True,
|
|
661
|
+
transfer_function: str='sigmoid',
|
|
662
|
+
result_format: str='best',
|
|
663
|
+
best_model_iterations: int=0,
|
|
664
|
+
log_agents: bool=False,
|
|
665
|
+
seed: int=None):
|
|
666
|
+
|
|
667
|
+
self.method = method
|
|
668
|
+
self.function = function
|
|
669
|
+
self.seed = seed
|
|
670
|
+
|
|
671
|
+
bits_count = int(bits_count)
|
|
672
|
+
if ((len(boundaries) == 0) and (bits_count <= 0)):
|
|
673
|
+
raise Exception('\nInvalid bit vector length. ' \
|
|
674
|
+
'\'bits_count\' need to be greater than 0 or define \'boundaries\' list.')
|
|
675
|
+
|
|
676
|
+
if (nan_protection < 0):
|
|
677
|
+
warn_message = 'Negative nan_protection given. NaN protection disabled.'
|
|
678
|
+
wrn.warn(warn_message, RuntimeWarning)
|
|
679
|
+
self._nan_protection = (nan_protection > 0)
|
|
680
|
+
|
|
681
|
+
self.result_bit_vector = None
|
|
682
|
+
|
|
683
|
+
self.executed_bin_fit = False
|
|
684
|
+
|
|
685
|
+
#Method selector
|
|
686
|
+
if (self.method == 'am'): #Angle Modulated
|
|
687
|
+
boundaries = [(-2, 2) for _ in range(bits_count)] if (len(boundaries) == 0) \
|
|
688
|
+
else boundaries
|
|
689
|
+
|
|
690
|
+
self._bin_abc_object = abc(function = _AMABC_engine(self).am_cost_function,
|
|
691
|
+
boundaries = boundaries,
|
|
692
|
+
colony_size = colony_size,
|
|
693
|
+
scouts = scouts,
|
|
694
|
+
iterations = iterations,
|
|
695
|
+
min_max = min_max,
|
|
696
|
+
nan_protection = self._nan_protection,
|
|
697
|
+
log_agents = log_agents,
|
|
698
|
+
seed = self.seed)
|
|
699
|
+
|
|
700
|
+
elif (self.method == 'bin'): #Binary ABC
|
|
701
|
+
self.transfer_function = transfer_function
|
|
702
|
+
self.min_max_selector = min_max
|
|
703
|
+
|
|
704
|
+
self.result_format = result_format
|
|
705
|
+
_BABC_engine(self).check_result_format()
|
|
706
|
+
|
|
707
|
+
best_model_iterations = best_model_iterations if (best_model_iterations > 0) \
|
|
708
|
+
else iterations
|
|
709
|
+
best_model_iterations += int(not(best_model_iterations % 2)) #Grants the odd value
|
|
710
|
+
if (best_model_iterations < 3):
|
|
711
|
+
warn_message = 'Using best_model_iterations = 3'
|
|
712
|
+
wrn.warn(warn_message, RuntimeWarning)
|
|
713
|
+
self.best_model_iterations = int(max([best_model_iterations, 3]))
|
|
714
|
+
|
|
715
|
+
self._nan_count = 2 if (isinstance(nan_protection, bool) and (self._nan_protection)) \
|
|
716
|
+
else int(max([(nan_protection - 1), 0]))
|
|
717
|
+
|
|
718
|
+
self.boundaries = [(-10, 10) for _ in range(bits_count)] if (len(boundaries) == 0) \
|
|
719
|
+
else boundaries
|
|
720
|
+
|
|
721
|
+
self._bin_abc_object = abc(function = _BABC_engine(self).bin_cost_function,
|
|
722
|
+
boundaries = self.boundaries,
|
|
723
|
+
colony_size = colony_size,
|
|
724
|
+
scouts = scouts,
|
|
725
|
+
iterations = iterations,
|
|
726
|
+
min_max = min_max,
|
|
727
|
+
nan_protection = self._nan_protection,
|
|
728
|
+
log_agents = log_agents,
|
|
729
|
+
seed = self.seed)
|
|
730
|
+
|
|
731
|
+
else:
|
|
732
|
+
raise Exception('\nInvalid method. Valid values include:\n\'am\'\n\'bin\'')
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def fit(self):
|
|
736
|
+
'''
|
|
737
|
+
Execute the algorithm with defined parameters.
|
|
738
|
+
|
|
739
|
+
Obs.: Returns a list with values found as minimum/maximum
|
|
740
|
+
coordinate.
|
|
741
|
+
'''
|
|
742
|
+
self._bin_abc_object.fit()
|
|
743
|
+
self.executed_bin_fit = True
|
|
744
|
+
if (self.method == 'am'): #Angle Modulated
|
|
745
|
+
self.result_bit_vector = _AMABC_engine(self).get_bit_vector(
|
|
746
|
+
self._bin_abc_object.get_solution())
|
|
747
|
+
elif (self.method == 'bin'): #Binary ABC
|
|
748
|
+
if (self.seed is not None):
|
|
749
|
+
rng.seed(self.seed)
|
|
750
|
+
|
|
751
|
+
self.result_bit_vector = _BABC_engine(self).get_result_vector(
|
|
752
|
+
self._bin_abc_object.get_solution())
|
|
753
|
+
return self.result_bit_vector
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def get_agents(self, reset_agents: bool=False):
|
|
757
|
+
'''
|
|
758
|
+
Returns a list with the position of each food source during
|
|
759
|
+
each iteration.
|
|
760
|
+
|
|
761
|
+
Obs.: In binary form, this method returns the position of
|
|
762
|
+
each food source after transformation "binary -> continuous".
|
|
763
|
+
I.e. returns the values applied on angle modulation function
|
|
764
|
+
in AMABC or the values applied on transfer function in BABC.
|
|
765
|
+
|
|
766
|
+
Parameters
|
|
767
|
+
----------
|
|
768
|
+
[reset_agents] : bool --optional-- (default: False)
|
|
769
|
+
If true, the food source position log will be cleaned in
|
|
770
|
+
next fit().
|
|
771
|
+
'''
|
|
772
|
+
return self._bin_abc_object.get_agents(reset_agents)
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def get_solution(self, probability_vector: bool=False):
|
|
776
|
+
'''
|
|
777
|
+
Returns the value obtained after fit() the method.
|
|
778
|
+
|
|
779
|
+
Parameters
|
|
780
|
+
----------
|
|
781
|
+
[probability_vector] : bool --optional-- (default: False)
|
|
782
|
+
Only used with "method='bin'". Returns the vector with
|
|
783
|
+
probability of each bit becomes "True". Useful to use
|
|
784
|
+
probability as component of stopping criteria or to
|
|
785
|
+
evaluate solution stability.
|
|
786
|
+
- If probability_vector = True :
|
|
787
|
+
"get_solution" returns a vector with the
|
|
788
|
+
probability of each bit becomes "True".
|
|
789
|
+
|
|
790
|
+
- If probability_vector = False: (default)
|
|
791
|
+
"get_solution" returns the solution bit vector.
|
|
792
|
+
'''
|
|
793
|
+
assert self.executed_bin_fit, 'fit() not executed yet!'
|
|
794
|
+
|
|
795
|
+
if (probability_vector and (self.method == 'bin') and self.executed_bin_fit):
|
|
796
|
+
return _BABC_engine(self).get_probability_vector(
|
|
797
|
+
self._bin_abc_object.get_solution())
|
|
798
|
+
else:
|
|
799
|
+
return self.result_bit_vector
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def get_status(self):
|
|
803
|
+
'''
|
|
804
|
+
Returns a tuple with:
|
|
805
|
+
- Number of complete iterations executed
|
|
806
|
+
- Number of scout events during iterations
|
|
807
|
+
- Number of times that NaN protection was activated
|
|
808
|
+
'''
|
|
809
|
+
return self._bin_abc_object.iteration_status, \
|
|
810
|
+
self._bin_abc_object.scout_status, \
|
|
811
|
+
self._bin_abc_object.nan_status
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
class _FoodSource:
|
|
818
|
+
def __init__(self, abc, engine):
|
|
819
|
+
#When a food source is initialized, randomize a position inside boundaries and calculate the "fit"
|
|
820
|
+
self.abc = abc
|
|
821
|
+
self.engine = engine
|
|
822
|
+
self.trial_counter = 0
|
|
823
|
+
self.position = [rng.uniform(*self.abc.boundaries[i]) for i in range(len(self.abc.boundaries))]
|
|
824
|
+
self.fit = self.engine.calculate_fit(self.position)
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def evaluate_neighbor(self, partner_position):
|
|
828
|
+
#Randomize one coodinate (one dimension) to generate a neighbor point
|
|
829
|
+
j = rng.randrange(0, len(self.abc.boundaries))
|
|
830
|
+
|
|
831
|
+
#eq. (2.2) [1] (new coordinate "x_j" to generate a neighbor point)
|
|
832
|
+
xj_new = self.position[j] + rng.uniform(-1, 1)*(self.position[j] - partner_position[j])
|
|
833
|
+
|
|
834
|
+
#Check boundaries
|
|
835
|
+
xj_new = self.abc.boundaries[j][0] if (xj_new < self.abc.boundaries[j][0]) else \
|
|
836
|
+
self.abc.boundaries[j][1] if (xj_new > self.abc.boundaries[j][1]) else xj_new
|
|
837
|
+
|
|
838
|
+
#Changes the coordinate "j" from food source to new "x_j" generating the neighbor point
|
|
839
|
+
neighbor_position = [(self.position[i] if (i != j) else xj_new) for i in range(len(self.abc.boundaries))]
|
|
840
|
+
neighbor_fit = self.engine.calculate_fit(neighbor_position)
|
|
841
|
+
|
|
842
|
+
#Greedy selection
|
|
843
|
+
if (neighbor_fit > self.fit):
|
|
844
|
+
self.position = neighbor_position
|
|
845
|
+
self.fit = neighbor_fit
|
|
846
|
+
self.trial_counter = 0
|
|
847
|
+
else:
|
|
848
|
+
self.trial_counter += 1
|
|
849
|
+
|
|
850
|
+
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
class _ABC_engine:
|
|
854
|
+
def __init__(self, abc):
|
|
855
|
+
self.abc = abc
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
def check_nan_lock(self):
|
|
859
|
+
if not(self.abc.nan_protection):
|
|
860
|
+
if np.all([np.isnan(food.fit) for food in self.abc.foods]):
|
|
861
|
+
raise Exception('All food sources\'s fit resulted in NaN and beecolpy got ' \
|
|
862
|
+
'stuck in an infinite loop. Enable nan_protection to prevent this.')
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def execute_nan_protection(self, food_index):
|
|
866
|
+
while (np.isnan(self.abc.foods[food_index].fit) and self.abc.nan_protection):
|
|
867
|
+
self.abc.nan_status += 1
|
|
868
|
+
self.abc.foods[food_index] = _FoodSource(self.abc, self)
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
def generate_food_source(self, index):
|
|
872
|
+
self.abc.foods[index] = _FoodSource(self.abc, self)
|
|
873
|
+
self.execute_nan_protection(index)
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
def prob_i(self, actual_fit, max_fit):
|
|
877
|
+
# Improved probability function [7]
|
|
878
|
+
return 0.9*(actual_fit/max_fit) + 0.1
|
|
879
|
+
# Original probability function [1]
|
|
880
|
+
# return actual_fit/np.sum([food.fit for food in self.abc.foods])
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def calculate_fit(self, evaluated_position):
|
|
884
|
+
#eq. (2) [2] (Convert "cost function" to "fit function")
|
|
885
|
+
cost = self.abc.cost_function(evaluated_position)
|
|
886
|
+
if (self.abc.min_max_selector == 'min'): #Minimize function
|
|
887
|
+
fit_value = (1 + np.abs(cost)) if (cost < 0) else (1/(1 + cost))
|
|
888
|
+
else: #Maximize function
|
|
889
|
+
fit_value = (1 + cost) if (cost > 0) else (1/(1 + np.abs(cost)))
|
|
890
|
+
return fit_value
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
def food_source_dance(self, index):
|
|
894
|
+
#Generate a partner food source to generate a neighbor point to evaluate
|
|
895
|
+
while True: #Criterion from [1] geting another food source at random
|
|
896
|
+
d = int(rng.randrange(0, self.abc.employed_onlookers_count))
|
|
897
|
+
if (d != index):
|
|
898
|
+
break
|
|
899
|
+
self.abc.foods[index].evaluate_neighbor(self.abc.foods[d].position)
|
|
900
|
+
|
|
901
|
+
|
|
902
|
+
def employer_bee_phase(self):
|
|
903
|
+
#Generate and evaluate a neighbor point to every food source
|
|
904
|
+
for i in range(len(self.abc.foods)):
|
|
905
|
+
self.food_source_dance(i)
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def onlooker_bee_phase(self):
|
|
909
|
+
#Based in probability, generate a neighbor point and evaluate again some food sources
|
|
910
|
+
#Same food source can be evaluated multiple times
|
|
911
|
+
self.check_nan_lock()
|
|
912
|
+
max_fit = np.nanmax([food.fit for food in self.abc.foods])
|
|
913
|
+
onlooker_probability = [self.prob_i(food.fit, max_fit) for food in self.abc.foods]
|
|
914
|
+
p = 0 #Onlooker bee index
|
|
915
|
+
i = 0 #Food source index
|
|
916
|
+
while (p < self.abc.employed_onlookers_count):
|
|
917
|
+
if (rng.uniform(0, 1) <= onlooker_probability[i]):
|
|
918
|
+
p += 1
|
|
919
|
+
self.food_source_dance(i)
|
|
920
|
+
self.check_nan_lock()
|
|
921
|
+
max_fit = np.nanmax([food.fit for food in self.abc.foods])
|
|
922
|
+
if (self.abc.foods[i].fit != max_fit):
|
|
923
|
+
onlooker_probability[i] = self.prob_i(self.abc.foods[i].fit, max_fit)
|
|
924
|
+
else:
|
|
925
|
+
onlooker_probability = [self.prob_i(food.fit, max_fit) for food in self.abc.foods]
|
|
926
|
+
i = (i+1) if (i < (len(self.abc.foods)-1)) else 0
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def scout_bee_phase(self):
|
|
930
|
+
#Generate up to one new food source that does not improve over scout_limit evaluation tries
|
|
931
|
+
trial_counters = [food.trial_counter for food in self.abc.foods]
|
|
932
|
+
if (max(trial_counters) > self.abc.scout_limit):
|
|
933
|
+
#Take the index of replaced food source
|
|
934
|
+
trial_counters = np.where(np.array(trial_counters) == max(trial_counters))[0].tolist()
|
|
935
|
+
i = trial_counters[rng.randrange(0, len(trial_counters))]
|
|
936
|
+
self.generate_food_source(i) #Replace food source
|
|
937
|
+
self.abc.scout_status += 1
|
|
938
|
+
|
|
939
|
+
|
|
940
|
+
def memorize_best_solution(self):
|
|
941
|
+
best_food_index = np.nanargmax([food.fit for food in self.abc.foods])
|
|
942
|
+
if (self.abc.foods[best_food_index].fit >= self.abc.best_food_source.fit):
|
|
943
|
+
self.abc.best_food_source = self.abc.foods[best_food_index]
|
|
944
|
+
|
|
945
|
+
|
|
946
|
+
|
|
947
|
+
|
|
948
|
+
class _BABC_engine:
|
|
949
|
+
def __init__(self, babc):
|
|
950
|
+
self.babc = babc
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
def check_result_format(self):
|
|
954
|
+
valid_formats = ('average', 'best')
|
|
955
|
+
if (self.babc.result_format not in valid_formats):
|
|
956
|
+
raise Exception('\nInvalid result format. Valid values include:' \
|
|
957
|
+
'\n\'average\'\n\'best\'')
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
def sigmoid(self, x):
|
|
961
|
+
return 1/(1 + np.exp((-1)*x))
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
def transfer(self, value): #Transfer functions discused in [6]
|
|
965
|
+
if (self.babc.transfer_function == 'sigmoid'):
|
|
966
|
+
return self.sigmoid(value) #S(x) = 1/(1 + exp(-x))
|
|
967
|
+
elif (self.babc.transfer_function == 'sigmoid-2x'):
|
|
968
|
+
return self.sigmoid(value*2) #S(x) = 1/(1 + exp(-2*x))
|
|
969
|
+
elif (self.babc.transfer_function == 'sigmoid-x/2'):
|
|
970
|
+
return self.sigmoid(value/2) #S(x) = 1/(1 + exp(-x/2))
|
|
971
|
+
elif (self.babc.transfer_function == 'sigmoid-x/3'):
|
|
972
|
+
return self.sigmoid(value/3) #S(x) = 1/(1 + exp(-x/3))
|
|
973
|
+
else:
|
|
974
|
+
raise Exception('\nInvalid transfer function. Valid values include:' \
|
|
975
|
+
'\n\'sigmoid\'\n\'sigmoid-2x\'\n\'sigmoid-x/2\'\n\'sigmoid-x/3\'')
|
|
976
|
+
|
|
977
|
+
|
|
978
|
+
def get_probability_vector(self, value_vector):
|
|
979
|
+
return [self.transfer(value) for value in value_vector]
|
|
980
|
+
|
|
981
|
+
|
|
982
|
+
def get_bit_vector(self, value_vector):
|
|
983
|
+
probability_vector = self.get_probability_vector(value_vector)
|
|
984
|
+
return [(rng.uniform(0, 1) < probability) for probability in probability_vector]
|
|
985
|
+
|
|
986
|
+
|
|
987
|
+
def recalculate_nan(self, bit_vector, cost_value, value_vector):
|
|
988
|
+
j = 0
|
|
989
|
+
while (np.isnan(cost_value) and (j < self.babc._nan_count)):
|
|
990
|
+
bit_vector = self.get_bit_vector(value_vector)
|
|
991
|
+
cost_value = self.babc.function(bit_vector)
|
|
992
|
+
j += 1
|
|
993
|
+
return bit_vector, cost_value
|
|
994
|
+
|
|
995
|
+
|
|
996
|
+
def bin_cost_function(self, value_vector):
|
|
997
|
+
bit_vector = self.get_bit_vector(value_vector)
|
|
998
|
+
cost_value = self.babc.function(bit_vector)
|
|
999
|
+
|
|
1000
|
+
if self.babc._nan_protection:
|
|
1001
|
+
_, cost_value = self.recalculate_nan(bit_vector, cost_value, value_vector)
|
|
1002
|
+
|
|
1003
|
+
return cost_value
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
def get_best_model(self, value_vector):
|
|
1007
|
+
cost_value = np.nan
|
|
1008
|
+
for i in range(self.babc.best_model_iterations):
|
|
1009
|
+
temp_bit_vector = self.get_bit_vector(value_vector)
|
|
1010
|
+
temp_cost_value = self.babc.function(temp_bit_vector)
|
|
1011
|
+
|
|
1012
|
+
if self.babc._nan_protection:
|
|
1013
|
+
temp_bit_vector, temp_cost_value = self.recalculate_nan(
|
|
1014
|
+
temp_bit_vector, temp_cost_value, value_vector)
|
|
1015
|
+
|
|
1016
|
+
if (self.babc.min_max_selector == 'min'): #Minimize function
|
|
1017
|
+
if ((i < 1) or (temp_cost_value < cost_value)):
|
|
1018
|
+
cost_value = temp_cost_value
|
|
1019
|
+
bit_vector = temp_bit_vector
|
|
1020
|
+
else: #Maximize function
|
|
1021
|
+
if ((i < 1) or (temp_cost_value > cost_value)):
|
|
1022
|
+
cost_value = temp_cost_value
|
|
1023
|
+
bit_vector = temp_bit_vector
|
|
1024
|
+
return bit_vector
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
def get_average_model(self, value_vector):
|
|
1028
|
+
solution_collection = np.zeros((self.babc.best_model_iterations,
|
|
1029
|
+
len(self.babc.boundaries)))
|
|
1030
|
+
solution_collection.fill(np.nan)
|
|
1031
|
+
bit_vector = [None] * len(self.babc.boundaries)
|
|
1032
|
+
|
|
1033
|
+
for i in range(self.babc.best_model_iterations):
|
|
1034
|
+
temp_bit_vector = self.get_bit_vector(value_vector)
|
|
1035
|
+
|
|
1036
|
+
if self.babc._nan_protection:
|
|
1037
|
+
temp_cost_value = self.babc.function(temp_bit_vector)
|
|
1038
|
+
temp_bit_vector, _ = self.recalculate_nan(
|
|
1039
|
+
temp_bit_vector, temp_cost_value, value_vector)
|
|
1040
|
+
|
|
1041
|
+
solution_collection[i,:] = temp_bit_vector
|
|
1042
|
+
|
|
1043
|
+
for j in range(len(self.babc.boundaries)):
|
|
1044
|
+
simulated_bits = solution_collection[:,j]
|
|
1045
|
+
bit_vector[j] = bool(Counter(simulated_bits).most_common(1)[0][0])
|
|
1046
|
+
return bit_vector
|
|
1047
|
+
|
|
1048
|
+
|
|
1049
|
+
def get_result_vector(self, value_vector):
|
|
1050
|
+
self.check_result_format()
|
|
1051
|
+
|
|
1052
|
+
if (self.babc.result_format == 'average'):
|
|
1053
|
+
return self.get_average_model(value_vector)
|
|
1054
|
+
elif (self.babc.result_format == 'best'):
|
|
1055
|
+
return self.get_best_model(value_vector)
|
|
1056
|
+
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
class _AMABC_engine:
|
|
1061
|
+
def __init__(self, amabc):
|
|
1062
|
+
self.amabc = amabc
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
def angle_modulation(self, angle):
|
|
1066
|
+
# Equation (8) from [5] with constants:
|
|
1067
|
+
# g(x) = sin{2 * pi * (x-a) * b * cos[2 * pi * (x-a) * c]} + d
|
|
1068
|
+
# a=0 b=1 c=1 d=0
|
|
1069
|
+
PI2 = 2 * np.pi
|
|
1070
|
+
return np.sin(PI2 * angle * np.cos(PI2 * angle))
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
def get_bit_vector(self, angle_vector):
|
|
1074
|
+
return [(self.angle_modulation(angle) > 0) for angle in angle_vector]
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def am_cost_function(self, angle_vector):
|
|
1078
|
+
return self.amabc.function(self.get_bit_vector(angle_vector))
|