QDpy
Loading...
Searching...
No Matches
heuristic_design.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Evolve heuristics with calibrated structural attributions and select on unseen instances."""
7
8import ast
9from collections import Counter
10from dataclasses import dataclass
11
12import numpy as np
13from sklearn.linear_model import Ridge
14
15from qdpy.containers import Grid
16from qdpy.phenotype import Features, Fitness, Individual
17from .constrained import _validate_grid
18from .modern import _positive_int
19
20__all__ = ["ast_node_counts", "HeuristicDesignStats", "QDHeuristicDesign"]
21
22
23
24def ast_node_counts(source, node_names):
25 """Return counts in the supplied AST class-name order.
26
27 SyntaxError from ast.parse lets callers reject malformed proposals
28 before they submit them to a training evaluator.
29 """
30 counts = Counter(type(node).__name__ for node in ast.walk(ast.parse(source)))
31 return tuple(counts[name] for name in node_names)
32
33
34
35@dataclass(frozen=True)
37 """Count proposals, distinct measured heuristics, evaluations, and admissions."""
38
39 proposals: int
40 measured: int
41 evaluations: int
42 archive_updates: int
43
44
45
47 """Build a grid of heuristics that can be selected without scoring a new instance.
48
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.
55
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.
68 """
69
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.")
84 self.archive, self._axes = archive, list(axes)
85 self._structure, self._propose, self._evaluate = structure, propose, evaluate
86 self._instance_features = instance_features
87 self._ridge, self._neighbors = ridge, _positive_int(neighbors, "neighbors")
88 self._rng = np.random.default_rng(seed)
89 self._weight = archive.fitness_weights[0]
90 self._direction = np.sign(self._weight)
91 self._panel = None
92
93 @staticmethod
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.")
98 return row
99
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.")
104 return scores
105
106 def _attributions(self, row):
107 return (row - self._structure_mean) / self._structure_scale * self._coefficients
108
109 def _offer(self, heuristic, row, scores):
110 attribution = self._attributions(row)
111 features = tuple(np.tanh(attribution[self._axes] / self._performance_scale))
112 quality = float(np.mean(scores))
113 grid = self.archive
114 cell = grid.index_grid(features)
115 if grid.in_bounds((quality,), grid.fitness_domain) and (grid.free or grid.solutions[cell]):
116 item = Individual([heuristic], fitness=Fitness((quality,), weights=(self._weight,)), features=Features(features))
117 item.scores["training_fitnesses"] = scores
118 item.scores["structural_attributions"] = tuple(attribution)
119 return grid.add(item) is not None
120 return False
121
122
123 def run(self, calibration, training_instances, budget, *, proposal_limit=None):
124 """Measure at least two distinct calibration heuristics, then evolve the repertoire.
125
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.
131 """
132 if self._panel is not None or len(self.archive):
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")
143 features = np.stack([self._feature_row(self._instance_features(instance)) for instance in instances])
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
147 structures = np.stack([self._feature_row(self._structure(heuristic)) for heuristic in calibration])
148 if max(self._axes) >= structures.shape[1]:
149 raise ValueError("A descriptor index exceeds the structural feature width.")
150 self._structure_mean, self._structure_scale = structures.mean(axis=0), structures.std(axis=0)
151 self._structure_scale[self._structure_scale == 0.] = 1.
152 scores = [self._performance(heuristic, instances) for heuristic in calibration]
153 quality = self._direction * np.asarray(scores).mean(axis=1)
154 self._performance_scale = float(quality.std()) or 1.
155 self._coefficients = Ridge(alpha=self._ridge).fit(
156 (structures - self._structure_mean) / self._structure_scale, quality).coef_
157 self._panel, self._panel_mean, self._panel_scale = panel, panel_mean, panel_scale
158 updates = sum(self._offer(heuristic, row, values)
159 for heuristic, row, values in zip(calibration, structures, scores))
160 seen = set(calibration)
161 proposals = 0
162 while len(seen) < panels and proposals < limit and self.archive:
163 parent = self.archive[self._rng.integers(len(self.archive))]
164 proposals += 1
165 heuristic = self._propose(parent[0], parent.scores["structural_attributions"], self._rng)
166 if heuristic is None or heuristic in seen:
167 continue
168 row = self._feature_row(self._structure(heuristic), structures.shape[1])
169 values = self._performance(heuristic, instances)
170 updates += self._offer(heuristic, row, values)
171 seen.add(heuristic)
172 return HeuristicDesignStats(proposals, len(seen), len(seen) * len(instances), updates)
173
174
175 def select(self, instance):
176 """Use mean elite fitness on the nearest training instances for selection.
177
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.
181 """
182 if self._panel is None or not self.archive:
183 raise RuntimeError("Train a nonempty heuristic repertoire before selecting.")
184 row = self._feature_row(self._instance_features(instance), self._panel.shape[1])
185 query = (row - self._panel_mean) / self._panel_scale
186 distances = np.sum((self._panel - query) ** 2, axis=1)
187 near = np.argsort(distances, kind="stable")[:self._neighbors]
188
189 def local_score(item):
190 quality = np.asarray(item.scores["training_fitnesses"])
191 return self._direction * quality[near].mean(), self._direction * item.fitness.values[0]
192
193 return max(self.archive, key=local_score)[0]
Work and admissions from heuristic repertoire construction.
Evolve a repertoire with structural Shapley features and select by instance similarity.
select(self, instance)
Retrieve a measured heuristic for an instance using its features only.
run(self, calibration, training_instances, budget, *, proposal_limit=None)
Calibrate niche definitions and build the repertoire under a shared assay budget.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405