QDpy
Loading...
Searching...
No Matches
aria.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Budgeted ARIA post-processing for scalar-objective Grid and CVT archives."""
7
8from copy import deepcopy
9from dataclasses import dataclass
10from itertools import combinations
11
12import numpy as np
13from scipy.spatial import Delaunay
14from scipy.stats import rankdata
15
16from qdpy.containers import CVTGrid, Grid
17from .modern import _bounds, _positive_int
18from .sampling import _aggregate, _fresh, _stage_archive
19from .uncertain import _Rollouts, _cell, _incumbent
20
21__all__ = ["ARIA", "ARIAResult"]
22
23
24
25@dataclass(frozen=True)
27 """Record the output archive, total/failed rollouts, and processed targets.
28
29 Each target counts once even when its measured mean misses the target.
30 Completion targets are empty cells processed after the source elites.
31 """
32
33 archive: Grid
34 rollouts: int
35 failed_rollouts: int
36 refined_cells: int
37 completion_cells: int
38 successful_targets: int
39
40
41def _geometry(archive, complete):
42 cells = tuple(archive.solutions)
43 if isinstance(archive, CVTGrid):
44 centers = archive.cluster_centers
45 else:
46 intervals = np.asarray(archive.features_domain, dtype=float)
47 widths = (intervals[:, 1] - intervals[:, 0]) / archive.shape
48 centers = intervals[:, 0] + (np.asarray(cells) + .5) * widths
49 points = dict(zip(cells, centers))
50 neighbors = {cell: set() for cell in cells}
51 if not complete or len(cells) < 2:
52 return points, neighbors
53 if isinstance(archive, CVTGrid):
54 if len(np.unique(centers, axis=0)) != len(cells):
55 raise ValueError("ARIA completion requires distinct CVT centroids.")
56 shifted = centers - centers[0]
57 _, singular, basis = np.linalg.svd(shifted, full_matrices=False)
58 rank = np.count_nonzero(singular > singular[0] * max(shifted.shape) * np.finfo(float).eps)
59 projected = shifted @ basis[:rank].T
60 if rank == 1:
61 order = np.argsort(projected[:, 0])
62 edges = zip(order[:-1], order[1:])
63 else:
64 simplices = [range(len(cells))] if len(cells) == rank + 1 else Delaunay(projected).simplices
65 edges = (edge for simplex in simplices for edge in combinations(simplex, 2))
66 for first, second in edges:
67 neighbors[cells[first]].add(cells[second])
68 neighbors[cells[second]].add(cells[first])
69 else:
70 for cell in cells:
71 for axis, coordinate in enumerate(cell):
72 if coordinate + 1 < archive.shape[axis]:
73 other = (*cell[:axis], coordinate + 1, *cell[axis + 1:])
74 neighbors[cell].add(other)
75 neighbors[other].add(cell)
76 return points, neighbors
77
78
79
80class ARIA:
81 """Run fixed-budget per-cell evolution strategies on real parameter vectors.
82
83 :param archive: Nonempty fixed Grid or CVTGrid with one signed objective.
84 The best member of each occupied cell seeds the search.
85 :param steps: Gaussian rank-gradient updates per target.
86 :param population_size: Independent perturbations per update, at least two.
87 :param sigma: Parameter perturbation standard deviation.
88 :param learning_rate: Gradient ascent step size.
89 :param samples: Fresh rollouts used to place each final center by its mean.
90 :param ind_domain: Optional shared finite bounds for parameter coordinates.
91 :param complete: Continue from refined targets into adjacent empty bins.
92 :param seed: Seed for perturbations, frontier selection, and rollout seeds.
93 """
94
95 def __init__(self, archive, *, steps=10, population_size=32, sigma=.05,
96 learning_rate=.02, samples=16, ind_domain=None, complete=True, seed=0):
97 if (type(archive) not in (Grid, CVTGrid) or not len(archive)
98 or len(archive.fitness_domain or ()) != 1 or len(archive.fitness_weights or ()) != 1
99 or not np.isfinite(archive.fitness_weights[0]) or not archive.fitness_weights[0]
100 or not np.isfinite(archive.features_domain).all()
101 or archive.fitness_score_names):
102 raise ValueError("ARIA requires a nonempty fixed Grid/CVTGrid with finite features "
103 "and one native signed fitness objective.")
104 self._initial = {cell: deepcopy(_incumbent(archive, cell))
105 for cell, entries in archive.solutions.items() if entries}
106 vectors = np.asarray([list(ind) for ind in self._initial.values()], dtype=float)
107 self._bounds = None if ind_domain is None else _bounds(ind_domain)
108 if (vectors.ndim != 2 or not vectors.shape[1] or not np.isfinite(vectors).all()
109 or not np.array_equal(vectors, self._clip(vectors))):
110 raise ValueError("Warm-start elites must be finite vectors with the same shape and bounds.")
111 if not 0 < sigma < np.inf or not 0 < learning_rate < np.inf:
112 raise ValueError("sigma and learning_rate must be positive and finite.")
113 self.steps = _positive_int(steps, "steps")
114 self.population_size = _positive_int(population_size, "population_size")
115 if self.population_size < 2:
116 raise ValueError("Use at least two perturbations per target update.")
117 self.samples = _positive_int(samples, "samples")
118 self.sigma, self.learning_rate, self.seed, self.complete = sigma, learning_rate, seed, complete
119 self._source = _stage_archive(archive)
120 self._source.clear()
121 self._source._max_items_per_bin = 1
122 self._source._capacity = len(self._source.solutions)
123 self._source.discard_random_on_bin_overload = False
124 self._direction = np.sign(archive.fitness_weights[0])
125
126 def _clip(self, vectors):
127 return vectors if self._bounds is None else np.clip(vectors, *self._bounds)
128
129 def _refine(self, original, target, center, runner, rng):
130 point = np.asarray(original, dtype=float)
131 for _ in range(self.steps):
132 noise = rng.standard_normal((self.population_size, point.size))
133 candidates = []
134 for vector in self._clip(point + self.sigma * noise):
135 candidate = _fresh(original)
136 candidate[:] = vector.tolist()
137 candidates.append(candidate)
138 observations = runner.evaluate_groups([(candidate, 1) for candidate in candidates])
139 ranks = []
140 for rows in observations:
141 if not rows:
142 ranks.append((-1, 0.))
143 continue
144 row = rows[0]
145 try:
146 inside = self._source.index_grid(row.features) == target
147 except IndexError:
148 inside = False
149 ranks.append((1, self._direction * row.fitness[0]) if inside else
150 (0, -np.linalg.norm(np.asarray(row.features) - center)))
151 # Rank the lexicographic scores, including ties, on equally spaced utilities.
152 distinct = {value: rank for rank, value in enumerate(sorted(set(ranks)))}
153 utilities = (rankdata([distinct[value] for value in ranks]) - 1) / (len(ranks) - 1) - .5
154 point = self._clip(point + self.learning_rate * (utilities @ noise) / (len(ranks) * self.sigma))
155 candidate = _fresh(original)
156 candidate[:] = point.tolist()
157 rows, = runner.evaluate_groups([(candidate, self.samples)])
158 measurement = _aggregate(self._source, candidate, rows, estimator=lambda x: np.mean(x, axis=0)) if rows else None
159 return candidate, measurement
160
161
166 def run(self, evaluate, budget, *, executor=None):
167 """Return a new archive. Untouched source cells retain their original elites."""
168 budget = _positive_int(budget, "budget")
169 per_target = self.steps * self.population_size + self.samples
170 targets = budget // per_target
171 output = _stage_archive(self._source)
172 runner = _Rollouts(self._source, evaluate, executor, self.seed, stream=2, seeded=True)
173 rng = np.random.default_rng([self.seed, 2])
174 centers, neighbors = _geometry(self._source, self.complete and targets > len(self._initial))
175 visited = {}
176 refined = completed = accepted = 0
177
178 def process(original, target):
179 nonlocal accepted
180 candidate, measured = self._refine(original, target, centers[target], runner, rng)
181 visited[target] = candidate
182 if measured is not None and _cell(output, measured) == target:
183 try:
184 output._check_if_can_be_added(measured)
185 except (IndexError, ValueError):
186 return
187 accepted += output.add(measured) is not None
188
189 for target, original in self._initial.items():
190 if refined < targets:
191 process(original, target)
192 refined += 1
193 else:
194 output.add(deepcopy(original))
195
196 frontier = {(source, target) for source in visited for target in neighbors[source]
197 if target not in visited}
198 while frontier and refined + completed < targets:
199 pairs = sorted(frontier)
200 source, target = pairs[rng.integers(len(pairs))]
201 process(visited[source], target)
202 frontier.difference_update((neighbor, target) for neighbor in neighbors[target])
203 frontier.update((target, neighbor) for neighbor in neighbors[target] if neighbor not in visited)
204 completed += 1
205 return ARIAResult(output, runner.attempted, runner.failed, refined, completed, accepted)
Independent post-processed archive and attempted rollout accounting.
Definition aria.py:26
Refine archived elites and explore adjacent empty cells using ARIA.
Definition aria.py:80
_refine(self, original, target, center, runner, rng)
Definition aria.py:129
run(self, evaluate, budget, *, executor=None)
Apply full target blocks under a strict rollout cap.
Definition aria.py:166
_clip(self, vectors)
Definition aria.py:126
Dispatch rollouts and resolve them in submission order.
Definition uncertain.py:95