24 """Fit objective, descriptor and residual GPs using only active genes."""
26 def __init__(self, search, branch):
27 self.
active = search._active[branch]
28 self.
continuous = np.asarray([isinstance(search.variables[i], RealVariable)
for i
in self.
active], dtype=bool)
29 lower = [search._bounds[i][0]
for i
in self.
active if isinstance(search.variables[i], RealVariable)]
30 upper = [search._bounds[i][1]
for i
in self.
active if isinstance(search.variables[i], RealVariable)]
31 self.
origin = np.asarray(lower)
32 self.
span = np.asarray([hi - lo
or 1.
for lo, hi
in zip(lower, upper)])
33 covariance = partial(_gower_covariance, continuous=self.
continuous,
34 length_scale=search.real_length_scale, correlation=search.discrete_correlation)
35 genomes, responses = zip(*search._observations[branch])
38 def _encode(self, genomes):
39 points = np.asarray([[genome[i + 1]
for i
in self.
active]
for genome
in genomes], dtype=float)
41 points[:, real] = (points[:, real] - self.
origin) / self.
span
44 def predict(self, genomes):
45 return self.
gp.predict(self.
_encode(genomes))
57 """Fit per-configuration surrogates and promote exact evaluations into a shared grid.
59 Each cheap pool uses a mix of uniform designs and perturbations of prior
60 measurements from that configuration. Assign each predicted design to
61 its posterior-mean descriptor cell. Rank proposals by feasibility-weighted
62 expected improvement over the measured cell incumbent. Select at most
63 one predicted winner per cell per batch before filling unused slots.
64 Only measured feasible designs are offered to the reporting grid.
66 :param container: Empty best-only Grid or CVTGrid with one objective.
67 :param budget: Total exact evaluation attempts.
68 :param variables: Ordered mapping from variable names to HiGeME gene specifications.
69 :param configurations: Allowed ConditionalConfiguration objects.
70 :param initial_samples: Space-filling draws per configuration before fitting.
71 :param surrogate_budget: Candidate prediction attempts per fitted configuration and batch.
72 :param quality_floor: Optional raw fitness reference for empty cells. By
73 default use the worst signed fitness measured so far.
74 :param exploration_probability: Chance of a fresh random draw after warm-up.
75 :param real_length_scale: Gaussian length scale on normalized real genes.
76 :param discrete_correlation: Kernel factor for mismatched discrete genes.
77 :param batch_size: Total exact proposals per acquisition update.
78 :param seed: Private random seed.
79 :param optimisation_task: Single objective direction or weight. Defaults
80 to the supplied archive's direction when set.
83 def __init__(self, container, budget, variables, *, configurations, initial_samples=4,
84 surrogate_budget=96, quality_floor=None, exploration_probability=.1,
85 real_length_scale=.25, discrete_correlation=.25, batch_size=1, seed=0,
86 optimisation_task=None):
87 if not (0 <= exploration_probability <= 1
and 0 < real_length_scale < np.inf
88 and 0 <= discrete_correlation < 1):
89 raise ValueError(
"Use finite GP settings and an exploration probability in [0, 1].")
90 if quality_floor
is not None and not np.isfinite(quality_floor):
91 raise ValueError(
"quality_floor must be finite.")
92 self.
initial_samples = _positive_int(initial_samples,
"initial_samples")
97 if optimisation_task
is None:
98 optimisation_task =
"minimisation" if container.fitness_weights
is None else container.fitness_weights
99 super().__init__(container, budget, variables, configurations=configurations, seed=seed,
100 batch_size=batch_size, optimisation_task=optimisation_task)
103 raise ValueError(
"Use a finite nonzero fitness weight.")
104 active = {i
for branch
in self.
_active for i
in branch}
105 if any(
not isinstance(self.
variables[i], RealVariable)
and max(map(abs, self.
_bounds[i])) > 2**53
107 raise ValueError(
"Active discrete genes must be exactly representable in float64.")
112 """Reset models, proposal streams, and conditional evaluation counts."""
121 """Return exact proposals in configuration order, including failed evaluations."""
126 """Return counts of finite observations used by each configuration model."""
131 """Return the number of distinct cheap predictions across all batches."""
136 """Return the number of per-configuration model refits."""
137 return self._model_fits
141 """Return exact proposals chosen by the surrogate."""
142 return self._modelled_proposals
144 def _random(self, branch):
145 genome = [lo
for lo, _
in self.
_bounds]
148 return (branch, *genome)
150 def _draw(self, branch, reserved=()):
153 if vector
not in self.
_seen and vector
not in reserved:
157 def _pool(self, branch, observations):
158 """Draw cheap trials from between and around prior exact designs."""
164 if self.
_rng.random() < .5:
165 genome = list(self.
_rng.choice(observations)[0])
166 i = self.
_rng.choice(mutable)
168 vector = tuple(genome)
171 if vector
not in self.
_seen:
175 def _rank_pool(self, branch, vectors, floor):
177 self._model_fits += 1
178 means, deviations = model.predict(vectors)
181 width = len(grid.features_domain)
182 probability = _probability_feasible(means[:, width + 1:], deviations[:, width + 1:])
184 for i, vector
in enumerate(vectors):
185 features = tuple(means[i, 1:width + 1])
186 if not np.isfinite(features).all()
or not grid.in_bounds(features, grid.features_domain):
188 cell = grid.index_grid(features)
190 rows.append((i, threshold, cell, vector))
193 indices, thresholds, _, _ = zip(*rows)
194 indices = list(indices)
195 with np.errstate(over=
"ignore", divide=
"ignore", invalid=
"ignore"):
196 improvement = _expected_improvement(means[indices, 0], deviations[indices, 0], np.asarray(thresholds))
197 scores = probability[indices] * improvement
198 return [(float(score), float(probability[i]), float(deviations[i, 0]), cell, vector)
199 for (i, _, cell, vector), score
in zip(rows, scores)
if np.isfinite(score)]
201 def _acquisition_reference(self, branch, cell, floor):
202 occupants = self.
container.solutions[cell]
203 return self.
_direction * self.
container.get_ind_fitness(occupants[0]).values[0]
if occupants
else floor
205 def _acquisition_key(self, cell, vector):
208 def _plan_batch(self, size):
210 min(row[0]
for observations
in self.
_observations for _, row
in observations))
214 pool = self.
_pool(branch, observations)
216 ranked.extend(self.
_rank_pool(branch, pool, floor))
217 ranked.sort(key=
lambda row: row[:3], reverse=
True)
219 for _, _, _, cell, vector
in ranked:
221 if len(selected) == size:
223 return selected.values()
231 """Queue model-based proposals for the next fixed batch."""
237 def _next_vector(self):
241 self._modelled_proposals += 1
244 else self.
_rng.randrange(count))
245 vector = self.
_draw(branch)
251 self.
_seen.add(vector)
255 def _check_candidate(self, individual):
258 if len(self.
container.get_ind_features(individual)) != len(self.
container.features_domain):
259 raise ValueError(
"Provide one measured descriptor per grid axis.")
260 _constraint_violation(individual, self.
configurations[individual[0]].constraints)
262 def _offer_feasible(self, individual, cell):
267 for slot, individual
in enumerate(evaluated):
268 if individual
is None:
270 branch = individual[0]
271 fitness = grid.get_ind_fitness(individual).values
272 features = tuple(grid.get_ind_features(individual))
273 residuals = tuple(float(individual.scores[name])
for name
in self.
configurations[branch].constraints)
274 response = (self.
_direction * float(fitness[0]), *features, *residuals)
275 self.
_observations[branch].append((tuple(individual), response))
276 if (all(value <= 0.
for value
in residuals)
and grid.in_bounds(fitness, grid.fitness_domain)
277 and grid.in_bounds(features, grid.features_domain)