Skip to content

Commit e133bb5

Browse files
Adding reference implementation and saving convergence scores
1 parent b942a20 commit e133bb5

File tree

9 files changed

+309
-34
lines changed

9 files changed

+309
-34
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
.oaenv/
22
.pytest_cache/
33
tests/__pycache__/
4+
rao_algorithms/__pycache__/
45
build/
56
dist/
7+
results/
68
*.egg-info/
79
.pypirc
810
example.py

README.md

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,32 @@ pip install .
3232

3333
## How to Use
3434

35+
### Example: Constrained BMR Algorithm
36+
37+
```python
38+
import numpy as np
39+
from rao_algorithms import run_optimization, BMR_algorithm, objective_function, constraint_1, constraint_2
40+
41+
# Constrained BMR
42+
# ---------------
43+
bounds = np.array([[-100, 100]] * 2)
44+
num_iterations = 100
45+
population_size = 50
46+
constraints = [constraint_1, constraint_2]
47+
48+
best_solution, best_scores = run_optimization(BMR_algorithm, bounds, num_iterations, population_size, 2, objective_function, constraints)
49+
print(f"Constrained BMR Best solution: {best_solution}")
50+
51+
```
52+
3553
### Example: Unconstrained BMR Algorithm
3654

3755
```python
3856
import numpy as np
3957
from rao_algorithms import BMR_algorithm, objective_function
4058

59+
# Unconstrained BMR
60+
# ---------------
4161
# Define the bounds for a 2D problem
4262
bounds = np.array([[-100, 100]] * 2)
4363

@@ -47,8 +67,8 @@ population_size = 50
4767
num_variables = 2
4868

4969
# Run the BMR algorithm
50-
best_fitness = BMR_algorithm(bounds, num_iterations, population_size, num_variables, objective_function)
51-
print(f"Best fitness found: {best_fitness}")
70+
best_solution, best_scores = BMR_algorithm(bounds, num_iterations, population_size, num_variables, objective_function)
71+
print(f"Unconstrained BMR Best solution found: {best_solution}")
5272
```
5373

5474
### Example: Constrained BWR Algorithm
@@ -57,6 +77,8 @@ print(f"Best fitness found: {best_fitness}")
5777
import numpy as np
5878
from rao_algorithms import BWR_algorithm, objective_function, constraint_1, constraint_2
5979

80+
# Constrained BWR
81+
# ---------------
6082
# Define the bounds for a 2D problem
6183
bounds = np.array([[-100, 100]] * 2)
6284

@@ -67,8 +89,8 @@ num_variables = 2
6789
constraints = [constraint_1, constraint_2]
6890

