79 """Repair a binary map with a rooted single-commodity flow MILP.
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.
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.
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)
95 start = np.ravel_multi_index(root, (rows, cols))
96 lower, upper = map(index, obstacle_range)
98 if not 0 <= lower <= upper < size:
99 raise ValueError(
"Obstacle counts must be ordered and leave at least one open cell.")
102 if node_limit
is not None:
103 self.
_options[
"node_limit"] = _positive_int(node_limit,
"node_limit")
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)
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()
127 lo, hi = np.r_[size - upper, np.zeros(size), np.full(edges, -np.inf)], np.r_[size - lower, np.zeros(variables)]
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)])
136 """Return whether the root, obstacle count, and connectivity are valid."""
137 layout = _layout(layout, self.
shape)
139 return not layout[self.
root]
and low <= layout.sum() <= high
and label(layout == 0)[1] == 1
142 """Return a minimum-edit feasible layout, or None on a solver limit."""
143 layout = _layout(layout, self.
shape)
147 cost = np.r_[2. * layout.ravel() - 1., np.zeros(len(self.
_integers) - count)]
150 if result.status != 0
or result.x
is 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)
157 raise RuntimeError(
"The map repair solver returned an invalid map.")
188 """Run the QD-MAPPER scenario workflow with bounded Iso+LineDD proposals.
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.
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.
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.")
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))
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"))))
235 """Snapshot cumulative search work."""
238 def _evaluate(self, layout, seeds, counts):
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.")
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.")
262 """Score the given map without updating the archive or search counters."""
263 seeds = tuple(map(index, seeds))
265 raise ValueError(
"Provide at least one evaluation seed.")
266 return self.
_evaluate(_layout(layout), seeds,
None)
269 def run(self, budget, *, proposal_budget=None, evolve=True):
270 """Return cumulative statistics, skipping duplicate repaired layouts.
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.
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"]
280 for _
in range(limit):
281 if self.
_counts[
"maps_evaluated"] - start >= budget:
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)
289 genome = tuple(map(float, genome))
293 self.
_counts[
"repair_calls"] += 1
294 repaired = self.
_repair(layout)
296 self.
_counts[
"failed_repairs"] += 1
298 layout = _layout(repaired, layout.shape)
299 key = tuple(tuple(map(int, row))
for row
in layout)
301 self.
_counts[
"duplicate_maps"] += 1
303 self.
_counts[
"maps_evaluated"] += 1
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