# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare conditional Bayesian depth and in-run changes to interpretable descriptors. """Run matched-budget Deep QD and descriptor-switch comparisons.""" import argparse import json from dataclasses import asdict from qdpy.algorithms import (BayesianDeepQD, ConditionalBayesianQD, ConditionalConfiguration, DeepQD, DescriptorAxis, DescriptorMutationMAPElites, IntegerVariable, RealVariable) from qdpy.containers import Grid VARIABLES = {"span": RealVariable(0., 1.), "rise": RealVariable(0., 1.), "layers": IntegerVariable(1, 3)} CONFIGURATIONS = ( ConditionalConfiguration({"frame": "solid"}, ("span", "rise"), ("load",)), ConditionalConfiguration({"frame": "laminated"}, ("span", "rise", "layers"), ("load", "clearance")), ) SPAN = DescriptorAxis("span", (0., 1.), 8) FLEX = DescriptorAxis("flex", (0., 1.), 8) RISE = DescriptorAxis("rise", (0., 1.), 8) def frame_archive(): """Report designs with common physical coordinates across both configurations.""" return Grid(shape=(7, 7), features_domain=((0., 1.),) * 2, fitness_domain=((0., 2.),), fitness_weights=(1.,)) def evaluate_frame(design): """Score a frame under configuration-specific load and clearance limits.""" x, y = design["span"], design["rise"] base = 1. - .4 * (x - .32)**2 - .45 * (y - .7)**2 if design["frame"] == "solid": return (base,), (x, y), {"load": x + .6 * y - 1.1} layers = design["layers"] bonus = .20 - .07 * (layers - 2)**2 - .14 * x return (base + bonus,), (x, y), {"load": x + .6 * y - (1.05 + .1 * layers), "clearance": y + .1 * layers - 1.12} def depth_trial(seed, budget): """Measure observed depth even for the baseline with a single retained elite per cell.""" for kind in (DeepQD, ConditionalBayesianQD, BayesianDeepQD): grid = frame_archive() extras = {} if kind is DeepQD else dict(initial_samples=4, surrogate_budget=80, quality_floor=0.) search = kind(grid, budget, VARIABLES, configurations=CONFIGURATIONS, batch_size=4, seed=seed, **extras) observed = {} attempts = [0] * len(CONFIGURATIONS) def evaluate(genome): branch = genome[0] attempts[branch] += 1 fitness, features, residuals = evaluate_frame(search.decode(genome)) if max(residuals.values()) <= 0: cell = grid.index_grid(features), branch observed[cell] = max(fitness[0], observed.get(cell, 0.)) return fitness, features, residuals search.optimise(evaluate) layers = getattr(search, "deep_archive", None) retained = tuple(grid if layers is None else layers) yield dict(method=kind.__name__, seed=seed, evaluations=search.nb_evaluations, cells=grid.filled_bins, retained_pairs=len(retained), measured_pairs=len(observed), configuration_attempts=attempts, configuration_cells=[sum(elite[0] == i for elite in retained) for i in range(len(CONFIGURATIONS))], best_quality=max(observed.values(), default=0.), layer_quality=sum(observed.values()), surrogate_evaluations=getattr(search, "surrogate_evaluations", 0)) def panel_measurement(genome, seed): """Return named physical measurements from one synthetic design evaluation.""" span, rise, flex = genome goal = .30 + .18 * span + .22 * rise fitness = 1. - .6 * (flex - goal)**2 - .25 * (span - .42)**2 - .18 * (rise - .4)**2 return fitness, {"span": span, "rise": rise, "flex": flex} def descriptor_trial(seed, budget): """Compare one axis mutation with the same two fixed descriptor geometries.""" midpoint = budget // 2 if midpoint < 10: raise ValueError("Use at least 20 evaluations for the midpoint comparison.") for mode in ("fixed-flex", "fixed-rise", "cached-switch", "refreshed-switch"): start = RISE if mode == "fixed-rise" else FLEX search = DescriptorMutationMAPElites((SPAN, start), 3, fitness_domain=(0., 1.), iso_sigma=.11, line_sigma=.15, seed=seed) def partial(genome, rollout_seed): fitness, measures = panel_measurement(genome, rollout_seed) del measures["rise"] return fitness, measures search.run(partial if mode == "refreshed-switch" else panel_measurement, midpoint) outcome = None if mode == "cached-switch": outcome = search.switch_axis("flex", RISE) if mode == "refreshed-switch": outcome = search.switch_axis( "flex", RISE, refresh=lambda genome, rollout_seed: panel_measurement(genome, rollout_seed)[1]["rise"], refresh_budget=SPAN.bins, ) search.run(panel_measurement, budget - midpoint - search.stats.refresh_evaluations) # Use measured physical descriptors for the common report, even for old # elites of the refreshed run that were affected by projection. report = search.report((SPAN, RISE)) yield dict(method=mode, seed=seed, **asdict(search.stats), reporting_cells=report.filled_bins, reporting_quality=sum(elite.fitness.values[0] for elite in report), best_quality=search.archive.best.fitness.values[0], switch_transfers=outcome.transferred_elites if outcome else 0, switch_source=outcome.source_elites if outcome else 0) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=("depth", "descriptors")) parser.add_argument("--budget", type=int, default=144) parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33]) args = parser.parse_args() search = depth_trial if args.task == "depth" else descriptor_trial for seed in args.seeds: for row in search(seed, args.budget): print(json.dumps(row, sort_keys=True))