ypea 0.1.0__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.
ypea/__init__.py ADDED
@@ -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
+ ]
ypea/algorithm.py ADDED
@@ -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"]
ypea/algorithms/de.py ADDED
@@ -0,0 +1,134 @@
1
+ """Differential Evolution (DE)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from ..algorithm import Algorithm, check, is_int, is_real
8
+
9
+ _BASES = {
10
+ "rand": "rand", "best": "best",
11
+ "current-to-best": "current-to-best", "target-to-best": "current-to-best",
12
+ "rand-to-best": "rand-to-best",
13
+ }
14
+ _CROSSOVERS = {"bin": "bin", "binomial": "bin", "exp": "exp", "exponential": "exp"}
15
+
16
+
17
+ def parse_strategy(text):
18
+ """Parse 'DE/base/k/crossover'. Missing parts default to 'DE/rand/1/bin'."""
19
+ parts = [p for p in str(text).replace("\\", "/").replace(" ", "").lower().split("/") if p]
20
+ if parts and parts[0] == "de":
21
+ parts = parts[1:]
22
+ base, k, cx = "rand", 1, "bin"
23
+ for p in parts:
24
+ if p.isdigit():
25
+ k = int(p)
26
+ elif p in _BASES:
27
+ base = _BASES[p]
28
+ elif p in _CROSSOVERS:
29
+ cx = _CROSSOVERS[p]
30
+ else:
31
+ raise ValueError(f"unknown part {p!r} in DE strategy {text!r}")
32
+ return base, k, cx
33
+
34
+
35
+ class DE(Algorithm):
36
+ """Differential Evolution (Storn and Price, 1997).
37
+
38
+ Parameters
39
+ ----------
40
+ strategy : str, optional
41
+ Short form like ``"DE/best/2/bin"``. Sets ``base_vector``, ``diff_vectors_count``
42
+ and ``crossover_method``.
43
+ base_vector : "rand", "best", "current-to-best" or "rand-to-best"
44
+ ("target-to-best" is accepted as the MATLAB name of "current-to-best").
45
+ diff_vectors_count : number of difference vectors
46
+ crossover_method : "bin" or "exp"
47
+ crossover_prob : crossover rate CR
48
+ beta_min, beta_max : the scale factor is drawn uniformly from [beta_min, beta_max]
49
+ for every component (dither), as in YPEA for MATLAB.
50
+
51
+ A trial vector replaces its target when it is at least as good (as in the paper).
52
+ All trial vectors of an iteration are built from the same population (synchronous).
53
+ """
54
+
55
+ name = "Differential Evolution"
56
+ short_name = "DE"
57
+
58
+ def __init__(self, strategy=None, *, base_vector="rand", diff_vectors_count=1,
59
+ crossover_method="bin", crossover_prob=0.2, beta_min=0.2, beta_max=0.9, **kwargs):
60
+ if strategy is not None:
61
+ base_vector, diff_vectors_count, crossover_method = parse_strategy(strategy)
62
+ self.base_vector = _BASES.get(base_vector, base_vector)
63
+ self.diff_vectors_count = diff_vectors_count
64
+ self.crossover_method = _CROSSOVERS.get(crossover_method, crossover_method)
65
+ self.crossover_prob = crossover_prob
66
+ self.beta_min, self.beta_max = beta_min, beta_max
67
+ super().__init__(**kwargs)
68
+
69
+ @property
70
+ def strategy(self):
71
+ return f"DE/{self.base_vector}/{self.diff_vectors_count}/{self.crossover_method}"
72
+
73
+ def validate(self):
74
+ super().validate()
75
+ check(self.base_vector in _BASES.values(), f"unknown base_vector {self.base_vector!r}")
76
+ check(self.crossover_method in ("bin", "exp"), "crossover_method must be 'bin' or 'exp'")
77
+ check(is_int(self.diff_vectors_count, 1), "diff_vectors_count must be a positive integer")
78
+ check(is_real(self.crossover_prob, 0, 1), "crossover_prob must be in [0, 1]")
79
+ check(is_real(self.beta_min, 0) and is_real(self.beta_max, 0) and self.beta_min <= self.beta_max,
80
+ "need 0 <= beta_min <= beta_max")
81
+ need = 2 * self.diff_vectors_count + (self.base_vector in ("rand", "rand-to-best")) + 1
82
+ check(self.pop_size >= need, f"{self.strategy} needs pop_size >= {need}")
83
+
84
+ def initialize(self):
85
+ self.pop = self.random_population()
86
+
87
+ def _beta(self, shape):
88
+ return self.rng.uniform(self.beta_min, self.beta_max, shape)
89
+
90
+ def iterate(self):
91
+ X = self.pop.X
92
+ n, d = X.shape
93
+ k = self.diff_vectors_count
94
+ uses_rand = self.base_vector in ("rand", "rand-to-best")
95
+ # distinct random partners for every target, none equal to the target itself
96
+ keys = self.rng.random((n, n))
97
+ np.fill_diagonal(keys, np.inf)
98
+ idx = np.argsort(keys, axis=1)[:, : 2 * k + uses_rand]
99
+
100
+ best = self.best.X
101
+ if self.base_vector == "rand":
102
+ base = X[idx[:, 0]]
103
+ elif self.base_vector == "best":
104
+ base = np.broadcast_to(best, X.shape)
105
+ elif self.base_vector == "current-to-best":
106
+ base = X + self._beta(X.shape) * (best - X)
107
+ else: # rand-to-best
108
+ r = X[idx[:, 0]]
109
+ base = r + self._beta(X.shape) * (best - r)
110
+ diffs = idx[:, int(uses_rand):]
111
+ mutant = base.copy()
112
+ for j in range(k):
113
+ mutant += self._beta(X.shape) * (X[diffs[:, 2 * j]] - X[diffs[:, 2 * j + 1]])
114
+
115
+ mask = self._crossover_mask(n, d)
116
+ trial = np.where(mask, mutant, X)
117
+ new = self.evaluate(trial)
118
+ self.pop.replace(self.no_worse(new, self.pop), new)
119
+
120
+ def _crossover_mask(self, n, d):
121
+ cr = self.crossover_prob
122
+ if self.crossover_method == "bin":
123
+ mask = self.rng.random((n, d)) <= cr
124
+ mask[np.arange(n), self.rng.integers(d, size=n)] = True
125
+ return mask
126
+ # exponential: from a random start, copy L consecutive components (cyclic), where
127
+ # L is 1 plus the number of successes before the first failure, at most d
128
+ start = self.rng.integers(d, size=n)
129
+ if cr >= 1:
130
+ length = np.full(n, d)
131
+ else:
132
+ length = np.minimum(self.rng.geometric(1 - cr, size=n), d)
133
+ offset = (np.arange(d)[None, :] - start[:, None]) % d
134
+ return offset < length[:, None]
ypea/algorithms/ga.py ADDED
@@ -0,0 +1,110 @@
1
+ """Genetic Algorithm (GA)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from ..algorithm import Algorithm, check, is_real
8
+
9
+ _SELECTION = {"random": "random", "rand": "random",
10
+ "roulettewheel": "roulettewheel", "roulette": "roulettewheel", "rw": "roulettewheel",
11
+ "tournament": "tournament"}
12
+
13
+
14
+ class GA(Algorithm):
15
+ """Real coded Genetic Algorithm with (mu + lambda) survival, as in YPEA for MATLAB.
16
+
17
+ Parameters
18
+ ----------
19
+ crossover_prob : fraction of the population size produced by crossover
20
+ crossover_inflation : gamma of blend crossover. Each child component is
21
+ a*x1 + (1 - a)*x2 with a drawn from [-gamma, 1 + gamma] (BLX alpha).
22
+ mutation_prob : fraction of the population size produced by mutation
23
+ mutation_rate : fraction of components changed in a mutant
24
+ mutation_step_size : standard deviation of the Gaussian mutation (in code units)
25
+ mutation_step_size_damp : the step size is multiplied by this after every iteration
26
+ selection : "roulettewheel" (rank based), "tournament" or "random"
27
+ selection_pressure : pressure for roulette wheel selection
28
+ tournament_size : number of competitors in tournament selection
29
+
30
+ Parents, mutants and children are merged, and the best ``pop_size`` survive.
31
+ Roulette wheel selection uses ranks, so it does not depend on the scale or sign of
32
+ the objective (MATLAB used raw objective values).
33
+
34
+ References: Goldberg (1989). Eshelman and Schaffer (1993) for blend crossover.
35
+ """
36
+
37
+ name = "Genetic Algorithm"
38
+ short_name = "GA"
39
+
40
+ def __init__(self, *, crossover_prob=0.7, crossover_inflation=0.1, mutation_prob=0.3,
41
+ mutation_rate=0.1, mutation_step_size=0.1, mutation_step_size_damp=0.99,
42
+ selection="roulettewheel", selection_pressure=5.0, tournament_size=3, **kwargs):
43
+ self.crossover_prob = crossover_prob
44
+ self.crossover_inflation = crossover_inflation
45
+ self.mutation_prob = mutation_prob
46
+ self.mutation_rate = mutation_rate
47
+ self.mutation_step_size = mutation_step_size
48
+ self.mutation_step_size_damp = mutation_step_size_damp
49
+ self.selection = _SELECTION.get(str(selection).lower(), selection)
50
+ self.selection_pressure = selection_pressure
51
+ self.tournament_size = tournament_size
52
+ super().__init__(**kwargs)
53
+
54
+ def validate(self):
55
+ super().validate()
56
+ check(is_real(self.crossover_prob, 0), "crossover_prob must be non negative")
57
+ check(is_real(self.mutation_prob, 0), "mutation_prob must be non negative")
58
+ check(is_real(self.crossover_inflation, 0), "crossover_inflation must be non negative")
59
+ check(is_real(self.mutation_rate, 0, 1), "mutation_rate must be in [0, 1]")
60
+ check(is_real(self.mutation_step_size, 0), "mutation_step_size must be non negative")
61
+ check(is_real(self.mutation_step_size_damp, 0) and self.mutation_step_size_damp > 0,
62
+ "mutation_step_size_damp must be positive")
63
+ check(self.selection in _SELECTION.values(),
64
+ "selection must be 'roulettewheel', 'tournament' or 'random'")
65
+ check(is_real(self.selection_pressure, 0), "selection_pressure must be non negative")
66
+ check(isinstance(self.tournament_size, int) and self.tournament_size >= 1,
67
+ "tournament_size must be a positive integer")
68
+
69
+ def initialize(self):
70
+ self.pop = self.sort(self.random_population())
71
+ self._sigma = self.mutation_step_size
72
+
73
+ def select(self, count):
74
+ """Indices of ``count`` parents from the current (sorted) population."""
75
+ n = len(self.pop)
76
+ if self.selection == "random":
77
+ return self.rng.integers(n, size=count)
78
+ if self.selection == "roulettewheel":
79
+ return self.rng.choice(n, size=count, p=self.selection_probs(self.pop, self.selection_pressure))
80
+ # tournament: the population is sorted, so the smallest index wins
81
+ return self.rng.integers(n, size=(count, self.tournament_size)).min(axis=1)
82
+
83
+ def crossover(self, x1, x2):
84
+ g = self.crossover_inflation
85
+ a = self.rng.uniform(-g, 1 + g, x1.shape)
86
+ return a * x1 + (1 - a) * x2, a * x2 + (1 - a) * x1
87
+
88
+ def mutate(self, x):
89
+ n, d = x.shape
90
+ k = int(np.ceil(self.mutation_rate * d))
91
+ cols = np.argsort(self.rng.random((n, d)), axis=1)[:, :k]
92
+ y = x.copy()
93
+ rows = np.arange(n)[:, None]
94
+ y[rows, cols] += self._sigma * self.rng.standard_normal((n, k))
95
+ return y
96
+
97
+ def iterate(self):
98
+ n = self.pop_size
99
+ nc = 2 * round(self.crossover_prob * n / 2)
100
+ nm = round(self.mutation_prob * n)
101
+ children = []
102
+ if nc:
103
+ p = self.select(nc)
104
+ y1, y2 = self.crossover(self.pop.X[p[0::2]], self.pop.X[p[1::2]])
105
+ children.append(self.evaluate(np.vstack([y1, y2])))
106
+ if nm:
107
+ children.append(self.evaluate(self.mutate(self.pop.X[self.rng.integers(len(self.pop), size=nm)])))
108
+ merged = self.pop.concat(self.pop, *children)
109
+ self.pop = self.sort(merged)[:n] if len(merged) > n else self.sort(merged)
110
+ self._sigma *= self.mutation_step_size_damp
ypea/algorithms/pso.py ADDED
@@ -0,0 +1,66 @@
1
+ """Particle Swarm Optimization (PSO)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from ..algorithm import Algorithm, check, is_real
8
+
9
+
10
+ class PSO(Algorithm):
11
+ """Particle Swarm Optimization with inertia weight (global best topology).
12
+
13
+ Parameters
14
+ ----------
15
+ w : inertia weight
16
+ wdamp : the inertia weight is multiplied by this after every iteration
17
+ c1 : personal acceleration coefficient
18
+ c2 : global acceleration coefficient
19
+
20
+ Particles that leave [0, 1] are clipped and the offending velocity components are
21
+ reversed (as in YPEA for MATLAB). Use ``use_constriction_coeffs`` for the
22
+ Clerc and Kennedy constriction coefficients.
23
+
24
+ References: Kennedy and Eberhart (1995). Shi and Eberhart (1998).
25
+ Clerc and Kennedy (2002).
26
+ """
27
+
28
+ name = "Particle Swarm Optimization"
29
+ short_name = "PSO"
30
+
31
+ def __init__(self, *, w=1.0, wdamp=0.99, c1=2.0, c2=2.0, **kwargs):
32
+ self.w, self.wdamp, self.c1, self.c2 = w, wdamp, c1, c2
33
+ super().__init__(**kwargs)
34
+
35
+ def validate(self):
36
+ super().validate()
37
+ check(is_real(self.w, 0), "w must be non negative")
38
+ check(is_real(self.wdamp, 0, 1) and self.wdamp > 0, "wdamp must be in (0, 1]")
39
+ check(is_real(self.c1, 0) and is_real(self.c2, 0), "c1 and c2 must be non negative")
40
+
41
+ def use_constriction_coeffs(self, phi1=2.05, phi2=2.05):
42
+ """Set w, c1 and c2 from Clerc and Kennedy (2002). phi1 + phi2 is raised to 4 if lower."""
43
+ phi = phi1 + phi2
44
+ if phi < 4:
45
+ phi1, phi2, phi = 4 * phi1 / phi, 4 * phi2 / phi, 4.0
46
+ chi = float(2 / (phi - 2 + np.sqrt(phi**2 - 4 * phi)))
47
+ self.w, self.wdamp, self.c1, self.c2 = chi, 1.0, chi * phi1, chi * phi2
48
+ return self
49
+
50
+ def initialize(self):
51
+ self.pop = self.random_population()
52
+ self.velocity = np.zeros_like(self.pop.X)
53
+ self.pbest = self.pop.copy()
54
+ self._w = self.w
55
+
56
+ def iterate(self):
57
+ X, V = self.pop.X, self.velocity
58
+ r1, r2 = self.rng.random((2, *X.shape))
59
+ V = self._w * V + self.c1 * r1 * (self.pbest.X - X) + self.c2 * r2 * (self.best.X - X)
60
+ X = X + V
61
+ out = (X < 0) | (X > 1)
62
+ V[out] = -V[out]
63
+ self.velocity = V
64
+ self.pop = self.evaluate(X)
65
+ self.pbest.replace(self.better(self.pop, self.pbest), self.pop)
66
+ self._w *= self.wdamp