Source code for qdpy.algorithms.heuristic_design

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Structure-directed heuristic repertoires with instance-specific selection.
# @see https://doi.org/10.1109/TEVC.2026.3721299

"""Evolve heuristics with calibrated structural attributions and select on unseen instances."""

import ast
from collections import Counter
from dataclasses import dataclass

import numpy as np
from sklearn.linear_model import Ridge

from qdpy.containers import Grid
from qdpy.phenotype import Features, Fitness, Individual
from .constrained import _validate_grid
from .modern import _positive_int

__all__ = ["ast_node_counts", "HeuristicDesignStats", "QDHeuristicDesign"]


## @brief Count named Python AST nodes without executing a candidate.
[docs] def ast_node_counts(source, node_names): """Return counts in the supplied AST class-name order. SyntaxError from ast.parse lets callers reject malformed proposals before they submit them to a training evaluator. """ counts = Counter(type(node).__name__ for node in ast.walk(ast.parse(source))) return tuple(counts[name] for name in node_names)
## @brief Work and admissions from heuristic repertoire construction.
[docs] @dataclass(frozen=True) class HeuristicDesignStats: """Count proposals, distinct measured heuristics, evaluations, and admissions.""" proposals: int measured: int evaluations: int archive_updates: int
## @brief Evolve a repertoire with structural Shapley features and select by instance similarity.
[docs] class QDHeuristicDesign: """Build a grid of heuristics that can be selected without scoring a new instance. A ridge model fits signed mean performance against structural features of the calibration heuristics. Its interventional Shapley values are exact for the fitted linear predictor. The caller selects which attributions to map to grid coordinates, and all attributions inform the proposal callback. The calibration baseline and mapping are frozen before search so any two elites use the same niche definitions. :param archive: Empty parentless rectangular best-only Grid with a finite nonzero scalar fitness weight and (-1, 1) bounds on each descriptor. :param structure: Callback returning a fixed-width finite vector from a hashable, immutable heuristic representation. :param propose: Callback receiving (parent, attribution_tuple, rng) and returning a heuristic or None to reject a proposal. :param evaluate: Callback returning raw scalar fitness for (heuristic, instance). :param instance_features: Callback returning a finite vector for one instance. :param descriptor_indices: Distinct structural feature indices, one per grid axis. :param neighbors: Number of most similar training instances used for selection. :param ridge: Positive ridge regularization used on standardized structural features. :param seed: Private proposal seed. """ def __init__(self, archive, *, structure, propose, evaluate, instance_features, descriptor_indices, neighbors=3, ridge=1., seed=0): _validate_grid(archive) if (type(archive) is not Grid or archive.parents or archive.fitness_score_names or archive.features_score_names or len(archive.fitness_weights or ()) != 1 or not np.isfinite(archive.fitness_weights[0]) or not archive.fitness_weights[0] or tuple(map(tuple, archive.features_domain or ())) != ((-1., 1.),) * len(archive.shape)): raise ValueError("Use a native fixed grid with one signed objective and descriptor bounds (-1, 1).") axes = tuple(descriptor_indices) if (len(axes) != len(archive.shape) or not all(isinstance(i, (int, np.integer)) and i >= 0 for i in axes) or len(set(axes)) != len(axes)): raise ValueError("Select one distinct nonnegative structural feature index per archive axis.") if not 0 < ridge < np.inf or not all(map(callable, (structure, propose, evaluate, instance_features))): raise ValueError("Provide four callbacks and finite positive ridge regularization.") self.archive, self._axes = archive, list(axes) self._structure, self._propose, self._evaluate = structure, propose, evaluate self._instance_features = instance_features self._ridge, self._neighbors = ridge, _positive_int(neighbors, "neighbors") self._rng = np.random.default_rng(seed) self._weight = archive.fitness_weights[0] self._direction = np.sign(self._weight) self._panel = None @staticmethod def _feature_row(values, width=None): row = np.asarray(values, dtype=float) if row.ndim != 1 or not len(row) or (width is not None and len(row) != width) or not np.isfinite(row).all(): raise ValueError("Feature callbacks must return fixed-width nonempty finite vectors.") return row def _performance(self, heuristic, instances): scores = tuple(float(self._evaluate(heuristic, instance)) for instance in instances) if not np.isfinite(scores).all(): raise ValueError("Each heuristic evaluation must return finite fitness.") return scores def _attributions(self, row): return (row - self._structure_mean) / self._structure_scale * self._coefficients def _offer(self, heuristic, row, scores): attribution = self._attributions(row) features = tuple(np.tanh(attribution[self._axes] / self._performance_scale)) quality = float(np.mean(scores)) grid = self.archive cell = grid.index_grid(features) if grid.in_bounds((quality,), grid.fitness_domain) and (grid.free or grid.solutions[cell]): item = Individual([heuristic], fitness=Fitness((quality,), weights=(self._weight,)), features=Features(features)) item.scores["training_fitnesses"] = scores item.scores["structural_attributions"] = tuple(attribution) return grid.add(item) is not None return False ## @brief Calibrate niche definitions and build the repertoire under a shared assay budget.
[docs] def run(self, calibration, training_instances, budget, *, proposal_limit=None): """Measure at least two distinct calibration heuristics, then evolve the repertoire. Each complete panel costs one call per training instance. The budget must cover calibration. A remainder smaller than one panel stays unused. Duplicate and declined proposals count toward proposal_limit, which defaults to ten times the affordable panels. Create a fresh search to calibrate on a different panel. """ if self._panel is not None or len(self.archive): raise RuntimeError("Create a fresh heuristic search for each training run.") budget = _positive_int(budget, "budget") calibration = tuple(calibration) instances = tuple(training_instances) if not instances or len(set(calibration)) < 2 or len(set(calibration)) != len(calibration): raise ValueError("Provide distinct calibration heuristics and a nonempty training panel.") panels = budget // len(instances) if panels < len(calibration): raise ValueError("The budget must cover a complete panel for every calibration heuristic.") limit = 10 * panels if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit") features = np.stack([self._feature_row(self._instance_features(instance)) for instance in instances]) panel_mean, panel_scale = features.mean(axis=0), features.std(axis=0) panel_scale[panel_scale == 0.] = 1. panel = (features - panel_mean) / panel_scale structures = np.stack([self._feature_row(self._structure(heuristic)) for heuristic in calibration]) if max(self._axes) >= structures.shape[1]: raise ValueError("A descriptor index exceeds the structural feature width.") self._structure_mean, self._structure_scale = structures.mean(axis=0), structures.std(axis=0) self._structure_scale[self._structure_scale == 0.] = 1. scores = [self._performance(heuristic, instances) for heuristic in calibration] quality = self._direction * np.asarray(scores).mean(axis=1) self._performance_scale = float(quality.std()) or 1. self._coefficients = Ridge(alpha=self._ridge).fit( (structures - self._structure_mean) / self._structure_scale, quality).coef_ self._panel, self._panel_mean, self._panel_scale = panel, panel_mean, panel_scale updates = sum(self._offer(heuristic, row, values) for heuristic, row, values in zip(calibration, structures, scores)) seen = set(calibration) proposals = 0 while len(seen) < panels and proposals < limit and self.archive: parent = self.archive[self._rng.integers(len(self.archive))] proposals += 1 heuristic = self._propose(parent[0], parent.scores["structural_attributions"], self._rng) if heuristic is None or heuristic in seen: continue row = self._feature_row(self._structure(heuristic), structures.shape[1]) values = self._performance(heuristic, instances) updates += self._offer(heuristic, row, values) seen.add(heuristic) return HeuristicDesignStats(proposals, len(seen), len(seen) * len(instances), updates)
## @brief Retrieve a measured heuristic for an instance using its features only.
[docs] def select(self, instance): """Use mean elite fitness on the nearest training instances for selection. Standardization is fit on the training instances. The evaluator is never called. Ties favor the better average training fitness and then the archive order. """ if self._panel is None or not self.archive: raise RuntimeError("Train a nonempty heuristic repertoire before selecting.") row = self._feature_row(self._instance_features(instance), self._panel.shape[1]) query = (row - self._panel_mean) / self._panel_scale distances = np.sum((self._panel - query) ** 2, axis=1) near = np.argsort(distances, kind="stable")[:self._neighbors] def local_score(item): quality = np.asarray(item.scores["training_fitnesses"]) return self._direction * quality[near].mean(), self._direction * item.fitness.values[0] return max(self.archive, key=local_score)[0]