QDpy
Loading...
Searching...
No Matches
mome_x.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Estimate fitness and descriptor dispersion together using paired rollouts."""
7
8from math import isfinite
9
10import numpy as np
11
12from qdpy.containers import Grid, ParetoGrid
13from qdpy.containers.pareto import _sampling_crowding
14from qdpy.phenotype import Features, Fitness, Individual
15from qdpy.tools import iso_line_dd
16from .modern import _positive_int, _variation_settings
17from .uncertain import _Rollouts
18
19__all__ = ["MOMEX"]
20
21
22
23class MOMEX:
24 """Search using fixed complete groups of ordinary scalar QD measurements.
25
26 :param container: Empty crowding ParetoGrid with fitness and reproducibility objectives,
27 in that order. Maximize the second objective.
28 :param budget: Raw rollout attempts. A remainder smaller than samples is left unused.
29 :param dimension: Number of bounded real decision variables.
30 :param samples: Rollouts per candidate, at least two.
31 :param batch_size: Maximum number of candidates before committing their fronts.
32 :param estimator: "median" or "mean" for fitness and descriptor coordinates.
33 :param ind_domain: Shared bounds on decision variables.
34 :param iso_sigma: Independent mutation scale for Iso+LineDD.
35 :param line_sigma: Directional mutation scale for Iso+LineDD.
36 :param seed: Private variation, selection, and evaluator seed.
37 """
38
39 def __init__(self, container, budget, dimension, *, samples=32, batch_size=8,
40 estimator="median", ind_domain=(0., 1.), iso_sigma=.01, line_sigma=.2, seed=0):
41 if (not isinstance(container, ParetoGrid) or len(container) or len(container.fitness_domain) != 2
42 or container.fitness_weights[1] <= 0 or container.truncation != "crowding"
43 or container.fitness_score_names or container.features_score_names):
44 raise ValueError("Use an empty two-objective crowding ParetoGrid maximizing reproducibility.")
45 if estimator not in ("mean", "median"):
46 raise ValueError("estimator must be 'mean' or 'median'.")
47 self.budget = _positive_int(budget, "budget")
48 self.samples = _positive_int(samples, "samples")
49 if not 2 <= self.samples <= self.budget:
50 raise ValueError("Use at least two samples and enough budget for one complete candidate.")
51 self.dimension = _positive_int(dimension, "dimension")
52 self.batch_size = _positive_int(batch_size, "batch_size")
53 self.ind_domain = _variation_settings(ind_domain, iso_sigma, line_sigma)
54 if not isfinite(self.ind_domain[1] - self.ind_domain[0]):
55 raise ValueError("Use finite decision spans.")
56 self.iso_sigma, self.line_sigma = iso_sigma, line_sigma
57 self.container = container
58 self.seed = int(np.random.SeedSequence(seed).generate_state(1, dtype=np.uint64)[0])
59 self._estimator = np.median if estimator == "median" else np.mean
60 self._rng = np.random.default_rng(self.seed)
61 self.nb_evaluations = self.failed_evaluations = self.completed_candidates = 0
62 self._scalar = Grid(shape=(1,) * len(container.features_domain),
63 features_domain=container.features_domain,
64 fitness_domain=container.fitness_domain[:1],
65 fitness_weights=container.fitness_weights[:1])
66
67 def _propose(self, count):
68 fronts = [(front, _sampling_crowding([item.fitness.values for item in front]))
69 for front in self.container.solutions.values() if front]
70
71 def parent():
72 front, distances = fronts[self._rng.integers(len(fronts))]
73 total = distances.sum()
74 return front[self._rng.choice(len(front), p=distances / total if total else None)]
75
76 if not fronts:
77 return [Individual(self._rng.uniform(*self.ind_domain, size=self.dimension)) for _ in range(count)]
78 return [Individual(iso_line_dd(parent(), parent(), iso_sigma=self.iso_sigma,
79 line_sigma=self.line_sigma, bounds=self.ind_domain,
80 rng=self._rng)) for _ in range(count)]
81
82 def _measurement(self, candidate, observations):
83 rows = np.asarray([(*obs.fitness, *obs.features) for obs in observations], dtype=float)
84 scales = np.max(np.abs(rows), axis=0)
85 normalized = rows / np.where(scales == 0., 1., scales)
86 central = self._estimator(normalized, axis=0) * scales
87 spread = np.std(normalized[:, 1:], axis=0, ddof=0).clip(max=1.) * scales[1:]
88 stability = -float(sum(spread / len(spread)))
89 fitness = (central[0], stability)
90 if not (self.container.in_bounds(fitness, self.container.fitness_domain)
91 and self.container.in_bounds(central[1:], self.container.features_domain)):
92 return None
93 candidate.fitness = Fitness(fitness, weights=self.container.fitness_weights)
94 candidate.features = Features(central[1:])
95 candidate.scores.update(descriptor_std=tuple(spread), rollout_count=len(rows))
96 return candidate
97
98
99 def optimise(self, evaluate, *, executor=None, seeded=False):
100 """Return the Pareto archive. A failed rollout invalidates its candidate group."""
101 if self.nb_evaluations:
102 raise RuntimeError("Construct a new MOMEX instance to restart the search.")
103 rollouts = _Rollouts(self._scalar, evaluate, executor, self.seed, seeded=seeded)
104 try:
105 while self.budget - rollouts.attempted >= self.samples:
106 count = min(self.batch_size, (self.budget - rollouts.attempted) // self.samples)
107 candidates = self._propose(count)
108 groups = rollouts.evaluate_groups([(candidate, self.samples) for candidate in candidates])
109 measured = []
110 for candidate, observations in zip(candidates, groups):
111 if len(observations) == self.samples:
112 self.completed_candidates += 1
113 measured_candidate = self._measurement(candidate, observations)
114 if measured_candidate is not None:
115 measured.append(measured_candidate)
116 self.container._merge_fronts(measured)
117 finally:
118 self.nb_evaluations, self.failed_evaluations = rollouts.attempted, rollouts.failed
119 return self.container
120
121
122 def project(self, reproducibility_weight=0.):
123 """Return a fresh scalar Grid scored by raw fitness, retaining descriptor spread in scores.
124
125 The utility is signed fitness plus reproducibility_weight times
126 negative mean descriptor standard deviation. Break exact utility
127 ties by favoring reproducibility.
128 """
129 weight = float(reproducibility_weight)
130 if not 0. <= weight < np.inf:
131 raise ValueError("The reproducibility weight must be finite and nonnegative.")
132 archive = self.container
133 direction = np.sign(archive.fitness_weights[0])
134 quality = Grid(shape=archive.shape, features_domain=archive.features_domain,
135 fitness_domain=archive.fitness_domain[:1], fitness_weights=archive.fitness_weights[:1])
136 for front in archive.solutions.values():
137 if front:
138 points = np.asarray([item.fitness.values for item in front])
139 points = points.astype(float) / (np.max(np.abs(points)) or 1.)
140 coefficients = np.array([direction, weight]) / max(1., weight)
141 choice = np.lexsort((points[:, 1], points @ coefficients))[-1]
142 elite = front[choice]
143 candidate = Individual(tuple(elite), fitness=Fitness(elite.fitness.values[:1], weights=quality.fitness_weights),
144 features=Features(elite.features.values), scores=dict(elite.scores))
145 quality.add(candidate)
146 return quality
Keep different performance–reproducibility trade-offs in every cell.
Definition mome_x.py:23
_measurement(self, candidate, observations)
Definition mome_x.py:82
project(self, reproducibility_weight=0.)
Select one elite per cell at a chosen reproducibility weight.
Definition mome_x.py:122
optimise(self, evaluate, *, executor=None, seeded=False)
Run complete rollout groups in proposal order under the raw-call cap.
Definition mome_x.py:99
Dispatch rollouts and resolve them in submission order.
Definition uncertain.py:95
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405