# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Discover maps that expose differences between path planners.
# @see https://arxiv.org/abs/2409.06888
"""QD benchmark scenario generation with paired planner evaluations."""
from collections import Counter
from dataclasses import dataclass
from math import isfinite
from operator import index
import numpy as np
from scipy.ndimage import correlate, label
from scipy.optimize import Bounds, LinearConstraint, milp
from scipy.sparse import coo_matrix
from scipy.special import expit
from qdpy.tools import iso_line_dd
from .modern import _positive_int, _variation_settings
from .repair import _bits
from .task_search import _measurement, _offer, _search_bounds, _validate_grid
__all__ = ["NeuralCellularMap", "ConnectedMapRepair", "MapEvaluation", "QDMapper", "QDMapperStats"]
def _layout(values, shape=None):
array = np.asarray(values)
if array.ndim != 2 or not all(array.shape) or (shape is not None and array.shape != shape):
raise ValueError("Supply a nonempty rectangular binary layout of the configured shape.")
result = _bits(array.ravel(), array.size).reshape(array.shape)
result.setflags(write=False)
return result
## @brief Generate repeatable binary maps with a small neural cellular automaton.
[docs]
class NeuralCellularMap:
"""Iterate shared local rules on a seed map using NumPy and SciPy.
Each hidden channel computes a 3x3 correlation and a ReLU.
A pointwise sigmoid readout updates the map. Threshold the final
map at one half. One denotes an obstacle and zero denotes open space.
:param seed_map: Fixed binary starting map.
:param iterations: Number of full cellular updates.
:param hidden: Number of local correlation channels.
"""
def __init__(self, seed_map, *, iterations=3, hidden=3):
self._seed_map = _layout(seed_map)
self._iterations = _positive_int(iterations, "iterations")
self._hidden = _positive_int(hidden, "hidden")
@property
def dimension(self):
"""Return the total number of kernel and readout parameters."""
return self._hidden * 11 + 1
def __call__(self, genome):
"""Generate a binary map for a vector of the configured dimension."""
vector = np.asarray(genome, dtype=float)
if vector.shape != (self.dimension,) or not np.isfinite(vector).all():
raise ValueError(f"Supply {self.dimension} finite cellular automaton parameters.")
weights = vector[:-1].reshape(self._hidden, 11)
state = self._seed_map.astype(float)
for _ in range(self._iterations):
logits = np.full(state.shape, vector[-1])
for row in weights:
local = correlate(2. * state - 1., row[:9].reshape((3, 3)), mode="constant")
logits += row[10] * np.maximum(local + row[9], 0.)
if not np.isfinite(logits).all():
raise ValueError("Cellular automaton output overflowed. Rescale the parameters.")
state = expit(logits)
return (state >= .5).astype(np.int8)
## @brief Find a minimum-edit map with a connected open component and obstacle limits.
[docs]
class ConnectedMapRepair:
"""Repair a binary map with a rooted single-commodity flow MILP.
The root is always open. Every other open cell consumes one unit
of flow, and outgoing arcs have zero capacity on closed cells.
Feasible input maps bypass the solver. If the solver cannot certify
a minimum-edit repair within the supplied limits, return None.
:param shape: Pair of positive map dimensions.
:param obstacle_range: Inclusive pair of obstacle-count bounds.
:param root: Fixed open cell, given as row and column.
:param node_limit: Optional positive number of MILP search nodes.
"""
def __init__(self, shape, obstacle_range, *, root=(0, 0), node_limit=None):
rows, cols = (_positive_int(value, "map extent") for value in shape)
root = tuple(root)
start = np.ravel_multi_index(root, (rows, cols))
lower, upper = map(index, obstacle_range)
size = rows * cols
if not 0 <= lower <= upper < size:
raise ValueError("Obstacle counts must be ordered and leave at least one open cell.")
self.shape, self.obstacle_range, self.root = (rows, cols), (lower, upper), root
self._options = {"mip_rel_gap": 0.}
if node_limit is not None:
self._options["node_limit"] = _positive_int(node_limit, "node_limit")
tails, heads = [], []
for r in range(rows):
for c in range(cols):
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < rows and 0 <= nc < cols:
tails.append(r * cols + c)
heads.append(nr * cols + nc)
tails, heads = np.asarray(tails, dtype=int), np.asarray(heads, dtype=int)
capacity = size - 1
edges = len(tails)
variables = size + edges
nodes = np.arange(size)
vertices = nodes[nodes != start]
flows = size + np.arange(edges)
outgoing, incoming = tails != start, heads != start
rows_index = np.r_[np.zeros(size, dtype=int), 1 + vertices, 1 + tails[outgoing], 1 + heads[incoming],
1 + flows, 1 + flows]
cols_index = np.r_[nodes, vertices, flows[outgoing], flows[incoming], flows, tails]
data = np.r_[np.ones(size), -np.ones(len(vertices)), -np.ones(outgoing.sum()), np.ones(incoming.sum()),
np.ones(edges), np.full(edges, -capacity)]
matrix = coo_matrix((data, (rows_index, cols_index)), shape=(1 + variables, variables)).tocsr()
# Row start + 1 is the root's unrestricted flow balance.
lo, hi = np.r_[size - upper, np.zeros(size), np.full(edges, -np.inf)], np.r_[size - lower, np.zeros(variables)]
self._constraints = LinearConstraint(matrix, lo, hi)
self._integers = np.r_[np.ones(size), np.zeros(edges)]
lower_bounds = np.zeros(variables)
lower_bounds[start] = 1.
self._bounds = Bounds(lower_bounds, np.r_[np.ones(size), np.full(edges, capacity)])
## @brief Check the complete domain constraints on a binary layout.
[docs]
def feasible(self, layout):
"""Return whether the root, obstacle count, and connectivity are valid."""
layout = _layout(layout, self.shape)
low, high = self.obstacle_range
return not layout[self.root] and low <= layout.sum() <= high and label(layout == 0)[1] == 1
def __call__(self, layout):
"""Return a minimum-edit feasible layout, or None on a solver limit."""
layout = _layout(layout, self.shape)
if self.feasible(layout):
return layout
count = layout.size
cost = np.r_[2. * layout.ravel() - 1., np.zeros(len(self._integers) - count)]
result = milp(cost, integrality=self._integers, bounds=self._bounds,
constraints=self._constraints, options=self._options)
if result.status != 0 or result.x is None:
return None
opened = result.x[:count].reshape(self.shape)
if not np.all(abs(opened - opened.round()) <= 1e-6):
raise RuntimeError("The map repair solver returned nonintegral cells.")
repaired = _layout(1. - opened.round(), self.shape)
if not self.feasible(repaired):
raise RuntimeError("The map repair solver returned an invalid map.")
return repaired
## @brief One map measured on a panel of shared planner instances.
[docs]
@dataclass(frozen=True)
class MapEvaluation:
"""Store quality, mean planner costs, descriptors, and total planner invocations."""
objective: float
planner_costs: tuple[float, ...]
descriptors: tuple[float, ...]
planner_calls: int
## @brief Separate generation, repair, archive, and exact planner work.
[docs]
@dataclass(frozen=True)
class QDMapperStats:
"""Cumulative search counts. Independent audits return their own counts."""
proposals: int = 0
repair_calls: int = 0
failed_repairs: int = 0
duplicate_maps: int = 0
maps_evaluated: int = 0
planner_calls: int = 0
archive_updates: int = 0
## @brief Illuminate maps by one planner's cost or the cost gap between two planners.
[docs]
class QDMapper:
"""Run the QD-MAPPER scenario workflow with bounded Iso+LineDD proposals.
A generator maps a real genome to a binary obstacle grid. Optionally
repair the grid before evaluation. Each distinct layout is measured
on the same seeded panel. All planners receive the same case per
seed. Save the actual repaired layout under the elite's "layout"
score to audit it without calling the generator or solver again.
:param archive: Empty parentless best-only Grid or CVTGrid maximizing the score.
:param dimension: Number of real genotype coordinates.
:param generate: Callable (genome) returning a rectangular binary layout.
:param make_case: Callable (layout, seed) returning an immutable planner instance.
:param planners: One or two callbacks (layout, case) -> finite costs, larger is harder.
:param describe: Callable (layout) returning the descriptor vector.
:param repair: Optional callable (layout) returning a valid layout or None.
:param panel_size: Number of training cases shared by the planners.
:param absolute_gap: Use absolute instead of signed cost difference for two planners.
:param ind_domain: Finite common genome bounds.
:param iso_sigma: Independent mutation deviation.
:param line_sigma: Directional mutation deviation.
:param seed: Independent proposal and training-panel seed.
"""
def __init__(self, archive, dimension, *, generate, make_case, planners, describe, repair=None,
panel_size=4, absolute_gap=False, ind_domain=(-2., 2.), iso_sigma=.2, line_sigma=.3, seed=0):
_validate_grid(archive)
if (archive.fitness_score_names or archive.features_score_names
or (archive.fitness_weights is not None and archive.fitness_weights[0] <= 0)):
raise ValueError("Use a maximizing grid with direct fitness and descriptors.")
self._planners = tuple(planners)
if (len(self._planners) not in (1, 2) or not all(map(callable, (generate, make_case, describe, *self._planners)))
or (repair is not None and not callable(repair)) or (absolute_gap and len(self._planners) != 2)):
raise ValueError("Provide a generator, case builder, descriptor, and one or two planner callbacks.")
self._dimension = _positive_int(dimension, "dimension")
self._bounds = _search_bounds(_variation_settings(ind_domain, iso_sigma, line_sigma))
self._iso, self._line, self._absolute = iso_sigma, line_sigma, absolute_gap
self._generate, self._make_case, self._describe, self._repair = generate, make_case, describe, repair
self.archive = archive
if archive.fitness_weights is None:
archive._set_fitness_weights((1.,))
self._rng, panel = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
self._panel = tuple(map(int, panel.integers(2**32, size=_positive_int(panel_size, "panel_size"))))
self._measured = set()
self._counts = Counter()
@property
def stats(self):
"""Snapshot cumulative search work."""
return QDMapperStats(**self._counts)
def _evaluate(self, layout, seeds, counts):
per_case = []
for seed in seeds:
case = self._make_case(layout, seed)
costs = []
for planner in self._planners:
if counts is not None:
counts["planner_calls"] += 1
cost = float(planner(layout, case))
if not isfinite(cost):
raise ValueError("Planner costs must be finite.")
costs.append(cost)
per_case.append(costs)
averages = tuple(map(float, np.mean(per_case, axis=0)))
objective = averages[0] if len(averages) == 1 else averages[0] - averages[1]
features = tuple(map(float, self._describe(layout)))
if (not isfinite(objective) or not all(map(isfinite, averages + features))
or len(features) != len(self.archive.features_domain)):
raise ValueError("Map descriptors and aggregated costs must be finite and fit the archive dimension.")
return MapEvaluation(abs(objective) if self._absolute else objective, averages, features,
len(seeds) * len(self._planners))
## @brief Measure an existing map independently on a caller-supplied seed panel.
[docs]
def audit(self, layout, seeds):
"""Score the given map without updating the archive or search counters."""
seeds = tuple(map(index, seeds))
if not seeds:
raise ValueError("Provide at least one evaluation seed.")
return self._evaluate(_layout(layout), seeds, None)
## @brief Spend an additional map budget and a separate proposal cap.
[docs]
def run(self, budget, *, proposal_budget=None, evolve=True):
"""Return cumulative statistics, skipping duplicate repaired layouts.
Stop before exceeding either cap. Rejected maps spend proposals
and repair attempts only. With evolve=False, sample uniformly as
a matched-budget control.
"""
budget = _positive_int(budget, "budget")
limit = 10 * budget if proposal_budget is None else _positive_int(proposal_budget, "proposal_budget")
start = self._counts["maps_evaluated"]
archive, rng = self.archive, self._rng
for _ in range(limit):
if self._counts["maps_evaluated"] - start >= budget:
break
if evolve and len(archive):
a, b = rng.integers(len(archive), size=2)
genome = iso_line_dd(archive[a], archive[b], bounds=self._bounds,
iso_sigma=self._iso, line_sigma=self._line, rng=rng)
else:
genome = rng.uniform(*self._bounds, size=self._dimension)
genome = tuple(map(float, genome))
self._counts["proposals"] += 1
layout = _layout(self._generate(genome))
if self._repair is not None:
self._counts["repair_calls"] += 1
repaired = self._repair(layout)
if repaired is None:
self._counts["failed_repairs"] += 1
continue
layout = _layout(repaired, layout.shape)
key = tuple(tuple(map(int, row)) for row in layout)
if key in self._measured:
self._counts["duplicate_maps"] += 1
continue
self._counts["maps_evaluated"] += 1
result = self._evaluate(layout, self._panel, self._counts)
measurement = _measurement(archive, ((result.objective,), result.descriptors), genome)
measurement[0].scores.update(layout=key, planner_costs=result.planner_costs)
before = archive.nb_added
_offer(archive, measurement)
self._counts["archive_updates"] += archive.nb_added - before
self._measured.add(key)
return self.stats