QDpy
Loading...
Searching...
No Matches
repair.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Separate constrained binary repair from expensive objective evaluations."""
7
8from dataclasses import dataclass
9
10import numpy as np
11from scipy.optimize import Bounds, LinearConstraint, milp
12
13from qdpy.containers import CVTGrid, Grid
14from qdpy.phenotype import Individual
15from .modern import _positive_int
16from .sampling import _aggregate
17from .uncertain import _Rollouts
18
19
20__all__ = ["BinaryMILPRepair", "BinaryRepairResult", "RepairedMAPElites", "RepairSearchStats"]
21
22
23
24@dataclass(frozen=True)
26 """A successful repair supplies a genome and its Hamming distance."""
27
28 genome: tuple[int, ...] | None
29 distance: int | None
30 status: int
31 optimal: bool
32
33
34def _bits(values, dimension):
35 array = np.asarray(values)
36 if array.shape != (dimension,) or array.dtype.kind not in "buif" or not np.isin(array, (0, 1)).all():
37 raise ValueError(f"Supply {dimension} binary coordinates.")
38 return array.astype(np.int8)
39
40
41
43 """Use SciPy/HiGHS to repair a binary genome.
44
45 :param dimension: Number of binary decision variables.
46 :param constraints: A scipy.optimize.LinearConstraint or a sequence of them.
47 :param time_limit: Optional positive limit per solver call, in seconds.
48 :param node_limit: Optional positive limit on explored solver nodes.
49 :param accept_incumbent: Use a verified feasible incumbent when status denotes a limit.
50 """
51
52 def __init__(self, dimension, constraints=(), *, time_limit=None, node_limit=None, accept_incumbent=False):
53 self.dimension = _positive_int(dimension, "dimension")
54 self.constraints = ((constraints,) if isinstance(constraints, LinearConstraint) else tuple(constraints))
55 if any(not isinstance(row, LinearConstraint) or row.A.shape[1] != self.dimension
56 for row in self.constraints):
57 raise ValueError("Use linear constraints with one column per binary coordinate.")
58 self._options = {"mip_rel_gap": 0.}
59 if time_limit is not None:
60 if not 0 < time_limit < np.inf:
61 raise ValueError("time_limit must be positive and finite.")
62 self._options["time_limit"] = time_limit
63 if node_limit is not None:
64 self._options["node_limit"] = _positive_int(node_limit, "node_limit")
65 self.accept_incumbent = accept_incumbent
66 self._bounds = Bounds(np.zeros(self.dimension), np.ones(self.dimension))
67 self._integrality = np.ones(self.dimension)
68
69
70 def feasible(self, genome):
71 """Use a fixed absolute tolerance of 1e-7 for solver residuals."""
72 vector = _bits(genome, self.dimension)
73 for constraint in self.constraints:
74 values = constraint.A @ vector
75 if not np.all((values >= constraint.lb - 1e-7) & (values <= constraint.ub + 1e-7)):
76 return False
77 return True
78
79
80 def repair(self, proposal):
81 """Call HiGHS even for a feasible input and verify its returned assignment."""
82 vector = _bits(proposal, self.dimension)
83 solution = milp(1. - 2. * vector, integrality=self._integrality, bounds=self._bounds,
84 constraints=self.constraints, options=self._options)
85 status = int(solution.status)
86 if solution.x is not None and (status == 0 or status == 1 and self.accept_incumbent):
87 rounded = np.rint(solution.x)
88 if np.all(np.abs(solution.x - rounded) <= 1e-6) and np.isin(rounded, (0., 1.)).all():
89 genome = tuple(map(int, rounded))
90 if self.feasible(genome):
91 return BinaryRepairResult(genome, int(np.count_nonzero(rounded != vector)), status, status == 0)
92 return BinaryRepairResult(None, None, status, False)
93
94
95
96@dataclass(frozen=True)
98 """Separate calls to the solver, unresolved results, duplicate repairs, and evaluations."""
99
100 repair_calls: int
101 failed_repairs: int
102 limited_repairs: int
103 duplicate_repairs: int
104 evaluations: int
105 failed_evaluations: int
106 archive_updates: int
107
108
109
111 """Manage flip mutation, exact repair, and measured archive updates.
112
113 :param archive: Parentless one-elite Grid or CVTGrid with one signed objective.
114 :param repair: BinaryMILPRepair defining the feasible region.
115 :param mutation_probability: Flip rate per gene. Defaults to the inverse genome length.
116 :param seed: Private proposal and rollout seed.
117 """
118
119 def __init__(self, archive, repair, *, mutation_probability=None, seed=0):
120 if (type(archive) not in (Grid, CVTGrid) or archive.parents or archive.max_items_per_bin != 1
121 or archive.discard_random_on_bin_overload or len(archive.fitness_domain or ()) != 1
122 or len(archive.fitness_weights or ()) != 1 or not np.isfinite(archive.fitness_weights[0])
123 or not archive.fitness_weights[0]):
124 raise ValueError("Use a parentless best-only Grid or CVTGrid with one signed objective.")
125 if not isinstance(repair, BinaryMILPRepair):
126 raise TypeError("repair must be a BinaryMILPRepair.")
127 if any(not repair.feasible(elite) for elite in archive):
128 raise ValueError("Initial elites must satisfy the repair constraints.")
129 probability = 1. / repair.dimension if mutation_probability is None else mutation_probability
130 if not 0. <= probability <= 1.:
131 raise ValueError("mutation_probability must be in [0, 1].")
132 self.archive, self.repair, self.seed = archive, repair, seed
133 self.mutation_probability = probability
134 self._rng = np.random.default_rng(seed)
135 self._attempted = {tuple(elite) for elite in archive}
136 self._runs = 0
137
138 def _propose(self):
139 dimension = self.repair.dimension
140 if not len(self.archive):
141 return self._rng.integers(0, 2, size=dimension, dtype=np.int8)
142 parent = np.asarray(self.archive[self._rng.integers(len(self.archive))], dtype=np.int8)
143 flip = self._rng.random(dimension) < self.mutation_probability
144 if not np.any(flip):
145 flip[self._rng.integers(dimension)] = True
146 return parent ^ flip
147
148
153 def run(self, evaluate, budget, *, repair_budget=None):
154 """Stop when either budget is spent. Repeated designs reuse their first attempt."""
155 budget = _positive_int(budget, "budget")
156 limit = 10 * budget if repair_budget is None else _positive_int(repair_budget, "repair_budget")
157 if not callable(evaluate):
158 raise TypeError("evaluate must be callable.")
159 runner = _Rollouts(self.archive, evaluate, None, self.seed, stream=self._runs)
160 self._runs += 1
161 calls = failures = limited = duplicates = updates = 0
162 while calls < limit and runner.attempted < budget:
163 result = self.repair.repair(self._propose())
164 calls += 1
165 limited += result.status == 1
166 if result.genome is None:
167 failures += 1
168 continue
169 if result.genome in self._attempted:
170 duplicates += 1
171 continue
172 self._attempted.add(result.genome)
173 candidate = Individual(list(result.genome))
174 observations, = runner.evaluate_groups([(candidate, 1)])
175 if observations:
176 measured = _aggregate(self.archive, candidate, observations)
177 fitness, features = self.archive.get_ind_fitness(measured).values, self.archive.get_ind_features(measured)
178 if (self.archive.in_bounds(fitness, self.archive.fitness_domain)
179 and self.archive.in_bounds(features, self.archive.features_domain)):
180 cell = self.archive.index_grid(features)
181 if self.archive.free >= 1 or self.archive.solutions[cell]:
182 updates += self.archive.add(measured) is not None
183 return RepairSearchStats(calls, failures, limited, duplicates, runner.attempted, runner.failed, updates)
Minimize Hamming distance under linear equalities and inequalities.
Definition repair.py:42
repair(self, proposal)
Solve for the closest feasible point, or report an unresolved repair.
Definition repair.py:80
feasible(self, genome)
Check the actual linear residuals of a rounded binary assignment.
Definition repair.py:70
A feasible binary assignment and the original HiGHS termination status.
Definition repair.py:25
Work and outcomes from one repair-assisted MAP-Elites run.
Definition repair.py:97
Repair binary offspring before calling the expensive evaluator.
Definition repair.py:110
run(self, evaluate, budget, *, repair_budget=None)
Keep the measured design budget separate from the repair-call cap.
Definition repair.py:153
Dispatch rollouts and resolve them in submission order.
Definition uncertain.py:95