QDpy
Loading...
Searching...
No Matches
qd_seeding.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Generate a repertoire of starts, then refine each with a user-supplied solver."""
7
8from dataclasses import dataclass
9
10import numpy as np
11
12from qdpy.tools import iso_line_dd
13from ._population import _attempt_budget, _finite_vector
14from .modern import _positive_int
15from .task_search import _measurement, _offer, _search_bounds, _validate_grid
16
17__all__ = ["QDIDStart", "QDIDResult", "qd_seeded_refinement"]
18
19
20
21@dataclass(frozen=True, slots=True)
23 """The reported seed remains available if all refinements are worse."""
24
25 seed: tuple[float, ...]
26 solution: tuple[float, ...]
27 initial_fitness: float
28 fitness: float
29 evaluations: int
30 failures: int
31
32
33
34@dataclass(frozen=True)
36 """Keep exact evaluator calls for the seed search and for local refinement."""
37
38 seeds: object
39 archive: object
40 starts: tuple[QDIDStart, ...]
41 search_evaluations: int
42 search_failures: int
43 refinement_evaluations: int
44 refinement_failures: int
45
46
47class _RefinementBudgetReached(Exception):
48 pass
49
50
51def _direction(archive):
52 if archive.fitness_weights is None:
53 return 1.
54 return float(np.sign(archive.fitness_weights[0]))
55
56
57
72def qd_seeded_refinement(seed_archive, archive, evaluate, refine, *, dimension, search_budget, starts,
73 refinement_budget_per_start, ind_domain=(0., 1.), initial_samples=8,
74 seed_selection="archive", propose=None, seed=0):
75 """Use the local solver's measured trials to choose one result per start.
76
77 The solver receives a scalar minimization objective and a measured start.
78 Return values from the solver are advisory. Selection uses the best
79 feasible measured point, including the start, so a failed or worse
80 trial cannot erase it. The objective raises a private stop signal before
81 exceeding its call cap. A rejected measurement returns positive infinity.
82
83 The random control samples seed designs independently and retains a
84 uniform reservoir of valid points for refinement. Both modes start up
85 to the configured number of solves without extra seed evaluations.
86 """
87 _validate_grid(seed_archive)
88 _validate_grid(archive)
89 direction = _direction(archive)
90 if seed_archive is archive or _direction(seed_archive) != direction:
91 raise ValueError("Supply distinct archives with the same fitness direction.")
92 if (tuple(seed_archive.features_domain) != tuple(archive.features_domain)
93 or tuple(seed_archive.fitness_domain) != tuple(archive.fitness_domain)):
94 raise ValueError("The seed and output archives must use common descriptor and fitness bounds.")
95 if not callable(evaluate) or not callable(refine) or (propose is not None and not callable(propose)):
96 raise TypeError("Supply an evaluator, local solver and an optional proposer.")
97 if seed_selection not in ("archive", "random"):
98 raise ValueError("Choose archive or random seed selection.")
99 dimension, starts = _positive_int(dimension, "dimension"), _positive_int(starts, "starts")
100 search_budget, initial_samples = _attempt_budget(search_budget), _attempt_budget(initial_samples)
101 limit = _attempt_budget(refinement_budget_per_start)
102 low, high = _search_bounds(ind_domain)
103 for grid in (seed_archive, archive):
104 if grid.fitness_weights is None:
105 grid._set_fitness_weights((direction,))
106 search_rng, panel_rng, local_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
107 pool, valid, failures = [], 0, 0
108 randomized = seed_selection == "random"
109
110 def measure(target, genome):
111 result = evaluate(genome)
112 return None if result is None else _measurement(target, result, genome)
113
114 search_evaluations = 0
115 for iteration in range(search_budget):
116 if propose is not None:
117 raw = propose(seed_archive if not randomized else (), search_rng)
118 elif randomized or iteration < initial_samples or not seed_archive:
119 raw = search_rng.uniform(low, high, size=dimension)
120 else:
121 left, right = (seed_archive[i] for i in search_rng.integers(len(seed_archive), size=2))
122 raw = iso_line_dd(left, right, iso_sigma=.05 * (high - low), bounds=(low, high), rng=search_rng)
123 genome = _finite_vector(raw, "Seed design", dimension)
124 if any(not low <= value <= high for value in genome):
125 raise ValueError("The seed proposer returned a point outside ind_domain.")
126 search_evaluations += 1
127 measured = measure(seed_archive, genome)
128 if measured is None:
129 failures += 1
130 continue
131 _offer(seed_archive, measured)
132 if randomized and measured[1] is not None:
133 valid += 1
134 if len(pool) < starts:
135 pool.append(measured[0])
136 elif (slot := panel_rng.integers(valid)) < starts:
137 pool[slot] = measured[0]
138
139 if not randomized and seed_archive:
140 selected = panel_rng.choice(len(seed_archive), size=min(starts, len(seed_archive)), replace=False)
141 pool = [seed_archive[i] for i in selected]
142
143 def refine_seed(elite):
144 initial = (tuple(elite.fitness.values), tuple(elite.features))
145 best = _measurement(archive, initial, tuple(elite))
146 attempts = misses = 0
147
148 def objective(raw):
149 nonlocal best, attempts, misses
150 if attempts == limit:
151 raise _RefinementBudgetReached
152 genome = _finite_vector(raw, "Local trial", dimension)
153 if any(not low <= value <= high for value in genome):
154 return np.inf
155 attempts += 1
156 trial = measure(archive, genome)
157 if trial is None or trial[1] is None:
158 misses += 1
159 return np.inf
160 quality = direction * trial[0].fitness.values[0]
161 if quality > direction * best[0].fitness.values[0]:
162 best = trial
163 return -quality
164
165 if limit:
166 try:
167 refine(tuple(elite), objective, local_rng)
168 except _RefinementBudgetReached:
169 pass
170 _offer(archive, best)
171 solution = best[0]
172 return QDIDStart(tuple(elite), tuple(solution), elite.fitness.values[0], solution.fitness.values[0],
173 attempts, misses)
174
175 refined = tuple(map(refine_seed, pool))
176 return QDIDResult(seed_archive, archive, refined, search_evaluations, failures,
177 sum(row.evaluations for row in refined), sum(row.failures for row in refined))
The measured starts, refined archive, and stage budgets.
Definition qd_seeding.py:35
One local solve, including the seed and its best verified result.
Definition qd_seeding.py:22