Solver repair, repertoire selection, and cross-component search =============================================================== The first three methods use the base installation. QDHUAC uses ``qdpy[rl]``. The :doc:`repair_transfer_benchmarks` page compares repair budgets, live trials, coherence calls, and learner updates on four small CPU tasks. .. _solver-repaired-map-elites: Solver-repaired MAP-Elites -------------------------- Use ``BinaryMILPRepair`` when a decision is a binary vector and the feasible region has linear constraints. The solver minimizes the number of bits changed. Equalities enforce exact counts, and inequalities can bound resources or exclude combinations of bits. .. code-block:: python from scipy.optimize import LinearConstraint from qdpy.algorithms import BinaryMILPRepair, RepairedMAPElites from qdpy.containers import Grid constraints = LinearConstraint([[1, 1, 1, 1], [1, 1, 0, 0]], [2, 0], [2, 1]) repair = BinaryMILPRepair(4, constraints) archive = Grid(shape=(3,), features_domain=((0., 1.),), fitness_domain=((0., 5.),), fitness_weights=(1.,)) def evaluate(bits): quality = sum((i + 1) * bit for i, bit in enumerate(bits)) / 2. return (quality,), (sum(bits[:2]) / 2.,) search = RepairedMAPElites(archive, repair, seed=7) stats = search.run(evaluate, budget=8, repair_budget=40) print(stats.evaluations, stats.repair_calls, stats.duplicate_repairs) The same binary design can result from several proposals. The search tracks attempted repaired genomes across calls and skips repeats. Set both budgets when the feasible space is small or heavily constrained. A failed repair consumes one solver call. Configure ``time_limit`` or ``node_limit`` for individual solves. With ``accept_incumbent=True``, a verified feasible assignment from a limited solve can enter the search even when minimal Hamming distance is unproven. Keep other expensive validity checks in the evaluator. The design follows the Hamming-distance repair step in `Zhang et al. `_. Compare it with Constrained MAP-Elites using ``python examples/repair_transfer.py repair``. .. _aprol: APROL ----- Prepare several repertoires of short policies, each with a nominal displacement for a different operating condition. Pass them to ``APROL`` as named collections of ``RTESkill`` records. The caller sets the local displacement subgoal, executes the selected genome, and reports the measured displacement. .. code-block:: python from qdpy.algorithms import APROL, RTESkill normal = [RTESkill((-1.,), (-.2,)), RTESkill((1.,), (.2,))] reversed_steering = [RTESkill((-1.,), (.2,)), RTESkill((1.,), (-.2,))] planner = APROL({"normal": normal, "reversed": reversed_steering}, compatibility_std=.1, exploration=.1) first = planner.ask((.2,)) # The live actuator in this example reverses the command. planner.tell((-.2 * first.genome[0],)) print(planner.repertoire_probabilities()) second = planner.ask((.2,)) planner.tell((-.2 * second.genome[0],)) The planner gives weight to priors whose nominal predictions match live observations and includes an exploration bonus for less-used priors. Each prior has a GP for correcting nominal displacements. When the same genome occurs in several repertoires, one live action can inform all of them, while only the selected repertoire is charged a live trial. Use a common policy representation and common physical units across the repertoires. A high-level planner can update the next subgoal after each completed action. The algorithm is based on `Kaushik, Desreumaux, and Mouret `_. Run ``python examples/repair_transfer.py aprol`` for a fixed-prior comparison under a simulated steering fault. .. _melita: MEliTA ------ MEliTA explores designs made of independently mutable components. Each component has a scalar descriptor and one archive axis. A coherence callback scores the result of combining all components. A mutation proposes one replacement. Transverse assessment then tries it with partners from elites in its new descriptor slice. The best-ranked combination that can improve its cell is admitted. .. code-block:: python import numpy as np from qdpy.algorithms import MEliTA from qdpy.containers import Grid archive = Grid(shape=(6, 6), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) def mutation(index): return lambda parts, rng: float(np.clip(parts[index] + rng.normal(0., .15), 0., 1.)) search = MEliTA( archive, initialize=lambda rng: tuple(rng.random(2)), mutations=(mutation(0), mutation(1)), descriptors=(float, float), coherence=lambda parts: 1. - abs(parts[0] - parts[1]), seed=7, ) stats = search.run(budget=80) print(stats.assessments, stats.transverse_assessments, archive.filled_bins) Use immutable components such as numbers, strings, or tuples. A mutation can read the full parent tuple and returns one component. Multiple pairings can spend the assessment budget for one edit. The direct combination is considered first if there is only enough budget for a partial assessment of that edit. Set ``transverse=False`` for a direct-only control at the same number of coherence calls. See `Zammit et al. `_ for the original formulation, and run ``python examples/repair_transfer.py melita`` for a layout and controller pairing example. .. _qdhuac: QDHUAC ------ QDHUAC applies replay-based critic and actor updates while evolving a fixed-size Dominated Novelty Search population. The categorical critic predicts a distribution over fixed return values. It uses a single shared forward pass on current and next state-action pairs for batch normalization. The actor uses the distribution's mean. Prioritized replay uses expected-return errors. .. code-block:: python from examples.qdhuac import CurveControl from qdpy.rl import PolicyConfig, QDHUAC, SACConfig search = QDHUAC( CurveControl, descriptor=lambda episode: (float(episode.observations[1:, 0].mean()),), config=SACConfig(batch_size=16, learning_starts=16, critic_hidden_sizes=(24,)), policy=PolicyConfig((16,)), return_bounds=(0., 16.), atoms=21, population_size=12, batch_size=6, updates_per_transition=2, gradient_steps=2, max_episode_steps=8, seed=7, ) stats = search.train(96) print(len(search.population), stats.env_steps, stats.critic_updates) actor = search.best_policy() Choose ``return_bounds`` for the task's discounted return range. Targets beyond those bounds place their probability on an endpoint. ``updates_per_transition`` specifies the number of critic updates for each step after replay warm-up. A cut episode still supplies replay, and only completed generations update the population. Save the Gaussian actor with ``actor.save(path)`` and reload it with ``SACPolicy.load(path)``. See `Koohy and Bayne `_. Run ``python examples/qdhuac.py`` to compare against TD3 under the same emitter schedule, transition budget, and critic update count.