Solver-backed archives, graph policies, and self-play ===================================================== Use a solver when the problem has linear objectives, constraints, and integer-valued features. For black-box evaluations, graph policies and youth selection plug into native MAP-Elites. QD Self-Play keeps two strategy archives for a competitive setting. All four use the base package. .. _milp-archive: Solve the best design in each niche ----------------------------------- An archive of small assignment problems can serve as a reference for an evolutionary search. Here each job selects one of two machines. The descriptor counts jobs sent to the first machine. .. code-block:: python from scipy.optimize import Bounds, LinearConstraint from qdpy.algorithms import MILPArchiveSearch from qdpy.containers import Grid archive = Grid(shape=(3,), features_domain=((0, 2),), fitness_domain=((0, 20),), fitness_weights=(-1.,)) search = MILPArchiveSearch( archive, [2, 4, 5, 1], Bounds(0, 1), [[1, 0, 1, 0]], constraints=LinearConstraint([[1, 1, 0, 0], [0, 0, 1, 1]], 1, 1), ) for row in search.run(): print(row.cell, row.status, row.fitness) The grid supplies the fitness bounds and objective direction. The default makes every coordinate integer. Pass ``integrality=[1, 0, ...]`` for mixed-integer problems. Descriptor coefficients for continuous coordinates must be zero. ``descriptor_offset`` adds an optional integer constant per descriptor. Each cell becomes a pair of inclusive integer limits using the same bin assignment as ``Grid.index_grid``. A cell can be ruled out before calling the solver if its limits have no possible integer value within the decision bounds. HiGHS supplies the remaining outcomes. QDpy verifies the rounded incumbent's decision bounds, linear residuals, and actual cell before admitting it. A limited solve can supply a verified incumbent with status ``"unresolved"``. You can retry a subset using ``run(cells)``. Solver optimality is relative to HiGHS tolerances and the supplied model. This is a QDpy workflow for per-niche optimization. Solver-based work on diverse integer solutions motivates the workflow. `Trapp and Konrad, Finding Diverse Optima and Near-Optima `_. `SciPy MILP API `_. .. _graph-qd: Evolve a graph controller with G-QD ----------------------------------- In Cartesian Genetic Programming, a node selects an operation and its operands. Operands can refer to observations, constants, or earlier nodes. Different output nodes can use the same intermediate result. .. code-block:: python from qdpy.algorithms import CartesianGraphSpace, GraphMAPElites from qdpy.containers import Grid space = CartesianGraphSpace(2, 1, 8) archive = Grid(shape=(5, 5), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) def evaluate(genome): graph = space.decode(genome) prediction, = graph.act((.2, .3)) fitness = 1. / (1. + abs(prediction - .5)) return (fitness,), graph.structure_descriptors GraphMAPElites(archive, 64, space, seed=11, batch_size=4).optimise(evaluate) controller = space.decode(archive.best) print(controller.act((.2, .3)), controller.active_nodes) The two structural features are the fractions of all genotype nodes that belong to the active graph and have either one or two operands. For joint illumination, append those two features to measured behavior descriptors. Some combinations of unary and binary fractions are unreachable, since their sum cannot exceed one. The graph evaluator runs reachable nodes once and leaves action transformations to the environment wrapper. Use ``ask_batch()`` and ``tell_batch()`` for manual evaluation. The native optimizer commits each batch in proposal order for reproducible parallel evaluation. ``controller.save(path)`` writes a JSON inference policy. ``CartesianGraphPolicy.load(path)`` restores it independently of the search. The implementation uses a one-dimensional feed-forward genotype with fixed final output nodes and protected built-in primitives. `Nadizar, Medvet, and Wilson, Searching for a Diversity of Interpretable Graph Control Policies `_. .. _qd-self-play: Discover and improve strategies in self-play -------------------------------------------- Give each role one seed strategy. A proposer receives a sampled matchup, its payoffs, and neighbors of the parent it can mutate. Here the strategies are bounded numbers that encode a cyclic game. .. code-block:: python from examples.structured_qd import cyclic_match, propose_cyclic from qdpy.algorithms import QDSelfPlay search = QDSelfPlay( ((.17,), (.17,)), play=cyclic_match, propose=propose_cyclic, embed=lambda role, strategy: strategy, novelty_radius=.16, seed=11, ) stats = search.run(144) print(stats.matches, search.archives) Each sampled matchup costs one match. The default novelty test checks distance to the closest archived strategy. An optional ``is_novel`` callback can judge novelty using the candidate and its nearest neighbors. A novel strategy enters the archive as a stepping stone. To replace a neighbor, a candidate has to score higher on the same opponent panel. Payoffs may differ by role. Each role maximizes its own score. The published method uses a foundation model for proposals and novelty judgments. This implementation exposes both as callbacks and matches opponents during local competitions. The search budget includes proposal context and local comparisons. Audit the resulting strategies on a separately specified opponent panel. `Dharna et al., Quality-Diversity Self-Play `_. .. _youth-map-elites: Sample parents from recent admissions ------------------------------------- Set ``parent_window`` to the number of recent surviving elites eligible for reproduction. The next proposal can use a replacement as soon as the replacement enters the archive. Rejections leave the eligible order intact. .. code-block:: python from qdpy.algorithms import YouthMAPElites from qdpy.containers import Grid archive = Grid(shape=(12,), features_domain=((0., 1.),), fitness_domain=((0., 1.),), fitness_weights=(1.,)) search = YouthMAPElites(archive, 96, 2, parent_window=4, sigma=.09, seed=11) def evaluate(genome): x, y = genome return (1. - (y - x)**2,), (x,) search.optimise(evaluate) print(archive.filled_bins, archive.best) A window of one always selects the latest retained admission. A window at least as large as the archive permits uniform selection across all elites. With batched evaluation, proposals see the previous committed archive and feedback is applied in proposal order. Use ``ask_batch()`` and ``tell_batch()`` for manual evaluation. For an existing ``RandomSearchMutPolyBounded`` configuration, pass ``parent_selector=functools.partial(select_youth, count=4)`` using ``qdpy.algorithms.select_youth``. `Coninx and Doncieux, Younger Is Better `_. Run the comparisons ------------------- .. code-block:: console python -m examples.structured_qd assignment python -m examples.structured_qd graphs python -m examples.structured_qd self-play python -m examples.structured_qd youth See :doc:`structured_qd_benchmarks` for the settings and results.