moofs 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.
moofs/__init__.py ADDED
@@ -0,0 +1,64 @@
1
+ """moofs — Multi-Objective Optimization for Feature Selection.
2
+
3
+ A reference library of multi-objective feature-selection algorithms with a
4
+ scikit-learn compatible API, Pareto-front visualization, and
5
+ PlatEMO-compatible quality indicators.
6
+
7
+ v0.1 algorithms: MOFS-RFGA (Xue, Zhu & Neri, 2023) and NSGA-II (Deb et al.,
8
+ 2002).
9
+
10
+ Quick start
11
+ -----------
12
+ >>> from moofs import MOFSSelector
13
+ >>> selector = MOFSSelector(algorithm="mofs-rfga", max_evals=2000,
14
+ ... random_state=0)
15
+ >>> X_reduced = selector.fit_transform(X, y)
16
+
17
+ Research-style API
18
+ ------------------
19
+ >>> from moofs import FeatureSelectionProblem, MOFSRFGA
20
+ >>> problem = FeatureSelectionProblem(X, y)
21
+ >>> result = MOFSRFGA(problem, pop_size=60, max_evals=2000, seed=0).run()
22
+ >>> result.F
23
+ """
24
+
25
+ from .algorithms import MOFSRFGA, NSGA2
26
+ from .core import (
27
+ Algorithm,
28
+ FeatureSelectionProblem,
29
+ Problem,
30
+ Result,
31
+ Solution,
32
+ )
33
+ from .filters import mutual_information, relieff
34
+ from .metrics import (
35
+ compare,
36
+ coverage,
37
+ gd,
38
+ hv,
39
+ hv_raw,
40
+ igd,
41
+ merge_reference_front,
42
+ nfs,
43
+ spacing,
44
+ )
45
+ from .plotting import plot_fronts, plot_pareto_front, plot_selector
46
+ from .selection import MOFSSelector
47
+
48
+ __version__ = "0.1.0"
49
+
50
+ ALGORITHMS = {
51
+ "mofs-rfga": MOFSRFGA,
52
+ "nsga2": NSGA2,
53
+ }
54
+
55
+ __all__ = [
56
+ "MOFSSelector",
57
+ "MOFSRFGA", "NSGA2", "ALGORITHMS",
58
+ "Problem", "FeatureSelectionProblem", "Solution", "Algorithm", "Result",
59
+ "relieff", "mutual_information",
60
+ "igd", "gd", "hv", "hv_raw", "coverage", "nfs", "spacing",
61
+ "merge_reference_front", "compare",
62
+ "plot_pareto_front", "plot_fronts", "plot_selector",
63
+ "__version__",
64
+ ]
@@ -0,0 +1,4 @@
1
+ from .mofs_rfga import MOFSRFGA
2
+ from .nsga2 import NSGA2
3
+
4
+ __all__ = ["MOFSRFGA", "NSGA2"]
@@ -0,0 +1,141 @@
1
+ """MOFS-RFGA: Multi-Objective Feature Selection with ReliefF and Genetic
2
+ Algorithm.
3
+
4
+ Reference: Y. Xue, H. Zhu, F. Neri, "A feature selection approach based on
5
+ NSGA-II with ReliefF", Applied Soft Computing 134 (2023) 109987.
6
+ https://doi.org/10.1016/j.asoc.2023.109987
7
+
8
+ Hybrid filter/wrapper method: a ReliefF (or any filter) score vector guides
9
+ the initialisation, a 3-parent crossover and the mutation; NSGA-II
10
+ environmental selection drives the multi-objective search.
11
+
12
+ Note on the crossover semantics: the paper's Fig. 1 and its Algorithm 3
13
+ disagree on which gene is removed from S2 / added from S1. The default here
14
+ follows Fig. 1 (remove the *worse*-scored gene from S2, add the
15
+ *better*-scored gene from S1), which is consistent with the mutation
16
+ operator's prose and the score-guided philosophy of the method. Pass
17
+ ``interpretation="pseudocode"`` for the literal Algorithm 3 reading.
18
+ """
19
+
20
+ import numpy as np
21
+
22
+ from ..core.algorithm import Algorithm
23
+ from ..core.dominance import dominates, environmental_selection
24
+ from ..core.operators import ensure_nonempty
25
+ from ..filters import relieff
26
+
27
+
28
+ class MOFSRFGA(Algorithm):
29
+ """MOFS-RFGA in the unified API.
30
+
31
+ Parameters
32
+ ----------
33
+ sc : array-like of float, optional
34
+ Feature-score vector (higher = better). If None, ReliefF scores are
35
+ computed automatically from ``problem.X`` and ``problem.y``.
36
+ D_init : int, optional
37
+ Upper bound on the number of features selected at initialisation;
38
+ defaults to ``n_var``.
39
+ """
40
+
41
+ name = "MOFS-RFGA"
42
+
43
+ def __init__(self, problem, pop_size=60, max_evals=20000, sc=None,
44
+ D_init=None, interpretation="figure", seed=None,
45
+ verbose=False):
46
+ super().__init__(problem, pop_size, max_evals, seed, verbose)
47
+ if sc is None:
48
+ sc = relieff(problem.X, problem.y)
49
+ self.sc = np.asarray(sc, dtype=float)
50
+ self.D_init = D_init if D_init is not None else problem.n_var
51
+ if interpretation not in ("figure", "pseudocode"):
52
+ raise ValueError("interpretation must be 'figure' or 'pseudocode'")
53
+ self.interpretation = interpretation
54
+
55
+
56
+ def _initial_population(self):
57
+ pop = []
58
+ for _ in range(self.pop_size):
59
+ x = np.zeros(self.problem.n_var, dtype=int)
60
+ R = self.rng.integers(1, max(2, self.D_init))
61
+ for _ in range(R):
62
+ i, j = self.rng.choice(len(self.sc), size=2, replace=False)
63
+ x[i if self.sc[i] >= self.sc[j] else j] = 1
64
+ x = ensure_nonempty(x, self.rng)
65
+ pop.append(self.evaluate(x))
66
+ return pop
67
+
68
+
69
+ def _tournament_parents(self, pop, k=3):
70
+ parents = []
71
+ for _ in range(k):
72
+ i, j = self.rng.choice(len(pop), size=2, replace=False)
73
+ a, b = pop[i], pop[j]
74
+ if dominates(a.F, b.F):
75
+ parents.append(a)
76
+ elif dominates(b.F, a.F):
77
+ parents.append(b)
78
+ else:
79
+ parents.append(a if self.rng.random() < 0.5 else b)
80
+ return parents
81
+
82
+ def _crossover_3_to_1(self, p1, p2, p3):
83
+ L1, L2, L3 = p1 & p2, p1 & p3, p2 & p3
84
+ O = np.logical_or(L1, np.logical_or(L2, L3)).astype(int)
85
+ S3 = L1 & L2 & L3 # genes selected 3 times
86
+ S2 = O ^ S3 # genes selected exactly twice
87
+ S1 = np.logical_or(p1, np.logical_or(p2, p3)).astype(int) ^ S3 ^ S2
88
+ remove_better = self.interpretation == "pseudocode"
89
+ if self.rng.random() < 0.5:
90
+ cand = np.where(S2 == 1)[0]
91
+ if len(cand) > 0:
92
+ picks = self.rng.choice(cand, size=min(2, len(cand)),
93
+ replace=False)
94
+ key = max if remove_better else min
95
+ target = key(picks, key=lambda d: self.sc[d])
96
+ O[target] = 0
97
+ else:
98
+ cand = np.where(S1 == 1)[0]
99
+ if len(cand) > 0:
100
+ picks = self.rng.choice(cand, size=min(2, len(cand)),
101
+ replace=False)
102
+ key = min if remove_better else max
103
+ target = key(picks, key=lambda d: self.sc[d])
104
+ O[target] = 1
105
+ return O
106
+
107
+ def _mutation(self, o):
108
+ o = o.copy()
109
+ if self.rng.random() < 0.5:
110
+ cand = np.where(o == 1)[0]
111
+ if len(cand) > 0:
112
+ picks = self.rng.choice(cand, size=min(2, len(cand)),
113
+ replace=False)
114
+ worst = min(picks, key=lambda d: self.sc[d])
115
+ o[worst] = 0
116
+ else:
117
+ cand = np.where(o == 0)[0]
118
+ if len(cand) > 0:
119
+ picks = self.rng.choice(cand, size=min(2, len(cand)),
120
+ replace=False)
121
+ best = max(picks, key=lambda d: self.sc[d])
122
+ o[best] = 1
123
+ return o
124
+
125
+
126
+ def _run(self):
127
+ pop = self._initial_population()
128
+ pop = environmental_selection(pop, self.pop_size)
129
+ gen = 0
130
+ while self.budget_left():
131
+ offspring = []
132
+ while len(offspring) < self.pop_size and self.budget_left():
133
+ p1, p2, p3 = self._tournament_parents(pop)
134
+ c = self._crossover_3_to_1(p1.x, p2.x, p3.x)
135
+ c = self._mutation(c)
136
+ c = ensure_nonempty(c, self.rng)
137
+ offspring.append(self.evaluate(c))
138
+ pop = environmental_selection(pop + offspring, self.pop_size)
139
+ gen += 1
140
+ self.log(f"gen={gen} evals={self.n_evals}")
141
+ return self._result(pop)
@@ -0,0 +1,70 @@
1
+ """NSGA-II (Deb et al., 2002) with binary encoding for feature selection.
2
+
3
+ Default parameters follow the MOFS literature: Pc = 0.9, Pm = 1/D.
4
+ """
5
+
6
+ from ..core.algorithm import Algorithm
7
+ from ..core.dominance import environmental_selection
8
+ from ..core.operators import (
9
+ binary_tournament,
10
+ bitflip_mutation,
11
+ ensure_nonempty,
12
+ single_point_crossover,
13
+ uniform_crossover,
14
+ )
15
+
16
+
17
+ class NSGA2(Algorithm):
18
+ """NSGA-II for binary multi-objective feature selection.
19
+
20
+ Parameters
21
+ ----------
22
+ pc : float, default=0.9
23
+ Crossover probability.
24
+ pm : float, optional
25
+ Per-gene mutation probability; defaults to 1/D.
26
+ crossover : {"single_point", "uniform"}, default="single_point"
27
+ """
28
+
29
+ name = "NSGA-II"
30
+
31
+ def __init__(self, problem, pop_size=60, max_evals=20000, pc=0.9, pm=None,
32
+ crossover="single_point", seed=None, verbose=False):
33
+ super().__init__(problem, pop_size, max_evals, seed, verbose)
34
+ self.pc = pc
35
+ self.pm = pm if pm is not None else 1.0 / problem.n_var
36
+ self._crossover = (uniform_crossover if crossover == "uniform"
37
+ else single_point_crossover)
38
+
39
+ def _initial_population(self):
40
+ pop = []
41
+ for _ in range(self.pop_size):
42
+ x = (self.rng.random(self.problem.n_var) < 0.5).astype(int)
43
+ x = ensure_nonempty(x, self.rng)
44
+ pop.append(self.evaluate(x))
45
+ return pop
46
+
47
+ def _sort_population(self, population):
48
+ """Hook overridden by NSGA-II/SDR."""
49
+ return environmental_selection(population, self.pop_size)
50
+
51
+ def _run(self):
52
+ pop = self._initial_population()
53
+ pop = self._sort_population(pop)
54
+ gen = 0
55
+ while self.budget_left():
56
+ offspring = []
57
+ while len(offspring) < self.pop_size and self.budget_left():
58
+ p1 = binary_tournament(pop, self.rng)
59
+ p2 = binary_tournament(pop, self.rng)
60
+ c1, c2 = self._crossover(p1.x, p2.x, self.rng, pc=self.pc)
61
+ for c in (c1, c2):
62
+ if len(offspring) >= self.pop_size or not self.budget_left():
63
+ break
64
+ c = bitflip_mutation(c, self.rng, pm=self.pm)
65
+ c = ensure_nonempty(c, self.rng)
66
+ offspring.append(self.evaluate(c))
67
+ pop = self._sort_population(pop + offspring)
68
+ gen += 1
69
+ self.log(f"gen={gen} evals={self.n_evals}")
70
+ return self._result(pop)
moofs/core/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ from .algorithm import Algorithm, Result
2
+ from .dominance import (
3
+ crowding_distance,
4
+ dominates,
5
+ environmental_selection,
6
+ fast_non_dominated_sort,
7
+ nondominated,
8
+ sdr_sort,
9
+ )
10
+ from .problem import FeatureSelectionProblem, Problem
11
+ from .solution import Solution, population_F
12
+
13
+ __all__ = [
14
+ "Algorithm", "Result", "Problem", "FeatureSelectionProblem",
15
+ "Solution", "population_F", "dominates", "fast_non_dominated_sort",
16
+ "crowding_distance", "environmental_selection", "nondominated", "sdr_sort",
17
+ ]
@@ -0,0 +1,94 @@
1
+ """Base class shared by every algorithm, and the Result container."""
2
+
3
+ import numpy as np
4
+
5
+ from .dominance import nondominated
6
+ from .solution import Solution, population_F
7
+
8
+
9
+ class Result:
10
+ """Outcome of a run.
11
+
12
+ Attributes
13
+ ----------
14
+ front : list of Solution
15
+ Non-dominated solutions found.
16
+ population : list of Solution
17
+ Final population (or archive).
18
+ n_evals : int
19
+ Number of objective-function evaluations consumed.
20
+ algorithm : str
21
+ Name of the algorithm.
22
+ """
23
+
24
+ def __init__(self, front, population, n_evals, algorithm):
25
+ self.front = front
26
+ self.population = population
27
+ self.n_evals = n_evals
28
+ self.algorithm = algorithm
29
+
30
+ @property
31
+ def F(self):
32
+ """Objective matrix of the front (n_solutions x n_obj)."""
33
+ return population_F(self.front)
34
+
35
+ def __repr__(self):
36
+ return (f"Result(algorithm={self.algorithm!r}, "
37
+ f"front={len(self.front)}, n_evals={self.n_evals})")
38
+
39
+
40
+ class Algorithm:
41
+ """Base class for all algorithms.
42
+
43
+ Parameters
44
+ ----------
45
+ problem : Problem
46
+ pop_size : int, default=60
47
+ Population (or swarm/archive) size N.
48
+ max_evals : int, default=20000
49
+ Maximum number of objective-function evaluations (maxFES).
50
+ seed : int, optional
51
+ Random seed for reproducibility.
52
+ verbose : bool, default=False
53
+ """
54
+
55
+ name = "algorithm"
56
+
57
+ def __init__(self, problem, pop_size=60, max_evals=20000, seed=None,
58
+ verbose=False):
59
+ self.problem = problem
60
+ self.pop_size = pop_size
61
+ self.max_evals = max_evals
62
+ self.rng = np.random.default_rng(seed)
63
+ self.verbose = verbose
64
+ self._start_evals = 0
65
+
66
+
67
+ def evaluate(self, x):
68
+ """Evaluate a decision vector and wrap it in a Solution."""
69
+ return Solution(x, self.problem.evaluate(x))
70
+
71
+ @property
72
+ def n_evals(self):
73
+ return self.problem.n_evals - self._start_evals
74
+
75
+ def budget_left(self):
76
+ return self.n_evals < self.max_evals
77
+
78
+ def log(self, *args):
79
+ if self.verbose:
80
+ print(f"[{self.name}]", *args)
81
+
82
+ def _result(self, population):
83
+ front = nondominated([s for s in population if s.F is not None])
84
+ return Result(front, population, self.n_evals, self.name)
85
+
86
+ # -- interface ---------------------------------------------------------
87
+
88
+ def run(self):
89
+ """Run the algorithm until the FE budget is exhausted."""
90
+ self._start_evals = self.problem.n_evals
91
+ return self._run()
92
+
93
+ def _run(self):
94
+ raise NotImplementedError
@@ -0,0 +1,165 @@
1
+ """Dominance relations and sorting procedures (Pareto and SDR)."""
2
+
3
+ import numpy as np
4
+
5
+ from .solution import population_F
6
+
7
+
8
+ def dominates(f1, f2):
9
+ """Pareto dominance for minimization: f1 dominates f2."""
10
+ f1 = np.asarray(f1)
11
+ f2 = np.asarray(f2)
12
+ return bool(np.all(f1 <= f2) and np.any(f1 < f2))
13
+
14
+
15
+ def fast_non_dominated_sort(population):
16
+ """Deb's fast non-dominated sort. Assigns ``rank`` (1-based) and returns fronts."""
17
+ n = len(population)
18
+ S = [[] for _ in range(n)]
19
+ n_dom = np.zeros(n, dtype=int)
20
+ fronts = [[]]
21
+
22
+ for i in range(n):
23
+ for j in range(i + 1, n):
24
+ if dominates(population[i].F, population[j].F):
25
+ S[i].append(j)
26
+ n_dom[j] += 1
27
+ elif dominates(population[j].F, population[i].F):
28
+ S[j].append(i)
29
+ n_dom[i] += 1
30
+ if n_dom[i] == 0:
31
+ population[i].rank = 1
32
+ fronts[0].append(i)
33
+
34
+ k = 0
35
+ while fronts[k]:
36
+ next_front = []
37
+ for i in fronts[k]:
38
+ for j in S[i]:
39
+ n_dom[j] -= 1
40
+ if n_dom[j] == 0:
41
+ population[j].rank = k + 2
42
+ next_front.append(j)
43
+ k += 1
44
+ fronts.append(next_front)
45
+ fronts.pop()
46
+ return [[population[i] for i in front] for front in fronts]
47
+
48
+
49
+ def crowding_distance(front):
50
+ """Compute and assign NSGA-II crowding distances within a front."""
51
+ n = len(front)
52
+ if n == 0:
53
+ return front
54
+ F = population_F(front)
55
+ dist = np.zeros(n)
56
+ for m in range(F.shape[1]):
57
+ order = np.argsort(F[:, m])
58
+ fmin, fmax = F[order[0], m], F[order[-1], m]
59
+ dist[order[0]] = dist[order[-1]] = np.inf
60
+ if fmax - fmin == 0:
61
+ continue
62
+ for k in range(1, n - 1):
63
+ dist[order[k]] += (F[order[k + 1], m] - F[order[k - 1], m]) / (fmax - fmin)
64
+ for s, d in zip(front, dist):
65
+ s.crowding = d
66
+ return front
67
+
68
+
69
+ def environmental_selection(population, n_survive):
70
+ """Standard NSGA-II environmental selection (rank then crowding)."""
71
+ fronts = fast_non_dominated_sort(population)
72
+ survivors = []
73
+ for front in fronts:
74
+ crowding_distance(front)
75
+ if len(survivors) + len(front) <= n_survive:
76
+ survivors.extend(front)
77
+ else:
78
+ front = sorted(front, key=lambda s: s.crowding, reverse=True)
79
+ survivors.extend(front[: n_survive - len(survivors)])
80
+ break
81
+ return survivors
82
+
83
+
84
+ def nondominated(population):
85
+ """Return the non-dominated subset of a population."""
86
+ if not population:
87
+ return []
88
+ fronts = fast_non_dominated_sort(population)
89
+ return fronts[0]
90
+
91
+
92
+ # ---------------------------------------------------------------------------
93
+ # Strengthened Dominance Relation (SDR), Tian et al., IEEE TEVC 2019.
94
+ # ---------------------------------------------------------------------------
95
+
96
+ def sdr_sort(population):
97
+ """Non-dominated sort under the Strengthened Dominance Relation.
98
+
99
+ x SDR-dominates y iff::
100
+
101
+ Con(x) < Con(y) if angle(x, y) < theta_bar
102
+ Con(x) * angle/theta_bar < Con(y) otherwise
103
+
104
+ where ``Con`` is the sum of normalized objectives and ``theta_bar`` is an
105
+ adaptive niche angle (mean angle of each solution to its nearest
106
+ neighbour, following the adaptive estimation of the original paper).
107
+ Assigns ``rank`` and returns the fronts.
108
+ """
109
+ n = len(population)
110
+ F = population_F(population)
111
+ fmin = F.min(axis=0)
112
+ fmax = F.max(axis=0)
113
+ span = np.where(fmax - fmin == 0, 1.0, fmax - fmin)
114
+ Fn = (F - fmin) / span
115
+ con = Fn.sum(axis=1)
116
+
117
+ # Pairwise angles between normalized objective vectors.
118
+ norms = np.linalg.norm(Fn, axis=1)
119
+ norms = np.where(norms == 0, 1e-12, norms)
120
+ cos = np.clip((Fn @ Fn.T) / np.outer(norms, norms), -1.0, 1.0)
121
+ angle = np.arccos(cos)
122
+ np.fill_diagonal(angle, np.inf)
123
+ nearest = angle.min(axis=1)
124
+ finite = nearest[np.isfinite(nearest)]
125
+ theta_bar = float(finite.mean()) if len(finite) else np.pi / 2
126
+ theta_bar = max(theta_bar, 1e-12)
127
+
128
+ def sdr_dom(i, j):
129
+ a = angle[i, j]
130
+ if a < theta_bar:
131
+ return con[i] < con[j]
132
+ return con[i] * (a / theta_bar) < con[j]
133
+
134
+ S = [[] for _ in range(n)]
135
+ n_dom = np.zeros(n, dtype=int)
136
+ fronts = [[]]
137
+ for i in range(n):
138
+ for j in range(i + 1, n):
139
+ if sdr_dom(i, j):
140
+ S[i].append(j)
141
+ n_dom[j] += 1
142
+ elif sdr_dom(j, i):
143
+ S[j].append(i)
144
+ n_dom[i] += 1
145
+ if n_dom[i] == 0:
146
+ population[i].rank = 1
147
+ fronts[0].append(i)
148
+
149
+ k = 0
150
+ while fronts[k]:
151
+ nxt = []
152
+ for i in fronts[k]:
153
+ for j in S[i]:
154
+ n_dom[j] -= 1
155
+ if n_dom[j] == 0:
156
+ population[j].rank = k + 2
157
+ nxt.append(j)
158
+ k += 1
159
+ fronts.append(nxt)
160
+ fronts.pop()
161
+ if not fronts: # degenerate case: everything mutually SDR-dominated
162
+ for s in population:
163
+ s.rank = 1
164
+ return [list(population)]
165
+ return [[population[i] for i in front] for front in fronts]
@@ -0,0 +1,113 @@
1
+ """Variation operators: binary GA operators, SBX, polynomial mutation, repair."""
2
+
3
+ import numpy as np
4
+
5
+ from .dominance import dominates
6
+
7
+
8
+
9
+ def binary_tournament(population, rng, key=None):
10
+ """Binary tournament selection.
11
+
12
+ ``key(s)`` must return a sortable value where *smaller is better*.
13
+ Default key: (rank, -crowding), i.e. NSGA-II comparison.
14
+ """
15
+ if key is None:
16
+ key = lambda s: (s.rank, -s.crowding)
17
+ i, j = rng.choice(len(population), size=2, replace=False)
18
+ a, b = population[i], population[j]
19
+ return a if key(a) <= key(b) else b
20
+
21
+
22
+ def dominance_tournament(population, rng):
23
+ """Binary tournament based on raw Pareto dominance (random tie-break)."""
24
+ i, j = rng.choice(len(population), size=2, replace=False)
25
+ a, b = population[i], population[j]
26
+ if dominates(a.F, b.F):
27
+ return a
28
+ if dominates(b.F, a.F):
29
+ return b
30
+ return a if rng.random() < 0.5 else b
31
+
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Binary operators
35
+ # ---------------------------------------------------------------------------
36
+
37
+ def single_point_crossover(x1, x2, rng, pc=0.9):
38
+ """Single-point crossover on binary vectors."""
39
+ x1 = x1.copy()
40
+ x2 = x2.copy()
41
+ if rng.random() < pc and len(x1) > 1:
42
+ point = rng.integers(1, len(x1))
43
+ c1 = np.concatenate([x1[:point], x2[point:]])
44
+ c2 = np.concatenate([x2[:point], x1[point:]])
45
+ return c1, c2
46
+ return x1, x2
47
+
48
+
49
+ def uniform_crossover(x1, x2, rng, pc=0.9):
50
+ """Uniform crossover on binary vectors."""
51
+ x1 = x1.copy()
52
+ x2 = x2.copy()
53
+ if rng.random() < pc:
54
+ mask = rng.random(len(x1)) < 0.5
55
+ c1 = np.where(mask, x1, x2)
56
+ c2 = np.where(mask, x2, x1)
57
+ return c1, c2
58
+ return x1, x2
59
+
60
+
61
+ def bitflip_mutation(x, rng, pm=None):
62
+ """Bit-flip mutation with probability ``pm`` per gene (default 1/D)."""
63
+ x = x.copy()
64
+ if pm is None:
65
+ pm = 1.0 / len(x)
66
+ flip = rng.random(len(x)) < pm
67
+ x[flip] = 1 - x[flip]
68
+ return x
69
+
70
+
71
+ def ensure_nonempty(mask, rng):
72
+ """Repair an all-zero mask by activating one random feature."""
73
+ if mask.sum() == 0:
74
+ mask = mask.copy()
75
+ mask[rng.integers(len(mask))] = 1
76
+ return mask
77
+
78
+
79
+
80
+ def sbx_crossover(x1, x2, rng, pc=1.0, eta=20, low=0.0, high=1.0):
81
+ """Simulated Binary Crossover (distribution index ``eta``, e.g. beta_c=20)."""
82
+ x1 = x1.astype(float).copy()
83
+ x2 = x2.astype(float).copy()
84
+ if rng.random() >= pc:
85
+ return x1, x2
86
+ for i in range(len(x1)):
87
+ if rng.random() < 0.5 and abs(x1[i] - x2[i]) > 1e-14:
88
+ u = rng.random()
89
+ if u <= 0.5:
90
+ beta = (2 * u) ** (1.0 / (eta + 1))
91
+ else:
92
+ beta = (1.0 / (2 * (1 - u))) ** (1.0 / (eta + 1))
93
+ c1 = 0.5 * ((1 + beta) * x1[i] + (1 - beta) * x2[i])
94
+ c2 = 0.5 * ((1 - beta) * x1[i] + (1 + beta) * x2[i])
95
+ x1[i] = np.clip(c1, low, high)
96
+ x2[i] = np.clip(c2, low, high)
97
+ return x1, x2
98
+
99
+
100
+ def polynomial_mutation(x, rng, pm=None, eta=20, low=0.0, high=1.0):
101
+ """Polynomial mutation (distribution index ``eta``, e.g. beta_m=20)."""
102
+ x = x.astype(float).copy()
103
+ if pm is None:
104
+ pm = 1.0 / len(x)
105
+ for i in range(len(x)):
106
+ if rng.random() < pm:
107
+ u = rng.random()
108
+ if u < 0.5:
109
+ delta = (2 * u) ** (1.0 / (eta + 1)) - 1
110
+ else:
111
+ delta = 1 - (2 * (1 - u)) ** (1.0 / (eta + 1))
112
+ x[i] = np.clip(x[i] + delta * (high - low), low, high)
113
+ return x