Firefly Optimization Algorithm


Reading time: about 6 minutes
In [1]:
get_ipython().ast_node_interactivity = 'all'
import os
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
import math
import numba
matplotlib.rcParams['figure.dpi'] = 150

def make_ackley(dimensions, a=20, b=0.2, c=2 * 3.14):
    @numba.njit
    def inner(*args):
        assert len(args) == dimensions
        x = 0
        for d in args:
            x += d ** 2
        x *= 1 / dimensions
        x = math.sqrt(x)
        x *= -b
        result = -a * math.exp(x)
        
        x = 0
        for d in args:
            x += math.cos(d * c)
        x *= 1 / dimensions
        result -= math.exp(x)
        
        result += a
        result -= math.exp(1)
        
        return result
    return inner

ackley_1d = make_ackley(1)
ackley_2d = make_ackley(2)
In [6]:
ackley_2d = make_ackley(2)

RES = 10
graph = np.zeros((80 * RES, 80 * RES))

for x in range(80 * RES):
    for y in range(80 * RES):
        graph[y][x] = ackley_2d((x / RES) - 40, (y / RES) - 40)

plt.imshow(graph)
plt.colorbar()
Out [6]:
Out [6]:
Out:
<Figure size 900x600 with 2 Axes>
In [5]:
bounds = [(-40, 40), (-40, 40)]

def random_firefly(bounds):
    values = []
    for lower, upper in bounds:
        val = np.random.uniform(lower, upper)
        values.append(val)
    return np.array(values)

random_firefly(bounds)
random_firefly(bounds)
Out [5]:
array([ 23.00306207, -16.43112704])
Out [5]:
array([ -6.56225474, -29.61629188])
In [13]:
fireflies = []

for _ in range(5):
    fireflies.append(random_firefly(bounds))

RES = 10
graph = np.zeros((80 * RES, 80 * RES))

for x in range(80 * RES):
    for y in range(80 * RES):
        graph[y][x] = ackley_2d((x / RES) - 40, (y / RES) - 40)

plt.imshow(graph, norm=True)
_ = plt.scatter([(x[0] * RES) + 40 for x in fireflies], [(x[1] * RES) + 40 for x in fireflies], color="orange", zorder=2)
Out:
[ERROR] TypeError: 'norm' must be an instance of matplotlib.colors.Normalize or None, not a bool
Out:
<Figure size 900x600 with 1 Axes>
In []:
 

The following pages link here

Citation

If you find this work useful, please cite it as:
@article{yaltirakliwikifireflyoptimizationalgorithm,
  title   = "Firefly Optimization Algorithm",
  author  = "Yaltirakli, Gokberk",
  journal = "gkbrk.com",
  year    = "2024",
  url     = "https://www.gkbrk.com/wiki/firefly-optimization-algorithm/"
}
Not using BibTeX? Click here for more citation styles.
IEEE Citation
Gokberk Yaltirakli, "Firefly Optimization Algorithm", December, 2024. [Online]. Available: https://www.gkbrk.com/wiki/firefly-optimization-algorithm/. [Accessed Dec. 17, 2024].
APA Style
Yaltirakli, G. (2024, December 17). Firefly Optimization Algorithm. https://www.gkbrk.com/wiki/firefly-optimization-algorithm/
Bluebook Style
Gokberk Yaltirakli, Firefly Optimization Algorithm, GKBRK.COM (Dec. 17, 2024), https://www.gkbrk.com/wiki/firefly-optimization-algorithm/

Comments

© 2024 Gokberk Yaltirakli