bioalgo 0.1.0__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.
bioalgo-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Developer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
bioalgo-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,194 @@
1
+ Metadata-Version: 2.4
2
+ Name: bioalgo
3
+ Version: 0.1.0
4
+ Summary: A lightweight, modular Python toolkit for bio-inspired and nature-inspired metaheuristic optimization algorithms.
5
+ Author-email: Developer <developer@example.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/example/bioalgo
8
+ Project-URL: Repository, https://github.com/example/bioalgo
9
+ Project-URL: Documentation, https://github.com/example/bioalgo#readme
10
+ Keywords: optimization,metaheuristics,bio-inspired,nature-inspired,particle-swarm-optimization,differential-evolution,simulated-annealing,firefly-algorithm,biogeography-based-optimization,hill-climbing,n-queens,traveling-salesman-problem
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Intended Audience :: Education
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=7.0; extra == "dev"
28
+ Requires-Dist: build; extra == "dev"
29
+ Requires-Dist: twine; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # bioalgo
33
+
34
+ [![PyPI version](https://img.shields.io/pypi/v/bioalgo.svg)](https://pypi.org/project/bioalgo/)
35
+ [![Python versions](https://img.shields.io/pypi/pyversions/bioalgo.svg)](https://pypi.org/project/bioalgo/)
36
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
37
+
38
+ **bioalgo** is a lightweight, pure-Python library for nature-inspired, bio-inspired, and metaheuristic optimization algorithms. It includes both discrete combinatorial solvers (N-Queens, Traveling Salesman Problem) and continuous multimodal function optimizers.
39
+
40
+ ---
41
+
42
+ ## Algorithms Included
43
+
44
+ | Algorithm | Type | Description / Operators | Typical Applications |
45
+ | :--- | :--- | :--- | :--- |
46
+ | **Hill Climbing** | Discrete Local Search | Steepest ascent, conflict evaluation, random-restart heuristics | N-Queens, constraint satisfaction |
47
+ | **Simulated Annealing (SA)** | Metaheuristic | Metropolis acceptance criterion ($P = e^{-\Delta E / T}$), 2-opt swaps, geometric cooling | Traveling Salesman Problem (TSP), combinatorial routing |
48
+ | **Particle Swarm Optimization (PSO)** | Swarm Intelligence | Velocity/position updates, cognitive ($\text{pBest}$) and social ($\text{gBest}$) components, inertia damping | Continuous multimodal minimization |
49
+ | **Differential Evolution (DE)** | Evolutionary | Mutation (`DE/rand/1`, `DE/best/1`), binomial crossover ($CR$), one-to-one selection | Non-linear parameter estimation, benchmark optimization |
50
+ | **Biogeography-Based Optimization (BBO)** | Ecological | Species migration ($\lambda, \mu$), Habitat Suitability Index (HSI), elitism, mutation | Continuous global optimization |
51
+ | **Firefly Algorithm (FA)** | Swarm Intelligence | Light intensity, distance attractiveness ($\beta(r) = \beta_0 e^{-\gamma r^2}$), randomized step damping | Multimodal landscapes with multiple local optima |
52
+
53
+ ---
54
+
55
+ ## Installation
56
+
57
+ Install via `pip`:
58
+
59
+ ```bash
60
+ pip install bioalgo
61
+ ```
62
+
63
+ Or install in development/editable mode:
64
+
65
+ ```bash
66
+ git clone https://github.com/example/bioalgo.git
67
+ cd bioalgo
68
+ pip install -e .
69
+ ```
70
+
71
+ ---
72
+
73
+ ## Quickstart
74
+
75
+ ### 1. Particle Swarm Optimization (PSO)
76
+ ```python
77
+ from bioalgo import ParticleSwarmOptimization
78
+ from bioalgo.benchmarks import rastrigin
79
+
80
+ # Optimize the multimodal Rastrigin function in 5 dimensions
81
+ pso = ParticleSwarmOptimization(
82
+ cost_func=rastrigin,
83
+ dim=5,
84
+ bounds=(-5.12, 5.12),
85
+ num_particles=40
86
+ )
87
+
88
+ best_vector, best_cost, history = pso.optimize(max_iter=100)
89
+ print(f"Optimal Cost: {best_cost:.6e}")
90
+ print(f"Optimal Solution: {best_vector}")
91
+ ```
92
+
93
+ ### 2. Differential Evolution (DE)
94
+ ```python
95
+ from bioalgo import DifferentialEvolution
96
+ from bioalgo.benchmarks import ackley
97
+
98
+ de = DifferentialEvolution(
99
+ cost_func=ackley,
100
+ dim=5,
101
+ bounds=(-32.768, 32.768),
102
+ pop_size=40,
103
+ strategy="best/1/bin"
104
+ )
105
+
106
+ best_vector, best_cost, history = de.optimize(max_generations=100)
107
+ print(f"Ackley Minimum: {best_cost:.6e}")
108
+ ```
109
+
110
+ ### 3. Solve N-Queens with Hill Climbing
111
+ ```python
112
+ from bioalgo import NQueensProblem, HillClimbing
113
+
114
+ problem = NQueensProblem(n=8)
115
+ solver = HillClimbing(problem)
116
+ solution, restarts, steps = solver.search_with_restarts(max_restarts=50)
117
+
118
+ print(f"Solved in {restarts} restart(s) and {steps} steps:")
119
+ print(problem.render_board(solution))
120
+ ```
121
+
122
+ ### 4. Traveling Salesman Problem (TSP) with Simulated Annealing
123
+ ```python
124
+ from bioalgo import TravelingSalesmanProblem, SimulatedAnnealing
125
+
126
+ problem = TravelingSalesmanProblem()
127
+ sa = SimulatedAnnealing(problem, initial_temp=1000.0, cooling_rate=0.995)
128
+
129
+ best_tour, best_distance, history = sa.optimize(seed=42)
130
+ print(f"Best Tour Length: {best_distance:.2f}")
131
+ print("Tour Sequence:", " -> ".join(best_tour))
132
+ ```
133
+
134
+ ---
135
+
136
+ ## Built-in Benchmark Functions
137
+
138
+ `bioalgo.benchmarks` includes standard continuous functions:
139
+ - `sphere(x)`
140
+ - `rastrigin(x)`
141
+ - `ackley(x)`
142
+ - `rosenbrock(x)`
143
+ - `griewank(x)`
144
+
145
+ ---
146
+
147
+ ## Command Line Interface (CLI)
148
+
149
+ `bioalgo` comes with a command-line interface:
150
+
151
+ ```bash
152
+ # Solve 8-Queens and render the board
153
+ bioalgo nqueens -n 8 --render
154
+
155
+ # Solve Traveling Salesman Problem
156
+ bioalgo tsp --temp 1000 --cooling 0.995
157
+
158
+ # Optimize a continuous benchmark using PSO, DE, BBO, or FA
159
+ bioalgo optimize pso --func rastrigin --dim 5 --iters 100
160
+ bioalgo optimize de --func ackley --dim 5 --iters 100
161
+ bioalgo optimize bbo --func sphere --dim 5 --iters 100
162
+ bioalgo optimize fa --func rastrigin --dim 5 --iters 100
163
+ ```
164
+
165
+ ---
166
+
167
+ ## Building and Publishing to PyPI
168
+
169
+ ### 1. Build the Distribution Archives
170
+ ```bash
171
+ python -m build
172
+ ```
173
+ This produces `.tar.gz` (source distribution) and `.whl` (built wheel) in `dist/`.
174
+
175
+ ### 2. Check Package Metadata
176
+ ```bash
177
+ twine check dist/*
178
+ ```
179
+
180
+ ### 3. Test on TestPyPI (Recommended first)
181
+ ```bash
182
+ twine upload --repository testpypi dist/*
183
+ ```
184
+
185
+ ### 4. Upload to Production PyPI
186
+ ```bash
187
+ twine upload dist/*
188
+ ```
189
+
190
+ ---
191
+
192
+ ## License
193
+
194
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,163 @@
1
+ # bioalgo
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/bioalgo.svg)](https://pypi.org/project/bioalgo/)
4
+ [![Python versions](https://img.shields.io/pypi/pyversions/bioalgo.svg)](https://pypi.org/project/bioalgo/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ **bioalgo** is a lightweight, pure-Python library for nature-inspired, bio-inspired, and metaheuristic optimization algorithms. It includes both discrete combinatorial solvers (N-Queens, Traveling Salesman Problem) and continuous multimodal function optimizers.
8
+
9
+ ---
10
+
11
+ ## Algorithms Included
12
+
13
+ | Algorithm | Type | Description / Operators | Typical Applications |
14
+ | :--- | :--- | :--- | :--- |
15
+ | **Hill Climbing** | Discrete Local Search | Steepest ascent, conflict evaluation, random-restart heuristics | N-Queens, constraint satisfaction |
16
+ | **Simulated Annealing (SA)** | Metaheuristic | Metropolis acceptance criterion ($P = e^{-\Delta E / T}$), 2-opt swaps, geometric cooling | Traveling Salesman Problem (TSP), combinatorial routing |
17
+ | **Particle Swarm Optimization (PSO)** | Swarm Intelligence | Velocity/position updates, cognitive ($\text{pBest}$) and social ($\text{gBest}$) components, inertia damping | Continuous multimodal minimization |
18
+ | **Differential Evolution (DE)** | Evolutionary | Mutation (`DE/rand/1`, `DE/best/1`), binomial crossover ($CR$), one-to-one selection | Non-linear parameter estimation, benchmark optimization |
19
+ | **Biogeography-Based Optimization (BBO)** | Ecological | Species migration ($\lambda, \mu$), Habitat Suitability Index (HSI), elitism, mutation | Continuous global optimization |
20
+ | **Firefly Algorithm (FA)** | Swarm Intelligence | Light intensity, distance attractiveness ($\beta(r) = \beta_0 e^{-\gamma r^2}$), randomized step damping | Multimodal landscapes with multiple local optima |
21
+
22
+ ---
23
+
24
+ ## Installation
25
+
26
+ Install via `pip`:
27
+
28
+ ```bash
29
+ pip install bioalgo
30
+ ```
31
+
32
+ Or install in development/editable mode:
33
+
34
+ ```bash
35
+ git clone https://github.com/example/bioalgo.git
36
+ cd bioalgo
37
+ pip install -e .
38
+ ```
39
+
40
+ ---
41
+
42
+ ## Quickstart
43
+
44
+ ### 1. Particle Swarm Optimization (PSO)
45
+ ```python
46
+ from bioalgo import ParticleSwarmOptimization
47
+ from bioalgo.benchmarks import rastrigin
48
+
49
+ # Optimize the multimodal Rastrigin function in 5 dimensions
50
+ pso = ParticleSwarmOptimization(
51
+ cost_func=rastrigin,
52
+ dim=5,
53
+ bounds=(-5.12, 5.12),
54
+ num_particles=40
55
+ )
56
+
57
+ best_vector, best_cost, history = pso.optimize(max_iter=100)
58
+ print(f"Optimal Cost: {best_cost:.6e}")
59
+ print(f"Optimal Solution: {best_vector}")
60
+ ```
61
+
62
+ ### 2. Differential Evolution (DE)
63
+ ```python
64
+ from bioalgo import DifferentialEvolution
65
+ from bioalgo.benchmarks import ackley
66
+
67
+ de = DifferentialEvolution(
68
+ cost_func=ackley,
69
+ dim=5,
70
+ bounds=(-32.768, 32.768),
71
+ pop_size=40,
72
+ strategy="best/1/bin"
73
+ )
74
+
75
+ best_vector, best_cost, history = de.optimize(max_generations=100)
76
+ print(f"Ackley Minimum: {best_cost:.6e}")
77
+ ```
78
+
79
+ ### 3. Solve N-Queens with Hill Climbing
80
+ ```python
81
+ from bioalgo import NQueensProblem, HillClimbing
82
+
83
+ problem = NQueensProblem(n=8)
84
+ solver = HillClimbing(problem)
85
+ solution, restarts, steps = solver.search_with_restarts(max_restarts=50)
86
+
87
+ print(f"Solved in {restarts} restart(s) and {steps} steps:")
88
+ print(problem.render_board(solution))
89
+ ```
90
+
91
+ ### 4. Traveling Salesman Problem (TSP) with Simulated Annealing
92
+ ```python
93
+ from bioalgo import TravelingSalesmanProblem, SimulatedAnnealing
94
+
95
+ problem = TravelingSalesmanProblem()
96
+ sa = SimulatedAnnealing(problem, initial_temp=1000.0, cooling_rate=0.995)
97
+
98
+ best_tour, best_distance, history = sa.optimize(seed=42)
99
+ print(f"Best Tour Length: {best_distance:.2f}")
100
+ print("Tour Sequence:", " -> ".join(best_tour))
101
+ ```
102
+
103
+ ---
104
+
105
+ ## Built-in Benchmark Functions
106
+
107
+ `bioalgo.benchmarks` includes standard continuous functions:
108
+ - `sphere(x)`
109
+ - `rastrigin(x)`
110
+ - `ackley(x)`
111
+ - `rosenbrock(x)`
112
+ - `griewank(x)`
113
+
114
+ ---
115
+
116
+ ## Command Line Interface (CLI)
117
+
118
+ `bioalgo` comes with a command-line interface:
119
+
120
+ ```bash
121
+ # Solve 8-Queens and render the board
122
+ bioalgo nqueens -n 8 --render
123
+
124
+ # Solve Traveling Salesman Problem
125
+ bioalgo tsp --temp 1000 --cooling 0.995
126
+
127
+ # Optimize a continuous benchmark using PSO, DE, BBO, or FA
128
+ bioalgo optimize pso --func rastrigin --dim 5 --iters 100
129
+ bioalgo optimize de --func ackley --dim 5 --iters 100
130
+ bioalgo optimize bbo --func sphere --dim 5 --iters 100
131
+ bioalgo optimize fa --func rastrigin --dim 5 --iters 100
132
+ ```
133
+
134
+ ---
135
+
136
+ ## Building and Publishing to PyPI
137
+
138
+ ### 1. Build the Distribution Archives
139
+ ```bash
140
+ python -m build
141
+ ```
142
+ This produces `.tar.gz` (source distribution) and `.whl` (built wheel) in `dist/`.
143
+
144
+ ### 2. Check Package Metadata
145
+ ```bash
146
+ twine check dist/*
147
+ ```
148
+
149
+ ### 3. Test on TestPyPI (Recommended first)
150
+ ```bash
151
+ twine upload --repository testpypi dist/*
152
+ ```
153
+
154
+ ### 4. Upload to Production PyPI
155
+ ```bash
156
+ twine upload dist/*
157
+ ```
158
+
159
+ ---
160
+
161
+ ## License
162
+
163
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,65 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "bioalgo"
7
+ version = "0.1.0"
8
+ description = "A lightweight, modular Python toolkit for bio-inspired and nature-inspired metaheuristic optimization algorithms."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "MIT"
12
+ authors = [
13
+ { name = "Developer", email = "developer@example.com" }
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Science/Research",
18
+ "Intended Audience :: Education",
19
+ "Intended Audience :: Developers",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.8",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
27
+ "Topic :: Scientific/Engineering :: Mathematics",
28
+ ]
29
+ keywords = [
30
+ "optimization",
31
+ "metaheuristics",
32
+ "bio-inspired",
33
+ "nature-inspired",
34
+ "particle-swarm-optimization",
35
+ "differential-evolution",
36
+ "simulated-annealing",
37
+ "firefly-algorithm",
38
+ "biogeography-based-optimization",
39
+ "hill-climbing",
40
+ "n-queens",
41
+ "traveling-salesman-problem",
42
+ ]
43
+ dependencies = []
44
+
45
+ [project.optional-dependencies]
46
+ dev = [
47
+ "pytest>=7.0",
48
+ "build",
49
+ "twine",
50
+ ]
51
+
52
+ [project.scripts]
53
+ bioalgo = "bioalgo.cli:main"
54
+
55
+ [project.urls]
56
+ Homepage = "https://github.com/example/bioalgo"
57
+ Repository = "https://github.com/example/bioalgo"
58
+ Documentation = "https://github.com/example/bioalgo#readme"
59
+
60
+ [tool.setuptools.packages.find]
61
+ where = ["src"]
62
+
63
+ [tool.pytest.ini_options]
64
+ testpaths = ["tests"]
65
+ python_files = ["test_*.py"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,70 @@
1
+ """
2
+ bioalgo: Bio-Inspired & Nature-Inspired Metaheuristic Optimization Library.
3
+
4
+ Algorithms included:
5
+ - Hill Climbing (N-Queens, local search)
6
+ - Simulated Annealing (TSP, Metropolis criterion)
7
+ - Particle Swarm Optimization (PSO, continuous global optimization)
8
+ - Differential Evolution (DE, continuous multimodal optimization)
9
+ - Biogeography-Based Optimization (BBO, migration & mutation)
10
+ - Firefly Algorithm (FA, multimodal attraction & brightness)
11
+
12
+ Utility functions:
13
+ - bioalgo.menu(): Launches interactive code viewer and runner.
14
+ - bioalgo.run_all(): Runs all 6 algorithms sequentially.
15
+ - bioalgo.print_code(): Prints code of a program.
16
+ - bioalgo.print_all_codes(): Prints code of all programs.
17
+ """
18
+
19
+ from bioalgo import benchmarks
20
+ from bioalgo.bbo import BiogeographyBasedOptimization, Habitat
21
+ from bioalgo.differential_evolution import DifferentialEvolution
22
+ from bioalgo.firefly import FireflyAlgorithm
23
+ from bioalgo.hill_climbing import HillClimbing, NQueensProblem, solve_n_queens
24
+ from bioalgo.pso import Particle, ParticleSwarmOptimization
25
+ from bioalgo.runner import (
26
+ menu,
27
+ print_all_codes,
28
+ print_code,
29
+ print_menu,
30
+ run_all,
31
+ run_bbo,
32
+ run_differential_evolution,
33
+ run_firefly,
34
+ run_hill_climbing,
35
+ run_pso,
36
+ run_simulated_annealing,
37
+ )
38
+ from bioalgo.simulated_annealing import (
39
+ SimulatedAnnealing,
40
+ TravelingSalesmanProblem,
41
+ )
42
+
43
+ __version__ = "0.1.0"
44
+
45
+ __all__ = [
46
+ "benchmarks",
47
+ "HillClimbing",
48
+ "NQueensProblem",
49
+ "solve_n_queens",
50
+ "SimulatedAnnealing",
51
+ "TravelingSalesmanProblem",
52
+ "Particle",
53
+ "ParticleSwarmOptimization",
54
+ "DifferentialEvolution",
55
+ "Habitat",
56
+ "BiogeographyBasedOptimization",
57
+ "FireflyAlgorithm",
58
+ "run_all",
59
+ "menu",
60
+ "print_menu",
61
+ "print_code",
62
+ "print_all_codes",
63
+ "run_hill_climbing",
64
+ "run_simulated_annealing",
65
+ "run_pso",
66
+ "run_differential_evolution",
67
+ "run_bbo",
68
+ "run_firefly",
69
+ "__version__",
70
+ ]
@@ -0,0 +1,103 @@
1
+ """
2
+ Biogeography-Based Optimization (BBO) Algorithm.
3
+ """
4
+
5
+ import random
6
+ from typing import Callable, List, Optional, Sequence, Tuple
7
+
8
+
9
+ class Habitat:
10
+ """Represents an island/habitat with SIVs and HSI."""
11
+
12
+ def __init__(self, siv: List[float], cost: float):
13
+ self.siv = list(siv)
14
+ self.cost = cost
15
+ self.lambda_rate = 0.0
16
+ self.mu_rate = 0.0
17
+
18
+
19
+ class BiogeographyBasedOptimization:
20
+ """Dan Simon's Biogeography-Based Optimization (BBO) solver."""
21
+
22
+ def __init__(
23
+ self,
24
+ cost_func: Callable[[Sequence[float]], float],
25
+ dim: int,
26
+ bounds: Tuple[float, float] = (-5.0, 5.0),
27
+ num_habitats: int = 50,
28
+ p_mutation: float = 0.05,
29
+ i_max: float = 1.0,
30
+ e_max: float = 1.0,
31
+ elite_count: int = 2,
32
+ ):
33
+ self.cost_func = cost_func
34
+ self.dim = dim
35
+ self.bounds = bounds
36
+ self.num_habitats = num_habitats
37
+ self.p_mutation = p_mutation
38
+ self.i_max = i_max
39
+ self.e_max = e_max
40
+ self.elite_count = elite_count
41
+
42
+ def optimize(
43
+ self, max_generations: int = 100, seed: Optional[int] = None
44
+ ) -> Tuple[List[float], float, List[float]]:
45
+ """
46
+ Executes BBO optimization.
47
+ Returns: (best_siv, best_cost, history)
48
+ """
49
+ if seed is not None:
50
+ random.seed(seed)
51
+
52
+ low, high = self.bounds
53
+ habitats: List[Habitat] = []
54
+
55
+ for _ in range(self.num_habitats):
56
+ siv = [random.uniform(low, high) for _ in range(self.dim)]
57
+ habitats.append(Habitat(siv, self.cost_func(siv)))
58
+
59
+ history = []
60
+
61
+ for _ in range(max_generations):
62
+ habitats.sort(key=lambda h: h.cost)
63
+ history.append(habitats[0].cost)
64
+
65
+ # Assign migration rates
66
+ for rank_idx, hab in enumerate(habitats):
67
+ rank = self.num_habitats - rank_idx
68
+ hab.lambda_rate = self.i_max * (1.0 - (rank / self.num_habitats))
69
+ hab.mu_rate = self.e_max * (rank / self.num_habitats)
70
+
71
+ total_mu = sum(h.mu_rate for h in habitats)
72
+ new_habitats: List[Habitat] = []
73
+
74
+ # Retain elites
75
+ for e in range(self.elite_count):
76
+ new_habitats.append(Habitat(habitats[e].siv, habitats[e].cost))
77
+
78
+ # Non-elite migration & mutation
79
+ for i in range(self.elite_count, self.num_habitats):
80
+ new_siv = list(habitats[i].siv)
81
+ for j in range(self.dim):
82
+ if random.random() < habitats[i].lambda_rate:
83
+ rand_pick = random.uniform(0, total_mu)
84
+ running = 0.0
85
+ selected_k = 0
86
+ for k_idx, h in enumerate(habitats):
87
+ running += h.mu_rate
88
+ if running >= rand_pick:
89
+ selected_k = k_idx
90
+ break
91
+ new_siv[j] = habitats[selected_k].siv[j]
92
+
93
+ # Mutation
94
+ if random.random() < self.p_mutation:
95
+ pert = random.gauss(0, 0.1 * (high - low))
96
+ new_siv[j] = max(low, min(high, new_siv[j] + pert))
97
+
98
+ new_habitats.append(Habitat(new_siv, self.cost_func(new_siv)))
99
+
100
+ habitats = new_habitats
101
+
102
+ habitats.sort(key=lambda h: h.cost)
103
+ return habitats[0].siv, habitats[0].cost, history
@@ -0,0 +1,66 @@
1
+ """
2
+ Standard mathematical benchmark functions for continuous optimization.
3
+ """
4
+
5
+ import math
6
+ from typing import List, Sequence
7
+
8
+
9
+ def sphere(x: Sequence[float]) -> float:
10
+ """
11
+ Sphere benchmark function (Unimodal).
12
+ Global minimum: f(0, ..., 0) = 0.0
13
+ Domain: [-5.12, 5.12]^D
14
+ """
15
+ return sum(xi ** 2 for xi in x)
16
+
17
+
18
+ def rastrigin(x: Sequence[float]) -> float:
19
+ """
20
+ Rastrigin benchmark function (Highly Multimodal).
21
+ Global minimum: f(0, ..., 0) = 0.0
22
+ Domain: [-5.12, 5.12]^D
23
+ """
24
+ d = len(x)
25
+ return 10.0 * d + sum(xi ** 2 - 10.0 * math.cos(2.0 * math.pi * xi) for xi in x)
26
+
27
+
28
+ def ackley(x: Sequence[float]) -> float:
29
+ """
30
+ Ackley benchmark function (Multimodal with many local minima).
31
+ Global minimum: f(0, ..., 0) = 0.0
32
+ Domain: [-32.768, 32.768]^D
33
+ """
34
+ d = len(x)
35
+ if d == 0:
36
+ return 0.0
37
+ sum_sq = sum(xi ** 2 for xi in x)
38
+ sum_cos = sum(math.cos(2.0 * math.pi * xi) for xi in x)
39
+ term1 = -20.0 * math.exp(-0.2 * math.sqrt(sum_sq / d))
40
+ term2 = -math.exp(sum_cos / d)
41
+ return term1 + term2 + 20.0 + math.e
42
+
43
+
44
+ def rosenbrock(x: Sequence[float]) -> float:
45
+ """
46
+ Rosenbrock banana valley function.
47
+ Global minimum: f(1, ..., 1) = 0.0
48
+ Domain: [-5.0, 10.0]^D
49
+ """
50
+ return sum(
51
+ 100.0 * (x[i + 1] - x[i] ** 2) ** 2 + (1.0 - x[i]) ** 2
52
+ for i in range(len(x) - 1)
53
+ )
54
+
55
+
56
+ def griewank(x: Sequence[float]) -> float:
57
+ """
58
+ Griewank benchmark function.
59
+ Global minimum: f(0, ..., 0) = 0.0
60
+ Domain: [-600.0, 600.0]^D
61
+ """
62
+ sum_term = sum(xi ** 2 for xi in x) / 4000.0
63
+ prod_term = 1.0
64
+ for i, xi in enumerate(x, start=1):
65
+ prod_term *= math.cos(xi / math.sqrt(i))
66
+ return sum_term - prod_term + 1.0