Skip to content

Commit 4fd4be3

Browse files
authored
Merge pull request #9 from HaaLeo/feature/artificial-bee-colony
Feature/artificial bee colony
2 parents bf6a6b2 + efa9ec6 commit 4fd4be3

22 files changed

+500
-82
lines changed

.vscode/launch.json

+17
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,23 @@
6464
"10",
6565
"14"
6666
]
67+
},
68+
{
69+
"name": "Run: Artificial Bee Colony",
70+
"type": "python",
71+
"request": "launch",
72+
"module": "swarmlib",
73+
"console": "internalConsole",
74+
"args": [
75+
// "--dark",
76+
"--continuous",
77+
"bees",
78+
"-n",
79+
"10",
80+
"-t",
81+
"5",
82+
"14"
83+
]
6784
}
6885
]
6986
}

.vscode/settings.json

+23-23
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,36 @@
11
{
2+
"cSpell.ignorePaths": [
3+
"**/.git/**",
4+
".vscode",
5+
".pylintrc"
6+
],
27
"cSpell.words": [
3-
"networkx",
4-
"pyplot",
5-
"wfunc",
6-
"pylint",
7-
"ioff",
8-
"qsize",
9-
"fignum",
10-
"Hanisch",
11-
"pypi",
12-
"isabs",
13-
"getcwd",
14-
"Dorigo",
158
"Birattari",
9+
"Dorigo",
10+
"Hanisch",
1611
"Stuetzle",
17-
"optimisation",
1812
"TSPLIB",
13+
"ackley",
14+
"fignum",
15+
"functools",
16+
"getcwd",
17+
"ioff",
18+
"isabs",
19+
"michalewicz",
20+
"networkx",
21+
"numpy",
22+
"optimisation",
1923
"paypal",
24+
"pylint",
25+
"pypi",
26+
"pyplot",
27+
"qsize",
2028
"swarmlib",
21-
"numpy",
22-
"michalewicz",
23-
"functools",
24-
"ackley"
25-
],
26-
"cSpell.ignorePaths": [
27-
"**/.git/**",
28-
".vscode",
29-
".pylintrc"
29+
"wfunc"
3030
],
31+
"files.eol": "\n",
3132
"files.insertFinalNewline": true,
3233
"files.trimFinalNewlines": true,
3334
"python.linting.enabled": true,
34-
"files.eol": "\n",
3535
"python.linting.pylintEnabled": true
3636
}

CHANGELOG.md

