Case-wise selection and policy repertoires ========================================== Use lexicase when each candidate has a vector of case errors. Use Quality Evolvability ES when the result you want is a single set of parameters whose future mutations cover different behaviours. The optional RL extra adds two continuous-control searches, MOME-PGX for vector rewards and WQDIL for expert demonstrations. .. _lexicase-selection: Regression with lexicase or epsilon-lexicase -------------------------------------------- Lexicase shuffles the training cases for each parent draw. It filters out any candidate whose error on the current case exceeds the best remaining error. If a case leaves one candidate, that candidate becomes the parent. Otherwise filtering continues, with a uniform tie break after the last case. Epsilon-lexicase allows near-best candidates to pass. With ``epsilon="mad"``, each case's tolerance is its median absolute deviation over the full population, and its best error comes from the current survivors. .. code-block:: python import numpy as np from qdpy.algorithms import lexicase_index from qdpy.symbolic import symbolic_regression rng = np.random.default_rng(11) parent = lexicase_index([[0.1, 0.8], [0.5, 0.1]], rng, epsilon="mad") x = np.linspace(-0.8, 0.8, 33)[:, None] y = np.sin(3 * x[:, 0]) + 0.4 * x[:, 0] ** 2 result = symbolic_regression(x, y, mode="epsilon-lexicase", budget=384, seed=11) print(result.best, result.stats, result.archive.filled_bins) Set ``mode="lexicase"`` for exact filtering. The symbolic search groups proposals into generations of ``population_size``. Repeated structures reuse their fits and occupy at most one slot per generation. The archive passively retains the lowest training RMSE per structural cell. Compare with ``mode="gp", passive_archive=True`` to report the same grid for aggregate-error GP, or use ``mode="structural"`` to let MAP-Elites select its parents from the grid. ``case_evaluations`` counts extra forward passes over the training data to build case errors. La Cava et al. describe the epsilon variants in `their lexicase analysis `_. Boldi, Ding and Spector compare case-based search with MAP-Elites in `Objectives Are All You Need `_. .. _quality-evolvability: Quality Evolvability ES ----------------------- The optimizer draws mirrored Gaussian mutations around its current center. It scores each offspring with task fitness and the squared distance of its descriptor from the batch's mean descriptor. Pareto front ranks and within-front crowding shape the ES ascent direction, which Adam uses to move the center. Scale descriptors in your evaluator when their axes use different units. .. code-block:: python import numpy as np from qdpy.algorithms import QualityEvolvabilityES def evaluate(parameters, seed): x, = parameters return 1.0 - 0.15 * x**2, (np.tanh(5 * (x - 0.65)),) search = QualityEvolvabilityES([0.3], pairs=8, sigma=0.16, seed=11) training = search.run(evaluate, budget=384) sample = search.sample_offspring(evaluate, 256, seed=1011) print(search.center, training, np.mean(sample.fitness), np.var(sample.descriptors)) A search update costs exactly ``2 * pairs`` evaluator calls. Smaller remainders stay unspent. The offspring panel uses its own seed and does not advance the search. Use the same panel seeds and mutation scale with ``quality_only=True`` to compare with fitness-only ES. The algorithm follows Katona, Franks and Walker's `Quality Evolvability ES `_. .. _mome-pgx: MOME-PGX on vector rewards -------------------------- Install the optional ``qdpy[rl]`` extra for this and the next section. Supply a Gymnasium environment with numeric Box observations and bounded floating-point Box actions. Return a vector of rewards per step and a behaviour descriptor per completed episode. .. code-block:: python from examples.mome_p2c import TradeoffControl, descriptor, reward_vector from qdpy.containers import ParetoGrid from qdpy.rl import MOMEPGX, PolicyConfig, TD3Config archive = ParetoGrid( shape=(8,), max_items_per_bin=8, features_domain=((-1.0, 1.0),), fitness_domain=((0.0, 6.0),) * 2, fitness_weights=(1.0, 1.0), truncation="crowding", ) search = MOMEPGX( TradeoffControl, archive, reward_vector=reward_vector, descriptor=descriptor, td3=TD3Config(batch_size=24, learning_starts=48), policy=PolicyConfig((16, 16)), population_size=8, max_episode_steps=6, seed=11, ) stats = search.train(1152) print(stats.objective_offspring, archive.qd_hypervolume((0.0, 0.0))) Parents come from uniformly sampled occupied cells. Within each front, the probability of choosing a policy is proportional to a normalized neighbour gap. At boundaries, sampling uses finite one-sided gaps. Archive truncation uses the grid's usual boundary preservation. Iso+LineDD supplies half of each generation after replay warm-up. The other half uses policy-gradient mutations with a rotating objective allocation. Each objective has its own TD3 learner with twin critics and target networks. The learners read different columns from the same replay buffer. A negative archive fitness weight reverses the training signal for that objective. The archive stores raw returns for both maximized and minimized objectives. Simulator steps spent on cut-off episodes count against the budget. Only policies with all requested episodes complete enter the archive. If a training call ends mid-generation, the completed prefix it measured is offered together and queued variation remains available for the next call. Training across such a split can therefore partition archive merges differently. An archived policy can be copied with ``search.policy_for(individual)`` and saved independently. See Janmohamed, Pierrot and Cully's `MOME-PGX paper `_ for their Brax implementation. This tutorial uses QDpy's rectangular ParetoGrid and synchronous Gymnasium evaluation. .. _wqdil: WQDIL from timestep demonstrations ----------------------------------- Provide one row per expert transition. Compute each row's measure with the same function you use during search. The three arrays hold the observation, action in the environment's units, and timestep measure. Observations and actions have the shapes declared by the environment. The measure array has shape ``(transitions, descriptor_dimensions)``. .. code-block:: python from examples.advanced_policy_qd import TargetControl, demonstrations, measure from qdpy.containers import Grid from qdpy.rl import PPOConfig, PolicyConfig, WQDIL archive = Grid( shape=(10, 10), max_items_per_bin=1, features_domain=((-1.0, 1.0),) * 2, fitness_domain=((-float("inf"), float("inf")),), ) search = WQDIL( lambda: TargetControl(reveal_reward=False), archive, demonstrations=demonstrations(with_measures=True), measure=measure, visit_shape=(12, 12), bonus_weight=1.0, latent_size=4, policy=PolicyConfig((12,)), ppo=PPOConfig(rollout_steps=24, epochs=2, batch_size=24), population_size=7, sigma0=0.7, threshold_min=-12.0, max_episode_steps=12, seed=11, ) stats = search.train(1152) print(stats.reward_model_updates, stats.visited_cells) A deterministic autoencoder reconstructs state-action-measure triples. A latent critic with a gradient penalty is trained to score expert triples above policy triples. The encoder uses the opposite discrimination objective alongside its reconstruction loss. Policy samples for these updates come from the most recent PPGA search-policy walk. PPGA learns with the critic's score and an exploration bonus ``bonus_weight / (1 + cell_frequency)``. The timestep count grid can use bounds wider than the episodic reporting grid. It updates during PPO collection and is read without updates during candidate scoring. Set ``bonus_weight=0`` to measure the effect of the exploration bonus. The archive scores policies on the learned objective at the time of their evaluation. Choose a finite ``threshold_min`` that fits the scale of the learned episode scores, and reevaluate the exported actors with a common held-out task reward when comparing methods. For a given configuration, ``generation_step_limit`` reports the reservation for one complete generation. Smaller remaining budgets stay unspent. This is a CPU-compatible PyTorch implementation of the measure-conditioned variant in Yu et al.'s `WQDIL paper `_ using QDpy's synchronous PPGA. See the `AAMAS proceedings `_. Run the comparisons ------------------- From the repository root, run: .. code-block:: bash python -m examples.case_evolvability --budget 384 --seeds 11 22 33 python -m examples.policy_repertoires --budget 1152 --seeds 11 22 33 The scripts print one JSON record per method and seed. The second script compares MOME-PGX with MOME and MOME-P2C, then WQDIL with its bonus disabled and with GAIL-EBC. See :doc:`case_evolvability_benchmarks` for metrics and the measured results.