5"""Illuminate several descriptor spaces with a shared success condition."""
7from collections.abc
import Mapping
8from dataclasses
import dataclass
13from .modern
import _positive_int
14from .task_search
import _measurement, _offer, _search_bounds, _validate_grid
16__all__ = [
"MultiBDMESResult",
"multi_bd_mes"]
20@dataclass(frozen=True)
22 """Grids, evaluator attempts and failures, successes, and admissions by view."""
27 successful_evaluations: int
31def _offer_success(grid, measurement):
32 candidate, cell = measurement
35 front = grid.solutions[cell]
36 if front
and candidate.scores[
"success"] != front[0].scores[
"success"]:
37 if not candidate.scores[
"success"]:
40 if candidate
in grid
and candidate != front[0]:
42 grid.discard(front[0])
43 _offer(grid, measurement)
47def multi_bd_mes(archives, evaluate, *, dimension, budget, ind_domain=(0, 1),
48 mutation_sigma=0.1, seed=0, on_step=
None):
49 """Run steady-state multi-descriptor MAP-Elites Success.
51 Each grid has independent local competition. A success takes precedence
52 within its cell. Fitness breaks comparisons between entries with equal
53 success status. Select parent grids in round-robin order, falling back
54 to a populated grid if necessary. Within each grid, sample uniformly
55 from successful elites when available, or from all elites while searching
56 for a first success. Mutate real-valued candidates with bounded Gaussian
57 noise. Garrabé et al. use the multi-grid method with inferred descriptor
58 functions. This runner accepts them as part of the supplied evaluator.
60 :param archives: Mapping from descriptor view names to distinct, empty,
61 parentless, best-only Grid or CVTGrid instances.
62 :param evaluate: Callable taking an immutable genome and returning
63 (success, (fitness,), {view: descriptors}). Success is a bool.
64 :param dimension: Number of real variables in each genome.
65 :param budget: Total evaluator attempts across all descriptor views.
66 :param ind_domain: Inclusive lower and upper genome bounds.
67 :param mutation_sigma: Gaussian standard deviation as a fraction of the bounds' span.
68 :param seed: Private random seed for initialization, selection and mutation.
69 :param on_step: Optional callback taking the archives and keyword arguments
70 iteration and evaluations after each attempted evaluation.
71 :returns: Live archives and shared evaluation accounting.
73 if not isinstance(archives, Mapping)
or not archives:
74 raise ValueError(
"Supply a nonempty mapping of descriptor views to grids.")
75 archives = dict(archives)
76 if len({id(grid)
for grid
in archives.values()}) != len(archives):
77 raise ValueError(
"Each descriptor view needs a distinct archive.")
78 for grid
in archives.values():
80 if "success" in (*grid.fitness_score_names, *grid.features_score_names):
81 raise ValueError(
"The score name 'success' is reserved for success status.")
82 if not callable(evaluate)
or (on_step
is not None and not callable(on_step)):
83 raise TypeError(
"Supply a callable evaluator and, optionally, a callable step hook.")
84 dimension = _positive_int(dimension,
"dimension")
85 budget = _positive_int(budget,
"budget")
86 bounds = _search_bounds(ind_domain)
87 sigma = mutation_sigma * (bounds[1] - bounds[0])
88 if not 0 < sigma < np.inf:
89 raise ValueError(
"Mutation must have a positive finite standard deviation.")
91 rng = np.random.default_rng(seed)
92 grids = tuple(archives.values())
93 admitted = dict.fromkeys(archives, 0)
94 failures = successes = 0
95 for step
in range(budget):
96 grid = grids[step % len(grids)]
98 populated = [item
for item
in grids
if item]
100 grid = populated[rng.integers(len(populated))]
102 parents = [elite
for elite
in grid
if elite.scores[
"success"]]
103 parents = parents
or grid
104 parent = parents[rng.integers(len(parents))]
105 point = np.clip(np.asarray(parent) + rng.normal(0, sigma, dimension), *bounds)
107 point = rng.uniform(*bounds, dimension)
108 genome = tuple(map(float, point))
111 success, fitness, descriptors = evaluate(genome)
112 if not isinstance(success, (bool, np.bool_))
or not isinstance(descriptors, Mapping):
113 raise ValueError(
"Return a boolean success and a mapping of descriptor views.")
114 if descriptors.keys() != archives.keys():
115 raise ValueError(
"Report descriptors for each configured view.")
116 staged = {name: _measurement(archive, (fitness, descriptors[name]), genome)
117 for name, archive
in archives.items()}
118 except Exception
as error:
119 warnings.warn(f
"MAP-Elites Success evaluation failed: {error}", stacklevel=2)
122 successes += int(success)
123 for name, archive
in archives.items():
124 measurement = staged[name]
125 measurement[0].scores[
"success"] = bool(success)
126 previous = archive.nb_added
127 _offer_success(archive, measurement)
128 admitted[name] += archive.nb_added - previous
129 if on_step
is not None:
130 on_step(archives, iteration=step + 1, evaluations=step + 1)
Live archives and accounting for a shared sequence of evaluations.