QDpy
Loading...
Searching...
No Matches
interactive_constrained.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
6
7"""Change descriptor axes and submit edited designs during constrained search."""
8
9from dataclasses import dataclass
10from math import fsum, isfinite
11
12import numpy as np
13
14from qdpy.containers import Grid
15from ._population import _attempt_budget, _finite_vector
16from .descriptor_mutation import DescriptorMutationMAPElites
17from .modern import _positive_int
18
19__all__ = ["InteractiveConstrainedMAPElites", "InteractiveConstrainedStats"]
20
21
22
23@dataclass(frozen=True)
25 """Admissions count new measurements. Reprojecting existing rows has its own counter."""
26
27 evaluations: int
28 edits: int
29 failures: int
30 feasible_evaluations: int
31 feasible_admissions: int
32 infeasible_admissions: int
33 reprojections: int
34
35
36
38 """Keep separate subpopulations for good designs and near-feasible ones.
39
40 Positive constraint residuals indicate violations. Feasible individuals
41 compete on user-provided fitness, infeasible individuals on total positive
42 residual. Both grids retain the configured number of breeders per cell.
43 Use hashable genome sequences and emit measurements for prospective axes.
44 """
45
46
56 def __init__(self, axes, *, fitness_domain, sample, mutate, crossover=None, maximize=True, cell_capacity=4,
57 initial_samples=8, anchor_probability=.2, seed=0):
58 axes = DescriptorMutationMAPElites._checked_axes(axes)
59 self._capacity = _positive_int(cell_capacity, "cell_capacity")
60 self._initial = _attempt_budget(initial_samples)
61 low, high = map(float, fitness_domain)
62 if (not low < high or not all(map(callable, (sample, mutate)))
63 or crossover is not None and not callable(crossover)
64 or not 0. <= anchor_probability <= 1.):
65 raise ValueError("Supply ordered fitness bounds, callable operators, and a probability in [0, 1].")
66 self._domain, self._weight = (low, high), 1. if maximize else -1.
67 self._sample, self._mutate, self._crossover = sample, mutate, crossover
68 self._anchor_probability = anchor_probability
69 self._variation, self._rollouts = (np.random.default_rng(child)
70 for child in np.random.SeedSequence(seed).spawn(2))
71 self._axes = axes
72 self._archive, self._infeasible = self._grids(axes)
73 self._anchor = self._residual_count = None
74 self._evaluations = self._edits = self._failures = self._feasible_evaluations = 0
76
77 def _grids(self, axes):
78 options = dict(shape=tuple(axis.bins for axis in axes), features_domain=tuple(axis.bounds for axis in axes),
79 storage_type="orderedset", max_items_per_bin=self._capacity)
80 return (Grid(fitness_domain=(self._domain,), fitness_weights=(self._weight,), **options),
81 Grid(fitness_domain=((-np.inf, 0.),), fitness_weights=(1.,), **options))
82
83
84 @property
85 def archive(self):
86 return self._archive
87
88
89 @property
90 def infeasible_archive(self):
91 return self._infeasible
92
93
94 @property
95 def axes(self):
96 return self._axes
97
98
99 @property
100 def anchor(self):
101 return self._anchor
102
103
104 @property
109 def _evaluate(self, genome, evaluate):
110 hash(genome)
111 seed = int(self._rollouts.integers(2**32))
112 self._evaluations += 1
113 result = evaluate(genome, seed)
114 if result is None:
115 self._failures += 1
116 return False
117 fitness, scores, residuals = result
118 residuals = _finite_vector(residuals, "constraint residuals", self._residual_count)
119 if not isfinite(fitness):
120 raise ValueError("Return finite scalar fitness.")
121 violation = fsum(max(0., residual) for residual in residuals)
122 grid = self._infeasible if violation else self._archive
123 before = grid.nb_added
124 DescriptorMutationMAPElites._put(grid, self._axes, genome, -violation if violation else fitness, scores)
125 self._residual_count = len(residuals)
126 if violation:
127 self._infeasible_admissions += grid.nb_added - before
128 else:
129 self._feasible_evaluations += 1
130 self._feasible_admissions += grid.nb_added - before
131 return True
132
133
136 def submit(self, genome, evaluate):
137 if not callable(evaluate):
138 raise TypeError("Supply a callable evaluator.")
139 genome = tuple(genome)
140 hash(genome)
141 self._edits += 1
142 if self._evaluate(genome, evaluate):
143 self._anchor = genome
144 return self.stats
145
146
147 def reproject(self, axes):
148 """Reuse cached measurements. A failed rebuild leaves both live archives intact."""
149 axes = DescriptorMutationMAPElites._checked_axes(axes)
150 if axes == self._axes:
151 return self.stats
152 grids = self._grids(axes)
153 for source, destination in zip((self.archive, self.infeasible_archive), grids):
154 for elite in source:
155 DescriptorMutationMAPElites._put(destination, axes, elite, elite.fitness.values[0], elite.scores)
156 self._archive, self._infeasible = grids
157 self._axes = axes
158 self._reprojections += 1
159 return self.stats
160
161 def _parent(self, grid):
162 cells = np.flatnonzero(grid.nb_items_per_bin)
163 cell = np.unravel_index(cells[self._variation.integers(len(cells))], grid.shape)
164 members = grid.solutions[cell]
165 contestants = (members[i] for i in self._variation.integers(len(members), size=2))
166 return tuple(max(contestants, key=lambda row: grid.fitness_weights[0] * row.fitness.values[0]))
167
168
171 def run(self, evaluate, budget):
172 if not callable(evaluate):
173 raise TypeError("Supply a callable evaluator.")
174 rng = self._variation
175 for _ in range(_attempt_budget(budget)):
176 available = [grid for grid in (self.archive, self.infeasible_archive) if grid]
177 if self._anchor is not None and (not available or rng.random() < self._anchor_probability):
178 genome = self._mutate(self._anchor, rng)
179 elif self._evaluations - self._edits < self._initial or not available:
180 genome = self._sample(rng)
181 else:
182 grid = available[int(rng.integers(len(available)))]
183 parent = self._parent(grid)
184 if self._crossover is not None:
185 parent = tuple(self._crossover(parent, self._parent(grid), rng))
186 genome = self._mutate(parent, rng)
187 self._evaluate(tuple(genome), evaluate)
188 return self.stats
Constrained MAP-Elites with a live editable design and replaceable axes.
submit(self, genome, evaluate)
Measure an edited genome immediately and make it the current breeding anchor.
__init__(self, axes, *, fitness_domain, sample, mutate, crossover=None, maximize=True, cell_capacity=4, initial_samples=8, anchor_probability=.2, seed=0)
anchor(self)
Most recent successfully evaluated edited design.
run(self, evaluate, budget)
Run additional proposals using the current archive geometry and editor input.
reproject(self, axes)
Reassign all currently retained designs to a new set of named axes.
stats(self)
Cumulative work across search, edits, and descriptor changes.
Attempt, admission, and redesign counters for the interactive search.