# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare solver certification, safe exploration, and diffusion illumination. """Run small seeded CPU comparisons. CP-SAT requires the optional cpsat extra.""" import argparse import json import random from itertools import product from pathlib import Path import numpy as np from qdpy.algorithms import ( BOPElites, CPSATArchiveSearch, DifferentialMAPElites, DiffusionEvolution, DiffusionMAPElites, IsoLineMAPElites, SafeBayesianIllumination, ) from qdpy.containers import Grid HORIZON = 9 DURATIONS = (2, 3, 2, 1) DEMANDS = (1, 2, 1, 1) SAFE_SEED_INDEX = 36 SAFE_SEED = SAFE_SEED_INDEX / 160 NARROW_PEAKS = np.array([(-.72, -.7, .65, -.55), (-.68, .73, -.62, .56), (.69, -.71, -.58, .67), (.73, .68, .58, -.62)]) HIMMELBLAU_PEAKS = np.array([(3., 2.), (-2.805118, 3.131312), (-3.779310, -3.283186), (3.584428, -1.848126)]) / 5. def quality_grid(shape): """Create a one-elite maximizing archive with unit domains.""" return Grid(shape=shape, features_domain=((0., 1.),) * len(shape), fitness_domain=((0., 1.),), fitness_weights=(1.,)) def scheduling_model(): """Set up two jobs that visit two machines in opposite order.""" from ortools.sat.python import cp_model model = cp_model.CpModel() starts = [model.new_int_var(0, HORIZON - d, f"start_{i}") for i, d in enumerate(DURATIONS)] ends = tuple(start + duration for start, duration in zip(starts, DURATIONS)) intervals = [model.new_fixed_size_interval_var(start, duration, f"operation_{i}") for i, (start, duration) in enumerate(zip(starts, DURATIONS))] model.add(starts[1] >= ends[0]) model.add(starts[3] >= ends[2]) for first, second in ((0, 3), (1, 2)): model.add_no_overlap((intervals[first], intervals[second])) model.add_cumulative(intervals, DEMANDS, 2) makespan = model.new_int_var(0, HORIZON, "makespan") model.add_max_equality(makespan, (ends[1], ends[3])) return model, ends[1] + ends[3], (makespan, ends[1] - ends[3]) def exhaustive_schedule(archive): """Find exact niche optima by enumerating integer start times.""" best = {} for starts in product(*(range(HORIZON - d + 1) for d in DURATIONS)): finishes = tuple(start + duration for start, duration in zip(starts, DURATIONS)) if starts[1] < finishes[0] or starts[3] < finishes[2]: continue if any(max(starts[a], starts[b]) < min(finishes[a], finishes[b]) for a, b in ((0, 3), (1, 2))): continue if any(sum(demand for start, end, demand in zip(starts, finishes, DEMANDS) if start <= tick < end) > 2 for tick in range(HORIZON)): continue a, b = finishes[1], finishes[3] cell = archive.index_grid((max(a, b), a - b)) best[cell] = min(best.get(cell, 2 * HORIZON), a + b) return best def solver_trial(): """Solve every cell and certify the reports against the enumerated reference.""" model, objective, descriptors = scheduling_model() archive = Grid(shape=(5, 7), features_domain=((0, HORIZON), (-HORIZON, HORIZON)), fitness_domain=((0, 2 * HORIZON),), fitness_weights=(-1.,)) reports = CPSATArchiveSearch(archive, model, objective=objective, descriptors=descriptors).run() exact = exhaustive_schedule(archive) solved = {row.cell: row.fitness for row in reports if row.status == "optimal"} if solved != exact or any(row.status != "infeasible" for row in reports if row.cell not in exact): raise AssertionError("The CP-SAT cell reports differ from exhaustive enumeration.") return {"task": "cpsat", "method": "cpsat", "cells": len(reports), "optimal": len(solved), "infeasible": len(reports) - len(solved), "solver_calls": sum(row.solver_status is not None for row in reports), "enumerated_starts": int(np.prod([HORIZON - d + 1 for d in DURATIONS]))} def simulate_design(genome): """Score a one-dimensional simulator with two separate safe regions.""" x, = genome margin = .15 - min(abs(x - .29), abs(x - .78)) quality = max(.82 * np.exp(-((x - .37) / .095)**2), np.exp(-((x - .82) / .11)**2)) return float(quality), (margin,) class SharedSeedBOPElites(BOPElites): """Give the feasibility-weighted baseline the same initial safe observation.""" def _sobol_point(self): if not self.nb_suggestions: return np.array([SAFE_SEED]) return super()._sobol_point() def safe_trial(seed, budget): """Compare safety gates and feasibility-weighted acquisition.""" rows = [] points = np.arange(161, dtype=float)[:, None] / 160 for method, bound in (("lipschitz", 1.), ("gp-gate", None)): archive = quality_grid((20,)) search = SafeBayesianIllumination(archive, points, points, safe_seeds=(SAFE_SEED_INDEX,), lipschitz=bound, expansion_budget=10, confidence=3., length_scale=.14) search.run(simulate_design, budget=budget) rows.append({"task": "safe", "method": method, "seed": seed, "budget": budget, "evaluations": len(search.trials), "expansion": sum(row.phase == "expansion" for row in search.trials), "unsafe": sum(any(value < 0. for value in row.margins) for row in search.trials), "halted": search.halted, "cells": len(archive), "qd": archive.qd_score()}) archive = quality_grid((20,)) baseline = SharedSeedBOPElites(archive, budget, 1, (0., 1.), 0., initial_samples=6, candidate_pool=64, restarts=2, model_feasibility=True, optimisation_task="maximisation", seed=seed) unsafe = 0 def benchmark(genome): nonlocal unsafe fitness, margins = simulate_design(genome) if min(margins) < 0.: unsafe += 1 return None, None, {"bop_valid": False} return (fitness,), tuple(genome) baseline.optimise(benchmark) rows.append({"task": "safe", "method": "feasibility-bop", "seed": seed, "budget": budget, "evaluations": baseline.nb_evaluations, "unsafe": unsafe, "halted": False, "cells": len(archive), "qd": archive.qd_score()}) return rows def diffusion_trial(seed, budget, workload): """Compare four emitters with the same bounded domains and reporting grid.""" peaks = HIMMELBLAU_PEAKS if workload == "himmelblau" else NARROW_PEAKS batch = min(24, budget) steps = max(2, (budget + batch - 1) // batch) rows = [] for name in ("diffusion-map-elites", "diffusion-evolution", "iso-line", "differential"): archive = quality_grid((12, 12)) if name.startswith("diffusion"): kind = DiffusionMAPElites if name.endswith("map-elites") else DiffusionEvolution run = kind(archive, budget, peaks.shape[1], batch, diffusion_steps=steps, seed=seed) elif name == "differential": run = DifferentialMAPElites(archive, budget, peaks.shape[1], (-1., 1.), batch_size=batch, optimisation_task="maximisation", seed=seed) else: np.random.seed(seed) random.seed(seed) run = IsoLineMAPElites(archive, budget, peaks.shape[1], (-1., 1.), batch_size=batch, optimisation_task="maximisation", iso_sigma=.12, line_sigma=.2) hits = set() def evaluate(genome, hits=hits): point = np.asarray(genome) delta = np.linalg.norm(peaks - point, axis=1) closest = int(np.argmin(delta)) if delta[closest] <= (.1 if workload == "himmelblau" else .2): hits.add(closest) if workload == "himmelblau": x, y = 5. * point quality = 1. / (1. + ((x * x + y - 11.)**2 + (x + y * y - 7.)**2) / 35.) else: quality = max(np.exp(-(delta[closest] / .30)**2), .78 * np.exp(-np.dot(point, point) / .85)) return (float(quality),), tuple(.5 + .5 * point[:2]) run.optimise(evaluate) rows.append({"task": workload, "method": name, "seed": seed, "budget": budget, "evaluations": run.nb_evaluations, "cells": len(archive), "qd": archive.qd_score(), "peaks": len(hits), "best": archive.best_fitness.values[0]}) return rows def main(): """Run selected methods and optionally write the per-seed records as JSONL.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=("cpsat", "safe", "diffusion", "all")) parser.add_argument("--include-cpsat", action="store_true", help="Run the solver in the all command.") parser.add_argument("--budget", type=int, help="Override the search evaluation budgets.") parser.add_argument("--seeds", type=int, nargs="+", default=[11, 12, 13, 14, 15]) parser.add_argument("--output", type=Path) args = parser.parse_args() if args.budget is not None and args.budget < 1: parser.error("budget must be positive.") rows = [] if args.task == "cpsat" or args.task == "all" and args.include_cpsat: rows.append(solver_trial()) if args.task in ("safe", "all"): for seed in args.seeds: rows.extend(safe_trial(seed, args.budget or 32)) if args.task in ("diffusion", "all"): for seed in args.seeds: for workload in ("himmelblau", "deceptive-peaks"): rows.extend(diffusion_trial(seed, args.budget or 720, workload)) report = "".join(json.dumps(row, sort_keys=True) + "\n" for row in rows) if args.output is None: print(report, end="") else: args.output.write_text(report, encoding="utf-8") if __name__ == "__main__": main()