QDpy
Loading...
Searching...
No Matches
variable_constraints.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Maintain a feasible MAP-Elites repertoire under changing score limits."""
7
8from collections import deque
9from collections.abc import Mapping
10from math import isfinite
11from operator import index
12
13import numpy as np
14
15from .modern import _positive_int
16from .task_search import _measurement, _offer, _validate_grid
17
18__all__ = ["VariableConstraintMAPElites"]
19
20
21
23 """Search and replay measured designs under inclusive score bounds.
24
25 :param archive: Empty parentless, best-only Grid or CVTGrid with a
26 single objective and native fitness and descriptors.
27 :param score_names: Names of the finite scalar measurements returned
28 by every successful evaluation, including currently unused scores.
29 :param constraints: Mapping from score names to (lower, upper). Use
30 None for an open end. Omit a name to remove its constraint.
31 :param history_size: Number of recent valid measurements to remember
32 alongside the live elites. Zero keeps only the live elites.
33 :param propose: Callback (rng) returning an immutable hashable genome.
34 :param mutate: Callback (parent_genome, rng) returning an offspring.
35 :param seed: Seed for proposal and parent selection.
36 """
37
38 def __init__(self, archive, *, score_names, constraints, history_size=1024,
39 propose, mutate, seed=0):
40 _validate_grid(archive)
41 if archive.fitness_score_names or archive.features_score_names:
42 raise ValueError("Supply a grid with native fitness and descriptors.")
43 names = (score_names,) if isinstance(score_names, str) else tuple(score_names)
44 if (not names or any(not isinstance(name, str) or not name for name in names)
45 or len(set(names)) != len(names)):
46 raise ValueError("Use distinct nonempty score names.")
47 if not callable(propose) or not callable(mutate):
48 raise TypeError("Supply callable proposal and mutation operators.")
49 self._score_names = frozenset(names)
50 self._constraints = self._validate_constraints(constraints)
51 self._history = deque(maxlen=index(history_size))
52 if archive.fitness_weights is None:
53 archive._set_fitness_weights((1.,))
54 self.archive = archive
55 self._propose, self._mutate = propose, mutate
56 self._rng = np.random.default_rng(seed)
57 self.nb_evaluations = 0
58 self.nb_failures = 0
59
60 @property
61 def constraints(self):
62 """Return a copy of the active score bounds."""
63 return dict(self._constraints)
64
65 def _validate_constraints(self, constraints):
66 if not isinstance(constraints, Mapping) or constraints.keys() - self._score_names:
67 raise ValueError("Constrain only declared measurement names.")
68 bounds = {}
69 for key, (lower, upper) in constraints.items():
70 lower = None if lower is None else float(lower)
71 upper = None if upper is None else float(upper)
72 if ((lower is not None and not isfinite(lower))
73 or (upper is not None and not isfinite(upper))
74 or (lower is not None and upper is not None and lower > upper)):
75 raise ValueError("Constraint bounds must be ordered and finite or None.")
76 bounds[key] = lower, upper
77 return bounds
78
79 @staticmethod
80 def _feasible(candidate, constraints):
81 return all((lower is None or candidate.scores[name] >= lower)
82 and (upper is None or candidate.scores[name] <= upper)
83 for name, (lower, upper) in constraints.items())
84
85
86 def set_constraints(self, constraints):
87 """Apply new bounds to live and remembered designs and return the archive."""
88 bounds = self._validate_constraints(constraints)
89 if bounds == self._constraints:
90 return self.archive
91 archive = self.archive
92 eligible = {elite[0]: (elite, archive.index_grid(elite)) for elite in archive}
93 eligible.update((candidate[0], (candidate, cell)) for candidate, cell in self._history)
94 feasible = [pair for pair in eligible.values() if self._feasible(pair[0], bounds)]
95 direction = np.sign(archive.fitness_weights[0])
96 feasible.sort(key=lambda pair: direction * pair[0].fitness.values[0], reverse=True)
97 archive.clear()
98 for measurement in feasible:
99 _offer(archive, measurement)
100 self._constraints = bounds
101 return archive
102
103
104 def run(self, evaluate, *, budget):
105 """Evaluate new genomes and return the live archive.
106
107 Return (scalar fitness, descriptors, scores) from evaluate(genome).
108 Scores must contain every declared measurement. Return None to report
109 a failed attempt. Use stable measurements for repeated genomes.
110 """
111 for _ in range(_positive_int(budget, "budget")):
112 if len(self.archive):
113 parent = self.archive[int(self._rng.integers(len(self.archive)))]
114 genome = self._mutate(parent[0], self._rng)
115 else:
116 genome = self._propose(self._rng)
117 hash(genome)
118 self.nb_evaluations += 1
119 result = evaluate(genome)
120 if result is None:
121 self.nb_failures += 1
122 continue
123 fitness, descriptors, measured = result
124 if not isinstance(measured, Mapping) or self._score_names != measured.keys():
125 raise ValueError("Return exactly the declared scores for every measured genome.")
126 scores = {name: float(value) for name, value in measured.items()}
127 if not all(map(isfinite, scores.values())):
128 raise ValueError("Constraint measurements must be finite.")
129 candidate, cell = _measurement(self.archive, ((fitness,), descriptors), (genome,))
130 if cell is None:
131 continue
132 candidate.scores.update(scores)
133 measurement = (candidate, cell)
134 self._history.append(measurement)
135 if self._feasible(candidate, self._constraints):
136 _offer(self.archive, measurement)
137 return self.archive
Rebuild a feasible repertoire from cached measurements.
set_constraints(self, constraints)
Rebuild the live archive without new evaluator calls.
run(self, evaluate, *, budget)
Continue the search under the current score limits.