30 """Use a frozen Matérn GP and a caller-supplied categorical prior.
32 Mutation samples single-locus changes and optionally chooses among
33 them using prior scores. At admission, increasing model uncertainty
34 increases the contribution of the prior to a normalized quality score.
35 The returned archive stores raw predicted quality and descriptors.
36 Disagreement is an acquisition signal and carries no coverage guarantee.
38 :param archive: Empty parentless best-only Grid or CVTGrid with one signed objective.
39 :param genomes: Integer training designs, one row per measurement.
40 :param fitnesses: Measured scalar qualities for the training designs.
41 :param descriptors: Measured descriptors for the training designs.
42 :param nvec: Number of zero-based categories in each locus.
43 :param prior: Callable scoring a design on [0, 1], with higher being more plausible.
44 :param prior_weight: Maximum fraction of the acquisition score determined by the prior.
45 :param uncertainty_scale: Predicted deviation at which the prior receives half its maximum weight.
46 Defaults to one quarter of the logged quality span.
47 :param uncertainty_penalty: Fixed standard-deviation penalty in quality units.
48 :param mutation_choices: Number of prior-scored edits per mutation.
49 :param proposal_strength: Inverse temperature applied to prior scores on edits.
50 :param length_scale: Fixed Matérn length scale on one-hot genomes.
51 :param noise: Positive GP covariance regularization.
52 :param seed: Private seed for seed selection and mutations.
55 def __init__(self, archive, genomes, fitnesses, descriptors, *, nvec, prior=None,
56 prior_weight=1., uncertainty_scale=None, uncertainty_penalty=0., mutation_choices=4,
57 proposal_strength=3., length_scale=1.8, noise=1e-6, seed=0):
58 _validate_grid(archive)
59 weights = archive.fitness_weights
60 if weights
is None or archive.fitness_score_names
or archive.features_score_names:
61 raise ValueError(
"Use native scores and an explicit nonzero fitness weight.")
62 counts = tuple(_positive_int(count,
"category count")
for count
in nvec)
64 raise ValueError(
"Supply at least one locus.")
65 rows = np.asarray(genomes)
66 scores = np.asarray(fitnesses, dtype=float)
67 descriptors = np.asarray(descriptors, dtype=float)
68 if (rows.ndim != 2
or len(rows) < 2
or rows.shape[1] != len(counts)
69 or rows.dtype.kind
not in "iu" or (rows < 0).any()
or (rows >= counts).any()
70 or scores.shape != (len(rows),)
or not np.isfinite(scores).all()
71 or descriptors.shape != (len(rows), len(archive.features_domain))
72 or not np.isfinite(descriptors).all()):
73 raise ValueError(
"Supply aligned finite measurements for valid categorical genomes.")
74 if (prior
is not None and not callable(prior)
or not 0. <= prior_weight <= 1.
75 or not 0. <= uncertainty_penalty < np.inf
or not 0. <= proposal_strength < np.inf
76 or not 0. < length_scale < np.inf
or not 0. < noise < np.inf):
77 raise ValueError(
"Provide a callable prior and finite, valid acquisition and GP settings.")
79 self.
_direction = 1.
if weights[0] > 0.
else -1.
80 minimum = float((self.
_direction * scores).min())
81 span = float((self.
_direction * scores).max()) - minimum
82 self.
_span = span
or max(1., abs(minimum))
83 self.
_uncertainty = max(self.
_span / 4., np.finfo(float).tiny)
if uncertainty_scale
is None else uncertainty_scale
85 raise ValueError(
"The logged quality span and uncertainty scale must be finite.")
88 self.
_offsets = np.cumsum((0, *counts[:-1]))
89 self.
_movable = tuple(i
for i, count
in enumerate(counts)
if count > 1)
90 self.
_rows = rows.astype(np.int64, copy=
True)
92 self.
_model = _frozen_matern(self.
_encode(self.
_rows), np.column_stack((scores, descriptors)),
94 self.
_prior = prior
if prior_weight
else None
96 self.
_choices = _positive_int(mutation_choices,
"mutation_choices")
100 def _encode(self, rows):
101 features = np.zeros((len(rows), sum(self.
_groups)))
102 features[np.arange(len(rows))[:,
None], rows + self.
_offsets] = 1.
105 def _acquire(self, mean, deviation, prior):
107 if self.
_prior is not None else 0.)
109 quality = (1. - weight) * normalized + weight * prior - self.
_penalty * (deviation / self.
_span)
110 return float(quality), float(weight)
112 def _edit(self, point, rng):
116 draw = int(rng.integers(self.
_groups[locus] - 1))
117 return (*point[:locus], draw + (draw >= point[locus]), *point[locus + 1:])
123 def run(self, budget, *, initial_samples=16):
124 """Make a new predicted archive and count every prior call."""
125 budget = _positive_int(budget,
"budget")
126 initial = min(_positive_int(initial_samples,
"initial_samples"), budget, len(self.
_rows))
127 rng = np.random.default_rng(self.
seed)
128 seeds = rng.permutation(len(self.
_rows))[:initial]
129 archive = _empty_geometry(self.
_geometry)
133 def prior_score(point):
138 value = float(self.
_prior(point))
139 if not 0. <= value <= 1.:
140 raise ValueError(
"The prior must return a finite score in [0, 1].")
143 for step
in range(budget):
145 point = tuple(map(int, self.
_rows[seeds[step]]))
146 prior = prior_score(point)
149 parent = tuple(winners.values())[int(rng.integers(len(winners)))]
151 parent = self.
_rows[int(rng.integers(len(self.
_rows)))]
152 parent = tuple(map(int, parent))
154 point = self.
_edit(parent, rng)
155 prior = prior_score(point)
157 edits = tuple(dict.fromkeys(self.
_edit(parent, rng)
for _
in range(self.
_choices)))
158 ranking = np.asarray([prior_score(point)
for point
in edits])
159 weights = np.exp(self.
_strength * (ranking - ranking.max()))
160 selected = int(rng.choice(len(edits), p=weights / weights.sum()))
161 point, prior = edits[selected], ranking[selected]
162 mean, std = self.
_model.predict(self.
_encode(np.asarray([point])), return_std=
True)
163 quality, *features = mean[0]
164 deviation = float(std[0, 0])
165 value, weight = self.
_acquire(quality, deviation, prior)
166 if not np.isfinite((value, quality, deviation, *features)).all():
167 raise ValueError(
"The frozen surrogate produced a nonfinite prediction or acquisition.")
168 if not (archive.in_bounds((quality,), archive.fitness_domain)
169 and archive.in_bounds(features, archive.features_domain)):
171 cell = archive.index_grid(features)
172 previous = winners.get(cell)
173 if previous
is None and len(winners) >= archive.capacity:
175 if previous
is None or value > previous.scores[
"acquisition"]:
177 features=
Features(features), scores={
178 "acquisition": value,
"prediction_std": deviation,
179 "predicted_fitness": float(quality),
"prior": prior,
180 "prior_fraction": weight,
182 archive.update(winners.values())
185 verify = staticmethod(OfflineMAPElites.verify)