ypea 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.
ypea-0.1.0/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv*/
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ build/
7
+ dist/
8
+ *.egg-info/
9
+ .coverage
10
+ results/
@@ -0,0 +1,24 @@
1
+ cff-version: 1.2.0
2
+ message: "If you use YPEA in your research, please cite it as below."
3
+ title: "YPEA: Yarpiz Evolutionary Algorithms for Python"
4
+ type: software
5
+ authors:
6
+ - family-names: "Kalami Heris"
7
+ given-names: "Mostapha"
8
+ version: 0.1.0
9
+ date-released: 2026-11-25
10
+ license: MIT
11
+ repository-code: "https://github.com/smkalami/ypea-python"
12
+ keywords:
13
+ - optimization
14
+ - metaheuristics
15
+ - evolutionary algorithms
16
+ - swarm intelligence
17
+ references:
18
+ - type: software
19
+ title: "Yarpiz Evolutionary Algorithms Toolbox for MATLAB (YPEA)"
20
+ authors:
21
+ - family-names: "Kalami Heris"
22
+ given-names: "Mostapha"
23
+ year: 2020
24
+ repository-code: "https://github.com/smkalami/ypea"
ypea-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Yarpiz / Mostapha Kalami Heris
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.
ypea-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,111 @@
1
+ Metadata-Version: 2.5
2
+ Name: ypea
3
+ Version: 0.1.0
4
+ Summary: Yarpiz Evolutionary Algorithms: define an optimization problem once, solve it with any metaheuristic.
5
+ Project-URL: Source, https://github.com/smkalami/ypea-python
6
+ Project-URL: MATLAB version, https://github.com/smkalami/ypea
7
+ Author: Mostapha Kalami Heris
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: evolutionary algorithms,metaheuristics,optimization,swarm intelligence
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
14
+ Requires-Python: >=3.12
15
+ Requires-Dist: numpy>=2.0
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest>=8; extra == 'dev'
18
+ Requires-Dist: ruff>=0.6; extra == 'dev'
19
+ Provides-Extra: plot
20
+ Requires-Dist: matplotlib>=3.8; extra == 'plot'
21
+ Provides-Extra: stats
22
+ Requires-Dist: scipy>=1.12; extra == 'stats'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # YPEA for Python
26
+
27
+ Yarpiz Evolutionary Algorithms (YPEA) is a toolbox for defining an optimization problem once and solving it with any of its metaheuristics. This is the Python version of [YPEA for MATLAB](https://github.com/smkalami/ypea), redesigned and with the known defects fixed.
28
+
29
+ **Status:** early development (0.1.0). The core framework and four algorithms (PSO, DE, GA, SA) work. The other algorithms, benchmark suites, test problems and the experiment runner are being added. See `review/2026-11-25-1859-matlab-review/implementation-plan.md` for the plan.
30
+
31
+ ## Install
32
+
33
+ YPEA is not on PyPI yet. Install it from a copy of this repository (Python 3.12 or newer):
34
+
35
+ ```
36
+ pip install -e . # core, needs only NumPy
37
+ pip install -e ".[plot]" # with matplotlib for plots
38
+ ```
39
+
40
+ Once 0.1 is released, `pip install ypea` will work.
41
+
42
+ ## Example
43
+
44
+ Find 20 real numbers in [-10, 10] that minimize the sphere function:
45
+
46
+ ```python
47
+ import ypea
48
+
49
+ problem = ypea.Problem(
50
+ vars=ypea.Real("x", shape=20, lb=-10, ub=10),
51
+ objective=lambda sol: ypea.benchmarks.sphere(sol.x),
52
+ )
53
+
54
+ pso = ypea.PSO(max_iter=100, pop_size=100, w=0.5, wdamp=1, c1=1, c2=2)
55
+ result = pso.solve(problem, seed=42)
56
+
57
+ print(result.best.solution.x)
58
+ print(result.best.obj_value)
59
+ ```
60
+
61
+ Any other algorithm solves the same problem:
62
+
63
+ ```python
64
+ de = ypea.DE(strategy="DE/best/2/bin", max_iter=1000, pop_size=20,
65
+ beta_min=0.1, beta_max=0.9, crossover_prob=0.1)
66
+ result = de.solve(problem, seed=42)
67
+ ```
68
+
69
+ ## Decision variables
70
+
71
+ All variable types are encoded as numbers in [0, 1], so every algorithm can solve every problem. Decoded indices are 0 based.
72
+
73
+ | Type | Decodes to | Typical use |
74
+ |---|---|---|
75
+ | `Real(name, shape, lb, ub)` | real array in [lb, ub] | continuous optimization |
76
+ | `Integer(name, shape, lb, ub)` | integer array in [lb, ub] | generalized knapsack |
77
+ | `Binary(name, shape)` | 0/1 array | knapsack |
78
+ | `Permutation(name, n, count=None)` | permutation of 0..n-1 (one per row) | TSP, QAP, n-Queens |
79
+ | `Selection(name, n, k, count=None)` | k distinct items out of n | feature selection |
80
+ | `BinarySelection(name, n, k, count=None)` | 0/1 mask with k ones | feature selection |
81
+ | `Partition(name, n, k, count=None)` | list of k groups of items | vehicle routing, allocation |
82
+ | `BinaryPartition(name, n, k, count=None)` | (k, n) 0/1 assignment matrix | hub location allocation |
83
+ | `FixedSum(name, shape, target, axis=None)` | non negative reals with a fixed total, row sums or column sums | transportation |
84
+
85
+ A problem can mix several variables. The decoded solution has one attribute per variable (`sol.x`, `sol.tour`).
86
+
87
+ ## Constraints
88
+
89
+ The objective may return `(f, g)`, where each value in `g` is satisfied when `g <= 0`. By default, solutions are compared with Deb's feasibility rules. Use `constraints="penalty"` for a penalty method.
90
+
91
+ ```python
92
+ def evaluate(sol):
93
+ x, y = sol.x
94
+ return (x - 1) ** 2 + (y - 2) ** 2, [x + y - 2]
95
+
96
+ problem = ypea.Problem(ypea.Real("x", shape=2, lb=-5, ub=5), evaluate)
97
+ ```
98
+
99
+ ## Citing
100
+
101
+ For this Python version (see `CITATION.cff`):
102
+
103
+ Mostapha Kalami Heris, YPEA: Yarpiz Evolutionary Algorithms for Python, version 0.1.0, 2026. https://github.com/smkalami/ypea-python
104
+
105
+ For the original MATLAB toolbox:
106
+
107
+ Mostapha Kalami Heris, Yarpiz Evolutionary Algorithms Toolbox for MATLAB (YPEA), Yarpiz, 2020.
108
+
109
+ ## License
110
+
111
+ MIT
ypea-0.1.0/README.md ADDED
@@ -0,0 +1,87 @@
1
+ # YPEA for Python
2
+
3
+ Yarpiz Evolutionary Algorithms (YPEA) is a toolbox for defining an optimization problem once and solving it with any of its metaheuristics. This is the Python version of [YPEA for MATLAB](https://github.com/smkalami/ypea), redesigned and with the known defects fixed.
4
+
5
+ **Status:** early development (0.1.0). The core framework and four algorithms (PSO, DE, GA, SA) work. The other algorithms, benchmark suites, test problems and the experiment runner are being added. See `review/2026-11-25-1859-matlab-review/implementation-plan.md` for the plan.
6
+
7
+ ## Install
8
+
9
+ YPEA is not on PyPI yet. Install it from a copy of this repository (Python 3.12 or newer):
10
+
11
+ ```
12
+ pip install -e . # core, needs only NumPy
13
+ pip install -e ".[plot]" # with matplotlib for plots
14
+ ```
15
+
16
+ Once 0.1 is released, `pip install ypea` will work.
17
+
18
+ ## Example
19
+
20
+ Find 20 real numbers in [-10, 10] that minimize the sphere function:
21
+
22
+ ```python
23
+ import ypea
24
+
25
+ problem = ypea.Problem(
26
+ vars=ypea.Real("x", shape=20, lb=-10, ub=10),
27
+ objective=lambda sol: ypea.benchmarks.sphere(sol.x),
28
+ )
29
+
30
+ pso = ypea.PSO(max_iter=100, pop_size=100, w=0.5, wdamp=1, c1=1, c2=2)
31
+ result = pso.solve(problem, seed=42)
32
+
33
+ print(result.best.solution.x)
34
+ print(result.best.obj_value)
35
+ ```
36
+
37
+ Any other algorithm solves the same problem:
38
+
39
+ ```python
40
+ de = ypea.DE(strategy="DE/best/2/bin", max_iter=1000, pop_size=20,
41
+ beta_min=0.1, beta_max=0.9, crossover_prob=0.1)
42
+ result = de.solve(problem, seed=42)
43
+ ```
44
+
45
+ ## Decision variables
46
+
47
+ All variable types are encoded as numbers in [0, 1], so every algorithm can solve every problem. Decoded indices are 0 based.
48
+
49
+ | Type | Decodes to | Typical use |
50
+ |---|---|---|
51
+ | `Real(name, shape, lb, ub)` | real array in [lb, ub] | continuous optimization |
52
+ | `Integer(name, shape, lb, ub)` | integer array in [lb, ub] | generalized knapsack |
53
+ | `Binary(name, shape)` | 0/1 array | knapsack |
54
+ | `Permutation(name, n, count=None)` | permutation of 0..n-1 (one per row) | TSP, QAP, n-Queens |
55
+ | `Selection(name, n, k, count=None)` | k distinct items out of n | feature selection |
56
+ | `BinarySelection(name, n, k, count=None)` | 0/1 mask with k ones | feature selection |
57
+ | `Partition(name, n, k, count=None)` | list of k groups of items | vehicle routing, allocation |
58
+ | `BinaryPartition(name, n, k, count=None)` | (k, n) 0/1 assignment matrix | hub location allocation |
59
+ | `FixedSum(name, shape, target, axis=None)` | non negative reals with a fixed total, row sums or column sums | transportation |
60
+
61
+ A problem can mix several variables. The decoded solution has one attribute per variable (`sol.x`, `sol.tour`).
62
+
63
+ ## Constraints
64
+
65
+ The objective may return `(f, g)`, where each value in `g` is satisfied when `g <= 0`. By default, solutions are compared with Deb's feasibility rules. Use `constraints="penalty"` for a penalty method.
66
+
67
+ ```python
68
+ def evaluate(sol):
69
+ x, y = sol.x
70
+ return (x - 1) ** 2 + (y - 2) ** 2, [x + y - 2]
71
+
72
+ problem = ypea.Problem(ypea.Real("x", shape=2, lb=-5, ub=5), evaluate)
73
+ ```
74
+
75
+ ## Citing
76
+
77
+ For this Python version (see `CITATION.cff`):
78
+
79
+ Mostapha Kalami Heris, YPEA: Yarpiz Evolutionary Algorithms for Python, version 0.1.0, 2026. https://github.com/smkalami/ypea-python
80
+
81
+ For the original MATLAB toolbox:
82
+
83
+ Mostapha Kalami Heris, Yarpiz Evolutionary Algorithms Toolbox for MATLAB (YPEA), Yarpiz, 2020.
84
+
85
+ ## License
86
+
87
+ MIT
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ypea"
7
+ dynamic = ["version"]
8
+ description = "Yarpiz Evolutionary Algorithms: define an optimization problem once, solve it with any metaheuristic."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Mostapha Kalami Heris" }]
13
+ requires-python = ">=3.12"
14
+ dependencies = ["numpy>=2.0"]
15
+ keywords = ["optimization", "metaheuristics", "evolutionary algorithms", "swarm intelligence"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Intended Audience :: Science/Research",
19
+ "Topic :: Scientific/Engineering :: Mathematics",
20
+ ]
21
+
22
+ [project.optional-dependencies]
23
+ plot = ["matplotlib>=3.8"]
24
+ stats = ["scipy>=1.12"]
25
+ dev = ["pytest>=8", "ruff>=0.6"]
26
+
27
+ [project.urls]
28
+ Source = "https://github.com/smkalami/ypea-python"
29
+ "MATLAB version" = "https://github.com/smkalami/ypea"
30
+
31
+ [tool.hatch.version]
32
+ path = "src/ypea/__init__.py"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/ypea"]
36
+
37
+ [tool.hatch.build.targets.sdist]
38
+ include = ["src/ypea", "tests", "README.md", "LICENSE", "CITATION.cff"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+
43
+ [tool.ruff]
44
+ line-length = 120
45
+ src = ["src"]
46
+
47
+ [tool.ruff.lint]
48
+ select = ["E", "F", "W", "I", "B", "UP", "NPY"]
@@ -0,0 +1,44 @@
1
+ """YPEA: Yarpiz Evolutionary Algorithms.
2
+
3
+ Define an optimization problem once, then solve it with any of the algorithms::
4
+
5
+ import numpy as np
6
+ import ypea
7
+
8
+ problem = ypea.Problem(
9
+ vars=ypea.Real("x", shape=20, lb=-10, ub=10),
10
+ objective=lambda sol: np.sum(sol.x**2),
11
+ )
12
+ result = ypea.PSO(max_iter=100).solve(problem, seed=1)
13
+ print(result.best.solution.x, result.best.obj_value)
14
+ """
15
+
16
+ from . import benchmarks, callbacks, plot
17
+ from .algorithm import Algorithm
18
+ from .algorithms import * # noqa: F403
19
+ from .algorithms import __all__ as _algorithms
20
+ from .comparison import Comparator
21
+ from .population import Individual, Population
22
+ from .problem import Problem, Solution
23
+ from .result import History, Result
24
+ from .variables import (
25
+ Binary,
26
+ BinaryPartition,
27
+ BinarySelection,
28
+ FixedSum,
29
+ Integer,
30
+ Partition,
31
+ Permutation,
32
+ Real,
33
+ Selection,
34
+ Variable,
35
+ )
36
+
37
+ __version__ = "0.1.0"
38
+
39
+ __all__ = [
40
+ "Algorithm", "Binary", "BinaryPartition", "BinarySelection", "Comparator", "FixedSum",
41
+ "History", "Individual", "Integer", "Partition", "Permutation", "Population", "Problem",
42
+ "Real", "Result", "Selection", "Solution", "Variable", "benchmarks", "callbacks", "plot",
43
+ *_algorithms,
44
+ ]
@@ -0,0 +1,253 @@
1
+ """Base class for all algorithms."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import numbers
7
+ import time
8
+
9
+ import numpy as np
10
+
11
+ from .evaluation import Evaluator
12
+ from .population import Individual, Population
13
+ from .problem import Problem
14
+ from .result import History, Result
15
+
16
+
17
+ def check(cond, message):
18
+ if not cond:
19
+ raise ValueError(message)
20
+
21
+
22
+ def is_int(x, low=None):
23
+ return isinstance(x, numbers.Integral) and not isinstance(x, bool) and (low is None or x >= low)
24
+
25
+
26
+ def is_real(x, low=None, high=None):
27
+ ok = isinstance(x, numbers.Real) and not isinstance(x, bool) and np.isfinite(x)
28
+ return ok and (low is None or x >= low) and (high is None or x <= high)
29
+
30
+
31
+ class Algorithm:
32
+ """Base class. Subclasses implement ``initialize()`` and ``iterate()``.
33
+
34
+ Common settings
35
+ ---------------
36
+ max_iter : int or None
37
+ Maximum number of iterations. If None (the default), the run is limited only by
38
+ ``max_nfe`` and ``max_time``, and when neither is set, ``max_iter`` is 100.
39
+ pop_size : int
40
+ Population size.
41
+ max_nfe : int or None
42
+ Maximum number of objective function evaluations. Never exceeded.
43
+ target : float or None
44
+ Stop when a feasible solution at least this good is found (the MATLAB ``goal``).
45
+ max_time : float or None
46
+ Stop after this many seconds (checked between iterations).
47
+ display : bool
48
+ Print one line per iteration.
49
+
50
+ Inside ``initialize()`` and ``iterate()`` a subclass can use ``self.rng``,
51
+ ``self.problem``, ``self.pop``, ``self.iter``, ``self.nfe``, ``self.best`` and the
52
+ helpers below. The best solution so far is tracked automatically.
53
+ """
54
+
55
+ name = "Abstract Algorithm"
56
+ short_name = "ALG"
57
+
58
+ def __init__(self, *, max_iter=None, pop_size=100, max_nfe=None, target=None,
59
+ max_time=None, display=False):
60
+ self.max_iter = max_iter
61
+ self.pop_size = pop_size
62
+ self.max_nfe = max_nfe
63
+ self.target = target
64
+ self.max_time = max_time
65
+ self.display = display
66
+ self.validate()
67
+
68
+ #: iterations used when no limit at all is given
69
+ default_max_iter = 100
70
+
71
+ @property
72
+ def iter_limit(self):
73
+ """The iteration limit in effect: ``max_iter``, or 100 when no limit is set at all."""
74
+ if self.max_iter is None and self.max_nfe is None and self.max_time is None:
75
+ return self.default_max_iter
76
+ return self.max_iter
77
+
78
+ def planned_iterations(self, evals_per_iter):
79
+ """Expected number of iterations, for schedules that must end with the run
80
+ (for example the SA temperature). Uses whichever limit binds first."""
81
+ limits = [self.iter_limit] if self.iter_limit is not None else []
82
+ if self.max_nfe is not None:
83
+ limits.append(int(np.ceil(self.max_nfe / max(evals_per_iter, 1))))
84
+ return max(min(limits), 1) if limits else self.default_max_iter
85
+
86
+ @property
87
+ def full_name(self):
88
+ return f"{self.name} ({self.short_name})"
89
+
90
+ def params(self) -> dict:
91
+ """The settings of this algorithm (the arguments of its constructor)."""
92
+ names = []
93
+ for cls in type(self).__mro__:
94
+ if "__init__" in vars(cls):
95
+ names += [p for p in inspect.signature(cls.__init__).parameters
96
+ if p not in ("self", "args", "kwargs") and p not in names]
97
+ return {n: getattr(self, n) for n in names if hasattr(self, n)}
98
+
99
+ def __getstate__(self):
100
+ # settings only: run state may hold a lambda objective or an executor
101
+ names = self.params()
102
+ return {k: v for k, v in self.__dict__.items() if k in names}
103
+
104
+ def __repr__(self):
105
+ args = ", ".join(f"{k}={v!r}" for k, v in self.params().items())
106
+ return f"{type(self).__name__}({args})"
107
+
108
+ def validate(self):
109
+ """Check the settings. Subclasses extend it and call ``super().validate()``."""
110
+ check(self.max_iter is None or is_int(self.max_iter, 1), "max_iter must be a positive integer or None")
111
+ check(is_int(self.pop_size, 1), "pop_size must be a positive integer")
112
+ check(self.max_nfe is None or is_int(self.max_nfe, 1), "max_nfe must be a positive integer or None")
113
+ check(self.target is None or is_real(self.target), "target must be a number or None")
114
+ check(self.max_time is None or is_real(self.max_time, 0), "max_time must be a positive number or None")
115
+
116
+ # running
117
+
118
+ def solve(self, problem: Problem, *, seed=None, callbacks=(), executor=None) -> Result:
119
+ """Solve ``problem`` and return a ``Result``.
120
+
121
+ seed : int, numpy Generator, or None
122
+ The same seed gives the same result.
123
+ callbacks : list of callables
124
+ Each is called as ``cb(algorithm)`` after every iteration. A callback that
125
+ returns True stops the run. Objects may also define ``on_start(algorithm)``
126
+ and ``on_end(algorithm, result)``.
127
+ executor : concurrent.futures.Executor, optional
128
+ Evaluate solutions in parallel (not used for vectorized problems).
129
+ """
130
+ if not isinstance(problem, Problem):
131
+ raise TypeError("problem must be a ypea.Problem")
132
+ self.validate()
133
+ self.problem = problem
134
+ self.seed = seed
135
+ self.rng = np.random.default_rng(seed)
136
+ self.evaluator = Evaluator(problem, self.max_nfe, self.target, executor)
137
+ self.iter = 0
138
+ self.pop = None
139
+ self._hist = []
140
+ self._t0 = time.perf_counter()
141
+ stop_reason = None
142
+
143
+ self.initialize()
144
+ self._record()
145
+ for cb in callbacks:
146
+ getattr(cb, "on_start", lambda alg: None)(self)
147
+
148
+ while True:
149
+ stop_reason = self._stop_reason()
150
+ if stop_reason:
151
+ break
152
+ self.iter += 1
153
+ nfe_before = self.nfe
154
+ self.iterate()
155
+ self._record()
156
+ if self.nfe == nfe_before:
157
+ # settings that create no new solutions (for example GA with pop_size=1)
158
+ stop_reason = "no_evaluations"
159
+ break
160
+ if self.display:
161
+ print(f"Iteration {self.iter}: Best Obj. Value = {self.best.obj_value[0]:.6g}, "
162
+ f"NFE = {self.nfe}")
163
+ if any([bool(cb(self)) for cb in callbacks]):
164
+ stop_reason = "callback"
165
+ break
166
+
167
+ result = self._result(stop_reason)
168
+ for cb in callbacks:
169
+ getattr(cb, "on_end", lambda alg, res: None)(self, result)
170
+ return result
171
+
172
+ def initialize(self):
173
+ raise NotImplementedError
174
+
175
+ def iterate(self):
176
+ raise NotImplementedError
177
+
178
+ def _stop_reason(self):
179
+ if self.evaluator.stop_reason:
180
+ return self.evaluator.stop_reason
181
+ if self.iter_limit is not None and self.iter >= self.iter_limit:
182
+ return "max_iter"
183
+ if self.max_time is not None and time.perf_counter() - self._t0 >= self.max_time:
184
+ return "max_time"
185
+ return None
186
+
187
+ def _record(self):
188
+ b = self.best
189
+ self._hist.append((self.iter, self.nfe, b.F[0, 0], b.V[0], time.perf_counter() - self._t0))
190
+
191
+ def _result(self, stop_reason):
192
+ it, nfe, f, v, t = (np.array(c) for c in zip(*self._hist, strict=True))
193
+ ev = self.evaluator
194
+ history = History(it, nfe, f, v, t, np.array(ev.trace_nfe), np.array(ev.trace_f),
195
+ np.array(ev.trace_v))
196
+ b = self.best
197
+ best = Individual(b.X[0].copy(), self.problem.decode_one(b.X[0]), float(b.F[0, 0]), float(b.V[0]))
198
+ return Result(best=best, history=history, algorithm=self.short_name, params=self.params(),
199
+ problem=self.problem.name, seed=self.seed, nfe=self.nfe,
200
+ iterations=self.iter, run_time=float(t[-1]), stop_reason=stop_reason,
201
+ optimum=self.problem.optimum)
202
+
203
+ # helpers for subclasses
204
+
205
+ @property
206
+ def nfe(self) -> int:
207
+ return self.evaluator.nfe
208
+
209
+ @property
210
+ def best(self) -> Population:
211
+ """Best solution found so far, as a Population of length 1."""
212
+ return self.evaluator.best
213
+
214
+ @property
215
+ def dim(self) -> int:
216
+ return self.problem.code_size
217
+
218
+ def evaluate(self, X) -> Population:
219
+ """Evaluate codes (clipped to [0, 1]). Always returns as many rows as ``X``."""
220
+ return self.evaluator(X)
221
+
222
+ def random_population(self, n=None) -> Population:
223
+ return self.evaluate(self.rng.random((self.pop_size if n is None else n, self.dim)))
224
+
225
+ def better(self, a: Population, b: Population) -> np.ndarray:
226
+ """Element wise: is a strictly better than b? Broadcasts a length 1 population."""
227
+ return self.problem.comparator.better(a.F, a.V, b.F, b.V)
228
+
229
+ def no_worse(self, a: Population, b: Population) -> np.ndarray:
230
+ """Element wise: is a at least as good as b?"""
231
+ return ~self.better(b, a)
232
+
233
+ def argsort(self, pop: Population) -> np.ndarray:
234
+ """Indices from best to worst (stable)."""
235
+ return self.problem.comparator.argsort(pop.F, pop.V)
236
+
237
+ def sort(self, pop: Population) -> Population:
238
+ return pop[self.argsort(pop)]
239
+
240
+ def argbest(self, pop: Population) -> int:
241
+ return int(self.argsort(pop)[0])
242
+
243
+ def ranks(self, pop: Population) -> np.ndarray:
244
+ """0 for the best solution, ties share a rank."""
245
+ return self.problem.comparator.ranks(pop.F, pop.V)
246
+
247
+ def selection_probs(self, pop: Population, pressure=1.0) -> np.ndarray:
248
+ """Selection probabilities from ranks: p is proportional to exp(-pressure * r),
249
+ where r goes from 0 (best) to 1 (worst). Independent of the scale of the objective."""
250
+ r = self.ranks(pop)
251
+ r = r / max(len(pop) - 1, 1)
252
+ p = np.exp(-pressure * r)
253
+ return p / p.sum()
@@ -0,0 +1,6 @@
1
+ from .de import DE
2
+ from .ga import GA
3
+ from .pso import PSO
4
+ from .sa import SA
5
+
6
+ __all__ = ["DE", "GA", "PSO", "SA"]