Constraint programming, safe exploration, and diffusion search =============================================================== The example covers a small job shop, a simulator with two separate safe regions, and two multimodal continuous problems. The :doc:`certified_safe_diffusion_benchmarks` page shows the comparisons. .. code-block:: bash python -m pip install . python -I examples/certified_safe_diffusion.py all python -m pip install ".[cpsat]" python -I examples/certified_safe_diffusion.py cpsat .. _cpsat-archive: CP-SAT archives --------------- :class:`qdpy.algorithms.CPSATArchiveSearch` solves one integer model per requested niche. Supply a native OR-Tools ``CpModel``, an integral linear objective, and one integral linear expression for each descriptor. Auxiliary variables can represent nonlinear functions of the decision variables through CP-SAT constraints. For example, use ``add_max_equality`` to describe the latest completion time. .. code-block:: python from ortools.sat.python import cp_model from qdpy.algorithms import CPSATArchiveSearch from qdpy.containers import Grid model = cp_model.CpModel() a = model.new_int_var(0, 4, "start_a") b = model.new_int_var(0, 5, "start_b") model.add_no_overlap([ model.new_fixed_size_interval_var(a, 2, "job_a"), model.new_fixed_size_interval_var(b, 1, "job_b"), ]) archive = Grid( shape=(5,), features_domain=((-4., 5.),), fitness_domain=((0., 15.),), fitness_weights=(-1.,), ) search = CPSATArchiveSearch( archive, model, objective=a + b + 3, descriptors=(b - a,), ) for row in search.run(): if row.genome is not None: print(row.cell, row.genome[a.index], row.fitness, row.objective_bound) QDpy clones the supplied model and uses the grid's objective direction and numeric domains. The grid converts each descriptor cell to the exact admissible integer interval, including the top endpoint in the last cell. Each stored genome contains the complete original model assignment in variable index order. An ``optimal`` report includes the optimal incumbent and its objective bound. A ``feasible`` report also retains the incumbent and bound, with optimality still open. ``infeasible`` means the solver proved the model empty or the cell has an empty integer interval. ``unresolved`` means the solver supplied no incumbent or proof. Choose per-cell elapsed or deterministic work limits and retry selected cells with ``run(cells=...)``. The bounds and conclusions apply to the model as stated, including the archive's domain constraints. `Perron2023 `__ .. _safe-bayesian-illumination: Safe Bayesian illumination -------------------------- :class:`qdpy.algorithms.SafeBayesianIllumination` chooses which designs to evaluate from a finite candidate pool with known descriptors. Supply at least one trusted safe design. The evaluator measures both quality and one or more safety margins. Nonnegative margins indicate safety. .. code-block:: python import numpy as np from qdpy.algorithms import SafeBayesianIllumination from qdpy.containers import Grid points = np.arange(161, dtype=float)[:, None] / 160 archive = Grid(shape=(20,), features_domain=((0., 1.),), fitness_domain=((0., 1.),), fitness_weights=(1.,)) search = SafeBayesianIllumination( archive, points, points, safe_seeds=(36,), lipschitz=1., expansion_budget=10, ) def evaluate(genome): x, = genome return float(np.exp(-((x - .37) / .095)**2)), (.15 - abs(x - .29),) search.run(evaluate, budget=32) print(len(archive), len(search.trials), search.certified_indices()) The safety gate and the quality model use separate observations from the same evaluator call. By default the safety gate uses the lower confidence bound of a fixed-kernel GP for each margin. Its conclusions depend on calibration. When given Lipschitz constants, the gate uses measured margins and their error bounds to extend the safe set in raw Euclidean decision coordinates. The constants and observation error bounds must hold throughout the candidate space. The first phase evaluates trusted seeds, then prioritizes safe points that might extend the safe set. Its GP mode scores uncertainty near the uncertified frontier. Its Lipschitz mode ranks possible expansions under optimistic GP predictions. After expansion, a separate GP ranks admissible points by expected improvement in their own descriptor niches. The gate still runs before each dispatch. Every attempted evaluation uses budget. A negative observed safety margin halts the search and stays in the trial log. The search may stop early when no untried candidate qualifies. `Sui2018 `__ .. _diffusion-map-elites: Diffusion Evolution and MAP-Elites ---------------------------------- :class:`qdpy.algorithms.DiffusionEvolution` generates offspring by denoising a population of bounded real genomes. The update combines nearby measured genomes using Gaussian proximity and their signed fitness. A cosine schedule progressively reduces the noise. This is a numerical update over measured candidates and uses the base installation. :class:`qdpy.algorithms.DiffusionMAPElites` uses the same reverse update. It draws a reference pool from occupied niches and seeds its noisy particles near those elites. The population-only baseline uses the previous generation for both roles and reports into the same kind of archive. Both start a new Gaussian population after a complete schedule. The bounded implementation clips proposals and scales fitness weights within the reference pool. .. code-block:: python from qdpy.algorithms import DiffusionMAPElites from qdpy.containers import Grid archive = Grid(shape=(12, 12), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) search = DiffusionMAPElites( archive, budget=720, dimension=2, batch_size=24, diffusion_steps=30, seed=11, ) def evaluate(genome): x, y = genome q = 1. / (1. + (x*x - .5)**2 + (y*y - .5)**2) return (q,), ((x + 1.) / 2., (y + 1.) / 2.) search.optimise(evaluate) print(archive.qd_score(), search.diffusion_proposals) Use ``ask_batch()`` and ``tell_batch()`` when running an external evaluator. Provide feedback in proposal order. The Gaussian neighborhood calculation compares every particle with each reference, so ``max_elites`` bounds its work in the archive-guided variant. `Zhang2025 `__