Build repertoires for classifiers, schedules, and skills ======================================================== Use Neuro-MAP-Elites to keep classifiers with complementary errors, SADE-QD to search feasible schedules, or cooperative MAP-Elites to find policies that work with unfamiliar partners. The same example also covers human-guided descriptors and planning with learned skills. .. _applied-repertoires-nme: Evolve complementary classifiers -------------------------------- Neuro-MAP-Elites learns which examples a classifier gets wrong, then uses that pattern to place the classifier in a repertoire. The first search mines classifiers using structural descriptors. A small beta-VAE learns an embedding of the qualifying elites' binary error masks. The second search uses normal quantiles of the latent means as descriptors. The quantiles make the final grid cells equal in probability under the standard normal latent prior. [Nickerson2021]_ .. code-block:: python import numpy as np from qdpy.algorithms import neuro_map_elites, nme_ensemble from qdpy.containers import Grid mining = Grid(shape=(8, 8), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) result = neuro_map_elites( y_train, predict_train, sample=sample, mutate=mutate, structural=lambda genome: genome[:2], mining_archive=mining, budget=320, mining_budget=160, fit_steps=200, seed=11, ) ensemble = nme_ensemble(result.archive, predict_validation, y_validation, classes=np.unique(y_train), max_members=8) predictions = ensemble.predict(predict_test) Each prediction callback takes a genome and returns one class label per example in its panel. Use a fixed example order and include every class in the training panel. The score is mean per-class accuracy. If your evaluator trains a model, build the search-time predictions using only training data or out-of-fold predictions. Choose the vote prefix on separate validation data and measure it on a third panel. Use ``size=3`` to compare equal-sized ensembles, or leave it unset to select the prefix with the best validation accuracy. The QDpy implementation seeds the second archive from the measured mining archive and counts each model call once. It uses binary error masks consistently for fitting and inference. PyTorch is required for training the VAE. The voting helper uses NumPy. .. _applied-repertoires-sade: Improve flexible job-shop schedules ----------------------------------- :func:`qdpy.algorithms.sade_qd` maintains a grid organized by transport time and machine idle time. It starts with random keys, then edits operations on the critical path. During a stall in admissions it can use the paper's differential evolution equations with collaborators from low-transport or low-idle cells. It measures each guided proposal, then uses its measured critical path for the next edit. Both steps consume the schedule evaluation budget. [Qin2026]_ .. code-block:: python import numpy as np from qdpy.algorithms import FlexibleJobShop, sade_qd from qdpy.containers import Grid jobs = ( (((0, 2.), (2, 3.)), ((1, 1.), (3, 4.))), (((1, 2.), (3, 2.)),), ) shop = FlexibleJobShop(jobs, machine_factories=(0, 0, 1, 1)) archive = Grid(shape=(4, 8), features_domain=((0., 10.), (0., 20.)), fitness_domain=((0., np.inf),), fitness_weights=(-1.,)) result = sade_qd(archive, shop.evaluate, shop.critical_edit, block_sizes=shop.block_sizes, budget=120, seed=11) print(shop.decode(result.archive.best).operations) The decoder assigns a job to one eligible factory and selects an eligible machine for each operation. It releases operations in job order and starts each after any travel and prior machine work. Machine idle time sums gaps from time zero to each machine's last completion. The travel matrix supplies delays between machines and assumes vehicles are available. The runner keeps one archive of complete schedules and models transportation as fixed delays. The source also uses separate subvector archives and explicit transportation resources. Set ``guided_probability=0`` for the critical-edit control. Differential MAP-Elites supplies a second comparison using the same decoder. Report coverage, best makespan, and the mean makespan of the retained schedules. .. _applied-repertoires-cooperation: Choose responses for unfamiliar partners ---------------------------------------- Evolve a repertoire in self-play, then measure how each policy works with every archived partner. The response table chooses the best policy for each niche and the best generalist across the common panel. At deployment, a partner descriptor estimated from observed actions selects a specialized response after enough observations. Missing or uncalibrated niches use the generalist. [Canaan2023]_ .. code-block:: python from qdpy.algorithms import cooperative_map_elites, build_partner_responses repertoire = cooperative_map_elites( archive, play, sample=sample, mutate=mutate, budget=180, repeats=2, seed=11, ) table = build_partner_responses( repertoire.archive, play, budget=200, repeats=2, seed=12, ) niche = repertoire.archive.index_grid(observed_descriptor) policy = table.select(niche, observations=4, min_observations=3) Supply a ``play(first, second, seed)`` callback that returns the team score and the first player's descriptors. The runner scores ordered pairs because roles can matter. A complete table costs ``len(archive) ** 2 * repeats`` matches. Cross-play checks its budget before calling the simulator. Keep the deployment observer separate from the match callback and test it with held-out partners. An oracle given the true partner niche can show how much accuracy is lost by estimating that niche. .. _applied-repertoires-divhf: Learn descriptors from the closest and farthest pairs ----------------------------------------------------- DivHF asks for the two extremes among the three pairs in an annotated triplet. The two pairs share one record. A Bradley-Terry likelihood trains the projection to put the closest pair nearer than the farthest pair. QDpy applies this objective to a linear map of fixed-width observations with squared Euclidean similarity. The paper uses a recurrent trajectory encoder and cosine similarity. [Wang2026]_ .. code-block:: python import numpy as np from qdpy.algorithms import divhf_search def judge(*trials): pairs = ((0, 1), (0, 2), (1, 2)) distances = [abs(trials[i].raw_features[0] - trials[j].raw_features[0]) for i, j in pairs] order = np.argsort(distances, kind="stable") return order[0], order[-1] result = divhf_search( evaluate, archive, feedback=judge, dimension=3, raw_feature_size=3, budget=256, feedback_budget=72, warmup=96, seed=11, ) print(result.fits, len(result.feedback)) The callback receives three read-only behavior records. Number pairs ``(0, 1)``, ``(0, 2)``, ``(1, 2)`` in that order and return the indices of the closest and farthest, or ``None`` to abstain. A query still counts if the provider abstains. The default fits once after warmup. Set ``refit_every`` to ask again on the live archive and re-bin cached elites in the new coordinates. Compare preference accuracy on fresh triplets at an equal annotation budget. .. _applied-repertoires-dads: Discover skills and plan with their effects ------------------------------------------- DADS trains an SAC actor without task rewards. Each episode uses a fixed continuous skill. The dynamics model fits a mixture of Gaussians to observed state changes conditioned on the initial state and skill. SAC maximizes the log likelihood under the chosen skill relative to the average likelihood under independent skills drawn from the prior. The ratio favors state changes that are both predictable and distinguishable across skills. [Sharma2020]_ .. code-block:: python from qdpy.rl import DADS, SkillConditionedPolicy model = DADS(make_environment, skill_bounds=((-1., 1.),), max_episode_steps=40, seed=11) stats = model.train(12_000) plan = model.plan(observation, lambda path: -abs(path[-1, 0] - .7), horizon=2, skill_steps=4, samples=32, seed=12) action = model.policy.act(observation, plan.skills[0]) model.policy.save("discovered-actor.npz") actor = SkillConditionedPolicy.load("discovered-actor.npz") Supply a Gymnasium Box/Box environment and scales for each state coordinate if changes differ substantially in magnitude. Define the planning objective over predicted observations at skill boundaries. For receding-horizon control, hold the chosen skill for ``plan.skill_steps`` real transitions and plan again from the actual observation. ``DADSPlan.model_steps`` counts imagined transitions across all candidate sequences. QDpy reuses off-policy SAC replay and plans under the mixture means with softmax-weighted proposal refinement. The saved actor can act independently. Planning uses the learned dynamics on the trainer. .. _applied-repertoires-results: Reproduce the CPU comparisons ----------------------------- The :download:`example script <../examples/applied_repertoires.py>` prints one JSON row per method and seed. Install PyTorch for ``classifiers`` and the existing ``rl`` extra for ``skills``. .. code-block:: console python examples/applied_repertoires.py classifiers --seeds 11 22 33 44 55 python examples/applied_repertoires.py scheduling --seeds 11 22 33 44 55 python examples/applied_repertoires.py cooperation --seeds 11 22 33 44 55 python examples/applied_repertoires.py feedback --seeds 11 22 33 44 55 python examples/applied_repertoires.py skills --seeds 11 22 33 44 55 Each classifier search made 320 training-panel calls. The three-member vote scored 66.0% balanced accuracy on the held-out panel with NME and 66.3% with cosine-kernel MAP-Elites. NME averaged 65 occupied cells and cosine search averaged 18.6 in their respective descriptor spaces. The cell counts use different geometry and the classifier comparison uses held-out accuracy. With 360 evaluations on the same shop, mean makespan among retained schedules was 53.94 for SADE-QD, 54.92 for critical edits, and 57.86 for fixed Differential MAP-Elites. The critical-only control had the shortest best makespan on average (34.2, compared with 34.8 for SADE-QD). Fixed DE filled the most cells (50.4, compared with 44.4 for SADE-QD). The cooperative search used 360 self-play matches and 200 calibration matches per seed. On ten held-out partners, mean team score was 0.917 for the fixed generalist, 0.988 for the observed-partner policy, and 0.998 for the true-niche oracle. With 72 judgments and 256 attempted measurements, DivHF identified the closest pair on 94.1% of 256 held-out triplets and QDHF did so on 97.2%. DivHF filled 6.2 cells and QDHF filled 5.2 after both repertoires were projected into the same oracle grid. Both DADS evaluations used the same actor after 1,800 training steps and spent 48 real audit steps per seed. Planning reduced mean goal distance from 0.509 to 0.433 at a cost of 3,072 model steps per audit. .. [Nickerson2021] `Principled quality diversity for ensemble classifiers using MAP-Elites `__. .. [Qin2026] `Self-Adaptive Differential Evolution-Enhanced Quality-Diversity Optimization for Distributed Flexible Job-Shop Scheduling With Transportation `__. .. [Canaan2023] `Generating and Adapting to Diverse Ad Hoc Partners in Hanabi `__. .. [Wang2026] `Diversity from Human Feedback `__. .. [Sharma2020] `Dynamics-Aware Unsupervised Discovery of Skills `__.