metaheuristicpy 1.0.1__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.
- metaheuristicpy/__init__.py +1 -0
- metaheuristicpy/continous/__init__.py +1 -0
- metaheuristicpy/continous/benchmark_math/ArchimedesOptimizationAlgorithm.py +179 -0
- metaheuristicpy/continous/benchmark_math/BaseMetaPy.py +203 -0
- metaheuristicpy/continous/benchmark_math/BenchmarkFormulas.py +89 -0
- metaheuristicpy/continous/benchmark_math/EelGrouperOptimizer.py +144 -0
- metaheuristicpy/continous/benchmark_math/ExplorationEnchancedGreyWolfOptimizer.py +137 -0
- metaheuristicpy/continous/benchmark_math/GeneticAlgorithm.py +210 -0
- metaheuristicpy/continous/benchmark_math/GreaterCaneRatAlgorithm.py +203 -0
- metaheuristicpy/continous/benchmark_math/GreaterCaneRatAlgorithmOctave.py +306 -0
- metaheuristicpy/continous/benchmark_math/GreyWolfOptimizer.py +115 -0
- metaheuristicpy/continous/benchmark_math/InspiredGreyWolfOptimizer.py +143 -0
- metaheuristicpy/continous/benchmark_math/KomodoMlipirAlgorithm.py +250 -0
- metaheuristicpy/continous/benchmark_math/MemorybasedGreyWolfOptimizer.py +131 -0
- metaheuristicpy/continous/benchmark_math/ParticleSwarmOptimization.py +136 -0
- metaheuristicpy/continous/benchmark_math/SlimeMouldAlgorithm.py +148 -0
- metaheuristicpy/continous/benchmark_math/Utils.py +25 -0
- metaheuristicpy/continous/benchmark_math/WalrusOptimizationAlgorithm.py +163 -0
- metaheuristicpy/continous/benchmark_math/WhaleOptimizationAlgorithm.py +109 -0
- metaheuristicpy/continous/benchmark_math/__init__.py +13 -0
- metaheuristicpy/discrete/__init__.py +1 -0
- metaheuristicpy/discrete/feature_selection/BaseMetaFeatureSelection.py +242 -0
- metaheuristicpy/discrete/feature_selection/EelGrouperOptimizer.py +214 -0
- metaheuristicpy/discrete/feature_selection/ExplorationEnhancedGreyWolfOptimizer.py +185 -0
- metaheuristicpy/discrete/feature_selection/GeneticAlgorithm.py +156 -0
- metaheuristicpy/discrete/feature_selection/GreaterCaneRatAlgorithm.py +242 -0
- metaheuristicpy/discrete/feature_selection/GreyWolfOptimizer.py +170 -0
- metaheuristicpy/discrete/feature_selection/MemoryBasedGreyWolfOptimizer.py +187 -0
- metaheuristicpy/discrete/feature_selection/ParticleSwarmOptimization.py +132 -0
- metaheuristicpy/discrete/feature_selection/__init__.py +8 -0
- metaheuristicpy-1.0.1.dist-info/LICENSE +28 -0
- metaheuristicpy-1.0.1.dist-info/METADATA +47 -0
- metaheuristicpy-1.0.1.dist-info/RECORD +35 -0
- metaheuristicpy-1.0.1.dist-info/WHEEL +5 -0
- metaheuristicpy-1.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .discrete import *
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .benchmark_math import *
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
from .BaseMetaPy import BaseMetaPy
|
|
2
|
+
from .Utils import Utils
|
|
3
|
+
import random as rd
|
|
4
|
+
import numpy as np
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AOA(BaseMetaPy, Utils):
|
|
9
|
+
|
|
10
|
+
def __init__(self,
|
|
11
|
+
N_OBJECTS=15,
|
|
12
|
+
MAX_ITERATIONS=200,
|
|
13
|
+
MAX_KONVERGEN=15,
|
|
14
|
+
C1=2,
|
|
15
|
+
C2=6,
|
|
16
|
+
C3=2,
|
|
17
|
+
C4=0.5,
|
|
18
|
+
EXPLORATION_RATE=0.5,
|
|
19
|
+
OPTIMIZER_NAME='Archimedes Optimization Algorithm',
|
|
20
|
+
FUNCTIONS={
|
|
21
|
+
'name': 'sphere',
|
|
22
|
+
'dimension': 15,
|
|
23
|
+
'lowerbound': -100,
|
|
24
|
+
'upperbound': 100,
|
|
25
|
+
'objective': 'min'
|
|
26
|
+
},
|
|
27
|
+
):
|
|
28
|
+
super().__init__(
|
|
29
|
+
N_AGENTS=N_OBJECTS,
|
|
30
|
+
MAX_ITERATIONS=MAX_ITERATIONS,
|
|
31
|
+
MAX_KONVERGEN=MAX_KONVERGEN,
|
|
32
|
+
FUNCTIONS=FUNCTIONS,
|
|
33
|
+
DROP_KEY_AGENTS=None,
|
|
34
|
+
)
|
|
35
|
+
self.optimizer['name'] = OPTIMIZER_NAME
|
|
36
|
+
self.optimizer['params'].update({
|
|
37
|
+
"C1": C1,
|
|
38
|
+
"C2": C2,
|
|
39
|
+
"C3": C3,
|
|
40
|
+
"C4": C4,
|
|
41
|
+
"EXPLORATION_RATE": EXPLORATION_RATE,
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
def solve(self):
|
|
45
|
+
MAX_ITERATIONS = self.optimizer['params']['MAX_ITERATIONS']
|
|
46
|
+
|
|
47
|
+
best_agent = None
|
|
48
|
+
best_fitness_old = float("-inf")
|
|
49
|
+
|
|
50
|
+
# initialize agents
|
|
51
|
+
# 1. initialize agents
|
|
52
|
+
agents = self._initialize_agents()
|
|
53
|
+
agents = self.__initialize_objects_properties(agents)
|
|
54
|
+
|
|
55
|
+
# 2. evaluate fitness and select the best object
|
|
56
|
+
agents = self._evaluate_fitness(agents)
|
|
57
|
+
best_object = self._retrieve_best_agent(agents)
|
|
58
|
+
self.LIST_BEST_FITNESS.append(best_object['fitness'])
|
|
59
|
+
|
|
60
|
+
# 3. Optimization Process
|
|
61
|
+
konvergen = 0
|
|
62
|
+
for idx_iteration in range(MAX_ITERATIONS):
|
|
63
|
+
# 4. update object position
|
|
64
|
+
agents = self.__update_object_position(
|
|
65
|
+
agents, best_object, idx_iteration)
|
|
66
|
+
|
|
67
|
+
# 5. Evaluate object fitness
|
|
68
|
+
agents = self._evaluate_fitness(agents)
|
|
69
|
+
|
|
70
|
+
# 6. select object with best fitness
|
|
71
|
+
best_object = self._retrieve_best_agent(agents)
|
|
72
|
+
|
|
73
|
+
# 6. check konvergensi
|
|
74
|
+
is_break, best_fitness_old, konvergen = self._check_convergence(
|
|
75
|
+
agents, best_fitness_old, konvergen, idx_iteration)
|
|
76
|
+
best_agent = best_object
|
|
77
|
+
if is_break:
|
|
78
|
+
break
|
|
79
|
+
|
|
80
|
+
self._IS_SOLVE = True
|
|
81
|
+
|
|
82
|
+
return best_agent
|
|
83
|
+
|
|
84
|
+
def __initialize_objects_properties(self, agents):
|
|
85
|
+
"""
|
|
86
|
+
Function for initialize object densities, volume, and acceleration
|
|
87
|
+
"""
|
|
88
|
+
N_DIMENSION = self.optimizer['params']['FUNCTIONS']['dimension']
|
|
89
|
+
LOWER_BOUND = self.optimizer['params']['FUNCTIONS']['lowerbound']
|
|
90
|
+
UPPER_BOUND = self.optimizer['params']['FUNCTIONS']['upperbound']
|
|
91
|
+
for idx_agent, agent in enumerate(agents):
|
|
92
|
+
agents[idx_agent].update({
|
|
93
|
+
'densities': np.array([np.random.random() for _ in range(N_DIMENSION)]),
|
|
94
|
+
'volume': np.array([np.random.random() for _ in range(N_DIMENSION)]),
|
|
95
|
+
'acceleration': np.array([
|
|
96
|
+
np.random.random() * (UPPER_BOUND - LOWER_BOUND) + LOWER_BOUND
|
|
97
|
+
for d in range(N_DIMENSION)
|
|
98
|
+
]
|
|
99
|
+
),
|
|
100
|
+
})
|
|
101
|
+
return agents
|
|
102
|
+
|
|
103
|
+
def __update_object_position(self, agents, best_object, iteration):
|
|
104
|
+
def normalize_acceleration(vector_acceleration):
|
|
105
|
+
U = 0.9
|
|
106
|
+
L = 0.1
|
|
107
|
+
normalize_vector = U * ((vector_acceleration - np.min(vector_acceleration))/(
|
|
108
|
+
np.max(vector_acceleration) - np.min(vector_acceleration))) + L
|
|
109
|
+
return normalize_vector
|
|
110
|
+
|
|
111
|
+
MAX_ITERATIONS = self.optimizer['params']['MAX_ITERATIONS']
|
|
112
|
+
EXPLORATION_RATE = self.optimizer['params']['EXPLORATION_RATE']
|
|
113
|
+
C1 = self.optimizer['params']['C1']
|
|
114
|
+
C2 = self.optimizer['params']['C2']
|
|
115
|
+
C3 = self.optimizer['params']['C3']
|
|
116
|
+
C4 = self.optimizer['params']['C4']
|
|
117
|
+
|
|
118
|
+
for idx_agent, agent in enumerate(agents):
|
|
119
|
+
# update density and volume of each object
|
|
120
|
+
agents[idx_agent]['densities'] = agent['densities'] + np.random.random() * \
|
|
121
|
+
(best_object['densities'] - agent['densities'])
|
|
122
|
+
agents[idx_agent]['volume'] = agent['volume'] + \
|
|
123
|
+
np.random.random() * (best_object['volume'] - agent['volume'])
|
|
124
|
+
|
|
125
|
+
# update transfer and density decreasing factors TF and d
|
|
126
|
+
TF = math.exp((iteration - MAX_ITERATIONS)/MAX_ITERATIONS)
|
|
127
|
+
d = math.exp((MAX_ITERATIONS-iteration) /
|
|
128
|
+
MAX_ITERATIONS) - (iteration/MAX_ITERATIONS)
|
|
129
|
+
|
|
130
|
+
# check exploration or exploitation based on TF
|
|
131
|
+
if TF <= EXPLORATION_RATE:
|
|
132
|
+
# exploration
|
|
133
|
+
# get random object
|
|
134
|
+
random_agent = self.__generate_random_agent(agents, agent)
|
|
135
|
+
|
|
136
|
+
# update acceleration
|
|
137
|
+
agents[idx_agent]['acceleration'] = (random_agent['densities'] + random_agent['volume'] *
|
|
138
|
+
random_agent['acceleration'])/(agents[idx_agent]['densities'] * agents[idx_agent]['volume'])
|
|
139
|
+
|
|
140
|
+
# normalize acceleration
|
|
141
|
+
agents[idx_agent]['acceleration'] = normalize_acceleration(
|
|
142
|
+
agents[idx_agent]['acceleration'])
|
|
143
|
+
|
|
144
|
+
# update position
|
|
145
|
+
agents[idx_agent]['position'] = agent['position'] + C1 * np.random.random(
|
|
146
|
+
) * agent['acceleration'] * d * (random_agent['position'] - agent['position'])
|
|
147
|
+
|
|
148
|
+
else:
|
|
149
|
+
# exploitation
|
|
150
|
+
|
|
151
|
+
# update acceleration
|
|
152
|
+
agents[idx_agent]['acceleration'] = (best_object['densities'] + best_object['volume'] * best_object['acceleration'])/(
|
|
153
|
+
agents[idx_agent]['densities'] * agents[idx_agent]['volume'])
|
|
154
|
+
|
|
155
|
+
# normalize acceleration
|
|
156
|
+
agents[idx_agent]['acceleration'] = normalize_acceleration(
|
|
157
|
+
agents[idx_agent]['acceleration'])
|
|
158
|
+
|
|
159
|
+
# update direction flag F
|
|
160
|
+
P = 2 * np.random.random() - C4
|
|
161
|
+
F = -1
|
|
162
|
+
if P <= 0.5:
|
|
163
|
+
F = 1
|
|
164
|
+
|
|
165
|
+
# update position
|
|
166
|
+
T = C3 * TF
|
|
167
|
+
agents[idx_agent]['position'] = best_object['position'] + F * C2 * np.random.random(
|
|
168
|
+
) * agent['acceleration'] * d * (T * best_object['position'] - agent['position'])
|
|
169
|
+
|
|
170
|
+
# apply boundaries for each agent new position
|
|
171
|
+
agents[idx_agent] = self._adjust_boundaries([agents[idx_agent]])[0]
|
|
172
|
+
return agents
|
|
173
|
+
|
|
174
|
+
def __generate_random_agent(self, agents, agent):
|
|
175
|
+
N_AGENTS = self.optimizer['params']['N_AGENTS']
|
|
176
|
+
random_agent = agents[rd.randint(0, N_AGENTS-1)]
|
|
177
|
+
while random_agent['name'] == agent['name']:
|
|
178
|
+
random_agent = agents[rd.randint(0, N_AGENTS-1)]
|
|
179
|
+
return random_agent
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from .BenchmarkFormulas import BenchmarkMathematicFormulas
|
|
3
|
+
import random as rd
|
|
4
|
+
import math
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class BaseMetaPy(BenchmarkMathematicFormulas):
|
|
8
|
+
def __init__(self,
|
|
9
|
+
N_AGENTS,
|
|
10
|
+
MAX_ITERATIONS,
|
|
11
|
+
MAX_KONVERGEN,
|
|
12
|
+
FUNCTIONS,
|
|
13
|
+
**kwargs):
|
|
14
|
+
"""
|
|
15
|
+
Base class for other metaheuristic classes
|
|
16
|
+
|
|
17
|
+
<Args>
|
|
18
|
+
- N_AGENTS <Integer>: number of population or swarm size
|
|
19
|
+
- MAX_ITERATIONS <Integer>: number of maximum iteration
|
|
20
|
+
- MAX_KONVERGEN <Integer>: The iteration process will be stoped if the fitness value is the same for MAX_KONVERGEN consecutive iterations
|
|
21
|
+
- FUNCTIONS <String>: Name of benchmark mathematical formula
|
|
22
|
+
-> Options: sphere, rastrigin, griewank, ackley_function, rosenbrock_function, schwefel_function, levi_function, zakharov_function, sum_of_different_powers_function, michalewicz_function, easom_function, six_hump_camel_function, beale_function
|
|
23
|
+
"""
|
|
24
|
+
self.optimizer = {
|
|
25
|
+
"name": None,
|
|
26
|
+
"params": {
|
|
27
|
+
'N_AGENTS': N_AGENTS,
|
|
28
|
+
'MAX_ITERATIONS': MAX_ITERATIONS,
|
|
29
|
+
"MAX_KONVERGEN": MAX_KONVERGEN,
|
|
30
|
+
"FUNCTIONS": FUNCTIONS
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
self.DROP_KEY_AGENTS = kwargs['DROP_KEY_AGENTS']
|
|
34
|
+
self._IS_SOLVE = False
|
|
35
|
+
self.__retrieve_fitness_function(
|
|
36
|
+
function_name=self.optimizer['params']['FUNCTIONS']['name']
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
# record best fitness each iterations:
|
|
40
|
+
self.LIST_BEST_FITNESS = list()
|
|
41
|
+
|
|
42
|
+
def solve(self):
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
def __retrieve_fitness_function(self, function_name):
|
|
46
|
+
self.FITNESS_FUNCTION = super().sphere
|
|
47
|
+
if function_name == "rastrigin":
|
|
48
|
+
self.FITNESS_FUNCTION = super().rastrigin
|
|
49
|
+
elif function_name == "griewank":
|
|
50
|
+
self.FITNESS_FUNCTION = super().griewank
|
|
51
|
+
elif function_name == "ackley_function":
|
|
52
|
+
self.FITNESS_FUNCTION = super().ackley_function
|
|
53
|
+
elif function_name == "rosenbrock_function":
|
|
54
|
+
self.FITNESS_FUNCTION = super().rosenbrock_function
|
|
55
|
+
elif function_name == "schwefel_function":
|
|
56
|
+
self.FITNESS_FUNCTION = super().schwefel_function
|
|
57
|
+
elif function_name == "levi_function":
|
|
58
|
+
self.FITNESS_FUNCTION = super().levi_function
|
|
59
|
+
elif function_name == "zakharov_function":
|
|
60
|
+
self.FITNESS_FUNCTION = super().zakharov_function
|
|
61
|
+
elif function_name == "sum_of_different_powers_function":
|
|
62
|
+
self.FITNESS_FUNCTION = super().sum_of_different_powers_function
|
|
63
|
+
elif function_name == "michalewicz_function":
|
|
64
|
+
self.FITNESS_FUNCTION = super().michalewicz_function
|
|
65
|
+
elif function_name == "easom_function":
|
|
66
|
+
self.FITNESS_FUNCTION = super().easom_function
|
|
67
|
+
elif function_name == "six_hump_camel_function":
|
|
68
|
+
self.FITNESS_FUNCTION = super().six_hump_camel_function
|
|
69
|
+
elif function_name == "beale_function":
|
|
70
|
+
self.FITNESS_FUNCTION = super().beale_function
|
|
71
|
+
|
|
72
|
+
def _initialize_agents(self, new_N_AGENTS=None):
|
|
73
|
+
"""
|
|
74
|
+
Function untuk inisialisasi agents sesuai jumlah dimensi
|
|
75
|
+
"""
|
|
76
|
+
N_AGENTS = self.optimizer['params']['N_AGENTS']
|
|
77
|
+
if new_N_AGENTS is not None:
|
|
78
|
+
N_AGENTS = new_N_AGENTS
|
|
79
|
+
N_DIMENSION = self.optimizer['params']['FUNCTIONS']['dimension']
|
|
80
|
+
LOWER_BOUND = self.optimizer['params']['FUNCTIONS']['lowerbound']
|
|
81
|
+
UPPER_BOUND = self.optimizer['params']['FUNCTIONS']['upperbound']
|
|
82
|
+
OBJECTIVE = self.optimizer['params']['FUNCTIONS']['objective']
|
|
83
|
+
|
|
84
|
+
agents = [None for _ in range(N_AGENTS)]
|
|
85
|
+
for idx_agent in range(N_AGENTS):
|
|
86
|
+
random_position = np.array(
|
|
87
|
+
[
|
|
88
|
+
np.random.random() * (UPPER_BOUND - LOWER_BOUND) + LOWER_BOUND
|
|
89
|
+
for d in range(N_DIMENSION)
|
|
90
|
+
]
|
|
91
|
+
)
|
|
92
|
+
agents[idx_agent] = {
|
|
93
|
+
"name": f"Agent-{idx_agent}",
|
|
94
|
+
"position": random_position,
|
|
95
|
+
|
|
96
|
+
}
|
|
97
|
+
# update inisialisasi nilai fitness
|
|
98
|
+
fitness = {
|
|
99
|
+
'fitness': float("-inf")
|
|
100
|
+
}
|
|
101
|
+
agents[idx_agent].update()
|
|
102
|
+
if OBJECTIVE == 'min':
|
|
103
|
+
fitness = {
|
|
104
|
+
'fitness': float("inf")
|
|
105
|
+
}
|
|
106
|
+
agents[idx_agent].update(fitness)
|
|
107
|
+
|
|
108
|
+
# update inisialisasi nilai PBest
|
|
109
|
+
agents[idx_agent].update({
|
|
110
|
+
'PBest': {
|
|
111
|
+
'position': random_position,
|
|
112
|
+
**fitness
|
|
113
|
+
}
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
return agents
|
|
117
|
+
|
|
118
|
+
def _adjust_boundaries(self, agents):
|
|
119
|
+
BATAS_BAWAH = self.optimizer['params']['FUNCTIONS']['lowerbound']
|
|
120
|
+
BATAS_ATAS = self.optimizer['params']['FUNCTIONS']['upperbound']
|
|
121
|
+
for idx_agent, agent in enumerate(agents):
|
|
122
|
+
agents[idx_agent]['position'] = np.clip(
|
|
123
|
+
agents[idx_agent]['position'], BATAS_BAWAH, BATAS_ATAS)
|
|
124
|
+
return agents
|
|
125
|
+
|
|
126
|
+
def _evaluate_fitness(self, agents):
|
|
127
|
+
"""
|
|
128
|
+
Fungsi untuk evaluasi fitness berdasarkan fungsi fitness yang diinputkan
|
|
129
|
+
F(P[i]) = fitness_function(P[i])
|
|
130
|
+
fitness_function:
|
|
131
|
+
-sphere: Sphere Function
|
|
132
|
+
-rastrigin: Rastrigin Function
|
|
133
|
+
-griewank: Griewank Function
|
|
134
|
+
dst
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
for idx_agent, agent in enumerate(agents):
|
|
138
|
+
agents[idx_agent]['fitness'] = self.FITNESS_FUNCTION(
|
|
139
|
+
agent['position'])
|
|
140
|
+
return agents
|
|
141
|
+
|
|
142
|
+
def _retrieve_best_agent(self, agents):
|
|
143
|
+
"""
|
|
144
|
+
Function untuk retrieve best agent pada iterasi terakhir setelah di solve
|
|
145
|
+
"""
|
|
146
|
+
OBJECTIVE = self.optimizer['params']['FUNCTIONS']['objective']
|
|
147
|
+
|
|
148
|
+
fitness = np.array([
|
|
149
|
+
agent_data['fitness'] for agent_data in agents
|
|
150
|
+
])
|
|
151
|
+
best_indices_agents = np.argmin(fitness)
|
|
152
|
+
if OBJECTIVE == 'max':
|
|
153
|
+
best_indices_agents = np.argmax(fitness)
|
|
154
|
+
|
|
155
|
+
return agents[best_indices_agents]
|
|
156
|
+
|
|
157
|
+
def _retrieve_worst_agent(self, agents):
|
|
158
|
+
"""
|
|
159
|
+
Function untuk retrieve worst agent pada iterasi terakhir setelah di solve
|
|
160
|
+
"""
|
|
161
|
+
OBJECTIVE = self.optimizer['params']['FUNCTIONS']['objective']
|
|
162
|
+
|
|
163
|
+
fitness = np.array([
|
|
164
|
+
agent_data['fitness'] for agent_data in agents
|
|
165
|
+
])
|
|
166
|
+
worst_indices_agents = np.argmax(fitness)
|
|
167
|
+
if OBJECTIVE == 'max':
|
|
168
|
+
worst_indices_agents = np.argmin(fitness)
|
|
169
|
+
|
|
170
|
+
return agents[worst_indices_agents]
|
|
171
|
+
|
|
172
|
+
def _check_convergence(self, agents, best_fitness_old, konvergen, idx_iteration):
|
|
173
|
+
MAX_KONVERGEN = self.optimizer['params']['MAX_KONVERGEN']
|
|
174
|
+
OBJECTIVE = self.optimizer['params']['FUNCTIONS']['objective']
|
|
175
|
+
is_break = False
|
|
176
|
+
|
|
177
|
+
# retrieve semua nilai fitness dari agents
|
|
178
|
+
fitnesses = [agent_data['fitness'] for agent_data in agents]
|
|
179
|
+
best_fitness = min(fitnesses)
|
|
180
|
+
if OBJECTIVE == 'max':
|
|
181
|
+
best_fitness = max(fitnesses)
|
|
182
|
+
|
|
183
|
+
self.LIST_BEST_FITNESS.append(best_fitness)
|
|
184
|
+
if math.isclose(best_fitness_old, best_fitness, rel_tol=1e-9, abs_tol=1e-9):
|
|
185
|
+
konvergen += 1
|
|
186
|
+
else:
|
|
187
|
+
konvergen = 0
|
|
188
|
+
print(
|
|
189
|
+
f'Generation {idx_iteration + 1}, Best Fitness: {best_fitness}, Konvergen: {konvergen}')
|
|
190
|
+
best_fitness_old = best_fitness
|
|
191
|
+
if konvergen == MAX_KONVERGEN:
|
|
192
|
+
print(f'Convergent is reached = {MAX_KONVERGEN}')
|
|
193
|
+
is_break = True
|
|
194
|
+
return is_break, best_fitness_old, konvergen
|
|
195
|
+
|
|
196
|
+
def get_optimizer_params(self):
|
|
197
|
+
return self.optimizer['params']
|
|
198
|
+
|
|
199
|
+
def get_fitness_values(self):
|
|
200
|
+
if self._IS_SOLVE:
|
|
201
|
+
return self.LIST_BEST_FITNESS
|
|
202
|
+
else:
|
|
203
|
+
raise Exception("Please solve the problem first!")
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class BenchmarkMathematicFormulas:
|
|
5
|
+
|
|
6
|
+
def __init__(self):
|
|
7
|
+
pass
|
|
8
|
+
|
|
9
|
+
# Define the benchmark functions
|
|
10
|
+
@staticmethod
|
|
11
|
+
def sphere(x):
|
|
12
|
+
return np.sum(x**2)
|
|
13
|
+
|
|
14
|
+
@staticmethod
|
|
15
|
+
def rastrigin(x):
|
|
16
|
+
d = len(x)
|
|
17
|
+
return 10*d + np.sum(x**2 - 10*np.cos(2*np.pi*x))
|
|
18
|
+
|
|
19
|
+
@staticmethod
|
|
20
|
+
def griewank(x):
|
|
21
|
+
d = len(x)
|
|
22
|
+
s = np.sum(x**2)
|
|
23
|
+
p = np.prod(np.cos(x / np.sqrt(np.arange(1, d+1))))
|
|
24
|
+
return 1 + s/4000 - p
|
|
25
|
+
|
|
26
|
+
@staticmethod
|
|
27
|
+
def ackley_function(x, a=20, b=0.2, c=2 * np.pi):
|
|
28
|
+
"""
|
|
29
|
+
Ackley Function as fitness function.
|
|
30
|
+
|
|
31
|
+
Parameters:
|
|
32
|
+
- x : array-like, the input array of points.
|
|
33
|
+
- a, b, c : constants, typically set to a=20, b=0.2, c=2π.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
- f(x) : The value of the Ackley function at point x.
|
|
37
|
+
"""
|
|
38
|
+
n = len(x)
|
|
39
|
+
sum1 = np.sum(x ** 2)
|
|
40
|
+
sum2 = np.sum(np.cos(c * x))
|
|
41
|
+
|
|
42
|
+
term1 = -a * np.exp(-b * np.sqrt(sum1 / n))
|
|
43
|
+
term2 = -np.exp(sum2 / n)
|
|
44
|
+
|
|
45
|
+
return term1 + term2 + a + np.e
|
|
46
|
+
|
|
47
|
+
@staticmethod
|
|
48
|
+
def rosenbrock_function(x):
|
|
49
|
+
return sum(100 * (x[1:] - x[:-1]**2)**2 + (x[:-1] - 1)**2)
|
|
50
|
+
|
|
51
|
+
@staticmethod
|
|
52
|
+
def schwefel_function(x):
|
|
53
|
+
return 418.9829 * len(x) - sum(x * np.sin(np.sqrt(np.abs(x))))
|
|
54
|
+
|
|
55
|
+
@staticmethod
|
|
56
|
+
def levi_function(x):
|
|
57
|
+
term1 = np.sin(3 * np.pi * x[0]) ** 2
|
|
58
|
+
term2 = sum((x[:-1] - 1) ** 2 * (1 + np.sin(3 * np.pi * x[1:]) ** 2))
|
|
59
|
+
term3 = (x[-1] - 1) ** 2 * (1 + np.sin(2 * np.pi * x[-1]) ** 2)
|
|
60
|
+
return term1 + term2 + term3
|
|
61
|
+
|
|
62
|
+
@staticmethod
|
|
63
|
+
def zakharov_function(x):
|
|
64
|
+
sum1 = sum(x**2)
|
|
65
|
+
sum2 = sum(0.5 * (i + 1) * x[i] for i in range(len(x)))
|
|
66
|
+
return sum1 + sum2**2 + sum2**4
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def sum_of_different_powers_function(x):
|
|
70
|
+
return sum(np.abs(x[i]) ** (i + 2) for i in range(len(x)))
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def michalewicz_function(x, m=10):
|
|
74
|
+
return -sum(np.sin(x[i]) * (np.sin((i + 1) * x[i] ** 2 / np.pi)) ** (2 * m) for i in range(len(x)))
|
|
75
|
+
|
|
76
|
+
@staticmethod
|
|
77
|
+
def easom_function(x):
|
|
78
|
+
return -np.cos(x[0]) * np.cos(x[1]) * np.exp(-((x[0] - np.pi)**2 + (x[1] - np.pi)**2))
|
|
79
|
+
|
|
80
|
+
@staticmethod
|
|
81
|
+
def six_hump_camel_function(x):
|
|
82
|
+
x1, x2 = x[0], x[1]
|
|
83
|
+
return (4 - 2.1 * x1**2 + (x1**4) / 3) * x1**2 + x1 * x2 + (-4 + 4 * x2**2) * x2**2
|
|
84
|
+
|
|
85
|
+
@staticmethod
|
|
86
|
+
def beale_function(x):
|
|
87
|
+
x1, x2 = x[0], x[1]
|
|
88
|
+
return (1.5 - x1 + x1 * x2)**2 + (2.25 - x1 + x1 * x2**2)**2 + (2.625 - x1 + x1 * x2**3)**2
|
|
89
|
+
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
from .BaseMetaPy import BaseMetaPy
|
|
2
|
+
from .Utils import Utils
|
|
3
|
+
import random as rd
|
|
4
|
+
import numpy as np
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class EGO(BaseMetaPy, Utils):
|
|
9
|
+
|
|
10
|
+
def __init__(self,
|
|
11
|
+
N_EELS=150,
|
|
12
|
+
MAX_ITERATIONS=200,
|
|
13
|
+
MAX_KONVERGEN=15,
|
|
14
|
+
OPTIMIZER_NAME='Eel and Grouper Optimizer',
|
|
15
|
+
FUNCTIONS={
|
|
16
|
+
'name': 'sphere',
|
|
17
|
+
'dimension': 15,
|
|
18
|
+
'lowerbound': -100,
|
|
19
|
+
'upperbound': 100,
|
|
20
|
+
'objective': 'min'
|
|
21
|
+
},
|
|
22
|
+
):
|
|
23
|
+
"""
|
|
24
|
+
Eel and Grouper Optimizer (EGO)
|
|
25
|
+
- Inspiration: Interaction and Foraging Strategy of Eels and Groupers in Marine Ecosystems
|
|
26
|
+
"""
|
|
27
|
+
super().__init__(
|
|
28
|
+
N_AGENTS=N_EELS,
|
|
29
|
+
MAX_ITERATIONS=MAX_ITERATIONS,
|
|
30
|
+
MAX_KONVERGEN=MAX_KONVERGEN,
|
|
31
|
+
FUNCTIONS=FUNCTIONS,
|
|
32
|
+
DROP_KEY_AGENTS=None
|
|
33
|
+
)
|
|
34
|
+
self.optimizer['name'] = OPTIMIZER_NAME
|
|
35
|
+
|
|
36
|
+
def solve(self):
|
|
37
|
+
MAX_ITERATIONS = self.optimizer['params']['MAX_ITERATIONS']
|
|
38
|
+
|
|
39
|
+
# initialize agents
|
|
40
|
+
# 1. initialize agents
|
|
41
|
+
agents = self._initialize_agents()
|
|
42
|
+
|
|
43
|
+
# 2. evaluate agents
|
|
44
|
+
XPrey, XGrouper, XEel = self.__divide_eel_grouper(agents)
|
|
45
|
+
best_fitness_old = XPrey['fitness']
|
|
46
|
+
self.LIST_BEST_FITNESS.append(XPrey['fitness'])
|
|
47
|
+
|
|
48
|
+
# 3. Optimization Process
|
|
49
|
+
konvergen = 0
|
|
50
|
+
for idx_iteration in range(MAX_ITERATIONS):
|
|
51
|
+
|
|
52
|
+
# update a and starvation rate
|
|
53
|
+
a = 2 - 2 * (idx_iteration/MAX_ITERATIONS)
|
|
54
|
+
starvation_rate = 100 * (idx_iteration/MAX_ITERATIONS)
|
|
55
|
+
|
|
56
|
+
# update position
|
|
57
|
+
agents = self.__update_position(
|
|
58
|
+
agents, XPrey, XGrouper, XEel, a, starvation_rate)
|
|
59
|
+
|
|
60
|
+
# apply boundaries
|
|
61
|
+
agents = self._adjust_boundaries(agents)
|
|
62
|
+
|
|
63
|
+
# Evaluate agents
|
|
64
|
+
agents = self._evaluate_fitness(agents)
|
|
65
|
+
|
|
66
|
+
# retrieve best agent
|
|
67
|
+
XPrey = self._retrieve_best_agent(agents)
|
|
68
|
+
|
|
69
|
+
# 6. check konvergensi
|
|
70
|
+
is_break, best_fitness_old, konvergen = self._check_convergence(
|
|
71
|
+
agents, best_fitness_old, konvergen, idx_iteration)
|
|
72
|
+
if is_break:
|
|
73
|
+
break
|
|
74
|
+
|
|
75
|
+
self._IS_SOLVE = True
|
|
76
|
+
|
|
77
|
+
return XPrey
|
|
78
|
+
|
|
79
|
+
def __divide_eel_grouper(self, agents):
|
|
80
|
+
"""
|
|
81
|
+
Bagi agents ke dalam tiga kelompok: XPrey, XGrouper, XEel
|
|
82
|
+
|
|
83
|
+
"""
|
|
84
|
+
N_AGENTS = self.optimizer['params']['N_AGENTS']
|
|
85
|
+
XPrey = agents[rd.randint(0, N_AGENTS-1)]
|
|
86
|
+
XGrouper = agents[rd.randint(0, N_AGENTS-1)]
|
|
87
|
+
XEel = agents[rd.randint(0, N_AGENTS-1)]
|
|
88
|
+
return XPrey, XGrouper, XEel
|
|
89
|
+
|
|
90
|
+
def __update_position(self, agents, XPrey, XGrouper, XEel, a, starvation_rate):
|
|
91
|
+
|
|
92
|
+
for idx_agent, agent in enumerate(agents):
|
|
93
|
+
# update r1, r2, r3, r4, C1, C2, and p
|
|
94
|
+
r1 = np.random.random()
|
|
95
|
+
r2 = np.random.random()
|
|
96
|
+
r3 = (a-2) * r1 + 2
|
|
97
|
+
|
|
98
|
+
# get random agent
|
|
99
|
+
random_agent = self.__generate_random_agent(agents)
|
|
100
|
+
|
|
101
|
+
# update agent position of grouper
|
|
102
|
+
C1 = 2 * a * r1 - a
|
|
103
|
+
C2 = 2*r1
|
|
104
|
+
D_grouper = np.abs(agent['position'] -
|
|
105
|
+
C2 * random_agent['position'])
|
|
106
|
+
agents[idx_agent]['position'] = random_agent['position'] - \
|
|
107
|
+
C1 * D_grouper
|
|
108
|
+
|
|
109
|
+
# calculate fitness of new position
|
|
110
|
+
agents[idx_agent] = self._evaluate_fitness([agents[idx_agent]])[0]
|
|
111
|
+
|
|
112
|
+
# change this to > for maximation
|
|
113
|
+
if agents[idx_agent]['fitness'] < XGrouper['fitness']:
|
|
114
|
+
XGrouper = agents[idx_agent].copy()
|
|
115
|
+
|
|
116
|
+
# update XEel position
|
|
117
|
+
r4 = 100 * np.random.random()
|
|
118
|
+
C2 = 2 * r1
|
|
119
|
+
if r4 <= starvation_rate:
|
|
120
|
+
XEel['position'] = C2*XGrouper['position']
|
|
121
|
+
else:
|
|
122
|
+
random_agent = self.__generate_random_agent(agents)
|
|
123
|
+
XEel['position'] = C2 * random_agent['position']
|
|
124
|
+
|
|
125
|
+
# update variabel X1 and X2
|
|
126
|
+
b = a*r2
|
|
127
|
+
Distance2Eel = np.abs(XEel['position'] - XPrey['position'])
|
|
128
|
+
X_1 = math.exp(b*r3) * math.sin(2*math.pi) * C1 * \
|
|
129
|
+
Distance2Eel + XEel['position']
|
|
130
|
+
|
|
131
|
+
Distance2Grouper = np.abs(XGrouper['position'] - XPrey['position'])
|
|
132
|
+
X_2 = XGrouper['position'] + C1 * Distance2Grouper
|
|
133
|
+
|
|
134
|
+
if np.random.random() < 0.5:
|
|
135
|
+
agents[idx_agent]['position'] = (0.8*X_1 + 0.2*X_2)/2
|
|
136
|
+
else:
|
|
137
|
+
agents[idx_agent]['position'] = (0.2*X_1 + 0.8*X_2)/2
|
|
138
|
+
|
|
139
|
+
return agents
|
|
140
|
+
|
|
141
|
+
def __generate_random_agent(self, agents):
|
|
142
|
+
N_AGENTS = self.optimizer['params']['N_AGENTS']
|
|
143
|
+
random_agent = agents[rd.randint(0, N_AGENTS-1)]
|
|
144
|
+
return random_agent
|