QDpy
Loading...
Searching...
No Matches
scheduled_cvt.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Switch CVT descriptor spaces on a fixed evaluation schedule."""
7
8from collections.abc import Mapping
9from dataclasses import dataclass
10
11import numpy as np
12
13from qdpy.containers import CVTGrid
14from qdpy.tools import iso_line_dd
15
16from .modern import _positive_int, _variation_settings
17from .sampling import _rollout_seed
18from .task_search import _measurement, _offer, _search_bounds, _validate_grid
19
20__all__ = ["ScheduledCVTMAPElites", "ScheduledCVTStats", "CVTViewSwitch"]
21
22
23
24@dataclass(frozen=True)
26 """Transfer admissions include both empty-cell insertions and replacements."""
27
28 after_evaluations: int
29 source: str
30 destination: str
31 transfer_admissions: int
32
33
34
35@dataclass(frozen=True)
37 """Report cumulative attempts and the current view."""
38
39 evaluations: int
40 active_view: str
41 evaluations_by_view: tuple[tuple[str, int], ...]
42 switches: tuple[CVTViewSwitch, ...]
43
44
45
47 """Use the active CVT archive as the parent pool for one phase.
48
49 At a phase boundary, re-bin each current elite into the incoming
50 archive using the measurements cached on the original evaluation.
51 The incoming archive also keeps any elites already found in earlier
52 phases. Transfer costs zero evaluator calls. Each view owns its
53 fitness weights and descriptor geometry.
54
55 :param archives: Ordered mapping of names to empty, distinct scalar CVT grids.
56 :param dimension: Number of real decision coordinates.
57 :param phase_evaluations: Number of evaluation attempts per active view.
58 :param shared_feedback: Also offer each evaluation to inactive views for a control.
59 :param ind_domain: Increasing finite genome bounds shared by all coordinates.
60 :param iso_sigma: Independent Iso+LineDD mutation scale.
61 :param line_sigma: Directional Iso+LineDD mutation scale.
62 :param seed: Seed for private variation and evaluator streams.
63 """
64
65 def __init__(self, archives, dimension, *, phase_evaluations, shared_feedback=False,
66 ind_domain=(0., 1.), iso_sigma=.03, line_sigma=.2, seed=0):
67 if (not isinstance(archives, Mapping) or not archives
68 or any(not isinstance(name, str) or not name for name in archives)
69 or len({id(grid) for grid in archives.values()}) != len(archives)):
70 raise ValueError("Provide a nonempty mapping of names to distinct CVTGrid instances.")
71 for archive in archives.values():
72 if type(archive) is not CVTGrid:
73 raise ValueError("Each view must be a CVTGrid.")
74 _validate_grid(archive)
75 if type(shared_feedback) is not bool:
76 raise TypeError("shared_feedback must be a bool.")
77 self._archives = dict(archives)
78 self._names = tuple(archives)
79 self._dimension = _positive_int(dimension, "dimension")
80 self._phase = _positive_int(phase_evaluations, "phase_evaluations")
81 self._bounds = _search_bounds(_variation_settings(ind_domain, iso_sigma, line_sigma))
82 self._iso, self._line, self._shared = iso_sigma, line_sigma, shared_feedback
83 variation, measurement = np.random.SeedSequence(seed).spawn(2)
84 self._rng = np.random.default_rng(variation)
85 self._seed = int(measurement.generate_state(1, dtype=np.uint64)[0])
86 self._active = self._evaluations = 0
87 self._view_counts = dict.fromkeys(self._names, 0)
88 self._switches = []
89
90 @property
91 def archives(self):
92 """Return a mapping of names to the live CVT grids owned by the search."""
93 return dict(self._archives)
94
95 @property
96 def current_archive(self):
97 """Return the active parent pool."""
98 return self._archives[self._names[self._active]]
99
100 @property
101 def stats(self):
102 """Return cumulative evaluator and phase counts."""
103 return ScheduledCVTStats(self._evaluations, self._names[self._active],
104 tuple(self._view_counts.items()), tuple(self._switches))
105
106 @staticmethod
107 def _project(archive, view, genome, fitness, views):
108 measured = _measurement(archive, ((fitness,), views[view]), genome)
109 measured[0]._descriptor_views = views
110 return measured
111
112 def _switch(self):
113 source = self._names[self._active]
114 slot = (self._active + 1) % len(self._names)
115 target = self._names[slot]
116 archive = self._archives[target]
117 previous = archive.nb_added
118 for elite in self._archives[source]:
119 fitness = self._archives[source].get_ind_fitness(elite).values[0]
120 _offer(archive, self._project(archive, target, elite, fitness, elite._descriptor_views))
121 self._active = slot
122 self._switches.append(CVTViewSwitch(self._evaluations, source, target, archive.nb_added - previous))
123
124
128 def run(self, evaluate, budget):
129 """Return a scalar fitness and one descriptor vector per configured view."""
130 if not callable(evaluate):
131 raise TypeError("Supply a callable evaluator.")
132 for _ in range(_positive_int(budget, "budget")):
133 if len(self._names) > 1 and self._evaluations and self._evaluations % self._phase == 0:
134 # A failed evaluation still spends its attempt. Switching occurs before the next call.
135 if not self._switches or self._switches[-1].after_evaluations != self._evaluations:
136 self._switch()
137 active = self._names[self._active]
138 archive = self.current_archive
139 if archive:
140 a, b = self._rng.integers(len(archive), size=2)
141 point = iso_line_dd(archive[int(a)], archive[int(b)], bounds=self._bounds,
142 iso_sigma=self._iso, line_sigma=self._line, rng=self._rng)
143 else:
144 point = self._rng.uniform(*self._bounds, size=self._dimension)
145 genome = tuple(map(float, point))
146 seed = _rollout_seed(self._seed, 0, self._evaluations)
147 self._evaluations += 1
148 self._view_counts[active] += 1
149 fitness, reported = evaluate(genome, seed)
150 if not isinstance(reported, Mapping) or reported.keys() != self._archives.keys():
151 raise ValueError("Return descriptors for each configured view.")
152 views = {name: tuple(row) for name, row in reported.items()}
153 measurements = {name: self._project(grid, name, genome, fitness, views)
154 for name, grid in self._archives.items()}
155 if self._shared:
156 for name, grid in self._archives.items():
157 _offer(grid, measurements[name])
158 else:
159 _offer(archive, measurements[active])
160 return self.stats
Log one descriptor-space switch at a completed evaluation count.
Run a phase-based search over complete descriptor spaces.
_project(archive, view, genome, fitness, views)
run(self, evaluate, budget)
Run additional evaluator calls without changing the phase schedule.
Snapshot parent selection counts and measured transfers by phase.