QDpy
Loading...
Searching...
No Matches
qd_mapper.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""QD benchmark scenario generation with paired planner evaluations."""
7
8from collections import Counter
9from dataclasses import dataclass
10from math import isfinite
11from operator import index
12
13import numpy as np
14from scipy.ndimage import correlate, label
15from scipy.optimize import Bounds, LinearConstraint, milp
16from scipy.sparse import coo_matrix
17from scipy.special import expit
18
19from qdpy.tools import iso_line_dd
20from .modern import _positive_int, _variation_settings
21from .repair import _bits
22from .task_search import _measurement, _offer, _search_bounds, _validate_grid
23
24__all__ = ["NeuralCellularMap", "ConnectedMapRepair", "MapEvaluation", "QDMapper", "QDMapperStats"]
25
26
27def _layout(values, shape=None):
28 array = np.asarray(values)
29 if array.ndim != 2 or not all(array.shape) or (shape is not None and array.shape != shape):
30 raise ValueError("Supply a nonempty rectangular binary layout of the configured shape.")
31 result = _bits(array.ravel(), array.size).reshape(array.shape)
32 result.setflags(write=False)
33 return result
34
35
36
38 """Iterate shared local rules on a seed map using NumPy and SciPy.
39
40 Each hidden channel computes a 3x3 correlation and a ReLU.
41 A pointwise sigmoid readout updates the map. Threshold the final
42 map at one half. One denotes an obstacle and zero denotes open space.
43
44 :param seed_map: Fixed binary starting map.
45 :param iterations: Number of full cellular updates.
46 :param hidden: Number of local correlation channels.
47 """
48
49 def __init__(self, seed_map, *, iterations=3, hidden=3):
50 self._seed_map = _layout(seed_map)
51 self._iterations = _positive_int(iterations, "iterations")
52 self._hidden = _positive_int(hidden, "hidden")
53
54 @property
55 def dimension(self):
56 """Return the total number of kernel and readout parameters."""
57 return self._hidden * 11 + 1
58
59 def __call__(self, genome):
60 """Generate a binary map for a vector of the configured dimension."""
61 vector = np.asarray(genome, dtype=float)
62 if vector.shape != (self.dimension,) or not np.isfinite(vector).all():
63 raise ValueError(f"Supply {self.dimension} finite cellular automaton parameters.")
64 weights = vector[:-1].reshape(self._hidden, 11)
65 state = self._seed_map.astype(float)
66 for _ in range(self._iterations):
67 logits = np.full(state.shape, vector[-1])
68 for row in weights:
69 local = correlate(2. * state - 1., row[:9].reshape((3, 3)), mode="constant")
70 logits += row[10] * np.maximum(local + row[9], 0.)
71 if not np.isfinite(logits).all():
72 raise ValueError("Cellular automaton output overflowed. Rescale the parameters.")
73 state = expit(logits)
74 return (state >= .5).astype(np.int8)
75
76
77
79 """Repair a binary map with a rooted single-commodity flow MILP.
80
81 The root is always open. Every other open cell consumes one unit
82 of flow, and outgoing arcs have zero capacity on closed cells.
83 Feasible input maps bypass the solver. If the solver cannot certify
84 a minimum-edit repair within the supplied limits, return None.
85
86 :param shape: Pair of positive map dimensions.
87 :param obstacle_range: Inclusive pair of obstacle-count bounds.
88 :param root: Fixed open cell, given as row and column.
89 :param node_limit: Optional positive number of MILP search nodes.
90 """
91
92 def __init__(self, shape, obstacle_range, *, root=(0, 0), node_limit=None):
93 rows, cols = (_positive_int(value, "map extent") for value in shape)
94 root = tuple(root)
95 start = np.ravel_multi_index(root, (rows, cols))
96 lower, upper = map(index, obstacle_range)
97 size = rows * cols
98 if not 0 <= lower <= upper < size:
99 raise ValueError("Obstacle counts must be ordered and leave at least one open cell.")
100 self.shape, self.obstacle_range, self.root = (rows, cols), (lower, upper), root
101 self._options = {"mip_rel_gap": 0.}
102 if node_limit is not None:
103 self._options["node_limit"] = _positive_int(node_limit, "node_limit")
104
105 tails, heads = [], []
106 for r in range(rows):
107 for c in range(cols):
108 for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
109 if 0 <= nr < rows and 0 <= nc < cols:
110 tails.append(r * cols + c)
111 heads.append(nr * cols + nc)
112 tails, heads = np.asarray(tails, dtype=int), np.asarray(heads, dtype=int)
113 capacity = size - 1
114 edges = len(tails)
115 variables = size + edges
116 nodes = np.arange(size)
117 vertices = nodes[nodes != start]
118 flows = size + np.arange(edges)
119 outgoing, incoming = tails != start, heads != start
120 rows_index = np.r_[np.zeros(size, dtype=int), 1 + vertices, 1 + tails[outgoing], 1 + heads[incoming],
121 1 + flows, 1 + flows]
122 cols_index = np.r_[nodes, vertices, flows[outgoing], flows[incoming], flows, tails]
123 data = np.r_[np.ones(size), -np.ones(len(vertices)), -np.ones(outgoing.sum()), np.ones(incoming.sum()),
124 np.ones(edges), np.full(edges, -capacity)]
125 matrix = coo_matrix((data, (rows_index, cols_index)), shape=(1 + variables, variables)).tocsr()
126 # Row start + 1 is the root's unrestricted flow balance.
127 lo, hi = np.r_[size - upper, np.zeros(size), np.full(edges, -np.inf)], np.r_[size - lower, np.zeros(variables)]
128 self._constraints = LinearConstraint(matrix, lo, hi)
129 self._integers = np.r_[np.ones(size), np.zeros(edges)]
130 lower_bounds = np.zeros(variables)
131 lower_bounds[start] = 1.
132 self._bounds = Bounds(lower_bounds, np.r_[np.ones(size), np.full(edges, capacity)])
133
134
135 def feasible(self, layout):
136 """Return whether the root, obstacle count, and connectivity are valid."""
137 layout = _layout(layout, self.shape)
138 low, high = self.obstacle_range
139 return not layout[self.root] and low <= layout.sum() <= high and label(layout == 0)[1] == 1
140
141 def __call__(self, layout):
142 """Return a minimum-edit feasible layout, or None on a solver limit."""
143 layout = _layout(layout, self.shape)
144 if self.feasible(layout):
145 return layout
146 count = layout.size
147 cost = np.r_[2. * layout.ravel() - 1., np.zeros(len(self._integers) - count)]
148 result = milp(cost, integrality=self._integers, bounds=self._bounds,
149 constraints=self._constraints, options=self._options)
150 if result.status != 0 or result.x is None:
151 return None
152 opened = result.x[:count].reshape(self.shape)
153 if not np.all(abs(opened - opened.round()) <= 1e-6):
154 raise RuntimeError("The map repair solver returned nonintegral cells.")
155 repaired = _layout(1. - opened.round(), self.shape)
156 if not self.feasible(repaired):
157 raise RuntimeError("The map repair solver returned an invalid map.")
158 return repaired
159
160
161
162@dataclass(frozen=True)
164 """Store quality, mean planner costs, descriptors, and total planner invocations."""
165
166 objective: float
167 planner_costs: tuple[float, ...]
168 descriptors: tuple[float, ...]
169 planner_calls: int
170
171
172
173@dataclass(frozen=True)
175 """Cumulative search counts. Independent audits return their own counts."""
176
177 proposals: int = 0
178 repair_calls: int = 0
179 failed_repairs: int = 0
180 duplicate_maps: int = 0
181 maps_evaluated: int = 0
182 planner_calls: int = 0
183 archive_updates: int = 0
184
185
186
188 """Run the QD-MAPPER scenario workflow with bounded Iso+LineDD proposals.
189
190 A generator maps a real genome to a binary obstacle grid. Optionally
191 repair the grid before evaluation. Each distinct layout is measured
192 on the same seeded panel. All planners receive the same case per
193 seed. Save the actual repaired layout under the elite's "layout"
194 score to audit it without calling the generator or solver again.
195
196 :param archive: Empty parentless best-only Grid or CVTGrid maximizing the score.
197 :param dimension: Number of real genotype coordinates.
198 :param generate: Callable (genome) returning a rectangular binary layout.
199 :param make_case: Callable (layout, seed) returning an immutable planner instance.
200 :param planners: One or two callbacks (layout, case) -> finite costs, larger is harder.
201 :param describe: Callable (layout) returning the descriptor vector.
202 :param repair: Optional callable (layout) returning a valid layout or None.
203 :param panel_size: Number of training cases shared by the planners.
204 :param absolute_gap: Use absolute instead of signed cost difference for two planners.
205 :param ind_domain: Finite common genome bounds.
206 :param iso_sigma: Independent mutation deviation.
207 :param line_sigma: Directional mutation deviation.
208 :param seed: Independent proposal and training-panel seed.
209 """
210
211 def __init__(self, archive, dimension, *, generate, make_case, planners, describe, repair=None,
212 panel_size=4, absolute_gap=False, ind_domain=(-2., 2.), iso_sigma=.2, line_sigma=.3, seed=0):
213 _validate_grid(archive)
214 if (archive.fitness_score_names or archive.features_score_names
215 or (archive.fitness_weights is not None and archive.fitness_weights[0] <= 0)):
216 raise ValueError("Use a maximizing grid with direct fitness and descriptors.")
217 self._planners = tuple(planners)
218 if (len(self._planners) not in (1, 2) or not all(map(callable, (generate, make_case, describe, *self._planners)))
219 or (repair is not None and not callable(repair)) or (absolute_gap and len(self._planners) != 2)):
220 raise ValueError("Provide a generator, case builder, descriptor, and one or two planner callbacks.")
221 self._dimension = _positive_int(dimension, "dimension")
222 self._bounds = _search_bounds(_variation_settings(ind_domain, iso_sigma, line_sigma))
223 self._iso, self._line, self._absolute = iso_sigma, line_sigma, absolute_gap
224 self._generate, self._make_case, self._describe, self._repair = generate, make_case, describe, repair
225 self.archive = archive
226 if archive.fitness_weights is None:
227 archive._set_fitness_weights((1.,))
228 self._rng, panel = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
229 self._panel = tuple(map(int, panel.integers(2**32, size=_positive_int(panel_size, "panel_size"))))
230 self._measured = set()
231 self._counts = Counter()
232
233 @property
234 def stats(self):
235 """Snapshot cumulative search work."""
236 return QDMapperStats(**self._counts)
237
238 def _evaluate(self, layout, seeds, counts):
239 per_case = []
240 for seed in seeds:
241 case = self._make_case(layout, seed)
242 costs = []
243 for planner in self._planners:
244 if counts is not None:
245 counts["planner_calls"] += 1
246 cost = float(planner(layout, case))
247 if not isfinite(cost):
248 raise ValueError("Planner costs must be finite.")
249 costs.append(cost)
250 per_case.append(costs)
251 averages = tuple(map(float, np.mean(per_case, axis=0)))
252 objective = averages[0] if len(averages) == 1 else averages[0] - averages[1]
253 features = tuple(map(float, self._describe(layout)))
254 if (not isfinite(objective) or not all(map(isfinite, averages + features))
255 or len(features) != len(self.archive.features_domain)):
256 raise ValueError("Map descriptors and aggregated costs must be finite and fit the archive dimension.")
257 return MapEvaluation(abs(objective) if self._absolute else objective, averages, features,
258 len(seeds) * len(self._planners))
259
260
261 def audit(self, layout, seeds):
262 """Score the given map without updating the archive or search counters."""
263 seeds = tuple(map(index, seeds))
264 if not seeds:
265 raise ValueError("Provide at least one evaluation seed.")
266 return self._evaluate(_layout(layout), seeds, None)
267
268
269 def run(self, budget, *, proposal_budget=None, evolve=True):
270 """Return cumulative statistics, skipping duplicate repaired layouts.
271
272 Stop before exceeding either cap. Rejected maps spend proposals
273 and repair attempts only. With evolve=False, sample uniformly as
274 a matched-budget control.
275 """
276 budget = _positive_int(budget, "budget")
277 limit = 10 * budget if proposal_budget is None else _positive_int(proposal_budget, "proposal_budget")
278 start = self._counts["maps_evaluated"]
279 archive, rng = self.archive, self._rng
280 for _ in range(limit):
281 if self._counts["maps_evaluated"] - start >= budget:
282 break
283 if evolve and len(archive):
284 a, b = rng.integers(len(archive), size=2)
285 genome = iso_line_dd(archive[a], archive[b], bounds=self._bounds,
286 iso_sigma=self._iso, line_sigma=self._line, rng=rng)
287 else:
288 genome = rng.uniform(*self._bounds, size=self._dimension)
289 genome = tuple(map(float, genome))
290 self._counts["proposals"] += 1
291 layout = _layout(self._generate(genome))
292 if self._repair is not None:
293 self._counts["repair_calls"] += 1
294 repaired = self._repair(layout)
295 if repaired is None:
296 self._counts["failed_repairs"] += 1
297 continue
298 layout = _layout(repaired, layout.shape)
299 key = tuple(tuple(map(int, row)) for row in layout)
300 if key in self._measured:
301 self._counts["duplicate_maps"] += 1
302 continue
303 self._counts["maps_evaluated"] += 1
304 result = self._evaluate(layout, self._panel, self._counts)
305 measurement = _measurement(archive, ((result.objective,), result.descriptors), genome)
306 measurement[0].scores.update(layout=key, planner_costs=result.planner_costs)
307 before = archive.nb_added
308 _offer(archive, measurement)
309 self._counts["archive_updates"] += archive.nb_added - before
310 self._measured.add(key)
311 return self.stats
Find a minimum-edit map with a connected open component and obstacle limits.
Definition qd_mapper.py:78
feasible(self, layout)
Check the complete domain constraints on a binary layout.
Definition qd_mapper.py:135
One map measured on a panel of shared planner instances.
Definition qd_mapper.py:163
Generate repeatable binary maps with a small neural cellular automaton.
Definition qd_mapper.py:37
Separate generation, repair, archive, and exact planner work.
Definition qd_mapper.py:174
Illuminate maps by one planner's cost or the cost gap between two planners.
Definition qd_mapper.py:187
audit(self, layout, seeds)
Measure an existing map independently on a caller-supplied seed panel.
Definition qd_mapper.py:261
_evaluate(self, layout, seeds, counts)
Definition qd_mapper.py:238
run(self, budget, *, proposal_budget=None, evolve=True)
Spend an additional map budget and a separate proposal cap.
Definition qd_mapper.py:269