Core Python API =============== Start with :doc:`tutorial_map_elites` for the default search or :doc:`tutorial_ask_tell` when your application drives evaluation. - :doc:`tutorial_noisy_qd` uses rollout budgets and a separate archive audit. - :doc:`tutorial_mc_aurora` uses PyTorch to learn descriptors for several archives. - :doc:`tutorial_discrete_qd_rl` and :doc:`tutorial_continuous_qd_rl` cover the standalone learners, native QD archives, and policy export in ``qdpy.rl``. - :doc:`tutorial_qdpg` covers state descriptors and replay-time novelty for ``QDPG``. - :doc:`tutorial_descriptor_conditioned_rl` covers ``DCGMAPElites``, ``DCRLMAPElites``, and ``DescriptorConditionedPolicy``. - :doc:`tutorial_qdac` covers ``SAC``, ``QDAC``, their portable actors, and the ``evaluate_skills`` fixed-skill evaluation API. - :doc:`tutorial_reference_skills` covers ``QDACMB``, ``QDACMBConfig``, and ``QDACMBPolicy.new_episode()`` for recurrent inference. - :doc:`tutorial_portfolio_transfer` covers tabular reward transfer and sparse continuous controllers from ``SVQDRL``. - :doc:`tutorial_linked_skills` covers ``SMERL``, ``SMERLConfig``, ``SMERLPolicy``, and ``evaluate_discovered_skills`` for learned skill IDs. - :doc:`tutorial_refqd` covers shared representations and measured archive refreshes. - :doc:`tutorial_pollination` covers controller distillation for morphology–controller co-design. - :doc:`tutorial_brpg` covers policy gradients with separate behavior estimation. - :doc:`tutorial_mome_p2c` covers vector rewards and objective preference policies. - :doc:`tutorial_advanced_policy_qd` covers PPGA, GAIL-EBC, and Dynamics-Aware QD. - :doc:`tutorial_case_evolvability` covers lexicase, Quality Evolvability ES, MOME-PGX, and WQDIL. - :doc:`tutorial_swarm_packing` covers binary novelty PSO, LUCIE-style races, and Traveling Thief. It also shows how to train ``qdpy.rl.GENEMAPElites`` with ``coordinate_size`` and export a dense policy via ``policy_for`` or ``best_policy``. - :doc:`tutorial_conditional_task_search` covers Conditional Bayesian QD, CMOEA, QED, and GDA-QD. - :doc:`tutorial_offline_planning` covers GA-ME, DynAMO, DiveOff, and temporal planning. - :doc:`tutorial_compact_repertoires` covers set scalarization, RePPO, QDOS, and MIQD. - :doc:`tutorial_scenario_discovery` covers deep Bayesian search, descriptor swaps, QD-MAPPER, and QD-Rec. - :doc:`tutorial_adaptive_diversity` covers novelty ES, QQD, equal-budget Bayesian Deep QD, PDO, and visual pre-training. - :doc:`tutorial_targeted_policy_qd` covers SAC populations and frozen latent controllers. - :doc:`tutorial_qdt` covers offline, descriptor-conditioned trajectory distillation. - :doc:`tutorial_symbolic_regression` fits analytical models using structural and semantic archives. - :doc:`tutorial_residual_window_qd` covers residual regression, Voronoi extinction, different descriptors for breeding and admission, interactive windows, and binary Pareto search. - :doc:`tutorial_portfolio_codesign` covers density flows, binary portfolios, LOKI, mixed-integer branching, and diverse planning. - :doc:`tutorial_coupled_search` covers fast Voronoi initialization, QDID, LLMatic, AC/DC, and cooperative MADECM. - :doc:`tutorial_relevance_search` covers RUDA, M2N2, portfolio MCTS, neuron-centric Hebbian learning, and Speciated Skill Discovery. - :doc:`tutorial_applied_repertoires` covers Neuro-MAP-Elites, SADE-QD, cross-play response tables, DivHF, and DADS. - :doc:`tutorial_layered_illumination` covers age-layered archives, alternative decoders, sensor prediction, PGA-AURORA, Ada-HOME, and benchmark generation from local-optima networks. - :doc:`tutorial_learned_exploration` covers dynamic mutation, TAXONS, STAX, BR-NS, and QD-DualDICE-JS. - :doc:`tutorial_ray` distributes evaluations for one search. :doc:`tutorial_rundra` runs independent searches by seed. - :doc:`run_results` covers portable JSON and replay. - :doc:`tutorial_visualization` covers ``compare_archive_cells``, ``LineageRecorder``, and ``align_archive_histories`` with rendered examples. - :doc:`tutorial_genealogy` covers ancestor archives, trajectory networks, classifier goal switching, and phylogeny-informed case estimation. .. toctree:: :maxdepth: 1 api_symbolic .. py:class:: qdpy.rl.DMOME(archive, *, initializer, operators, config=None, initial_samples=16, seed=0, device="cpu") Train a DQN to select among named variation operators for a two-objective ParetoGrid. Requires ``qdpy[rl]``. Pass a ``DMOMEConfig`` to set replay, optimizer, and exploration settings. .. py:method:: run(evaluate, budget) Spend the additional evaluation budget and preserve replay, operator counts, and the next sampled parent. .. py:class:: qdpy.rl.SVQDRL(env_factory, archive, *, descriptor, policy=None, td3=None, branch_capacity=12, training_steps_per_candidate=48, keep_fractions=(1., .5, .25), sparsity_edges=(.10, .60, .85), novelty_weight=.25, masks=True, private_critics=True, evaluation_episodes=1, max_episode_steps=300, seed=0, device="cpu") Train continuous actors in a bounded pool of structure-conditioned TD3 branches. Requires ``qdpy[rl]``. .. py:method:: train(max_env_steps) Spend additional environment steps and return cumulative collection, evaluation, and optimizer costs. .. py:attribute:: branches Immutable summaries ordered by descriptor cell and sparsity tier. .. py:method:: branch_policy(cell, tier) Return an independent ContinuousPolicy that reproduces the specified live branch and supports standard NPZ export. .. py:class:: qdpy.rl.SMERL(env_factory, *, return_threshold, policy=None, config=None, max_episode_steps=300, seed=0, device="cpu") Train a categorical-skill actor for a single continuous Box environment. Requires ``qdpy[rl]``. Pass a ``SMERLConfig`` to set the number of skills, the diversity bonus weight, and SAC or discriminator settings. .. py:method:: train(max_env_steps) Spend additional training steps. Return cumulative SAC costs, completed and eligible episode counts, and budget-cut steps. .. py:attribute:: policy The trained :class:`qdpy.rl.SMERLPolicy`. .. py:class:: qdpy.rl.SMERLPolicy An exportable stochastic Box actor conditioned on a zero-based skill ID. .. py:method:: act(observation, skill, deterministic=True) Return one physical action for the selected skill. .. py:method:: save(path) Write the actor to a portable NPZ file. .. py:method:: load(path, *, device="cpu", seed=0) :classmethod: Open an exported actor independently of the trainer. .. py:function:: qdpy.rl.evaluate_discovered_skills(env_factory, policy, *, descriptor=None, archive=None, episodes=1, max_episode_steps=300, seed=0, qd_offset=0.) Evaluate each skill on the same seeded resets. Supply a descriptor callback on a complete episode and a Grid or CVTGrid geometry for achieved-cell coverage and QD score. The audit returns metrics independently of existing archive entries. .. py:class:: qdpy.rl.RefQD(env_factory, archive, *, descriptor, policy=None, depth=4, refresh_top=1, refresh_every=50, seed=0) Continuous-action training with one shared encoder and a ranked archive of decision heads. Requires ``qdpy[rl]``. .. py:method:: train(max_env_steps) Spend an additional training budget on offspring and refreshes. The returned stats give the step and update counts. .. py:method:: policy_for(cell, rank=0, *, device=None) Return an independent continuous policy built with the current encoder. .. py:method:: audit(max_env_steps, *, seed=0) Reevaluate the top stored heads and return a fresh grid and its audit cost. .. py:class:: qdpy.rl.PollinationMAPElites(env_factory, archive, *, initial_bodies, body_descriptor, mutate_body, pollination_every=500, seed=0) Evolve a body and its continuous controller. Periodic rounds fit a student controller and test it on its teachers' bodies. Requires ``qdpy[rl]``. .. py:method:: train(max_env_steps) Spend an additional interaction budget and return cumulative search, teacher, student, and migration counts. .. py:method:: body_for(individual) Decode the body as an immutable numeric tuple. .. py:method:: policy_for(individual, *, device=None) Return an independent controller for the archived individual. .. py:class:: qdpy.rl.BRPGMAPElites(env_factory, archive, *, feature, behavior_steps=4, behavior_gamma=.98, descriptor_tolerance=.025, behavior_prior=.05, goal_relabel_fraction=.75, gradient_ema=.01, **kwargs) Evolve bounded continuous policies with separate reward and behavior learning. Requires ``qdpy[rl]``. .. py:method:: train(max_env_steps) Spend an additional step budget and return cumulative search and update counts. The stats include ``behavior_updates``. .. py:method:: conditioned_policy(*, device=None) Return a serializable continuous policy accepting a target descriptor. .. py:method:: policy_for(individual, *, device=None, seed=0) Rebuild an independent continuous policy from an archived genome. .. py:class:: qdpy.rl.MOMEP2C(env_factory, archive, *, reward_vector, descriptor, td3=None, **kwargs) Train continuous policies for a Pareto front in each cell. Requires ``qdpy[rl]``. .. py:method:: train(max_env_steps) Spend a hard simulator step budget and return cumulative statistics. .. py:method:: conditioned_policy(*, device=None) Return a portable actor accepting nonnegative objective preferences that sum to one. .. py:class:: qdpy.rl.PreferenceConditionedPolicy The preference actor supports ``act(observation, preference)``, ``specialize(preference)``, ``save(path)``, and ``load(path)``. .. py:class:: qdpy.rl.MOMEPGX(env_factory, archive, *, reward_vector, descriptor, td3=None, population_size=32, **kwargs) Evolve a crowding-truncated Pareto grid with genetic variation and objective-specific TD3 updates. ``train(max_env_steps)`` reports environment steps and the number of candidates started per objective. ``policy_for(individual)`` rebuilds an archived actor. .. py:class:: qdpy.rl.CMAMEGATD3ES(env_factory, archive, *, descriptor, td3=None, batch_size=8, es_samples=8, es_sigma=.02, sigma0=1., step_size=1., gradient_batch_size=512, critic_steps=16, policy=None, evaluation_episodes=1, max_episode_steps=300, seed=0, device="cpu", on_step=None) Branch in combinations of TD3 reward and mirrored ES descriptor gradients. ``train(max_env_steps)`` returns cumulative :class:`qdpy.rl.CMAMEGATD3ESStats`. ``centre`` returns a copy of the current flat policy parameters. ``policy_for(individual)`` and ``best_policy()`` build independent, serializable continuous actors. See :doc:`tutorial_pareto_gradients`. .. py:class:: qdpy.rl.CMAMEGATD3ESStats The inherited training steps count descriptor probes. Evaluation steps count policies scored for the archive. The additional fields count completed generations, proposed and completed perturbations, reward gradients, and restarts. .. py:class:: qdpy.rl.PPGA(env_factory, archive, *, measure, ppo=None, population_size=16, **kwargs) Estimate objective and descriptor directions with PPO, then explore their combinations with xNES. ``generation_step_limit`` gives the budget reservation per generation. ``train(max_env_steps)`` returns cumulative PPGA statistics. .. py:class:: qdpy.rl.GAILEBC(env_factory, archive, *, demonstrations, curiosity_weight=2.0, **kwargs) Use expert observation and action arrays to train a discriminator. Add an episode-wide PPO bonus for a descriptor in an empty cell. ``train(max_env_steps)`` reports discriminator and curiosity counts. .. py:class:: qdpy.rl.WQDIL(env_factory, archive, *, demonstrations, bonus_weight=1.0, **kwargs) Train a Wasserstein reward model from observation, action, and timestep-measure arrays. ``train(max_env_steps)`` reports PPGA statistics, reward-model updates, and timestep visits. .. py:class:: qdpy.rl.DynamicsAwareQD(env_factory, archive, *, descriptor, model_reward, **kwargs) Fit an ensemble of dynamics models from true transitions. ``train(max_env_steps)`` searches under the model, verifies selected policies in the environment, and reports counts for both. .. py:class:: qdpy.rl.ResetFreeQD(env_factory, archive, *, safety_margin, fallback_action, skill_steps, safety_buffer=0., warmup_action=None, **kwargs) Screen imagined policies from the live observation and evaluate selected skills in a continuing environment. ``train(max_env_steps)`` returns cumulative :class:`qdpy.rl.ResetFreeQDStats`. Use as a context manager or call ``close()`` when you finish training. .. py:class:: qdpy.rl.ResetFreeQDStats Report real and imagined steps, archive updates, the initial reset, unsafe steps, recovery work, and Gymnasium termination or truncation. .. py:class:: qdpy.rl.GDAQD(env_factory, archive, *, descriptor, model_reward, td3=None, gradient_fraction=0.1, **kwargs) Seed an imagined archive from real elites and apply TD3 mutations to some selected candidates. ``train(max_env_steps)`` reports real interactions, model rollouts, and policy-gradient work. .. py:class:: qdpy.rl.DiveOff(observation_space, action_space, *, observations, actions, rewards, next_observations, terminated, config=None, policy=None, seed=0, device="cpu") Learn a latent-conditioned continuous actor from a fixed transition log. ``train(updates)`` reports pretraining and main optimizer work. ``policy()`` returns an independent inference actor. .. py:class:: qdpy.rl.DiveOffPolicy The actor supports ``act(observation, latent, deterministic=True)``, ``save(path)``, and ``load(path)``. .. py:class:: qdpy.rl.DiveOffConfig Configure latent size, minibatches, VAE pretraining, advantage temperatures, information weight, and critic target updates. .. py:class:: qdpy.rl.DiveOffStats Report log size and counts of pretraining, critic, weighted actor, representation, and information updates. .. py:class:: qdpy.rl.RePPO(env_factory, *, feature, feature_bounds, population_size=4, **kwargs) Train under a shared interaction budget with ``train(max_env_steps)``. ``policies()`` returns one exportable actor per population member. .. py:class:: qdpy.rl.RePPOStats Report steps and completed episodes per member and total PPO updates. .. py:class:: qdpy.rl.PDO(env_factory, *, archive=None, descriptor=None, **kwargs) Alternate reward-only PPO and a diversity phase using copies of archived policies. Use ``train(max_env_steps)`` to progress in complete rounds. Call ``policies()`` to reconstruct independent exportable actors and ``evaluate(episodes_per_policy=8, seed=1337)`` for a separate audit. See :ref:`adaptive-diversity-pdo`. .. py:class:: qdpy.rl.PDOStats Count reward and diversity updates, population replacements, complete rounds, and training and archive evaluation steps. .. py:class:: qdpy.rl.PDOEvaluation Report a tuple of ``PDOMeasurement`` records and the number of audit environment steps. Each measurement contains mean return and descriptor. .. py:class:: qdpy.rl.LOKI(designs, *, env_factory, descriptor, clusters=2, pool_size=4, **kwargs) Train design-conditioned PPO actors within catalog clusters. Use ``train(max_env_steps)`` for complete rounds and ``evaluate(designs)`` for a separate audit. Export one actor with ``policy(cluster)``; ``observation(design, observation)`` prepares its input. Save ``embedding_scale`` and ``cluster_centers`` for independent deployment. See :ref:`portfolio-codesign-loki`. .. py:class:: qdpy.rl.LOKIStats Track the real search budget and split steps into PPO rollout and design-competition interactions. Report replacements and completed rounds. .. py:class:: qdpy.rl.LOKIMeasurement Record a design's identifier, cluster, and audited mean return. .. py:class:: qdpy.rl.LOKIEvaluation Collect one measurement per audited design and the total audit steps. .. py:class:: qdpy.rl.MADECM(env_factory, archive, *, descriptor, config=None, population_size=4, **kwargs) Alternate cooperative MADDPG updates and measured archive evaluations. ``train(max_env_steps)`` returns cumulative step and update counts. Use ``policy_for(elite)`` or ``best_policy()`` to export local actors. See :ref:`coupled-search-madecm`. .. py:class:: qdpy.rl.MADECMConfig Set replay and optimizer settings, the number of extra role updates, and whether to allocate them by curiosity or uniformly. .. py:class:: qdpy.rl.MADECMStats Report the step split, actor and critic updates by role, and predictor updates for the random network distillation models. .. py:class:: qdpy.rl.MADECMPolicy Use ``act(observation)`` with a fixed leading agent axis. ``save(path)`` and ``load(path, device="cpu")`` persist the local actors. .. py:class:: qdpy.rl.SSD(env_factory, *, config=None, sac=None, policy=None, max_episode_steps=300, seed=0, device="cpu") Train independent SAC species with a shared contrastive encoder. Use ``train(max_env_steps)`` to spend a transition budget. ``evaluate(episodes=..., descriptor=...)`` audits all skills with common reset seeds, and ``policy(species)`` exports a skill actor. See :ref:`relevance-search-ssd`. .. py:class:: qdpy.rl.SSDConfig Set species and skill counts, contrastive representation parameters, particle exploration, and the update period. .. py:class:: qdpy.rl.SSDStats Report collected steps, episodes, optimizer updates, temperatures, and replay sizes across species. .. py:class:: qdpy.rl.SSDPolicy Use ``act(observation, skill, deterministic=True)`` for inference. ``save(path)`` and ``load(path, device="cpu")`` persist the actor. .. py:class:: qdpy.rl.DADS(env_factory, *, skill_bounds=((-1., 1.),), state_scale=None, policy=None, config=None, max_episode_steps=300, seed=0, device="cpu") Learn continuous skills from a conditional transition likelihood ratio. Use ``train(max_env_steps)`` to set the interaction budget, ``predict_successor(observation, skill)`` to measure the model, and ``plan(observation, score, ...)`` to compose skills. Export the conditioned actor with ``policy.save(path)``. See :ref:`applied-repertoires-dads`. .. py:class:: qdpy.rl.DADSConfig Set SAC, Gaussian mixture, state-delta likelihood, and prior sampling parameters. .. py:class:: qdpy.rl.DADSPlan Report physical skills, predicted observations at skill boundaries, candidate scores and model work. .. py:class:: qdpy.rl.DADSStats Report real environment steps, SAC costs, and dynamics updates. .. py:class:: qdpy.rl.PGAAURORA(env_factory, *, trajectory=None, latent_size=2, capacity=128, radius=.08, training_period=32, encoder_epochs=4, encoder_batch_size=32, size_gain=.02, gradient=True, initial_policies=8, seed=0, **kwargs) Run PGA-MAP-Elites in an unstructured archive of learned trajectory descriptors. Call ``train(max_env_steps)`` to search, inspect ``archive`` after the search, and call ``policy_for(individual)`` to export an elite. See :ref:`layered-illumination-pga`. .. py:class:: qdpy.rl.PGAAuroraStats Report completed training steps and policies, encoder refits and optimizer updates, and the current novelty radius. .. py:class:: qdpy.rl.AdaHOME(env_factory, archive, *, adaptive=True, exploration=1., swap_probability=.1, elite_capacity=1024, elite_fraction=.25, **kwargs) Allocate genetic and policy-gradient proposals using archive feedback. Train with ``train(max_env_steps)`` and inspect the operator totals in ``stats``. See :ref:`layered-illumination-adahome`. .. py:class:: qdpy.rl.AdaHOMEStats Report completed and admitted proposals by operator, plus the number of transitions in the bounded elite replay buffer. .. py:class:: qdpy.rl.QDDualDICEJS(env_factory, *, population_size=3, policy=None, config=None, max_episode_steps=200, seed=0, device="cpu") Use ``train(max_env_steps)`` to learn a policy ensemble and ``policies()`` to export portable actors. Read ``last_divergences`` after a complete update. See :ref:`learned-exploration-dice`. .. py:class:: qdpy.rl.QDDualDICEConfig Configure the discount, kernel temperature, repulsion weight, actor and estimator learning rates, and the size of each rollout panel. .. py:class:: qdpy.rl.QDDualDICEStats Report real environment steps, completed or cutoff episodes, estimator optimizer steps, and actor updates. .. py:function:: qdpy.vision.invariance_descriptors(clean, augmented) Compute per-sample cosine similarities for aligned embeddings of shape ``(members, batch, features)`` and ``(members, augmentations, batch, features)``. .. py:function:: qdpy.vision.visual_qd_loss(quality_losses, invariances, *, diversity_weight=1.) Sum the mean task loss and the weighted invariance-diversity penalty. The returned ``InvarianceQDLoss`` carries the differentiable ``total``, ``quality``, and ``diversity`` scalars. See :ref:`adaptive-diversity-vision`. .. py:class:: qdpy.rl.QSDPBT(env_factory, *, descriptor, descriptor_size, population_size=4, **kwargs) Train categorical PPO actors with adaptive diversity weights and a critic for complete-episode descriptors. Use ``train(max_env_steps)``, ``evaluate(episodes_per_policy=8)``, or ``policies()`` for portable actors. See :ref:`qsd-pbt`. .. py:class:: qdpy.rl.QSDPBTStats Track per-policy steps, complete episodes, returns, and diversity weights. .. py:class:: qdpy.rl.QSDPBTEvaluation Report held-out mean returns and descriptors. Use ``diversity_by_quality(edges)`` for mean pairwise diversity in each return bin. .. py:class:: qdpy.rl.QDOS(env_factory, *, episodes, config=None, sac=None, **kwargs) Fit the trajectory encoder and decoder with ``pretrain(updates)``. ``train(max_env_steps)`` continues high-level SAC with mixed replay. ``policy()`` returns an independently usable ``QDOSPolicy``. .. py:class:: qdpy.rl.QDOSConfig Set the skill horizon, latent dimension, expectile, weighting, replay mix, and optimization schedule. .. py:class:: qdpy.rl.QDOSStats Report usable and excluded logged data, offline updates, live interactions, and online and offline replay draws. .. py:class:: qdpy.rl.QDOSPolicy Reset episode state with ``reset()`` and execute with ``act(observation)``. Inspect a skill with ``select_skill(observation)`` or execute a specified skill with ``act_skill(observation, skill)``. Use ``save(path)`` and ``load(path)`` for standalone inference. .. py:class:: qdpy.rl.PBTMAPElites(env_factory, archive, *, descriptor, sac=None, population_size=6, **kwargs) Train independent SAC learners with archive injection and hyperparameter resampling. ``train(max_env_steps)`` returns population and scoring costs. ``population_configs`` lists the live learner settings. Export measured policies with ``best_policy()``. .. py:class:: qdpy.rl.BFMQD(env_factory, archive, *, controller, descriptor, latent_size, **kwargs) Search a spherical latent space with a caller-supplied frozen policy. ``train(max_env_steps)`` returns measured environment costs. Bind a code with ``policy_for(individual)`` to use the controller at inference time. .. py:class:: qdpy.rl.QualityDiversityTransformer(observation_space, action_space, descriptor_size, *, config=None, seed=0, device="cpu") Train with ``fit(episodes, descriptors)`` and bind a target with ``policy_for(descriptor)``. Each policy session tracks its own observation and action history. Use ``save(path)`` and ``load(path)`` for numeric artifacts. .. py:class:: qdpy.rl.QDTConfig(context_length=128, width=64, heads=4, layers=2) Set the episode context and transformer dimensions for the offline Quality-Diversity Transformer. .. py:class:: qdpy.rl.DOMiNO(env_factory, *, feature, feature_dimension, num_skills=4, reward_floor=None, **kwargs) Learn latent policies with a shared PPO actor, mean occupancy features, and skill-specific reward multipliers. Requires the optional RL extra. See :doc:`tutorial_selection_and_skills`. .. py:method:: train(max_env_steps) Spend an additional interaction budget and return training counts. .. py:method:: act(observation, skill, *, deterministic=True) Choose an action for one latent policy. .. py:method:: evaluate(*, episodes_per_skill=4, seed=1337) Report complete held-out episodes, reward-floor satisfaction, and pairwise occupancy distances. .. py:class:: qdpy.algorithms.ARIA(archive, **kwargs) Refine occupied cells and optionally complete adjacent cells. ``run(evaluate, budget)`` builds an independent archive and returns rollout counts. .. py:class:: qdpy.algorithms.QDOES(probabilities, labels, **kwargs) Optimize cached classifiers with ``fit(budget)``. Use the result's ``predict_proba(probabilities)`` to combine probabilities on new rows. .. py:class:: qdpy.algorithms.SurpriseSearchLC(archive, dimension, **kwargs) Breed real vectors with forecast-based surprise and local fitness competition. ``run(evaluate, budget)`` reports evaluated candidates and the final population. .. py:class:: qdpy.algorithms.OfflineMAPElites(archive, genomes, fitnesses, descriptors, **kwargs) Use ``run(budget)`` to search a frozen surrogate. Then call ``verify(result, evaluate, budget)`` for a separate measured archive. .. py:class:: qdpy.containers.TraceArchive(geometry) Store one measurement with multiple cell references. Iterate for distinct measurement records or inspect ``cell_elites`` for winners. .. py:class:: qdpy.algorithms.TraceElites(archive, dimension, **kwargs) Use ``run(evaluate, budget)`` with a scalar fitness and a sequence of descriptor points for each genome. .. py:class:: qdpy.algorithms.DeepQD(container, budget, variables, *, configurations, **kwargs) Use the HiGeME evaluator and read ``deep_archive.cell_elites(cell)`` for configuration alternatives or ``configuration_grid(index)`` for an independent native snapshot of one layer. .. py:class:: qdpy.containers.VoronoiArchive(capacity, *, features_domain, **kwargs) At capacity, consider the candidate together with the incumbents and discard the lower-quality member of the closest descriptor pair. Use ``prune_to(size)`` to repeat this rule until at most size elites remain. .. py:class:: qdpy.algorithms.VoronoiElites(container, budget, dimension, **kwargs) Use Gaussian mutation and proposal-ordered feedback with a VoronoiArchive. Set ``extinction_period`` and ``extinction_size`` for scheduled reductions in the live population. Read ``extinctions`` and ``pruned`` for the counts. .. py:class:: qdpy.algorithms.OccupancyHistogram(state_centroids) Use ``encode(trajectory)`` for normalized visits to fixed state bins or ``make_archive(cells)`` for a native CVTGrid over those histograms. .. py:class:: qdpy.algorithms.OccupancyMAPElites(container, budget, dimension, *, histogram, **kwargs) Pass a callback returning ``(fitness, trajectory)`` to ``optimise()``. For manual batch feedback, supply the encoded descriptors. .. py:function:: qdpy.plots.plot_trace_archive(archive, *, ax=None, trace_color="black", trace_alpha=.35, **options) Draw the reporting cells and overlay each retained two-dimensional trace. .. py:class:: qdpy.algorithms.MEMES(archive, initial_centers, **kwargs) Use ``run(evaluate, budget, executor=None)`` for ordered scalar evaluations or ``run(None, budget, evaluate_batch=batch)`` for matrices. .. py:class:: qdpy.algorithms.SERENE(archive, dimension, **kwargs) Call ``run(evaluate, budget)`` with an evaluator returning ``(reward, descriptor)`` for each ``(genome, rollout_seed)``. Inspect ``stats``, ``novelty_archive``, and the supplied reward grid. .. py:class:: qdpy.algorithms.DvDES(initial_population, **kwargs) Call ``run(evaluate, budget)`` with an evaluator returning ``(reward, embedding)`` for each ``(genome, rollout_seed)``. Inspect ``population`` for measured centers and ``stats`` for costs. .. py:class:: qdpy.algorithms.PathSignature(observation_size, *, order=2, scale=None, time_channel=False) Use ``encode(trajectory, times=None)`` for fixed signatures and ``make_archive(trajectories, cells)`` for a reference-fitted CVT archive. .. py:class:: qdpy.algorithms.PathSignatureMAPElites(container, budget, dimension, *, signature, **kwargs) Use ``optimise(evaluate)`` with callbacks returning scalar fitness and a raw trajectory. Use encoded signatures for native batch feedback. .. py:class:: qdpy.algorithms.AuroraXCon(dimension, **kwargs) Use ``run(evaluate, budget)`` with a callback returning scalar fitness and a fixed-shape trajectory. Read the current unstructured container through ``archive`` after each refit and inspect ``stats`` for costs. .. py:class:: qdpy.algorithms.MCBOElites(container, budget, dimension, ind_domain, quality_floor, **kwargs) Use ``optimise(evaluate)`` or ``ask_batch()`` and ``tell_batch()`` with measured fitness and descriptors. ``stats`` exposes model and acquisition timings. .. py:class:: qdpy.rl.ASCIIME(env_factory, archive, *, descriptor, **kwargs) Train with ``train(max_env_steps)``. Use the existing policy export API, and inspect ``stats`` for live rollout and offline mutation counts. .. py:function:: qdpy.algorithms.behavior_logdet(embeddings, *, bandwidth=1., ridge=1e-6) Return the log determinant of the regularized population RBF Gram matrix. .. py:class:: qdpy.algorithms.DecisionTreePolicy(tree, observation_shape, action_count, action_start=0) Evaluate one observation with ``act(observation)``. Use ``save(path)`` and ``load(path)`` for versioned JSON artifacts. .. py:class:: qdpy.rl.DecisionTreeMAPElites(observation_bounds, **kwargs) Train with ``run(env_factory, max_env_steps)``. Inspect the grid with ``policy_for(individual)`` and use ``evaluate()`` for a separate audit. .. py:class:: qdpy.algorithms.AIM(islands, tasks, *, role_sizes, **kwargs) Run local and team evaluations with separate budgets. Read ``team_populations`` and ``allocation_probabilities`` to inspect the task repertoires and the current migration weights. .. py:class:: qdpy.algorithms.CardinalityMAPElites(dimension, **kwargs) Use ``run(evaluate, budget)`` to measure subsets and ``best_at_most(max_items)`` to choose an elite within an item limit. .. py:class:: qdpy.algorithms.VQElites(dimension, observation_size, **kwargs) Train learned codes with ``run(evaluate, budget)`` or feed logged measurements using ``observe(genome, fitness, observation)``. This class requires PyTorch at construction. .. py:class:: qdpy.rl.CCQD(env_factory, archive, *, descriptor, **kwargs) Use ``train(max_env_steps)`` to measure full actors built from cooperating representations and ``audit(max_env_steps, seed=0)`` to remeasure them. Export ``best_policy()`` through the continuous policy codec. .. py:class:: qdpy.rl.MASQD(env_factory, archive, *, descriptor, **kwargs) Search cooperative teams with role-specific descriptor-conditioned critics. ``train(max_env_steps)`` reports interaction and training counts. ``best_policy()`` returns an exportable team actor. .. py:class:: qdpy.rl.MIQD(env_factory, archive, *, descriptor, fragment_feature, **kwargs) Search cooperative teams with fragment-conditioned critics and bootstrap values from nearby archived teams. Use ``train(max_env_steps)`` to update the archive and ``policy_for(individual)`` to extract an actor. .. py:class:: qdpy.rl.MIQDStats Add information-estimator updates and archived-policy bootstrap queries to the team search counters. .. py:class:: qdpy.rl.TeamPolicy(observation_space, action_space, **kwargs) Apply a shared encoder and role-specific heads to a joint Box observation. ``save(path)`` and ``load(path)`` are available independently of MASQD. .. py:class:: qdpy.rl.PolicyDiffusion(observation_space, action_space, descriptor_domain, **kwargs) Learn a descriptor-conditioned generator from a fixed-layout archive with ``fit_archive(archive)``. Sample an actor with ``sample_policy(descriptor, seed=0)`` and export the generator with ``save(path)``. .. py:class:: qdpy.algorithms.DifferentialMAPElites(container, budget, dimension, **kwargs) Generate real-valued offspring from elites in four different occupied cells. Use native optimisation or ordered ``ask_batch()`` and ``tell_batch(results)``. .. py:class:: qdpy.algorithms.MixedBayesianQD(container, budget, variables, **kwargs) Optimise a mixed-variable space with GP predictions and measured constraints. ``decode(candidate)`` resolves categorical labels. ``surrogate_evaluations`` and ``nb_evaluations`` report the two budgets. .. py:class:: qdpy.algorithms.PreferenceLearningMAPElites(container, budget, dimension, **kwargs) Call ``record_feedback(selected, displayed=None)`` between generations to update the parent model. ``parent_probabilities()`` reports its current cell weights. .. py:class:: qdpy.rl.DiverseQualitySpecies(env_factory, **kwargs) Call ``train(max_env_steps)`` to evolve species and ``best_policy()`` to recover a deployable continuous actor. ``evaluate()`` uses separate held-out episodes and can bin achieved descriptors in a fresh grid. .. py:class:: qdpy.algorithms.BinaryMILPRepair(dimension, constraints=(), **kwargs) Minimize Hamming distance to a feasible binary assignment. ``repair(proposal)`` reports the verified genome and solver status. .. py:class:: qdpy.algorithms.RepairedMAPElites(archive, repair, **kwargs) Run binary variation and repair. ``run(evaluate, budget, repair_budget=None)`` separately caps solver calls and expensive evaluations. .. py:class:: qdpy.algorithms.APROL(repertoires, **kwargs) Use ``ask(desired_displacement)`` to select a policy genome and ``tell(achieved_displacement)`` to record the live observation. .. py:class:: qdpy.algorithms.MEliTA(archive, *, initialize, mutations, descriptors, coherence, **kwargs) Evolve separable components with transverse assessment. ``run(budget)`` counts each coherence call and reports how many edits reached admission. .. py:class:: qdpy.rl.QDHUAC(env_factory, *, descriptor, **kwargs) Train with ``train(max_env_steps)`` and inspect the measured ``population``. Reconstruct an exportable Gaussian actor with ``policy_for(individual)`` or ``best_policy()``. .. toctree:: :maxdepth: 1 api_algorithms api_experiments api_benchmarks Python shortcuts ---------------- Use these constructors and runner to start a search from Python. The returned optimiser also supports the native methods below. .. automodule:: qdpy.simple :members: map_elites, nslc, run, RunResult Algorithms and logging ---------------------- .. py:module:: qdpy.algorithms .. autoclass:: QDAlgorithm :members: ask, tell, optimise, best, add_callback, tell_container_entries, reinit, optimisation_task, batch_size, nb_suggestions, nb_evaluations, nb_updated .. autoclass:: RandomUniform .. autoclass:: RandomSearchMutPolyBounded .. autoclass:: CuriosityMutPolyBounded .. autoclass:: RandomSearchMutGaussian .. autoclass:: Lambda .. autoclass:: AlgorithmLogger :members: monitor, register_stat, evals, iterations .. autoclass:: LoggerStat .. automethod:: AlgorithmLogger.save Containers ---------- .. py:module:: qdpy.containers Use a :class:`Container` to retain candidates within their domains, a :class:`Grid` to retain elites by descriptor cell, and a :class:`NoveltyArchive` to select using parent history. The parent links are omitted from saved results by default. Set ``disable_parents_pickling=False`` to retain an archive's links to its immediate parents. .. autoclass:: Container :members: add, update, discard, clear, best, best_fitness, best_features, qd_score, get_ind_fitness, get_ind_features, to_grid .. autoclass:: Grid :members: index_grid, filled_bins, quality, quality_array, best_index, qd_score .. autoclass:: CVTGrid .. autofunction:: qdpy.containers.generate_centroids .. autoclass:: ParetoGrid :members: front, cell_hypervolume, qd_hypervolume, global_hypervolume .. autoclass:: LocalParetoArchive .. autoclass:: qdpy.containers.TDominOGrid :members: anchors, tournament_score .. autoclass:: qdpy.containers.SlidingBoundariesGrid :members: bin_edges, remaps .. autoclass:: AutoScalingGrid :members: rescale .. autoclass:: NoveltyArchive .. autoclass:: SelfAdaptiveNoveltyArchive :members: recompute_threshold .. autoclass:: Population .. autoclass:: ContainerDecorator .. autoclass:: qdpy.containers.base.ContainerLike .. autoclass:: qdpy.containers.base.SimpleOrderedSet .. _learned-descriptors: Learned descriptors ------------------- Install PyTorch to use joint autoencoder training. See :doc:`tutorial_mc_aurora` for a runnable search with fixed grids and a shared depot. .. autoclass:: MCAurora :members: fit, attach, retrain_if_needed .. autoclass:: MCAuroraTraining Candidates and their scores --------------------------- .. py:module:: qdpy.phenotype An :class:`Individual` holds the genome as a list and stores scores separately. :class:`Fitness` applies objective weights when comparing individuals. :class:`Features` holds the descriptor vector. With ``fitness_score_names`` or ``features_score_names``, a container can select the relevant entries of a :class:`ScoresDict`. .. autoclass:: Individual :members: fitness, features, scores, dominates, reset .. autoclass:: Score :members: dominates .. autoclass:: Fitness :members: values, valid, weighted_values .. autoclass:: Features .. autoclass:: ScoresDict :members: select, to_fitness, to_features The following protocols describe the interfaces used by optimisers and archives. Custom candidate and measurement classes can implement them. .. autoclass:: IndividualLike .. autoclass:: FitnessLike .. autoclass:: FeaturesLike .. autoclass:: ScoresDictLike Novelty metrics --------------- .. py:module:: qdpy.metrics With ``ignore_first=True``, these functions skip the nearest entry. This is useful when the query itself is in the reference archive. Local competition divides by the requested neighbour count even if fewer are available. .. autofunction:: features_distances .. autofunction:: novelty .. autofunction:: novelty_nn .. autofunction:: novelty_local_competition Multi-archive metrics --------------------- .. autofunction:: archive_originality .. autofunction:: archive_overlap .. autofunction:: pairwise_kl_coverage Language model workflows ------------------------ .. autoclass:: qdpy.algorithms.NeighborhoodElites :members: entries, stats, run, probe .. autoclass:: qdpy.algorithms.NeighborhoodEntry .. autoclass:: qdpy.algorithms.NeighborhoodStats .. autoclass:: qdpy.algorithms.NeighborhoodProbe .. autofunction:: qdpy.algorithms.answer_entropy .. autoclass:: qdpy.algorithms.IDEAgent :members: entries, stats, run .. autoclass:: qdpy.algorithms.IdeaAssessment .. autoclass:: qdpy.algorithms.IdeaRequest .. autoclass:: qdpy.algorithms.IdeaEntry .. autoclass:: qdpy.algorithms.IdeaStats .. autofunction:: qdpy.algorithms.idea_yield .. autoclass:: qdpy.algorithms.TaskArchiveSearch :members: entries, failed, stats, run .. autoclass:: qdpy.algorithms.TaskAssessment .. autoclass:: qdpy.algorithms.TaskRequest .. autoclass:: qdpy.algorithms.TaskEntry .. autoclass:: qdpy.algorithms.TaskArchiveStats Changing constraints, structured niches, fidelity, and replay ------------------------------------------------------------- .. autoclass:: qdpy.algorithms.VariableConstraintMAPElites :members: constraints, set_constraints, run .. autoclass:: qdpy.algorithms.MagnitudeArchive :members: from_reference, landmarks, cells, weights, index, add .. autoclass:: qdpy.algorithms.MagnitudeGoExplore :members: optimise .. autofunction:: qdpy.algorithms.magnitude_weights .. autoclass:: qdpy.algorithms.AsyncQDHalving :members: quotas, pending, trials, spent, reserved, ask, tell, run .. autoclass:: qdpy.algorithms.FidelityRequest .. autoclass:: qdpy.algorithms.EliteReplay :members: stats, dataset, offer, run .. autoclass:: qdpy.algorithms.EliteReplayDataset :members: entries, sample, save, load .. autoclass:: qdpy.algorithms.EliteReplayEntry .. autoclass:: qdpy.algorithms.EliteReplayStats Hierarchical archives, counterfactuals, and generative QD --------------------------------------------------------- .. autoclass:: qdpy.algorithms.HierarchicalArchive :members: subarchives, index, alternatives, coarse_descriptor, query, add, sample .. autoclass:: qdpy.algorithms.HierarchicalMAPElites :members: run .. autoclass:: qdpy.algorithms.CounterfactualEvaluator :special-members: __call__ .. autoclass:: qdpy.algorithms.CounterfactualMOME :members: run .. autoclass:: qdpy.algorithms.ConstructiveDAG :members: states, terminals .. autoclass:: qdpy.algorithms.PreferenceGFlowNet :members: stats, fit, sample, distribution, target_distribution, illuminate .. autoclass:: qdpy.algorithms.GFlowNetStats .. autoclass:: qdpy.algorithms.SoftPromptMAPElites :members: stats, embedding, run .. autoclass:: qdpy.algorithms.SoftPromptStats Constraint programming, safe exploration, and diffusion search --------------------------------------------------------------- .. autoclass:: qdpy.algorithms.CPSATArchiveSearch :members: run .. autoclass:: qdpy.algorithms.CPSATCellResult .. autoclass:: qdpy.algorithms.SafeBayesianIllumination :members: trials, halted, certified_indices, run .. autoclass:: qdpy.algorithms.SafeIlluminationTrial .. autoclass:: qdpy.algorithms.DiffusionEvolution :members: diffusion_proposals .. autoclass:: qdpy.algorithms.DiffusionMAPElites Execution and result files -------------------------- .. py:module:: qdpy.base .. autoclass:: ParallelismManager .. autoclass:: ExecutorLike .. autoclass:: FutureLike .. autofunction:: generic_as_completed .. py:module:: qdpy.tools .. autofunction:: sel_roulette_score .. autofunction:: open_pickle_file