+5-4
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,22 @@ All notable changes to the "swarmlib" pypi package will be documented in this fi
33
This project follows [semantic versioning](https://semver.org/).
44

55
## Unreleased
6+
* Added the _artificial bee colony_ algorithm. After each step the intermediate solution is plotted.
67

7-
## 2019-02-17 -v0.7.0
8+
## 2020-02-17 -v0.7.0
89
* **Added** dark mode. It is enabled via the `--dark` flag.
910
* **Changed** `--continuous` and `--interval` flags. Both are now top level flags.
1011
* **Changed** the API of the ant colony optimization.
1112
* **Changed** the `tsp_file` argument to an option. Now `--tsp-file` is optional. By default the built-in burma14 problem is used.
1213

13-
## 2019-01-25 - v0.6.2
14+
## 2020-01-25 - v0.6.2
1415
* **Changed** cuckoo search visualization: when a nest is abandoned / newly generated color its transition differently.
1516
* **Fixed** cuckoo search visualization: now the abandon transition is mapped to the correct nest.
1617

17-
## 2019-01-24 - v0.6.1
18+
## 2020-01-24 - v0.6.1
1819
* **Changed** cuckoo search: Ensure each nest is assigned a cuckoo position in the update step
1920

20-
## 2019-01-24 - v0.6.0
21+
## 2020-01-24 - v0.6.0
2122
* **Changed** the visualization of the _firefly algorithm_ and the _cuckoo search_. Now they both include velocities.
2223
* **Changed** the firefly algorithm including its API. Now it replays the same problem if `--continuous` is set.
2324
* **Changed** the `--continuous` flag. It requires no parameter anymore.

README.md

+43-4
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,20 @@
88
## Description
99

1010
This repository implements several swarm optimization algorithms and visualizes their (intermediate) solutions.
11-
To run the algorithms one can either use the command line interface or the API.
11+
To run the algorithms one can either use the CLI (recommended) or the API.
1212
Currently, the following algorithms are implemented:
1313
* [Firefly Algorithm](#firefly-algorithm)
1414
* [Cuckoo Search](#cuckoo-search)
1515
* [Particle Swarm Optimization](#particle-swarm-optimization)
1616
* [Ant Colony Optimization](#ant-colony-optimization)
17+
* [Artificial Bee Colony](#artificial-bee-colony)
1718

1819
## Installation
1920

2021
You can install the package with `pip` from [pypi](https://pypi.org/project/swarmlib):
2122

2223
```
23-
pip3 install swarmlib
24+
pip install swarmlib
2425
2526
swarm --version
2627
```
@@ -72,7 +73,7 @@ In addition to the cli you can also use the API:
7273
```python
7374
from swarmlib import FireflyProblem, FUNCTIONS
7475

75-
problem = FireflyProblem(FUNCTIONS['michalewicz'], 14)
76+
problem = FireflyProblem(function=FUNCTIONS['michalewicz'], firefly_number=14)
7677
best_firefly = problem.solve()
7778
problem.replay()
7879
```
@@ -116,7 +117,7 @@ This repository also implements modified _particle swarm optimization_ that was
116117

117118
#### Features
118119

119-
Enables to particle swarm optimization to one of the provided 2D functions. The algorithm tries to find the global minimum of the selected function.
120+
Enables particle swarm optimization to one of the provided 2D functions. The algorithm tries to find the global minimum of the selected function.
120121

121122
Currently two functions can be selected:
122123
* [ackley](https://www.sfu.ca/~ssurjano/ackley.html)
@@ -175,3 +176,41 @@ problem = ACOProblem(ant_number=10)
175176
path, distance = problem.solve()
176177
problem.replay()
177178
```
179+
180+
### Artificial Bee Colony
181+
182+
The Artificial Bee Colony (ABC) algorithm was initially proposed 2005 by Dervis Karaboga in his paper [An Idea Based on Honey Bee Swarm For Numerical Optimization](https://pdfs.semanticscholar.org/015d/f4d97ed1f541752842c49d12e429a785460b.pdf).
183+
In his paper Karaboga did not specify _how exactly_ new solutions shall be discovered.
184+
185+
Research has shown that the flight behavior of birds, fruit flies and other insects model properties of Levy flights ([Brown, Liebovitch & Glendon, 2007](https://link.springer.com/article/10.1007/s10745-006-9083-4); [Pavlyukevich, 2007](https://arxiv.org/pdf/cond-mat/0701653.pdf)). Therefore, this library's ABC implementation leverages levy flights to generate new solutions.
186+
187+
#### Features
188+
189+
Enables the ABC algorithm to one of the provided 2D functions. The algorithm tries to find the global minimum of the selected function.
190+
191+
Currently two functions can be selected:
192+
* [ackley](https://www.sfu.ca/~ssurjano/ackley.html)
193+
* [michalewicz](https://www.sfu.ca/~ssurjano/michal.html)
194+
195+
![ABC Sample](https://raw.githubusercontent.com/HaaLeo/swarmlib/master/doc/bees.gif)
196+
197+
The plot shows all _employee bees_ as _red_ markers, the _onlooker bees_ are visualized as _blue_ markers. The best bees of all (previous) iterations are indicated by _yellow_ markers. When an employee bee exceeded its maximum _trials_ the bee is assigned a new random position. This is visualized by a _dark grey_ transition.
198+
Since the onlooker bees pick up an employee bee's position randomly visualizing their transitions confuses rather than it helps understanding the algorithm and therefore is omitted.
199+
200+
To print all available options execute:
201+
202+
```
203+
swarm bees -h
204+
```
205+
206+
#### API
207+
208+
In addition to the cli you can also use the API:
209+
210+
```python
211+
from swarmlib import ABCProblem, FUNCTIONS
212+
213+
problem = ABCProblem(bees=10, function=FUNCTIONS['michalewicz'])
214+
best_bee = problem.solve()
215+
problem.replay()
216+
```

doc/bees.gif

1020 KB
Loading

setup.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@
4141
keywords=[
4242
'swarm',
4343
'swarmlib',
44+
'lib',
45+
'library',
4446
'ant',
4547
'colony',
4648
'optimization',
@@ -68,7 +70,14 @@
6870
'particle',
6971
'particles',
7072
'pso',
71-
'PSO'
73+
'PSO',
74+
'artificial',
75+
'bee',
76+
'bees',
77+
'colony',
78+
'ABC',
79+
'abc',
80+
'heuristic'
7281
],
7382
classifiers=[
7483
'Development Status :: 5 - Production/Stable',

swarmlib/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,5 @@
77
from .fireflyalgorithm.firefly_problem import FireflyProblem
88
from .cuckoosearch.cuckoo_problem import CuckooProblem
99
from .pso.pso_problem import PSOProblem
10+
from .abc.abc_problem import ABCProblem
1011
from .util.functions import FUNCTIONS

swarmlib/__main__.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@
77
import sys
88
import argparse
99

10-
# pylint: disable=import-error
11-
# to do remove import-error
1210

1311
from .aco4tsp.main import configure_parser as aco_parser
1412
from .fireflyalgorithm.main import configure_parser as firefly_parser
1513
from .cuckoosearch.main import configure_parser as cuckoo_parser
1614
from .pso.main import configure_parser as pso_parser
15+
from .abc.main import configure_parser as abc_parser
16+
1717
from ._version import __version__
1818

1919
logging.basicConfig(
@@ -61,6 +61,7 @@ def run_swarm():
6161
firefly_parser(sub_parsers)
6262
cuckoo_parser(sub_parsers)
6363
pso_parser(sub_parsers)
64+
abc_parser(sub_parsers)
6465

6566
args = vars(parser.parse_args())
6667
if args:

swarmlib/abc/__init__.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# ------------------------------------------------------------------------------------------------------
2+
# Copyright (c) Leo Hanisch. All rights reserved.
3+
# Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information.
4+
# ------------------------------------------------------------------------------------------------------

swarmlib/abc/abc_problem.py

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# ------------------------------------------------------------------------------------------------------
2+
# Copyright (c) Leo Hanisch. All rights reserved.
3+
# Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information.
4+
# ------------------------------------------------------------------------------------------------------
5+
6+
from copy import deepcopy
7+
from functools import reduce
8+
import logging
9+
10+
import numpy as np
11+
12+
from .bees.employee_bee import EmployeeBee
13+
from .bees.onlooker_bee import OnlookerBee
14+
from .visualizer import Visualizer
15+
16+
LOGGER = logging.getLogger(__name__)
17+
18+
class ABCProblem():
19+
"""Artificial Bee Colony Problem"""
20+
21+
def __init__(self, **kwargs):
22+
"""
23+
Initializes a new instance of the ABCProblem class.
24+
"""
25+
26+
self.__iteration_number = kwargs['iteration_number']
27+
self.__employee_bees = [
28+
EmployeeBee(**kwargs)
29+
for _ in range(kwargs['bees'])
30+
]
31+
32+
self.__onlooker_bees = [
33+
OnlookerBee(**kwargs)
34+
for _ in range(kwargs['bees'])
35+
]
36+
37+
self.__visualizer = Visualizer(**kwargs)
38+
39+
def solve(self):
40+
"""
41+
Solve the ABC problem
42+
"""
43+
best = min(self.__employee_bees + self.__onlooker_bees, key=lambda bee: bee.value)
44+
self.__visualizer.add_data(employee_bees=self.__employee_bees, onlooker_bees=self.__onlooker_bees, best_position=best.position)
45+
46+
for iteration in range(self.__iteration_number):
47+
# Employee bee phase
48+
for bee in self.__employee_bees:
49+
bee.explore()
50+
51+
# Calculate the employee bees fitness values and probabilities
52+
overall_fitness = reduce(lambda acc, curr: acc + curr.fitness, self.__employee_bees, 0)
53+
employee_bees_fitness_probs = [bee.fitness/overall_fitness for bee in self.__employee_bees]
54+
55+
# Choose the employee bees positions proportional to their fitness
56+
choices = np.random.choice(self.__employee_bees, size=len(self.__employee_bees), p=employee_bees_fitness_probs)
57+
58+
# Onlooker phase
59+
# Explore new food sources based on the chosen employees' food sources
60+
for bee, choice in zip(self.__onlooker_bees, choices):
61+
bee.explore(choice.position, choice.value)
62+
63+
# Scout phase
64+
for bee in self.__employee_bees + self.__onlooker_bees:
65+
bee.reset()
66+
67+
# Update best food source
68+
current_best = min(self.__employee_bees + self.__onlooker_bees, key=lambda bee: bee.value)
69+
if current_best.value < best.value:
70+
best = deepcopy(current_best)
71+
LOGGER.info('Iteration %i Found new best solution="%s" at position="%s"', iteration+1, best.value, best.position)
72+
73+
# Add data for plotting
74+
self.__visualizer.add_data(employee_bees=self.__employee_bees, onlooker_bees=self.__onlooker_bees, best_position=best.position)
75+
76+
return best
77+
78+
def replay(self):
79+
"""
80+
Start the problems visualization.
81+
"""
82+
self.__visualizer.replay()

swarmlib/abc/bees/__init__.py

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# ------------------------------------------------------------------------------------------------------
2+
# Copyright (c) Leo Hanisch. All rights reserved.
3+
# Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information.
4+
# ------------------------------------------------------------------------------------------------------

0 commit comments

Comments
 (0)