metaheuristicpy 1.0.1__tar.gz

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.
Files changed (40) hide show
  1. metaheuristicpy-1.0.1/LICENSE +28 -0
  2. metaheuristicpy-1.0.1/PKG-INFO +47 -0
  3. metaheuristicpy-1.0.1/README.md +18 -0
  4. metaheuristicpy-1.0.1/metaheuristicpy/__init__.py +1 -0
  5. metaheuristicpy-1.0.1/metaheuristicpy/continous/__init__.py +1 -0
  6. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/ArchimedesOptimizationAlgorithm.py +179 -0
  7. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/BaseMetaPy.py +203 -0
  8. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/BenchmarkFormulas.py +89 -0
  9. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/EelGrouperOptimizer.py +144 -0
  10. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/ExplorationEnchancedGreyWolfOptimizer.py +137 -0
  11. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/GeneticAlgorithm.py +210 -0
  12. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/GreaterCaneRatAlgorithm.py +203 -0
  13. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/GreaterCaneRatAlgorithmOctave.py +306 -0
  14. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/GreyWolfOptimizer.py +115 -0
  15. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/InspiredGreyWolfOptimizer.py +143 -0
  16. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/KomodoMlipirAlgorithm.py +250 -0
  17. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/MemorybasedGreyWolfOptimizer.py +131 -0
  18. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/ParticleSwarmOptimization.py +136 -0
  19. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/SlimeMouldAlgorithm.py +148 -0
  20. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/Utils.py +25 -0
  21. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/WalrusOptimizationAlgorithm.py +163 -0
  22. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/WhaleOptimizationAlgorithm.py +109 -0
  23. metaheuristicpy-1.0.1/metaheuristicpy/continous/benchmark_math/__init__.py +13 -0
  24. metaheuristicpy-1.0.1/metaheuristicpy/discrete/__init__.py +1 -0
  25. metaheuristicpy-1.0.1/metaheuristicpy/discrete/feature_selection/BaseMetaFeatureSelection.py +242 -0
  26. metaheuristicpy-1.0.1/metaheuristicpy/discrete/feature_selection/EelGrouperOptimizer.py +214 -0
  27. metaheuristicpy-1.0.1/metaheuristicpy/discrete/feature_selection/ExplorationEnhancedGreyWolfOptimizer.py +185 -0
  28. metaheuristicpy-1.0.1/metaheuristicpy/discrete/feature_selection/GeneticAlgorithm.py +156 -0
  29. metaheuristicpy-1.0.1/metaheuristicpy/discrete/feature_selection/GreaterCaneRatAlgorithm.py +242 -0
  30. metaheuristicpy-1.0.1/metaheuristicpy/discrete/feature_selection/GreyWolfOptimizer.py +170 -0
  31. metaheuristicpy-1.0.1/metaheuristicpy/discrete/feature_selection/MemoryBasedGreyWolfOptimizer.py +187 -0
  32. metaheuristicpy-1.0.1/metaheuristicpy/discrete/feature_selection/ParticleSwarmOptimization.py +132 -0
  33. metaheuristicpy-1.0.1/metaheuristicpy/discrete/feature_selection/__init__.py +8 -0
  34. metaheuristicpy-1.0.1/metaheuristicpy.egg-info/PKG-INFO +47 -0
  35. metaheuristicpy-1.0.1/metaheuristicpy.egg-info/SOURCES.txt +38 -0
  36. metaheuristicpy-1.0.1/metaheuristicpy.egg-info/dependency_links.txt +1 -0
  37. metaheuristicpy-1.0.1/metaheuristicpy.egg-info/requires.txt +7 -0
  38. metaheuristicpy-1.0.1/metaheuristicpy.egg-info/top_level.txt +1 -0
  39. metaheuristicpy-1.0.1/setup.cfg +4 -0
  40. metaheuristicpy-1.0.1/setup.py +72 -0
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2025, I Made Satria Bimantara
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.1
2
+ Name: metaheuristicpy
3
+ Version: 1.0.1
4
+ Summary: A Python-based package of Metaheuristic Optimization Algorithms for Solving Continous and Discrete Optimization Problem
5
+ Author: I Made Satria Bimantara
6
+ Author-email: satriabimantara.imd@gmail.com
7
+ Keywords: Optimization,Metaheuristic,Swarm Intelligence,Evolutionary Algorithm,Soft Computing
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: BSD License
12
+ Classifier: Framework :: Jupyter
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Natural Language :: Indonesian
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
19
+ Requires-Python: >=3.8
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: pandas==1.5.3
23
+ Requires-Dist: numpy==1.24.2
24
+ Requires-Dist: openpyxl==3.1.0
25
+ Requires-Dist: matplotlib==3.6.3
26
+ Requires-Dist: seaborn==0.11.1
27
+ Requires-Dist: scipy==1.10.0
28
+ Requires-Dist: scikit-learn==1.2.1
29
+
30
+ # metaheuristicpy
31
+
32
+ A Python-based package of Metaheuristic Optimization Algorithms for Solving Continous and Discrete Optimization Problem
33
+
34
+ <hr>
35
+
36
+ # Cite
37
+
38
+ If you think this package is useful, please cite this paper in your project: <br>
39
+ [1] Bimantara, I.M.S., Sanjaya ER, N., Purwitasari, D. (2023). Character Entity Recognition Using Hybrid Binary-Particle Swarm Optimization and Conditional Random Field on Balinese Folklore Text. In: Delir Haghighi, P., et al. Information Integration and Web Intelligence. iiWAS 2023. Lecture Notes in Computer Science, vol 14416. Springer, Cham. https://doi.org/10.1007/978-3-031-48316-5_15 <br>
40
+ [2] Bimantara, I. M. S., & Widiartha, I. M. (2023). Optimization of K-Means Clustering Using Particle Swarm Optimization Algorithm for Grouping Traveler Reviews Data on Tripadvisor Sites. Jurnal Ilmiah Kursor, 12(1), 1-10. <br>
41
+ [3] Supriana, I. W., Raharja, M. A., Bimantara, I. M. S., & Bramantya, D. (2021). Implementasi dua model crossover pada algoritma genetika untuk optimasi penggunaan ruang perkuliahan. Jurnal RESISTOR (Rekayasa Sistem Komputer), 4(2), 167-177. <br>
42
+ [4] BIMANTARA, I Made Satria et al. Implementasi Generalized Learning Vector Quantization (GLVQ) dan Particle Swarm Optimization (PSO) Untuk Klasifikasi Kanker Payudara. JELIKU (Jurnal Elektronik Ilmu Komputer Udayana), [S.l.], v. 10, n. 4, p. 307-318, may 2022. ISSN 2654-5101. Available at: <https://ojs.unud.ac.id/index.php/jlk/article/view/85746>. Date accessed: 31 may 2025. doi: https://doi.org/10.24843/JLK.2022.v10.i04.p01. <br>
43
+
44
+ # Contributors and Developer
45
+
46
+ - I Made Satria Bimantara
47
+ - email: satriabimantara.idm@gmail.com
@@ -0,0 +1,18 @@
1
+ # metaheuristicpy
2
+
3
+ A Python-based package of Metaheuristic Optimization Algorithms for Solving Continous and Discrete Optimization Problem
4
+
5
+ <hr>
6
+
7
+ # Cite
8
+
9
+ If you think this package is useful, please cite this paper in your project: <br>
10
+ [1] Bimantara, I.M.S., Sanjaya ER, N., Purwitasari, D. (2023). Character Entity Recognition Using Hybrid Binary-Particle Swarm Optimization and Conditional Random Field on Balinese Folklore Text. In: Delir Haghighi, P., et al. Information Integration and Web Intelligence. iiWAS 2023. Lecture Notes in Computer Science, vol 14416. Springer, Cham. https://doi.org/10.1007/978-3-031-48316-5_15 <br>
11
+ [2] Bimantara, I. M. S., & Widiartha, I. M. (2023). Optimization of K-Means Clustering Using Particle Swarm Optimization Algorithm for Grouping Traveler Reviews Data on Tripadvisor Sites. Jurnal Ilmiah Kursor, 12(1), 1-10. <br>
12
+ [3] Supriana, I. W., Raharja, M. A., Bimantara, I. M. S., & Bramantya, D. (2021). Implementasi dua model crossover pada algoritma genetika untuk optimasi penggunaan ruang perkuliahan. Jurnal RESISTOR (Rekayasa Sistem Komputer), 4(2), 167-177. <br>
13
+ [4] BIMANTARA, I Made Satria et al. Implementasi Generalized Learning Vector Quantization (GLVQ) dan Particle Swarm Optimization (PSO) Untuk Klasifikasi Kanker Payudara. JELIKU (Jurnal Elektronik Ilmu Komputer Udayana), [S.l.], v. 10, n. 4, p. 307-318, may 2022. ISSN 2654-5101. Available at: <https://ojs.unud.ac.id/index.php/jlk/article/view/85746>. Date accessed: 31 may 2025. doi: https://doi.org/10.24843/JLK.2022.v10.i04.p01. <br>
14
+
15
+ # Contributors and Developer
16
+
17
+ - I Made Satria Bimantara
18
+ - email: satriabimantara.idm@gmail.com
@@ -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
+