6991
# Run the BWR algorithm with constraints
70-
best_fitness = BWR_algorithm(bounds, num_iterations, population_size, num_variables, objective_function, constraints)
71-
print(f"Best fitness found: {best_fitness}")
92+
best_solution, best_scores = BWR_algorithm(bounds, num_iterations, population_size, num_variables, objective_function, constraints)
93+
print(f"Constrained BWR Best solution found: {best_solution}")
7294
```
7395

7496
### Unit Testing

rao_algorithms/__init__.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
from .algorithms import BMR_algorithm, BWR_algorithm
2-
from .penalty import penalty_function, constrained_objective_function
2+
from .optimization import run_optimization, save_convergence_curve
33
from .objective_functions import objective_function, constraint_1, constraint_2
44

55
__all__ = [
6-
"BMR_algorithm",
7-
"BWR_algorithm",
8-
"penalty_function",
9-
"constrained_objective_function",
10-
"objective_function",
11-
"constraint_1",
12-
"constraint_2"
6+
'BMR_algorithm',
7+
'BWR_algorithm',
8+
'run_optimization',
9+
'save_convergence_curve',
10+
'objective_function',
11+
'constraint_1',
12+
'constraint_2',
1313
]

rao_algorithms/algorithms.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
def BMR_algorithm(bounds, num_iterations, population_size, num_variables, objective_func, constraints=None):
55
population = np.random.uniform(low=bounds[:, 0], high=bounds[:, 1], size=(population_size, num_variables))
66

7+
best_scores = []
8+
79
for iteration in range(num_iterations):
810
if constraints:
911
fitness = [constrained_objective_function(ind, objective_func, constraints) for ind in population]
@@ -12,6 +14,8 @@ def BMR_algorithm(bounds, num_iterations, population_size, num_variables, object
1214

1315
best_solution = population[np.argmin(fitness)]
1416
mean_solution = np.mean(population, axis=0)
17+
best_score = np.min(fitness)
18+
best_scores.append(best_score)
1519

1620
for i in range(population_size):
1721
r1, r2, r3, r4 = np.random.rand(4)
@@ -23,15 +27,16 @@ def BMR_algorithm(bounds, num_iterations, population_size, num_variables, object
2327
else:
2428
population[i] = bounds[:, 1] - (bounds[:, 1] - bounds[:, 0]) * r3
2529

26-
print(f"Iteration {iteration+1}, Best Fitness: {np.min(fitness)}")
30+
population = np.clip(population, bounds[:, 0], bounds[:, 1])
2731

28-
best_fitness = np.min(fitness)
29-
return best_fitness
32+
return best_solution, best_scores
3033

3134

3235
def BWR_algorithm(bounds, num_iterations, population_size, num_variables, objective_func, constraints=None):
3336
population = np.random.uniform(low=bounds[:, 0], high=bounds[:, 1], size=(population_size, num_variables))
3437

38+
best_scores = []
39+
3540
for iteration in range(num_iterations):
3641
if constraints:
3742
fitness = [constrained_objective_function(ind, objective_func, constraints) for ind in population]
@@ -40,6 +45,8 @@ def BWR_algorithm(bounds, num_iterations, population_size, num_variables, object
4045

4146
best_solution = population[np.argmin(fitness)]
4247
worst_solution = population[np.argmax(fitness)]
48+
best_score = np.min(fitness)
49+
best_scores.append(best_score)
4350

4451
for i in range(population_size):
4552
r1, r2, r3, r4 = np.random.rand(4)
@@ -51,7 +58,6 @@ def BWR_algorithm(bounds, num_iterations, population_size, num_variables, object
5158
else:
5259
population[i] = bounds[:, 1] - (bounds[:, 1] - bounds[:, 0]) * r3
5360

54-
print(f"Iteration {iteration+1}, Best Fitness: {np.min(fitness)}")
61+
population = np.clip(population, bounds[:, 0], bounds[:, 1])
5562

56-
best_fitness = np.min(fitness)
57-
return best_fitness
63+
return best_solution, best_scores

rao_algorithms/objective_functions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import numpy as np
22

3-
# Example of an objective function (Sphere function)
3+
# Sphere function (default objective)
44
def objective_function(x):
55
return np.sum(x**2)
66

rao_algorithms/optimization.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import numpy as np
2+
import os
3+
import csv
4+
5+
def initialize_population(bounds, population_size, num_variables):
6+
"""Initialize population with random values within bounds."""
7+
return np.random.uniform(low=bounds[:, 0], high=bounds[:, 1], size=(population_size, num_variables))
8+
9+
def clip_position(position, bounds):
10+
"""Clip the position to make sure it stays within bounds."""
11+
return np.clip(position, bounds[:, 0], bounds[:, 1])
12+
13+
def run_optimization(algorithm, bounds, num_iterations, population_size, num_variables, objective_function, constraints=None):
14+
"""Run the selected algorithm and handle logging, saving results, etc."""
15+
16+
# Initialize population and variables
17+
population = initialize_population(bounds, population_size, num_variables)
18+
best_scores = []
19+
20+
# Prepare directory for saving results
21+
if not os.path.exists('results'):
22+
os.makedirs('results')
23+
24+
# Run the algorithm
25+
best_solution, best_scores = algorithm(bounds, num_iterations, population_size, num_variables, objective_function, constraints)
26+
27+
# Save results
28+
save_convergence_curve(best_scores)
29+
30+
return best_solution, best_scores
31+
32+
def save_convergence_curve(best_scores):
33+
"""Save the convergence curve as a CSV."""
34+
with open(f'results/convergence_curve.csv', 'w', newline='') as file:
35+
writer = csv.writer(file)
36+
writer.writerow(['Iteration', 'Best Score'])
37+
for i, score in enumerate(best_scores):
38+
writer.writerow([i, score])

0 commit comments

Comments
 (0)