47 """Build a grid of heuristics that can be selected without scoring a new instance.
49 A ridge model fits signed mean performance against structural features
50 of the calibration heuristics. Its interventional Shapley values are
51 exact for the fitted linear predictor. The caller selects which
52 attributions to map to grid coordinates, and all attributions inform
53 the proposal callback. The calibration baseline and mapping are frozen
54 before search so any two elites use the same niche definitions.
56 :param archive: Empty parentless rectangular best-only Grid with a finite
57 nonzero scalar fitness weight and (-1, 1) bounds on each descriptor.
58 :param structure: Callback returning a fixed-width finite vector from a
59 hashable, immutable heuristic representation.
60 :param propose: Callback receiving (parent, attribution_tuple, rng) and
61 returning a heuristic or None to reject a proposal.
62 :param evaluate: Callback returning raw scalar fitness for (heuristic, instance).
63 :param instance_features: Callback returning a finite vector for one instance.
64 :param descriptor_indices: Distinct structural feature indices, one per grid axis.
65 :param neighbors: Number of most similar training instances used for selection.
66 :param ridge: Positive ridge regularization used on standardized structural features.
67 :param seed: Private proposal seed.
70 def __init__(self, archive, *, structure, propose, evaluate, instance_features,
71 descriptor_indices, neighbors=3, ridge=1., seed=0):
72 _validate_grid(archive)
73 if (type(archive)
is not Grid
or archive.parents
or archive.fitness_score_names
74 or archive.features_score_names
or len(archive.fitness_weights
or ()) != 1
75 or not np.isfinite(archive.fitness_weights[0])
or not archive.fitness_weights[0]
76 or tuple(map(tuple, archive.features_domain
or ())) != ((-1., 1.),) * len(archive.shape)):
77 raise ValueError(
"Use a native fixed grid with one signed objective and descriptor bounds (-1, 1).")
78 axes = tuple(descriptor_indices)
79 if (len(axes) != len(archive.shape)
or not all(isinstance(i, (int, np.integer))
and i >= 0
for i
in axes)
80 or len(set(axes)) != len(axes)):
81 raise ValueError(
"Select one distinct nonnegative structural feature index per archive axis.")
82 if not 0 < ridge < np.inf
or not all(map(callable, (structure, propose, evaluate, instance_features))):
83 raise ValueError(
"Provide four callbacks and finite positive ridge regularization.")
88 self.
_rng = np.random.default_rng(seed)
89 self.
_weight = archive.fitness_weights[0]
94 def _feature_row(values, width=None):
95 row = np.asarray(values, dtype=float)
96 if row.ndim != 1
or not len(row)
or (width
is not None and len(row) != width)
or not np.isfinite(row).all():
97 raise ValueError(
"Feature callbacks must return fixed-width nonempty finite vectors.")
100 def _performance(self, heuristic, instances):
101 scores = tuple(float(self.
_evaluate(heuristic, instance))
for instance
in instances)
102 if not np.isfinite(scores).all():
103 raise ValueError(
"Each heuristic evaluation must return finite fitness.")
106 def _attributions(self, row):
109 def _offer(self, heuristic, row, scores):
112 quality = float(np.mean(scores))
114 cell = grid.index_grid(features)
115 if grid.in_bounds((quality,), grid.fitness_domain)
and (grid.free
or grid.solutions[cell]):
117 item.scores[
"training_fitnesses"] = scores
118 item.scores[
"structural_attributions"] = tuple(attribution)
119 return grid.add(item)
is not None
123 def run(self, calibration, training_instances, budget, *, proposal_limit=None):
124 """Measure at least two distinct calibration heuristics, then evolve the repertoire.
126 Each complete panel costs one call per training instance. The
127 budget must cover calibration. A remainder smaller than one panel
128 stays unused. Duplicate and declined proposals count toward
129 proposal_limit, which defaults to ten times the affordable panels.
130 Create a fresh search to calibrate on a different panel.
133 raise RuntimeError(
"Create a fresh heuristic search for each training run.")
134 budget = _positive_int(budget,
"budget")
135 calibration = tuple(calibration)
136 instances = tuple(training_instances)
137 if not instances
or len(set(calibration)) < 2
or len(set(calibration)) != len(calibration):
138 raise ValueError(
"Provide distinct calibration heuristics and a nonempty training panel.")
139 panels = budget // len(instances)
140 if panels < len(calibration):
141 raise ValueError(
"The budget must cover a complete panel for every calibration heuristic.")
142 limit = 10 * panels
if proposal_limit
is None else _positive_int(proposal_limit,
"proposal_limit")
144 panel_mean, panel_scale = features.mean(axis=0), features.std(axis=0)
145 panel_scale[panel_scale == 0.] = 1.
146 panel = (features - panel_mean) / panel_scale
148 if max(self.
_axes) >= structures.shape[1]:
149 raise ValueError(
"A descriptor index exceeds the structural feature width.")
152 scores = [self.
_performance(heuristic, instances)
for heuristic
in calibration]
153 quality = self.
_direction * np.asarray(scores).mean(axis=1)
158 updates = sum(self.
_offer(heuristic, row, values)
159 for heuristic, row, values
in zip(calibration, structures, scores))
160 seen = set(calibration)
162 while len(seen) < panels
and proposals < limit
and self.
archive:
165 heuristic = self.
_propose(parent[0], parent.scores[
"structural_attributions"], self.
_rng)
166 if heuristic
is None or heuristic
in seen:
170 updates += self.
_offer(heuristic, row, values)
176 """Use mean elite fitness on the nearest training instances for selection.
178 Standardization is fit on the training instances. The evaluator is
179 never called. Ties favor the better average training fitness and
180 then the archive order.
183 raise RuntimeError(
"Train a nonempty heuristic repertoire before selecting.")
186 distances = np.sum((self.
_panel - query) ** 2, axis=1)
187 near = np.argsort(distances, kind=
"stable")[:self.
_neighbors]
189 def local_score(item):
190 quality = np.asarray(item.scores[
"training_fitnesses"])
193 return max(self.
archive, key=local_score)[0]
run(self, calibration, training_instances, budget, *, proposal_limit=None)
Calibrate niche definitions and build the repertoire under a shared assay budget.