Core Python API¶
Start with Run a seeded MAP-Elites search for the default search or Control evaluation with ask and tell when your application drives evaluation.
MAP-Elites with noisy evaluations uses rollout budgets and a separate archive audit.
MC-AURORA with learned descriptors uses PyTorch to learn descriptors for several archives.
Discrete policy search with PPO and MAP-Elites and Continuous control with PPO, TD3, and PGA-MAP-Elites cover the standalone learners, native QD archives, and policy export in
qdpy.rl.Quality-diversity policy gradient covers state descriptors and replay-time novelty for
QDPG.Descriptor-conditioned MAP-Elites covers
DCGMAPElites,DCRLMAPElites, andDescriptorConditionedPolicy.Quality-Diversity Actor-Critic covers
SAC,QDAC, their portable actors, and theevaluate_skillsfixed-skill evaluation API.Reference niches, repertoire selection, and model-based skills covers
QDACMB,QDACMBConfig, andQDACMBPolicy.new_episode()for recurrent inference.Near-optimal portfolios, novelty, and policy reuse covers tabular reward transfer and sparse continuous controllers from
SVQDRL.Case novelty, linked variation, and discovered skills covers
SMERL,SMERLConfig,SMERLPolicy, andevaluate_discovered_skillsfor learned skill IDs.Share policy representations with RefQD covers shared representations and measured archive refreshes.
Co-design bodies and controllers with Pollination covers controller distillation for morphology–controller co-design.
Behavior-regulated policy gradients covers policy gradients with separate behavior estimation.
Train controllers for objective trade-offs covers vector rewards and objective preference policies.
Gradient, imitation, and dynamics-aware policy search covers PPGA, GAIL-EBC, and Dynamics-Aware QD.
Case-wise selection and policy repertoires covers lexicase, Quality Evolvability ES, MOME-PGX, and WQDIL.
Binary swarms, geometric policies, and budgeted archives covers binary novelty PSO, LUCIE-style races, and Traveling Thief. It also shows how to train
qdpy.rl.GENEMAPEliteswithcoordinate_sizeand export a dense policy viapolicy_fororbest_policy.Conditional designs and task repertoires covers Conditional Bayesian QD, CMOEA, QED, and GDA-QD.
Offline search and diverse plans covers GA-ME, DynAMO, DiveOff, and temporal planning.
Compact repertoires and skill composition covers set scalarization, RePPO, QDOS, and MIQD.
Deep archives and scenario discovery covers deep Bayesian search, descriptor swaps, QD-MAPPER, and QD-Rec.
Adaptive exploration, operator selection, and phased diversity covers novelty ES, QQD, equal-budget Bayesian Deep QD, PDO, and visual pre-training.
SAC populations and search over frozen policy latents covers SAC populations and frozen latent controllers.
Distill a repertoire with the Quality-Diversity Transformer covers offline, descriptor-conditioned trajectory distillation.
Symbolic regression with MAP-Elites fits analytical models using structural and semantic archives.
Residual regression and focused QD search covers residual regression, Voronoi extinction, different descriptors for breeding and admission, interactive windows, and binary Pareto search.
Learned density, design portfolios, and shared controllers covers density flows, binary portfolios, LOKI, mixed-integer branching, and diverse planning.
Refine diverse starts and coevolve complementary solutions covers fast Voronoi initialization, QDID, LLMatic, AC/DC, and cooperative MADECM.
Guide search with task feedback and local adaptation covers RUDA, M2N2, portfolio MCTS, neuron-centric Hebbian learning, and Speciated Skill Discovery.
Build repertoires for classifiers, schedules, and skills covers Neuro-MAP-Elites, SADE-QD, cross-play response tables, DivHF, and DADS.
Search across age layers, decoders, and learned behaviors covers age-layered archives, alternative decoders, sensor prediction, PGA-AURORA, Ada-HOME, and benchmark generation from local-optima networks.
Dynamic mutation and learned novelty covers dynamic mutation, TAXONS, STAX, BR-NS, and QD-DualDICE-JS.
Evaluate a MAP-Elites search with Ray distributes evaluations for one search. Run a QDpy seed sweep with Rundra runs independent searches by seed.
Replay a saved search covers portable JSON and replay.
Plot archive geometry and evolution covers
compare_archive_cells,LineageRecorder, andalign_archive_historieswith rendered examples.Genealogy and stepping stones covers ancestor archives, trajectory networks, classifier goal switching, and phylogeny-informed case estimation.
- 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 aDMOMEConfigto set replay, optimizer, and exploration settings.- run(evaluate, budget)¶
Spend the additional evaluation budget and preserve replay, operator counts, and the next sampled parent.
- 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].- train(max_env_steps)¶
Spend additional environment steps and return cumulative collection, evaluation, and optimizer costs.
- branches¶
Immutable summaries ordered by descriptor cell and sparsity tier.
- branch_policy(cell, tier)¶
Return an independent ContinuousPolicy that reproduces the specified live branch and supports standard NPZ export.
- 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 aSMERLConfigto set the number of skills, the diversity bonus weight, and SAC or discriminator settings.- train(max_env_steps)¶
Spend additional training steps. Return cumulative SAC costs, completed and eligible episode counts, and budget-cut steps.
- policy¶
The trained
qdpy.rl.SMERLPolicy.
- class qdpy.rl.SMERLPolicy¶
An exportable stochastic Box actor conditioned on a zero-based skill ID.
- act(observation, skill, deterministic=True)¶
Return one physical action for the selected skill.
- save(path)¶
Write the actor to a portable NPZ file.
- classmethod load(path, *, device='cpu', seed=0)¶
Open an exported actor independently of the trainer.
- 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.
- 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].- train(max_env_steps)¶
Spend an additional training budget on offspring and refreshes. The returned stats give the step and update counts.
- policy_for(cell, rank=0, *, device=None)¶
Return an independent continuous policy built with the current encoder.
- audit(max_env_steps, *, seed=0)¶
Reevaluate the top stored heads and return a fresh grid and its audit cost.
- 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].- train(max_env_steps)¶
Spend an additional interaction budget and return cumulative search, teacher, student, and migration counts.
- body_for(individual)¶
Decode the body as an immutable numeric tuple.
- policy_for(individual, *, device=None)¶
Return an independent controller for the archived individual.
- 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].- train(max_env_steps)¶
Spend an additional step budget and return cumulative search and update counts. The stats include
behavior_updates.
- conditioned_policy(*, device=None)¶
Return a serializable continuous policy accepting a target descriptor.
- policy_for(individual, *, device=None, seed=0)¶
Rebuild an independent continuous policy from an archived genome.
- 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].- train(max_env_steps)¶
Spend a hard simulator step budget and return cumulative statistics.
- conditioned_policy(*, device=None)¶
Return a portable actor accepting nonnegative objective preferences that sum to one.
- class qdpy.rl.PreferenceConditionedPolicy¶
The preference actor supports
act(observation, preference),specialize(preference),save(path), andload(path).
- 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.
- 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 cumulativeqdpy.rl.CMAMEGATD3ESStats.centrereturns a copy of the current flat policy parameters.policy_for(individual)andbest_policy()build independent, serializable continuous actors. See Pareto fronts, noisy elites, and policy gradients.
- 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.
- 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_limitgives the budget reservation per generation.train(max_env_steps)returns cumulative PPGA statistics.
- 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.
- 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.
- 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.
- 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 cumulativeqdpy.rl.ResetFreeQDStats. Use as a context manager or callclose()when you finish training.
- class qdpy.rl.ResetFreeQDStats¶
Report real and imagined steps, archive updates, the initial reset, unsafe steps, recovery work, and Gymnasium termination or truncation.
- 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.
- 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.
- class qdpy.rl.DiveOffPolicy¶
The actor supports
act(observation, latent, deterministic=True),save(path), andload(path).
- class qdpy.rl.DiveOffConfig¶
Configure latent size, minibatches, VAE pretraining, advantage temperatures, information weight, and critic target updates.
- class qdpy.rl.DiveOffStats¶
Report log size and counts of pretraining, critic, weighted actor, representation, and information updates.
- 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.
- class qdpy.rl.RePPOStats¶
Report steps and completed episodes per member and total PPO updates.
- 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. Callpolicies()to reconstruct independent exportable actors andevaluate(episodes_per_policy=8, seed=1337)for a separate audit. See Train a policy population in phases.
- class qdpy.rl.PDOStats¶
Count reward and diversity updates, population replacements, complete rounds, and training and archive evaluation steps.
- class qdpy.rl.PDOEvaluation¶
Report a tuple of
PDOMeasurementrecords and the number of audit environment steps. Each measurement contains mean return and descriptor.
- 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 andevaluate(designs)for a separate audit. Export one actor withpolicy(cluster);observation(design, observation)prepares its input. Saveembedding_scaleandcluster_centersfor independent deployment. See Train a shared controller for similar designs.
- class qdpy.rl.LOKIStats¶
Track the real search budget and split steps into PPO rollout and design-competition interactions. Report replacements and completed rounds.
- class qdpy.rl.LOKIMeasurement¶
Record a design’s identifier, cluster, and audited mean return.
- class qdpy.rl.LOKIEvaluation¶
Collect one measurement per audited design and the total audit steps.
- 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. Usepolicy_for(elite)orbest_policy()to export local actors. See Allocate cooperative learning updates with MADECM.
- class qdpy.rl.MADECMConfig¶
Set replay and optimizer settings, the number of extra role updates, and whether to allocate them by curiosity or uniformly.
- class qdpy.rl.MADECMStats¶
Report the step split, actor and critic updates by role, and predictor updates for the random network distillation models.
- class qdpy.rl.MADECMPolicy¶
Use
act(observation)with a fixed leading agent axis.save(path)andload(path, device="cpu")persist the local actors.
- 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, andpolicy(species)exports a skill actor. See Pretrain species with Speciated Skill Discovery.
- class qdpy.rl.SSDConfig¶
Set species and skill counts, contrastive representation parameters, particle exploration, and the update period.
- class qdpy.rl.SSDStats¶
Report collected steps, episodes, optimizer updates, temperatures, and replay sizes across species.
- class qdpy.rl.SSDPolicy¶
Use
act(observation, skill, deterministic=True)for inference.save(path)andload(path, device="cpu")persist the actor.
- 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, andplan(observation, score, ...)to compose skills. Export the conditioned actor withpolicy.save(path). See Discover skills and plan with their effects.
- class qdpy.rl.DADSConfig¶
Set SAC, Gaussian mixture, state-delta likelihood, and prior sampling parameters.
- class qdpy.rl.DADSPlan¶
Report physical skills, predicted observations at skill boundaries, candidate scores and model work.
- class qdpy.rl.DADSStats¶
Report real environment steps, SAC costs, and dynamics updates.
- 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, inspectarchiveafter the search, and callpolicy_for(individual)to export an elite. See Teach PGA-AURORA from trajectories.
- class qdpy.rl.PGAAuroraStats¶
Report completed training steps and policies, encoder refits and optimizer updates, and the current novelty radius.
- 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 instats. See Allocate Ada-HOME operators from admission feedback.
- class qdpy.rl.AdaHOMEStats¶
Report completed and admitted proposals by operator, plus the number of transitions in the bounded elite replay buffer.
- 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 andpolicies()to export portable actors. Readlast_divergencesafter a complete update. See Train policies with diverse state and action visitation.
- class qdpy.rl.QDDualDICEConfig¶
Configure the discount, kernel temperature, repulsion weight, actor and estimator learning rates, and the size of each rollout panel.
- class qdpy.rl.QDDualDICEStats¶
Report real environment steps, completed or cutoff episodes, estimator optimizer steps, and actor updates.
- qdpy.vision.invariance_descriptors(clean, augmented)¶
Compute per-sample cosine similarities for aligned embeddings of shape
(members, batch, features)and(members, augmentations, batch, features).
- qdpy.vision.visual_qd_loss(quality_losses, invariances, *, diversity_weight=1.)¶
Sum the mean task loss and the weighted invariance-diversity penalty. The returned
InvarianceQDLosscarries the differentiabletotal,quality, anddiversityscalars. See Pre-train encoders with different invariances.
- 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), orpolicies()for portable actors. See Quality-Similar Diversity with Population-Based Training.
- class qdpy.rl.QSDPBTStats¶
Track per-policy steps, complete episodes, returns, and diversity weights.
- class qdpy.rl.QSDPBTEvaluation¶
Report held-out mean returns and descriptors. Use
diversity_by_quality(edges)for mean pairwise diversity in each return bin.
- 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 usableQDOSPolicy.
- class qdpy.rl.QDOSConfig¶
Set the skill horizon, latent dimension, expectile, weighting, replay mix, and optimization schedule.
- class qdpy.rl.QDOSStats¶
Report usable and excluded logged data, offline updates, live interactions, and online and offline replay draws.
- class qdpy.rl.QDOSPolicy¶
Reset episode state with
reset()and execute withact(observation). Inspect a skill withselect_skill(observation)or execute a specified skill withact_skill(observation, skill). Usesave(path)andload(path)for standalone inference.
- 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_configslists the live learner settings. Export measured policies withbest_policy().
- 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 withpolicy_for(individual)to use the controller at inference time.
- 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 withpolicy_for(descriptor). Each policy session tracks its own observation and action history. Usesave(path)andload(path)for numeric artifacts.
- 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.
- 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 Parent selection, surrogate search, and diverse skills.
- train(max_env_steps)¶
Spend an additional interaction budget and return training counts.
- act(observation, skill, *, deterministic=True)¶
Choose an action for one latent policy.
- evaluate(*, episodes_per_skill=4, seed=1337)¶
Report complete held-out episodes, reward-floor satisfaction, and pairwise occupancy distances.
- 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.
- class qdpy.algorithms.QDOES(probabilities, labels, **kwargs)¶
Optimize cached classifiers with
fit(budget). Use the result’spredict_proba(probabilities)to combine probabilities on new rows.
- 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.
- class qdpy.algorithms.OfflineMAPElites(archive, genomes, fitnesses, descriptors, **kwargs)¶
Use
run(budget)to search a frozen surrogate. Then callverify(result, evaluate, budget)for a separate measured archive.
- class qdpy.containers.TraceArchive(geometry)¶
Store one measurement with multiple cell references. Iterate for distinct measurement records or inspect
cell_elitesfor winners.
- class qdpy.algorithms.TraceElites(archive, dimension, **kwargs)¶
Use
run(evaluate, budget)with a scalar fitness and a sequence of descriptor points for each genome.
- class qdpy.algorithms.DeepQD(container, budget, variables, *, configurations, **kwargs)¶
Use the HiGeME evaluator and read
deep_archive.cell_elites(cell)for configuration alternatives orconfiguration_grid(index)for an independent native snapshot of one layer.
- 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.
- class qdpy.algorithms.VoronoiElites(container, budget, dimension, **kwargs)¶
Use Gaussian mutation and proposal-ordered feedback with a VoronoiArchive. Set
extinction_periodandextinction_sizefor scheduled reductions in the live population. Readextinctionsandprunedfor the counts.
- class qdpy.algorithms.OccupancyHistogram(state_centroids)¶
Use
encode(trajectory)for normalized visits to fixed state bins ormake_archive(cells)for a native CVTGrid over those histograms.
- class qdpy.algorithms.OccupancyMAPElites(container, budget, dimension, *, histogram, **kwargs)¶
Pass a callback returning
(fitness, trajectory)tooptimise(). For manual batch feedback, supply the encoded descriptors.
- 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.
- class qdpy.algorithms.MEMES(archive, initial_centers, **kwargs)¶
Use
run(evaluate, budget, executor=None)for ordered scalar evaluations orrun(None, budget, evaluate_batch=batch)for matrices.
- class qdpy.algorithms.SERENE(archive, dimension, **kwargs)¶
Call
run(evaluate, budget)with an evaluator returning(reward, descriptor)for each(genome, rollout_seed). Inspectstats,novelty_archive, and the supplied reward grid.
- class qdpy.algorithms.DvDES(initial_population, **kwargs)¶
Call
run(evaluate, budget)with an evaluator returning(reward, embedding)for each(genome, rollout_seed). Inspectpopulationfor measured centers andstatsfor costs.
- class qdpy.algorithms.PathSignature(observation_size, *, order=2, scale=None, time_channel=False)¶
Use
encode(trajectory, times=None)for fixed signatures andmake_archive(trajectories, cells)for a reference-fitted CVT archive.
- 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.
- 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 througharchiveafter each refit and inspectstatsfor costs.
- class qdpy.algorithms.MCBOElites(container, budget, dimension, ind_domain, quality_floor, **kwargs)¶
Use
optimise(evaluate)orask_batch()andtell_batch()with measured fitness and descriptors.statsexposes model and acquisition timings.
- class qdpy.rl.ASCIIME(env_factory, archive, *, descriptor, **kwargs)¶
Train with
train(max_env_steps). Use the existing policy export API, and inspectstatsfor live rollout and offline mutation counts.
- qdpy.algorithms.behavior_logdet(embeddings, *, bandwidth=1., ridge=1e-6)¶
Return the log determinant of the regularized population RBF Gram matrix.
- class qdpy.algorithms.DecisionTreePolicy(tree, observation_shape, action_count, action_start=0)¶
Evaluate one observation with
act(observation). Usesave(path)andload(path)for versioned JSON artifacts.
- class qdpy.rl.DecisionTreeMAPElites(observation_bounds, **kwargs)¶
Train with
run(env_factory, max_env_steps). Inspect the grid withpolicy_for(individual)and useevaluate()for a separate audit.
- class qdpy.algorithms.AIM(islands, tasks, *, role_sizes, **kwargs)¶
Run local and team evaluations with separate budgets. Read
team_populationsandallocation_probabilitiesto inspect the task repertoires and the current migration weights.
- class qdpy.algorithms.CardinalityMAPElites(dimension, **kwargs)¶
Use
run(evaluate, budget)to measure subsets andbest_at_most(max_items)to choose an elite within an item limit.
- class qdpy.algorithms.VQElites(dimension, observation_size, **kwargs)¶
Train learned codes with
run(evaluate, budget)or feed logged measurements usingobserve(genome, fitness, observation). This class requires PyTorch at construction.
- class qdpy.rl.CCQD(env_factory, archive, *, descriptor, **kwargs)¶
Use
train(max_env_steps)to measure full actors built from cooperating representations andaudit(max_env_steps, seed=0)to remeasure them. Exportbest_policy()through the continuous policy codec.
- 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.
- 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 andpolicy_for(individual)to extract an actor.
- class qdpy.rl.MIQDStats¶
Add information-estimator updates and archived-policy bootstrap queries to the team search counters.
- class qdpy.rl.TeamPolicy(observation_space, action_space, **kwargs)¶
Apply a shared encoder and role-specific heads to a joint Box observation.
save(path)andload(path)are available independently of MASQD.
- 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 withsample_policy(descriptor, seed=0)and export the generator withsave(path).
- 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()andtell_batch(results).
- 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_evaluationsandnb_evaluationsreport the two budgets.
- 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.
- class qdpy.rl.DiverseQualitySpecies(env_factory, **kwargs)¶
Call
train(max_env_steps)to evolve species andbest_policy()to recover a deployable continuous actor.evaluate()uses separate held-out episodes and can bin achieved descriptors in a fresh grid.
- class qdpy.algorithms.BinaryMILPRepair(dimension, constraints=(), **kwargs)¶
Minimize Hamming distance to a feasible binary assignment.
repair(proposal)reports the verified genome and solver status.
- 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.
- class qdpy.algorithms.APROL(repertoires, **kwargs)¶
Use
ask(desired_displacement)to select a policy genome andtell(achieved_displacement)to record the live observation.
- 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.
- class qdpy.rl.QDHUAC(env_factory, *, descriptor, **kwargs)¶
Train with
train(max_env_steps)and inspect the measuredpopulation. Reconstruct an exportable Gaussian actor withpolicy_for(individual)orbest_policy().
Python shortcuts¶
Use these constructors and runner to start a search from Python. The returned optimiser also supports the native methods below.
Construct MAP-Elites and NSLC searches and run existing QDpy optimisers.
- class qdpy.simple.RunResult(algorithm: QDAlgorithmLike, archive: Container, best: IndividualLike, evaluations: int, manifest_path: Path | None)[source]¶
References to a completed search and its evaluation count.
- Variables:
algorithm – The optimiser supplied to
run().archive – The live container at the end of the run.
best – The live individual returned by the optimiser.
evaluations – Candidate slots consumed during this invocation.
manifest_path – The manifest path if an output directory was supplied.
- qdpy.simple.map_elites(*, dimension: int, budget: int, shape: int | Sequence[int], fitness_domain: Sequence[Tuple[float, float]], features_domain: Sequence[Tuple[float, float]], ind_domain: Tuple[float, float] = (0, 1), batch_size: int = 1, optimisation_task: str | Sequence[float] = 'minimisation') RandomSearchMutPolyBounded[source]¶
Make a MAP-Elites search for real-valued genomes.
- Parameters:
dimension – Number of coordinates in each genome.
budget – Number of candidate evaluations per run.
shape – Number of bins for each descriptor, or an integer for one descriptor.
fitness_domain – One closed interval per objective.
features_domain – One closed interval per grid axis.
ind_domain – Bounds shared by all genome coordinates.
batch_size – Candidate count per batch. The default gives each proposal feedback from the previous evaluation.
optimisation_task – Objective direction or a sequence of objective weights.
- Returns:
An optimiser ready for
run()or the native ask/tell API.
- qdpy.simple.nslc(*, dimension: int, budget: int, fitness_domain: Sequence[Tuple[float, float]], features_domain: Sequence[Tuple[float, float]], threshold_novelty: float, k: int = 15, ind_domain: Tuple[float, float] = (0, 1), batch_size: int = 1, optimisation_task: str | Sequence[float] = 'minimisation') RandomSearchMutPolyBounded[source]¶
Make an NSLC search with a fixed novelty threshold.
The child archive uses Euclidean distances to its parent history. The optimiser keeps that parent when saved with the native pickle tools.
- Parameters:
dimension – Number of coordinates in each genome.
budget – Number of candidate evaluations per run.
fitness_domain – One closed interval per objective.
features_domain – One closed interval per descriptor.
threshold_novelty – Finite, nonnegative threshold in descriptor units.
k – Number of nearest neighbours to consider.
ind_domain – Bounds shared by all genome coordinates.
batch_size – Candidate count per batch.
optimisation_task – Objective direction or a sequence of objective weights.
- Returns:
An optimiser with a child novelty archive and a separate parent.
- qdpy.simple.run(algorithm: QDAlgorithmLike, evaluate: Callable, *, seed: int | None = None, backend: str | None = None, executor: ExecutorLike | None = None, max_workers: int | None = None, ray_address: str | None = None, batch_mode: bool = True, pack_size: int | None = None, output_dir: str | PathLike[str] | None = None, configuration: Mapping[str, Any] | None = None, bundle: RunBundleOptions | None = None) RunResult[source]¶
Drive an existing optimiser with its native evaluation contract.
The optimiser keeps its archive, counters and callbacks between calls. Evaluator results and failures follow the algorithm’s
optimise()behavior. Parallel feedback follows the executor’s completion order.- Parameters:
algorithm – An optimiser with the native
optimise()interface.evaluate – Candidate evaluator, or a list-taking evaluator with
pack_size.seed – Optional seed for the calling process’s Python and NumPy global random streams. Their states are restored after the run.
backend – Backend accepted by the parallelism manager. Defaults to sequential.
executor – A caller-owned executor. Use it on its own or select a managed backend.
max_workers – Worker limit passed to the parallelism manager.
ray_address – Address passed to the optional Ray backend.
batch_mode – Complete each batch before proposing the next one.
pack_size – Maximum number of candidates passed to a packed evaluator.
output_dir – Optional directory for a new
run.jsonand supported grid export.configuration – Run settings to record in the manifest. The actual seed passed to the runner is recorded under
seed.bundle – Optional portable history, lineage, and checkpoint settings. Supply
output_dir. Checkpointed bundles use the native batch driver with a sequential scalar evaluator or one packed call per batch.
- Returns:
References to the live run objects and the evaluation count for this call.
- Raises:
FileExistsError – If the directory already has a manifest or an active run.
Algorithms and logging¶
- class qdpy.algorithms.QDAlgorithm(container: Container, budget: int, batch_size: int | None = None, dimension: int | None = None, nb_objectives: int | None = None, optimisation_task: str | Sequence[float] = 'minimisation', base_ind_gen: Generator[IndividualLike, None, None] | None = None, tell_container_at_init: bool | str = False, add_default_logger: bool = False, name: str | None = None, **kwargs)[source]¶
Combine a candidate generator, an evaluation budget, and an archive.
The container resolves objective and descriptor vectors and controls admission. The optimiser generates genomes and consumes feedback. Ask and tell support an application-managed evaluator. Optimise adds scheduling, timing, and callbacks to the same protocol.
- Parameters:
container – Archive used for admission and best-candidate queries.
budget – Candidate evaluations available to each managed run.
batch_size – Candidates in one iteration and maximum number pending at once. Defaults to the budget.
dimension – Genome length for algorithms that generate vectors.
nb_objectives – Objective count. When omitted, infer it from the container’s fitness domain or use one objective.
optimisation_task – Minimise, maximise, or supply one finite comparison weight per objective.
base_ind_gen – Iterator supplying a fresh candidate for each ask.
tell_container_at_init – Feed stored entries to the algorithm when true or
"yes". Use"parents"to feed entries from immediate parents and pass their child membership to the hook.add_default_logger – Attach the shared console logger.
name – Name for callbacks, logs, and saved result metadata.
- add_callback(event: str, fn: Callable) None[source]¶
Attach a callable fn to the optimiser. fn will be called each time the event specified in event occurs.
Parameters¶
- param event:
str The event triggering the callback. Can be either ‘ask’, ‘tell’, ‘iteration’ (when an iteration finishes) ‘started_optimisation’, or ‘finished_optimisation’.
- param fn:
Callable The callback function called when the event specified in event occurs.
- ask() IndividualLike[source]¶
Return the next candidate for evaluation.
Create the base individual, let the subclass propose its genome, assign a name if empty, increment the suggestion counters, and invoke ask callbacks. Keep the suggested object available when sending feedback to a wrapper with multiple emitters.
- property batch_size: int¶
Configured candidate count per iteration, or the current budget when omitted.
- best() IndividualLike[source]¶
Return the best retained candidate.
- Raises:
RuntimeError – If the container has no candidates.
- property nb_evaluations: int¶
Number of tell calls or candidate slots consumed by the managed scheduler.
- property nb_suggestions: int¶
Number of candidates returned by ask since initialisation or reinitialisation.
- property nb_updated: int¶
Number of evaluations for which the archive reported a local update.
- property optimisation_task: str | Sequence[float]¶
The objective direction or explicit comparison weights.
- optimise(evaluate: Callable, budget: int | None = None, batch_mode: bool = True, executor: ExecutorLike | None = None, send_several_suggestions_to_fn: bool = False, max_nb_suggestions_per_call: int = 10, verbose: bool = False) IndividualLike[source]¶
Manage evaluation and return the best candidate in the archive.
A single-candidate evaluator can return a fitness and descriptor pair, that pair followed by named scores, or an evaluated individual. Return an empty sequence after updating the supplied object in place during in-process execution. A packed evaluator receives a list and returns one such result per candidate in the same order.
Both the budget and batch size count candidates. A failed evaluation or malformed group consumes its dispatched slots. Results are consumed in completion order, which can affect archive-dependent searches. Iteration callbacks run after full batches.
- Parameters:
evaluate – Callable executed for each candidate or packed group.
budget – Optional override of the configured budget.
batch_mode – Wait for the current batch before asking for the next one. In steady state, refill available slots as work completes.
executor – Evaluation executor. Defaults to in-process sequential execution. The caller manages any supplied executor’s lifetime.
send_several_suggestions_to_fn – Pass a list per evaluator call.
max_nb_suggestions_per_call – Positive cap on a packed call.
verbose – Emit archive validation warnings.
- Returns:
The best retained candidate after the run.
- Raises:
RuntimeError – If no candidate is available to return.
ValueError – If the budget is missing or a positive run has an invalid batch size or packed-call limit.
- reinit() None[source]¶
Reset counters for suggestions, evaluation, and archive updates.
This base method leaves the archive and callbacks in place. Subclasses may also reset their generator or optimiser state.
- tell(individual: IndividualLike, fitness: Any | None = None, features: FeaturesLike | None = None, scores: ScoresDictLike | None = None, elapsed: float | None = None, verbose: bool = False, tell_container=True) bool[source]¶
Report an evaluated candidate and offer it to the container.
A call updates the candidate’s supplied evaluation attributes. The container applies comparison weights to raw objective values. The algorithm’s pre-admission hook may add feedback metadata or decline insertion. Feedback and evaluation counters still run when archive insertion is disabled.
- Parameters:
individual – Candidate associated with this evaluation.
fitness – Objective values or a fitness object. If omitted, use the candidate’s existing or named fitness.
features – Descriptor values or a descriptor object.
scores – Named scores to store on the candidate first.
elapsed – Evaluation duration in seconds.
verbose – Report archive validation warnings.
tell_container – Permit an archive update.
- Returns:
Whether the container reported a local update.
- Raises:
ValueError – If the objective count differs from the configured count.
- tell_container_entries(cont: Container | None = None) None[source]¶
Send stored entries to the optimiser’s internal feedback hook.
- Parameters:
cont – Source of the warm-start entries. Defaults to the optimiser’s own archive.
Entries are marked as accepted for the hook. Archive admission, evaluation counters, and tell callbacks are bypassed.
- class qdpy.algorithms.RandomUniform(container: Container, budget: int, ind_domain: Tuple[float, float], **kwargs)[source]¶
Generate independent uniform genome coordinates.
Set
dimensionto the genome length andind_domainto the common interval. The generator uses Python’s random state.
- class qdpy.algorithms.RandomSearchMutPolyBounded(container: Container, budget: int, dimension: int, ind_domain: Tuple[float, float] = (0., 1.), sel_pb: float = 0.5, init_pb: float = 0.5, mut_pb: float = 0.2, eta: float = 20., *, parent_selector=tools.sel_random, **kwargs)[source]¶
Alternate uniform initialisation and bounded polynomial mutation.
Initialisation samples each coordinate independently from
ind_domain. Mutation selects an archived genome, copies it, and applies Deb’s bounded polynomial operator.- Parameters:
sel_pb – Probability of selecting for variation in a nonempty archive.
init_pb – Probability of uniform initialisation in a nonempty archive.
mut_pb – Independent mutation probability per coordinate.
eta – Polynomial distribution index. Larger values concentrate changes near the parent.
ind_domain – Common lower and upper genome coordinate bounds.
parent_selector – Callable drawing one archived parent. Defaults to a uniform draw.
- class qdpy.algorithms.CuriosityMutPolyBounded(container: Container, budget: int, dimension: int, ind_domain: Tuple[float, float] = (0., 1.), *, score_name: str = 'curiosity', default_score: float = 0.01, reward: float = 1., penalty: float = 0.5, init_pb: float = 0.5, mut_pb: float = 0.2, eta: float = 20., **kwargs)[source]¶
Use named curiosity scores to select parents for polynomial mutation.
Update the proposing parent’s score by
rewardwhen the archive reports an update, or subtractpenaltyon rejection. Uniform initialisation has no parent to credit. Feedback is applied in tell order on the coordinator, including when workers return a new object.- Parameters:
score_name – Name of the curiosity score stored on parents.
default_score – Initial curiosity for an unscored parent.
reward – Nonnegative credit for an archive update.
penalty – Nonnegative amount to subtract on rejection.
init_pb – Probability of uniform initialisation with a nonempty archive.
mut_pb – Independent mutation probability per coordinate.
eta – Distribution index for bounded polynomial mutation.
ind_domain – Common lower and upper genome bounds.
- class qdpy.algorithms.RandomSearchMutGaussian(container: Container, budget: int, dimension: int, sel_pb: float = 0.5, init_pb: float = 0.5, mut_pb: float = 0.2, mu: float = 0., sigma: float = 1.0, *, ind_domain: Tuple[float, float] | None = None, **kwargs)[source]¶
Initialise and mutate real-valued genomes with a Gaussian.
The mean and standard deviation are
muandsigma. Mutation adds a Gaussian draw to each selected coordinate with probabilitymut_pb. An explicitind_domainclips both initialisation and mutation. The default search is unbounded.
- class qdpy.algorithms.Lambda(container: Container, budget: int, ask: Callable[[], IndividualLike] | Callable[[IndividualLike], IndividualLike], tell: Callable | None = None, **kwargs)[source]¶
Build an algorithm from user-supplied ask and optional tell functions.
The ask function can return a genome or accept and return a base individual. A tell function receives the evaluated individual and the container’s update flag.
- class qdpy.algorithms.AlgorithmLogger(algorithms: QDAlgorithmLike | Sequence[QDAlgorithmLike] = (), iteration_filenames: str | Callable = 'iteration-%i.p', final_filename: str = 'final.p', final_hdf_filename: str | None = None, save_period: int = 0, verbose: bool = True, log_base_path: str = '.', config: Any = None, saved_dict: Mapping | None = None, tabs_size: int = 5, stats: Sequence[LoggerStat] = ())[source]¶
Collect evaluation and iteration records through optimiser callbacks.
Evaluation records include the incumbent’s raw objectives, archive size, and duration. The objective columns are named
max0,max1, and so on, including in minimising runs. Missing objective values in mixed runs are represented by NaN.Display an unavailable normalised QD score as
N/Aand store it asnanin the iteration table so it can be read as a number.Set
save_periodto write periodic iteration snapshots, or zero to disable them.final_filenamecontrols the final pickle snapshot.final_hdf_filenameoptionally writes evaluation and iteration tables with the HDF5 extra.A saved result contains the archive, metrics, and supplied config where available. Continue a current experiment with an explicit warm start when needed. Result logs do not capture all evaluator and random generator state.
- property evals: DataFrame¶
The recorded evaluation statistics as a data frame.
- property iterations: DataFrame¶
The recorded iteration statistics as a data frame.
- monitor(algorithms: QDAlgorithmLike | Sequence[QDAlgorithmLike]) None[source]¶
Attach evaluation, iteration, start, and finish callbacks to the specified optimisers.
- register_stat(*stat: LoggerStat) None[source]¶
Register one or more LoggerStat entries on this logger.
- class qdpy.algorithms.LoggerStat(name: str, fn: Callable, every_iteration: bool = True)[source]¶
Describe a named custom statistic.
With
every_iteration=True, the callable receives the optimiser. Otherwise it receives the optimiser and the evaluated individual. The returned value is stored in the corresponding table.
- AlgorithmLogger.save(output_path: str, output_type: str = 'pickle') None¶
Serialize a result dictionary and replace the destination atomically.
Write the new pickle to a temporary file in the destination directory. Preserve the previous result if serialisation or replacement fails.
- Parameters:
output_path – Destination file in an existing directory.
output_type – Output format. The supported value is
pickle.
- Raises:
ValueError – If another output type is requested.
Containers¶
Use a Container to retain candidates within their domains, a
Grid to retain elites by descriptor cell, and a
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.
- class qdpy.containers.Container(iterable: Iterable | None = None, storage_type: str | MutableSequence[T] | SimpleOrderedSet[T] | Type[MutableSequence[T] | SimpleOrderedSet[T]] = list, parents: Sequence[ContainerLike] | None = None, fitness_domain: Sequence[Tuple[float, float]] | None = None, features_domain: Sequence[Tuple[float, float]] | None = None, fitness_score_names: Sequence[str] = (), features_score_names: Sequence[str] = (), fitness_weights: Sequence[Any] | ndarray | None = None, capacity: float | None = None, name: str | None = None, only_add_accepted_inds_to_parents: bool = False, disable_parents_pickling: bool = True, **kwargs: Any)[source]¶
Store evaluated candidates subject to capacity and domain bounds.
Each declared objective and descriptor coordinate has a closed interval. Omit a domain to leave its vector unbounded. An evaluated candidate needs nonempty fitness without NaN values.
- Parameters:
iterable – Initial candidates, admitted in order by update.
storage_type – Storage implementation or supported storage name. The default list compares genomes for duplicates. Use
"orderedset"for indexed lookup when candidates are hashable and their genomes stay unchanged while stored.parents – Archives offered candidates for evaluation history.
fitness_domain – One closed interval per objective.
features_domain – One closed interval per behaviour descriptor.
fitness_score_names – Named scores used as objectives, in order.
features_score_names – Named scores used as descriptors, in order.
fitness_weights – Comparison weights to apply in this container.
capacity – Total local capacity. None allows unbounded storage.
name – Display name used by loggers and configuration.
only_add_accepted_inds_to_parents – Forward local admissions only. Otherwise a rejected local candidate can reach the parents.
disable_parents_pickling – Omit parent links from result files by default. Set false to keep the immediate links.
The archive stores candidate objects. Mutate a copy during variation, and serialise archive updates through the controlling process.
- add(individual: IndividualLike, raise_if_not_added_to_parents: bool = False) int | None[source]¶
Validate one candidate and return its local storage index.
An equal entry can return its existing index. Grid and novelty subclasses can decline a candidate locally and return None. Pass
raise_if_not_added_to_parents=Trueto propagate parent insertion failures and preserve the current local entry. A failure across built-in parents restores the earlier branch contents. Custom parents are responsible for their own external side effects.
- property best: Any¶
Return the best individual.
- property best_features: FeaturesLike | None¶
Return the features values of the individual with the best quality, or None.
- property best_fitness: FitnessLike | None¶
Return the fitness values of the individual with the best quality, or None.
- clear(also_from_parents: bool = False) None[source]¶
Remove all local entries and refresh the cached best.
With
also_from_parents=True, remove matching local entries from the parents as well. Parent-only entries may remain.
- discard(individual: IndividualLike, also_from_parents: bool = False) None[source]¶
Remove the matching entry if present.
Use
also_from_parentsto request removal from parent history as well. Removing the cached best triggers recomputation from the remaining entries.
- get_ind_features(individual: IndividualLike, *args, **kwargs) FeaturesLike[source]¶
Resolve the descriptor vector used by this container.
Select configured named scores in descriptor order when names are supplied. Otherwise use the candidate’s feature object.
- get_ind_fitness(individual: IndividualLike, *args, **kwargs) FitnessLike[source]¶
Resolve the fitness used by this container for admission and ranking.
Select named scores in objective order or use the candidate’s fitness. When the container applies different weights, return a weighted copy so other archives sharing the same candidate keep their own semantics.
- qd_score(normalized: bool = True) float[source]¶
Sum quality over all locally stored individuals.
With normalisation, measure each objective’s improvement from the worst domain endpoint and divide by the interval width. Use the lower endpoint for maximisation and the upper for minimisation. A collapsed interval uses a divisor of one. A populated archive with an infinite fitness bound returns NaN when normalised. An empty archive with a fitness domain has a score of zero. Use
normalized=Falseto sum raw values without applying weights.
- to_grid(shape: Tuple[int, ...] | int, max_items_per_bin: int = 1, capacity: float | None = None, **kwargs: Any) Any[source]¶
Re-admit the stored entries to a new descriptor grid.
Reuse declared domains by default. If absent, use the archive’s observed extrema. Supply explicit domains when converting an empty archive. Named score selection and fitness weights are inherited unless overridden.
- Parameters:
shape – Number of cells per descriptor coordinate.
max_items_per_bin – Maximum number of local entries in one cell.
capacity – Total capacity override. None leaves it unbounded.
kwargs – Other Grid options such as domains or storage type.
- Returns:
A new grid containing the entries it admitted.
- update(iterable: Iterable, ignore_exceptions: bool = True, issue_warning: bool = False) int[source]¶
Offer each candidate for insertion and count reported local indexes.
The count can include an existing equal entry. Use the change in
nb_addedto count actual insertions. Withignore_exceptions=True, validation failures can be offered to parents instead. Setissue_warning=Trueto report them. Capacity and parent storage errors can still propagate.
- class qdpy.containers.Grid(iterable: Iterable | None = None, shape: Tuple[int, ...] | int = (1,), max_items_per_bin: int = 1, fitness_domain: Sequence[Tuple[float, float]] | None = ((0., np.inf),), discard_random_on_bin_overload=False, **kwargs: Any)[source]¶
Retain quality-diversity elites in a rectangular descriptor grid.
Each descriptor coordinate maps into a discrete bin, and the coordinates together identify a cell. Both boundaries are included. The upper boundary of an axis maps to its final bin.
An occupied cell with spare space can accept another genome. At capacity the candidate must dominate the selected incumbent, unless random replacement is configured. With multiple objectives the incumbent comparisons use Pareto dominance and storage order. This policy retains cell representatives without maintaining a full Pareto front.
- Parameters:
iterable – Initial candidate sequence.
shape – Number of cells along each descriptor axis.
max_items_per_bin – Local capacity of each cell.
fitness_domain – Closed intervals for the objective vector.
discard_random_on_bin_overload – Replace a random member when the selected cell is full.
kwargs – Container options. Provide
features_domainwith one interval per axis. The default total capacity is the number of cells times the per-cell capacity.
- property best_index: Tuple[int, ...] | None¶
Stored cell index of the cached best individual, or None for an empty grid.
- property filled_bins: int¶
Return the number of filled bins of the container.
- index_grid(features: FeaturesLike) Tuple[int, ...][source]¶
- index_grid(scores: ScoresDictLike) Tuple[int, ...]
- index_grid(ind: IndividualLike) Tuple[int, ...]
Return a cell index from an individual, descriptors, or named scores.
Individuals use this grid’s descriptor accessor. A score mapping requires
features_score_names. The regular grid includes both endpoints and places the upper endpoint in the last bin.- Raises:
IndexError – If descriptors have the wrong length or exceed their domain.
RuntimeError – If a score mapping lacks configured names.
- qd_score(normalized: bool = True) float[source]¶
Sum quality across the grid.
By default use the normalised fitness of one representative per occupied cell, with direction determined by each objective’s weight sign. A populated grid with an infinite fitness bound returns NaN when normalised. An empty grid has a score of zero. With
normalized=False, sum raw objective values across all stored entries, including multiple entries in one cell.
- property quality: MutableMapping[Tuple[int, ...], FitnessLike | None]¶
One representative fitness object per cell, or None when empty.
- property quality_array: ndarray¶
Array of representative raw fitness values with objectives on the last axis.
Empty cells contain NaN. For one objective, use
quality_array[..., 0]to get the descriptor-shaped fitness surface.
- class qdpy.containers.CVTGrid(iterable: Iterable | None = None, shape: Tuple[int, ...] | int = (1,), max_items_per_bin: int = 1, grid_shape: Tuple[int, ...] | int | None = None, nb_sampled_points: int = 50000, *, centroids=None, **kwargs: Any)[source]¶
Assign descriptors to the nearest fitted centroid.
Sample a uniform set of points inside the specified feature domain, then fit one k-means centroid per cell. Retain individuals with the same admission policy as Grid. Centroid fitting uses NumPy’s random state, so seed it before constructing the grid for a repeatable setup.
- Parameters:
shape – Number of centroid cells as an integer or a one-item sequence.
grid_shape – Optional legacy shape with one entry per descriptor. The descriptor domain determines dimensionality when omitted.
nb_sampled_points – Number of samples used to fit the centroids.
centroids – Optional precomputed matrix with one row per cell and one column per descriptor. Omit to fit centroids by sampling.
kwargs – Grid options including the descriptor domain.
- qdpy.containers.generate_centroids(count, features_domain, *, method='sobol', seed=0, blue_noise_candidates=32)[source]¶
Generate sites for
CVTGrid(centroids=...)without changing its default geometry.Scramble Sobol and Halton sequences. Any positive count is supported. For Sobol, retain the prefix of the next power-of-two block. Blue noise starts uniformly and repeatedly selects the best-separated candidate from a fresh uniform pool. Separation is measured in normalized coordinates before applying the requested physical bounds.
- class qdpy.containers.ParetoGrid(iterable=None, *, shape, max_items_per_bin, fitness_domain, features_domain, fitness_weights=None, name=None, truncation='random')[source]¶
A descriptor grid with configurable truncation of overfull Pareto fronts.
Configure the objective directions before adding candidates. Bounds and bin geometry follow Grid. This archive uses local storage without parents.
- Parameters:
shape – Number of bins along each descriptor coordinate.
max_items_per_bin – Maximum number of nondominated entries per cell.
fitness_domain – One interval per objective.
features_domain – One interval per descriptor coordinate.
fitness_weights – Signed weights. The default minimises each objective.
truncation – Choose “random”, normalized “crowding”, or “hypervolume” contribution with two objectives and finite fitness intervals.
- cell_hypervolume(cell, reference)[source]¶
Return the front’s hypervolume with a reference in raw objective units.
- class qdpy.containers.LocalParetoArchive(iterable=None, *, radius, descriptor_size, fitness_weights, fitness_domain=None, capacity=None, name=None)[source]¶
Apply the fixed-radius MOUR-QD admission rule in descriptor units.
Each candidate competes with incumbents at Euclidean distance strictly below the radius. A dominated candidate leaves the archive unchanged. Otherwise it enters and removes every incumbent it dominates nearby. Equal genomes keep their first retained evaluation. Distinct genomes with equal objective values can coexist.
- Parameters:
iterable – Initial candidates, admitted in the supplied order.
radius – Positive finite distance threshold.
descriptor_size – Number of finite descriptor coordinates.
fitness_weights – Two or more signed, finite nonzero weights.
fitness_domain – Optional intervals in raw objective units.
capacity – Optional limit on archive entries. At capacity, a new entry must replace at least one incumbent.
name – Display name used by loggers.
- class qdpy.containers.TDominOGrid(iterable=None, *, shape, fitness_domain, features_domain, anchor_capacity=10, neighbor_radius=4, **kwargs)[source]¶
T-DominO admission following Gaier et al. (PPSN 2022).
Compare challenger and incumbent to the challenger and to present and historical elites in the cell and its neighborhood. For each objective count how many anchors the candidate matches or beats, then multiply the counts. The incumbent remains on a tie. Store the raw multiobjective measurements for reporting.
- Parameters:
iterable – Optional measured individuals to offer in order.
shape – Number of cells along each descriptor axis.
fitness_domain – Raw bounds for at least two objectives.
features_domain – Bounds for each descriptor axis.
anchor_capacity – Maximum displaced objective vectors retained per cell.
neighbor_radius – Maximum coordinate difference in bins to include.
kwargs – Other Grid configuration, including fitness_weights.
- class qdpy.containers.SlidingBoundariesGrid(iterable=None, *, remap_frequency=100, buffer_capacity=1000, **kwargs)[source]¶
Best-only MAP-Elites grid with periodically updated internal bin edges.
Valid offers enter the bounded FIFO even when they lose local competition. A remap recomputes descriptor quantiles and replays old elites and the buffer with the new bin edges. Finite declared outer bounds stay fixed. Tied quantiles can leave zero-width cells. Treat offered objects as immutable while the grid can still replay them.
- Parameters:
remap_frequency – Number of valid offers between remaps.
buffer_capacity – Maximum number of recent offers retained for remapping.
kwargs – Native Grid shape, descriptor and objective settings. This grid uses one elite per bin and owns its storage.
- property bin_edges¶
Return one immutable sequence of physical edges per axis.
- property remaps¶
Return the number of committed boundary rebuilds.
- class qdpy.containers.AutoScalingGrid(iterable: Iterable | None = None, shape: Tuple[int, ...] | int = (1,), max_items_per_bin: int = 1, scaling_containers: Sequence[Container] = (), fitness_scaling: bool = True, features_scaling: bool = True, rescaling_period: int = 1, **kwargs: Any)[source]¶
Rebuild a grid as its observed objective or descriptor ranges change.
Each enabled axis family is checked independently. The first finite descriptor vector can bootstrap initially unbounded axes before the normal rescaling interval. With
rescaling_period <= 0, automatic rescaling is disabled.- Parameters:
scaling_containers – Preferred source of records on rebuild. If empty, use immediate parents or the entries in this grid.
fitness_scaling – Update the objective bounds.
features_scaling – Update descriptor bounds and cell widths.
rescaling_period – Candidate interval between automatic rescale checks after a rebuild.
- rescale(fitness_domain: Sequence[Tuple[float, float]], features_domain: Sequence[Tuple[float, float]]) None[source]¶
Rebuild the cells with explicit objective and descriptor bounds.
Read records from scaling containers, parents, or the retained grid before clearing it. Reapply admission to those records in order. Entries that fail readmission are omitted from the rebuilt grid.
- class qdpy.containers.NoveltyArchive(iterable: Iterable | None = None, k: int = 15, threshold_novelty: float = 0.01, novelty_distance: str | Callable = 'euclidean', parents: Sequence[ContainerLike] = [], *, indexed: bool = False, **kwargs: Any)[source]¶
Retain novel or locally better candidates using parent history.
Compute novelty from up to
knearest reference entries. The archive’s descriptor accessor is used on both sides of the distance, including when the descriptor vector comes from named scores. With no neighbours, admit a valid candidate. Otherwise admit when mean distance exceedsthreshold_noveltyor the candidate dominates its nearest neighbour.A dominating candidate can replace the neighbour in the child only when that neighbour has a local entry. The parent keeps its record. Attach a parent archive before adding to a result restored without parent links.
- Parameters:
indexed – Enable an exact Euclidean parent index. The index validates live descriptors and reuses an unchanged prefix between queries. Other metrics continue to use the ordinary scan.
- class qdpy.containers.SelfAdaptiveNoveltyArchive(iterable=None, *, k_resolution: float = 60000, threshold_update_period: int = 256, max_threshold_samples: int = 2048, min_threshold: float = 1e-12, seed: int = 0, **kwargs)[source]¶
Re-estimate an NSLC novelty threshold as the reference set grows.
Use the sampled Euclidean diameter divided by the square root of
k_resolution, floored bymin_threshold. The initial threshold is used until two parent entries are available. Recompute before everythreshold_update_period-th valid local query. The default Euclidean admission rule and parent replacement semantics still apply.- Parameters:
k_resolution – Positive scale parameter for the diameter heuristic.
threshold_update_period – Valid query count between updates. Zero disables them.
max_threshold_samples – Maximum number of parents used in a diameter estimate.
min_threshold – Lower bound for the computed threshold.
seed – Seed for sampling parents, independent of the search RNG.
- class qdpy.containers.Population(iterable: Iterable | None = None, capacity: float | None = None, **kwargs: Any)[source]¶
Keep a fixed-size population in insertion order.
A new genome at capacity evicts the oldest local entry after required parent admission succeeds. Equal genomes keep their existing entry. A parent-only offer leaves the population intact.
- class qdpy.containers.ContainerDecorator(container: ContainerLike, name: str | None = None, **kwargs: Any)[source]¶
Forward the archive interface to a wrapped container.
Subclasses can intercept admission or transform measurements while retaining the underlying collection and storage configuration.
- class qdpy.containers.base.ContainerLike(*args, **kwargs)[source]¶
Structural interface for archives and archive decorators.
Optimisers use the archive’s fitness and descriptor accessors, even when a candidate carries a separate fitness object or named scores.
- class qdpy.containers.base.SimpleOrderedSet(iterable: Iterable | None = None)[source]¶
Store unique hashable entries in insertion order with integer indexing.
Equality controls uniqueness. Re-adding an equal entry keeps the original entry and index. Keep the hash-relevant part of a genome unchanged while stored.
Learned descriptors¶
Install PyTorch to use joint autoencoder training. See MC-AURORA with learned descriptors for a runnable search with fixed grids and a shared depot.
- class qdpy.containers.MCAurora(grids, training_container, *, base_scores=None, observation_score=None, models=None, training_period: int = 512, epochs: int = 5, batch_size: int = 128, learning_rate: float = 1e-3, quantile_transform: bool = True, diversity: str = 'none', diversity_weight: float = 0., rebuild_from: str = 'elites', max_training_samples: int | None = None, seed: int = 0)[source]¶
Coordinate a multi-container AURORA search on a shared observation depot.
Pass distinct, initially empty fixed grids and a separate training container. Each wrapped grid forwards evaluated candidates to the depot, including local rejects. Use
archivesas the containers of ordinary ask/tell optimisers, for example with an alternating wrapper. The coordinator keeps training and archive updates on the calling thread. Evaluation workers only need to return fitness and observations.- Parameters:
grids – Fixed
Gridinstances to wrap.training_container – Shared archive of evaluated observations.
base_scores – Ordered scalar score names to encode.
observation_score – Name of one fixed-shape numeric observation.
models – Optional autoencoder per grid, with encoder and decoder. The default is a dense autoencoder with a tanh output.
training_period – Depot growth between scheduled refits. A value of zero enables manual training only.
epochs – Training epochs per refit.
batch_size – Target training batch size.
learning_rate – Adam learning rate.
quantile_transform – Map latent coordinates into the unit interval.
diversity – One of
none,outputs,covariance, orcorrelation.diversity_weight – Weight subtracted times the diversity reward. A positive weight penalises off-diagonal covariance.
rebuild_from – Reinsert the full
depotinto all grids or rebuild from each grid’s ownelites. An empty grid starts from the depot on the first refit in either mode.max_training_samples – Optional cap on records used per refit. All rebuild records are encoded even when training uses a sample.
seed – Seed for model creation, training and depot sampling. Seed the search RNG and any stochastic evaluator separately.
- fit() MCAuroraTraining[source]¶
Train the full ensemble from the current depot and rebuild its grids.
The live models, grids and training history are installed only after training, encoding and staged readmission succeed for every grid. Train and call ask/tell serially on the coordinator.
- retrain_if_needed() MCAuroraTraining | None[source]¶
Train when the depot crosses a new multiple of the training period.
- class qdpy.containers.MCAuroraTraining(depot_size: int, sample_size: int, reconstruction: float, diversity: float, loss: float)[source]¶
One completed refit, with separate reconstruction and diversity terms.
depot_sizecounts available records.sample_sizecounts records actually used for training and quantile fitting.diversityis the reward before applying the configured weight.lossis the resulting mean training objective.
Candidates and their scores¶
An Individual holds the genome as a list and stores scores separately.
Fitness applies objective weights when comparing individuals.
Features holds the descriptor vector. With fitness_score_names or
features_score_names, a container can select the relevant entries of a
ScoresDict.
- class qdpy.phenotype.Individual(iterable: Iterable | None = None, name: str | None = None, fitness: FitnessLike | None = None, features: FeaturesLike | None = None, scores: ScoresDictLike | None = None)[source]¶
Store a mutable genome with separate evaluation results.
The list contents are the genome. Fitness, descriptors, named scores, elapsed evaluation time, and the name are stored separately. Genome equality is independent of those measurements.
Keep the genome unchanged while the candidate is in an archive. Use a copy for mutation or remove the candidate before editing it. Updating the descriptor of a stored individual does not relocate its grid cell automatically.
- dominates(other: Any, score_name: str | None = None) bool[source]¶
Compare fitness or the specified named score by dominance.
Without a score name, compare the attached fitness objects. With a name, both candidates must supply a score with a dominance operation at that key.
- property features: FeaturesLike¶
Descriptor object attached to this candidate.
- property fitness: FitnessLike¶
Fitness object attached to this candidate.
- reset() None[source]¶
Clear named scores and reset the attached fitness, descriptors, and elapsed time.
- property scores: ScoresDictLike¶
Named measurements attached to this candidate.
- class qdpy.phenotype.Score(values: Sequence[Any] | ndarray = (), *args, **kwargs)[source]¶
Represent an ordered vector of measurements.
The sequence interface exposes the stored values. Equality and ordering operators use raw values. Use
dominates()for Pareto comparisons. An empty vector represents missing measurements.- dominates(other: Any, obj: Any = slice(None), weights: Sequence[Any] | ndarray | None = None) bool[source]¶
Compare two score vectors by Pareto dominance.
Every selected value must be at least as good as its counterpart, and at least one must be strictly better. A plain score treats larger values as better. A fitness uses objective weights.
- Parameters:
other – Score to compare against.
obj – Slice selecting the objectives to compare.
weights – Optional comparison weights applied to both vectors.
- Raises:
ValueError – If the selected vectors have different lengths.
- class qdpy.phenotype.Fitness(values: Sequence[Any] | ndarray = (), weights: Sequence[Any] | ndarray | None = None)[source]¶
Store raw objectives and their comparison weights.
Supply one weight per objective. Negative weights minimise and positive weights maximise. A weight of zero ignores its objective in a weighted comparison. The default is minimisation.
Assigning weights keeps the raw objective values unchanged. Empty fitness and fitness containing NaN are invalid. Use container domains to specify which otherwise valid scores may enter an archive.
- property valid: bool¶
Whether the fitness has at least one objective and contains no NaN values.
- property values: Sequence[Any] | ndarray¶
Objective values before applying weights.
- class qdpy.phenotype.Features(values: Sequence[Any] | ndarray = (), *args, **kwargs)[source]¶
Hold the ordered behaviour descriptors of a candidate.
Descriptor coordinates are separate from objectives. A grid expects the vector length and coordinate domains declared by its configuration.
- class qdpy.phenotype.ScoresDict[source]¶
Store named measurements that can supply objectives or descriptors.
Containers select measurements in their configured name order. A missing name yields NaN, which fails validation in a bounded descriptor domain or as fitness.
- select(names: Sequence[str]) Sequence[Any][source]¶
Return values in name order and use NaN for missing names.
- to_features(names: Sequence[str], *args, **kwargs) FeaturesLike[source]¶
Build a descriptor vector in the requested name order.
- to_fitness(names: Sequence[str], *args, **kwargs) FitnessLike[source]¶
Build a fitness vector in the requested name order.
The following protocols describe the interfaces used by optimisers and archives. Custom candidate and measurement classes can implement them.
- class qdpy.phenotype.IndividualLike(*args, **kwargs)[source]¶
Describe the candidate interface accepted by native QD algorithms.
A candidate exposes a mutable genome, fitness, descriptors, scores, and a reset operation. Implementations used in hash-based containers also need stable equality and hashing while stored.
- class qdpy.phenotype.FitnessLike(*args, **kwargs)[source]¶
Fitness protocol inspired from (and compatible with) DEAP Fitness class.
Novelty 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.
- qdpy.metrics.features_distances(individual: IndividualLike, container: Sequence, dist: str | Callable = 'euclidean', *, get_features: Callable | None = None) Sequence[source]¶
Measure distance from a candidate to each reference entry.
- Parameters:
individual – Candidate to compare.
container – Reference entries in the order to report.
dist – The string
"euclidean"or a callable taking two descriptor vectors.get_features – Descriptor accessor. Defaults to the candidate’s
featuresattribute.
- Returns:
A one-dimensional NumPy array in reference order.
- Raises:
ValueError – If a metric name is unsupported or descriptor dimensions differ.
- qdpy.metrics.novelty(individual: IndividualLike, container: Sequence, k: int = 1, dist: str | Callable = 'euclidean', ignore_first: bool = False, default_novelty: float = 0.1) float[source]¶
Return the mean distance to the nearest scored neighbours.
- Parameters:
individual – Candidate whose descriptors define the query.
container – Reference entries.
k – Maximum number of neighbours in the mean.
dist – Metric accepted by
features_distances().ignore_first – Skip the closest entry before selecting neighbours. Use it when the reference includes the query.
default_novelty – Result when no neighbours are scored.
- Returns:
The mean over the neighbours that are available.
- qdpy.metrics.novelty_nn(individual: IndividualLike, container: Sequence, k: int = 1, nn_size: int = 1, dist: str | Callable = 'euclidean', ignore_first: bool = False, default_novelty: float = np.inf, *, get_features: Callable | None = None) Tuple[float, Sequence][source]¶
Return novelty and the indexes of the nearest entries.
The novelty calculation uses up to
kneighbours independently of the requested number of returned indexes. Ties in distance keep reference order. Whenignore_firstis true, both operations skip the closest entry.- Parameters:
nn_size – Maximum number of neighbour indexes to return.
default_novelty – Fallback score when the mean has no entries.
get_features – Optional accessor for the query and reference descriptors. Archives use this to compare named descriptors.
- Returns:
A novelty score and indexes into the reference sequence.
- qdpy.metrics.novelty_local_competition(individual: IndividualLike, container: Sequence, k: int = 1, dist: str | Callable = 'euclidean', ignore_first: bool = False, default_novelty: float = 0.1, default_local_competition: float = 1.0) Tuple[float, float][source]¶
Return novelty and the fraction of requested neighbours outperformed.
Compare the query’s fitness to each nearest neighbour using dominance. Divide the number outperformed by
keven when fewer neighbours are available. The novelty mean uses the actual number of neighbours available.ignore_firstskips the closest entry.Return
(default_novelty, default_local_competition)when no neighbours are scored.
Multi-archive metrics¶
- qdpy.metrics.archive_originality(archives, *, key=tuple) tuple[float, ...][source]¶
Return each archive’s fraction of distinct solutions exclusive to it.
The default identity is the genome tuple. Provide a hashable key for candidates with nested or otherwise unhashable genes. Multiple copies inside one archive count once. An empty archive contributes zero.
- qdpy.metrics.archive_overlap(archives, *, key=tuple) ndarray[source]¶
Return pairwise Jaccard overlap in archive order.
Two empty archives have overlap one. A pair with one empty and one populated archive has overlap zero. By default, compare genome tuples.
- qdpy.metrics.pairwise_kl_coverage(reference, compared, *, coordinate_pairs=None, bins: int = 10, ranges=None, pseudocount: float = 1e-12) float[source]¶
Compare descriptor distributions on explicit two-dimensional projections.
Use common histogram edges for both inputs. With no explicit ranges, derive the edges from both samples together. Explicit ranges must contain every observation. Smooth the counts before normalising each histogram. Smaller values indicate more similar distributions.
Language model workflows¶
- class qdpy.algorithms.NeighborhoodElites(context, *, edits=('distractor', 'reorder', 'style'), support=('direct', 'paraphrastic', 'discourse', 'multi-sentence'), inherit_support=None, bootstrap=None, target_attempts=2, coverage_patience=5, seed=0)[source]¶
Use a staged targeted scheduler with caller-defined rewrite strategies and checks.
- Parameters:
context – Original context. Bind the question and answer specification to the editor and validator callbacks.
edits – Ordered nonempty labels for the edit axis.
support – Ordered nonempty labels for the support axis. The first label is the default bootstrap target.
inherit_support – Edit labels that require a parent in the target support level. The default uses insertion and reordering labels.
bootstrap – Ordered cells to attempt from the original context.
target_attempts – Maximum attempts to fill each cell during coverage.
coverage_patience – End coverage after this many attempts with no new cell.
seed – Seed for ties in target selection.
- property entries¶
Return one immutable elite per occupied cell in axis order.
- probe(predict, *, group=None, limit=None)[source]¶
Call predict once per selected text and group answers by a hashable key.
The default groups exact answer strings. Pass a normalizer or a semantic class callback for equivalent answers. When limited, query the highest-quality elites first. Empty neighborhoods have undefined entropy.
- run(edit, assess, *, budget, refinement_reserve=0)[source]¶
Spend up to budget editor calls. Leave unused work if no action is possible.
- Parameters:
edit – Callback (parent_context, target_cell, rng) returning text or None.
assess – Callback (parent_context, rewrite, target_cell) returning (realized_cell, quality), or None when answer preservation or edit verification fails. Use the same original answer specification throughout.
budget – Maximum additional editor calls, including rejected edits.
refinement_reserve – Portion of budget reserved for occupied cells.
- property stats¶
Return cumulative construction and answer call counts.
- class qdpy.algorithms.NeighborhoodEntry(text: str, cell: tuple[str, str], quality: float)[source]¶
Store a context rewrite, its categorical cell and its quality.
- class qdpy.algorithms.NeighborhoodStats(edits: int = 0, assessments: int = 0, rejections: int = 0, admissions: int = 0, answer_calls: int = 0)[source]¶
Count attempted callbacks, rejected proposals and archive updates.
- class qdpy.algorithms.NeighborhoodProbe(answers: tuple[str, ...], entropy: float | None)[source]¶
Return raw answers and empirical semantic entropy in nats.
- qdpy.algorithms.answer_entropy(answers, *, group=None)[source]¶
Return entropy in nats, or None for an empty collection.
Pass a grouping callback that maps equivalent answers to the same hashable key. Without it, compare exact answers.
- class qdpy.algorithms.IDEAgent(*, capacity=10, thresholds=(.6, .6, .6), refinement_targets=(.9, .8, .8), repair_margin=.2, duplicate_threshold=.8, auxiliary_attempts=2, memory_size=32, seed=0)[source]¶
Run the IDEAgent lineage workflow with caller-supplied proposal and evaluation.
- Parameters:
capacity – Maximum accepted lineages.
thresholds – Inclusive non-obviousness, soundness and clarity gates.
refinement_targets – Try improving accepted entries below these scores.
repair_margin – Maximum deficit for a draft eligible for repair.
duplicate_threshold – Similarity at which two signatures share a mechanism.
auxiliary_attempts – Total repairs and refinements allowed per fresh draft.
memory_size – Maximum history signatures and rejected signatures in each store.
seed – Private seed supplied to the proposer.
- property entries¶
Return accepted ideas in lineage admission order.
- run(propose, evaluate, similarity, *, budget, refinement_preference=None)[source]¶
Continue search with an exact cap covering every proposal stage.
- Parameters:
propose – Callback (IdeaRequest, rng) returning an immutable draft or None.
evaluate – Callback (draft) returning an IdeaAssessment. Fitness scores, judgment panels and compact signatures are evaluator concerns.
similarity – Symmetric callback (signature, signature) returning [0, 1].
budget – Maximum additional drafts, including repairs and refinements.
refinement_preference – Optional callback (parent, revision) returning whether an otherwise eligible refinement should replace its parent. Use it for an independent comparison, such as judging both presentation orders.
- property stats¶
Return cumulative call and admission counts.
- class qdpy.algorithms.IdeaAssessment(signature: str, non_obviousness: float, soundness: float, clarity: float, feasibility: float, feedback: str = '', valid: bool = True, disputed: bool = False)[source]¶
Scores lie in [0, 1]. Feedback can carry observations from the evaluator.
- class qdpy.algorithms.IdeaRequest(stage: str, parent: IdeaEntry | None, active: tuple[IdeaEntry, ...], historical: tuple[tuple[int, str], ...], rejected: tuple[str, ...])[source]¶
Pass active ideas and compact historical and rejection memory.
- class qdpy.algorithms.IdeaEntry(idea: object, assessment: IdeaAssessment, lineage: int)[source]¶
Keep the caller’s immutable candidate and its measurements.
- class qdpy.algorithms.IdeaStats(proposals: int = 0, evaluations: int = 0, comparisons: int = 0, repairs: int = 0, refinements: int = 0, refinement_checks: int = 0, admissions: int = 0, rejected: int = 0)[source]¶
Track every attempted callback and archive admission.
- qdpy.algorithms.idea_yield(assessments, similarity, *, thresholds=(.6, .6, .6), duplicate_threshold=.8)[source]¶
Return the exact cardinality for a small evaluated set.
Each pair in the selected set must have similarity strictly below duplicate_threshold. The maximum clique search can be exponential. The similarity callback should be symmetric and accept signatures.
- class qdpy.algorithms.TaskArchiveSearch(archive, *, neighbors=3, failure_memory=8, seed=0)[source]¶
Adapt OMNI-EPIC’s successful/failed task archive to deterministic benchmarks.
Use a one-elite Grid or CVTGrid. The evaluator measures the result of a fixed solver or solver panel. An optional post-generation reviewer checks a solved candidate against its nearest measured tasks. This workflow leaves policy training and task representation to the caller.
- Parameters:
archive – Empty best-only, scalar maximizing Grid or CVTGrid.
neighbors – Maximum nearby examples passed to proposal and review callbacks.
failure_memory – Maximum measured unsolved tasks passed back to the proposer.
seed – Seed for parent selection and proposal callbacks.
- property entries¶
Return a snapshot of the retained measured tasks.
- property failed¶
Return bounded memory of tasks that the evaluator could not solve.
- run(propose, evaluate, *, budget, review=None)[source]¶
Spend up to budget new proposals, counting failed and duplicate proposals.
- Parameters:
propose – Callback (TaskRequest, rng) returning an immutable, hashable task or None.
evaluate – Callback (task) returning TaskAssessment, or None for an invalid encoding. A complete solver panel counts as one call.
review – Optional callback (TaskEntry, nearby_entries) returning whether a solved task qualifies for admission.
budget – Maximum additional calls to propose.
- property stats¶
Return cumulative search calls and outcomes.
- class qdpy.algorithms.TaskAssessment(quality: float, descriptors: tuple[float, ...], solved: bool, feedback: str = '')[source]¶
A solved task can compete in the archive. Feedback is available to later proposals.
- class qdpy.algorithms.TaskRequest(parent: TaskEntry | None, examples: tuple[TaskEntry, ...], failed: tuple[TaskEntry, ...])[source]¶
Pass examples from the archive or just failures when the archive is empty.
- class qdpy.algorithms.TaskEntry(task: object, assessment: TaskAssessment)[source]¶
Represent a usable archived task or a measured failed task.
Changing constraints, structured niches, fidelity, and replay¶
- class qdpy.algorithms.VariableConstraintMAPElites(archive, *, score_names, constraints, history_size=1024, propose, mutate, seed=0)[source]¶
Search and replay measured designs under inclusive score bounds.
- Parameters:
archive – Empty parentless, best-only Grid or CVTGrid with a single objective and native fitness and descriptors.
score_names – Names of the finite scalar measurements returned by every successful evaluation, including currently unused scores.
constraints – Mapping from score names to (lower, upper). Use None for an open end. Omit a name to remove its constraint.
history_size – Number of recent valid measurements to remember alongside the live elites. Zero keeps only the live elites.
propose – Callback (rng) returning an immutable hashable genome.
mutate – Callback (parent_genome, rng) returning an offspring.
seed – Seed for proposal and parent selection.
- property constraints¶
Return a copy of the active score bounds.
- class qdpy.algorithms.MagnitudeArchive(landmarks, distance, *, rank=2, capacity=256, maximize=True)[source]¶
Keep one elite per occupied landmark signature and cache elite distances.
- Parameters:
landmarks – Ordered distinct immutable and hashable descriptors.
distance – Symmetric, finite dissimilarity, zero for equal points and strictly positive for distinct points.
rank – Number of closest landmarks in each signature. Equal distances are ordered by the supplied landmark order.
capacity – Maximum number of occupied signatures. If a new niche would exceed it, evict the least magnitude-weighted candidate in the expanded set, breaking ties by fitness and admission order.
maximize – Compare larger scalar fitness values as better.
- add(genome, fitness, descriptor)[source]¶
Return whether the candidate filled or improved its niche.
- property cells¶
Return a copy of the occupied signatures and their measured elites.
- classmethod from_reference(reference, distance, *, count, **kwargs)[source]¶
Fit landmarks by trying magnitude-increasing swaps at a fixed kernel scale.
Use the first count distinct descriptors as the initial set, then try each remaining descriptor in place of the least-weighted one. The ordered reference panel is consumed once and needs no fitness.
- property landmarks¶
Return the fixed landmarks in tie-breaking order.
- property weights¶
Return a copy of the unnormalized magnitude weights by signature.
- class qdpy.algorithms.MagnitudeGoExplore(archive, *, propose, mutate, selection='magnitude', quality_weight=1., random_fraction=.1, seed=0)[source]¶
Use Huntsman’s landmark and magnitude selection with direct evaluation.
- Parameters:
archive – MagnitudeArchive to fill.
propose – Callback (rng) returning a new genome.
mutate – Callback (parent_genome, rng) returning an offspring.
selection – Use “magnitude” or the “uniform” parent control.
quality_weight – Weight of normalized fitness in parent logits.
random_fraction – Fraction of proposals sampled without a parent.
seed – Private seed for proposals and parent selection.
- qdpy.algorithms.magnitude_weights(distances, *, scale=None)[source]¶
Return the unnormalized weights of exp(-scale * distances).
- Parameters:
distances – Nonempty square symmetric array with a zero diagonal and finite positive off-diagonal values.
scale – Positive kernel scale. By default choose a scale with strict diagonal dominance and nonnegative weights.
- Raises:
ValueError – If the matrix is invalid or the requested kernel lacks a positive-definite solve with nonnegative weights.
- class qdpy.algorithms.AsyncQDHalving(archive, dimension, fidelities, *, budget, eta=3, late_fraction=.25, ind_domain=(0., 1.), propose=None, seed=0)[source]¶
Run a descriptor-aware single-ladder adaptation of asynchronous halving.
Each group of eta completed requests at one rung unlocks a promotion to the next rung. Eligible niches with fewer previous promotions go first. Within that niche choose the best measured candidate. Reserve the whole ladder’s resources up front and charge each request in full. When a rung cannot supply enough candidates, fill the next rung with direct proposals. Only the highest fidelity populates the archive.
- Parameters:
archive – Empty parentless best-only Grid or CVTGrid.
dimension – Number of real design coordinates.
fidelities – Strictly increasing positive integer resource costs.
budget – Total planned resource units, at least the highest cost.
eta – Minimum number of completed lower rung calls per promotion.
late_fraction – Fraction of promotion slots held until the upstream rung finishes, so slower niches can still compete. Keep at least one slot available to early results.
ind_domain – Common bounds for real coordinates.
propose – Optional callback (rng) for new genomes. By default draw them uniformly within ind_domain.
seed – Seed for new proposals in scheduling order.
- ask()[source]¶
Schedule the deepest ready promotion before starting new designs.
A None result with pending tickets means more completions are needed. With no pending tickets, the planned evaluation slots are exhausted. Call ask and tell from the same coordinator.
- property pending¶
Return outstanding tickets in submission order.
- property quotas¶
Return the number of evaluation slots budgeted at each fidelity.
- property reserved¶
Return resource units assigned to outstanding tickets.
- run(evaluate, *, executor=None, max_pending=1)[source]¶
Use evaluate(genome, fidelity) and return the full-fidelity archive.
With a QDpy-supported executor consume first completions and dispatch new requests up to max_pending at a time. Evaluator exceptions are warned and charged as failed attempts. The caller owns the executor’s lifetime.
- property spent¶
Return completed resource units, including failed evaluations.
- tell(request, result)[source]¶
Record (scalar fitness, descriptors) or a failed evaluation (None).
Pass back the ticket returned by ask. A malformed measurement raises and leaves the ticket pending so the caller can correct it or record a failure. Valid measurements outside the archive domain are charged.
- property trials¶
Return attempted measurements in the order accepted by tell.
- class qdpy.algorithms.FidelityRequest(id: int, genome: tuple[float, ...], fidelity: int, promoted_from: int | None = None)[source]¶
An ask/tell ticket with its target fidelity and optional promotion source.
- class qdpy.algorithms.EliteReplay(targets, *, length=len, seed=0)[source]¶
Build EliteReplay’s pre-training solution data with generic callbacks.
- Parameters:
targets – Mapping from problem IDs to ordered distinct strategy descriptors. Each descriptor is a string or tuple of string labels.
length – Callback (solution) returning its positive token count or another integer cost. The default counts characters.
seed – Seed for proposal randomness and cross-cell parent selection.
- offer(problem, solution, verify)[source]¶
Return whether the verified solution filled a cell or shortened its elite.
verify(problem, solution) independently checks correctness and returns a declared achieved descriptor or None on failure.
- run(propose, verify, *, budget, guided=True)[source]¶
Return a replay snapshot after budget additional proposal attempts.
propose(problem, target, parent, rng) returns solution text or None. When guided, request an uncovered target first, with ties favoring the least attempted target, and pass a verified parent from another cell if available. In the independent control both target and parent are None. Each attempt counts against budget.
- property stats¶
Return cumulative proposal, verifier call, success, and admission counts.
- class qdpy.algorithms.EliteReplayDataset(entries)[source]¶
Replay verified solution text independently of the search or trainer.
- Parameters:
entries – EliteReplayEntry records with unique problem/descriptor pairs.
- property entries¶
Return the immutable replay records in archive order.
Hierarchical archives, counterfactuals, and generative QD¶
- class qdpy.algorithms.HierarchicalArchive(coarse, make_fine)[source]¶
Use a fixed coarse geometry and one best-only archive per occupied niche.
- Parameters:
coarse – Empty best-only Grid or CVTGrid. Its descriptors locate a branch, and its fitness bounds and objective direction apply to each branch. The geometry stays empty.
make_fine – Callback (coarse_index) constructing a fresh empty best-only Grid or CVTGrid for that branch. Fine geometry and capacity may differ across branches. Treat returned grids as views when reading them through this archive.
- add(genome, fitness, coarse_descriptor, fine_descriptor)[source]¶
Return True if the candidate fills or improves a fine cell.
Genomes are immutable and hashable. Fine archive entries store the original genome at index zero, its measured fine features, and the coarse descriptor used to route it. Measurements outside either descriptor domain are skipped.
- alternatives(descriptor)[source]¶
Return the measured fine elites as a tuple, or an empty tuple for an empty branch.
- property subarchives¶
Return the occupied coarse indices and their fine archives.
- class qdpy.algorithms.HierarchicalMAPElites(archive, *, propose, mutate, random_fraction=.1, seed=0)[source]¶
Search with caller-defined initialization, mutation and evaluation.
- Parameters:
archive – HierarchicalArchive, optionally seeded.
propose – Callback (rng) returning a new genome.
mutate – Callback (parent_genome, rng) returning an offspring.
random_fraction – Probability of drawing a fresh genome when parents are available.
seed – Seed for parent selection and genome proposals.
- class qdpy.algorithms.CounterfactualEvaluator(rollout: object, references: tuple, describe: object, base: object = None)[source]¶
Call the rollout once and concatenate base and reference descriptor blocks.
- Parameters:
rollout – Callback (genome) returning (objectives, trace).
references – Ordered reference agents, trajectories, or policies.
describe – Callback (trace, reference) measuring the agent’s interaction with one virtual reference. Return a numeric vector.
base – Optional callback (trace) returning the measured agent’s descriptor block before any reference blocks.
- class qdpy.algorithms.CounterfactualMOME(container, budget, dimension, batch_size, *, ind_domain=(0.0, 1.0), iso_sigma=0.01, line_sigma=0.2, **kwargs)[source]¶
Reuse native MOME evolution and front admission with a trace evaluator.
The ParetoGrid’s descriptor domains follow the order of the optional base measurements and then the reference blocks. Virtual agents may be superimposed on one recorded trace. The rollout callback owns any simulated dynamics and computes the unchanged objective vector.
- class qdpy.algorithms.ConstructiveDAG(root, successors)[source]¶
Provide a deterministic construction graph with terminal leaves.
- Parameters:
root – Hashable starting state.
successors – Ordered mapping from every state to its distinct successors. Use an empty sequence for a terminal state. Multiple paths may lead to the same state. All states must be reachable. An explicit stop action can lead to a separate terminal node.
- property states¶
Return states in topological order starting at the root.
- property terminals¶
Return terminal states in topological order.
- class qdpy.algorithms.PreferenceGFlowNet(graph, reward, *, objectives, hidden_size=32, reward_power=1., learning_rate=.01, exploration=.15, seed=0)[source]¶
Train on a small named DAG with a fixed uniform backward policy.
The terminal target is proportional to (preference.dot(positive_objectives)) ** reward_power. The forward network and trajectory normalizer both receive the preference. Terminal objectives are cached across trajectories and audits. Import PyTorch only when a sampler is constructed.
- Parameters:
graph – ConstructiveDAG containing the legal transitions.
reward – Callback (terminal) returning the positive objective vector.
objectives – Length of the objective and preference vectors.
hidden_size – Width of the state embeddings and hidden layers.
reward_power – Temper the terminal reward with this positive power.
learning_rate – Adam step size.
exploration – Probability of a uniform transition during training.
seed – Private seed for network initialization and sampling.
- distribution(preference)[source]¶
Return exact terminal probabilities of the current forward policy.
- fit(preferences, *, updates, batch_size=64)[source]¶
Draw preferences uniformly from the supplied panel and train on sampled paths.
- illuminate(archive, evaluate, preferences, *, budget)[source]¶
Evaluate budget samples for (scalar fitness, descriptors) or None.
Cycle preferences in the given order. Archive measurements are independent of the training reward cache. Supply a parentless best-only Grid or CVTGrid, optionally populated.
- sample(preference, *, size=1)[source]¶
Return a tuple sampled from the learned policy under one preference.
- property stats¶
Return the current training and audit work counters.
- class qdpy.algorithms.GFlowNetStats(updates: int = 0, trajectories: int = 0, reward_calls: int = 0, archive_calls: int = 0, last_loss: float | None = None)[source]¶
Cumulative optimizer updates, training trajectories and evaluator calls.
- class qdpy.algorithms.SoftPromptMAPElites(archive, initial_embedding, *, sigma=.1, probe_step=.1, probe_directions=4, targeted_probability=.35, crossover_probability=.3, seed=0)[source]¶
Run the fixed-archive, callback-based variant of QD-LLM.
- Parameters:
archive – Empty parentless best-only Grid or CVTGrid.
initial_embedding – Finite 2D array with one vector per soft token.
sigma – Gaussian exploration scale per embedding coordinate.
probe_step – Length of updates along random unit probe directions.
probe_directions – Maximum number of paired probes per targeted update.
targeted_probability – Probability of selecting targeted variation.
crossover_probability – Probability of interpolating two prompts.
seed – Private seed for embedding search and decoder calls.
- run(generate, evaluate, *, budget, mode='targeted')[source]¶
Fill the archive using frozen decoding and independent output assessment.
generate(embedding, seed) returns text or None. evaluate(text) returns (scalar fitness, descriptor vector) or None. Paired probes receive the same seed and can enter the archive. Choose “gaussian” for a mutation control or “fixed” to decode repeatedly from the initial embedding.
- property stats¶
Return cumulative decoding and archive work.
Constraint programming, safe exploration, and diffusion search¶
- class qdpy.algorithms.CPSATArchiveSearch(archive, model, *, objective, descriptors, time_limit=None, deterministic_time_limit=None, seed=0)[source]¶
Solve independent grid cells using an existing integer CP-SAT model.
- Parameters:
archive – Empty best-only rectangular Grid with one configured objective and room for every cell. Use finite objective and descriptor bounds within the float64 exact-integer range.
model – OR-Tools CpModel containing the design constraints.
objective – Integral linear expression over that model’s variables. The grid’s fitness direction governs the solve.
descriptors – Integral linear expressions over the model variables in grid axis order, including constant integer expressions if desired.
time_limit – Optional positive seconds per solve.
deterministic_time_limit – Optional positive CP-SAT work limit per cell.
seed – Nonnegative 32-bit CP-SAT seed. Each cell uses one worker.
- class qdpy.algorithms.CPSATCellResult(cell: tuple[int, ...], status: str, genome: tuple[int, ...] | None = None, fitness: int | None = None, features: tuple[int, ...] | None = None, objective_bound: int | float | None = None, solver_status: str | None = None)[source]¶
Report solver status, incumbent, and raw-objective bound when available.
The status is “optimal”, “feasible”, “infeasible”, or “unresolved”. The genome lists values of all model variables in model index order. Integer-empty cells are infeasible without calling the solver.
- class qdpy.algorithms.SafeBayesianIllumination(archive, points, descriptors, *, safe_seeds, constraints=1, expansion_budget=8, quality_floor=None, confidence=3., length_scale=.2, noise=1e-6, lipschitz=None, observation_error=0.)[source]¶
Use a StageOpt-inspired expansion phase and then per-niche improvement.
- Parameters:
archive – Empty parentless best-only Grid or CVTGrid.
points – Finite matrix of distinct real candidate genomes.
descriptors – Known descriptor vector for each candidate. All must lie in the reporting archive’s descriptor domain.
safe_seeds – Ordered distinct indices trusted safe to evaluate. Their evaluations count against the same budget as other trials.
constraints – Number of reported safety margins. Zero is safe.
expansion_budget – Maximum post-seed attempts in the expansion phase.
quality_floor – Raw objective baseline for an empty niche. The default uses the archive’s worst allowed objective.
confidence – Safety confidence multiplier for the Gaussian processes.
length_scale – Fixed Matérn length scale in raw decision units.
noise – Positive GP diagonal regularization.
lipschitz – Scalar or per-constraint Lipschitz upper bounds in raw Euclidean units. When supplied, use the deterministic margin certificates for dispatch and the GPs for ranking.
observation_error – Absolute bound on measurement error for each safety margin in Lipschitz mode.
- certified_indices()[source]¶
Return safe-set indices, including trusted seeds, or empty after a halt.
- property halted¶
Return whether an observed negative safety margin stopped the search.
- run(evaluate, *, budget)[source]¶
Use evaluate(genome) for (scalar fitness, safety-margin vector) or None.
Each pool candidate is evaluated at most once. Stop when no new point satisfies the safety gate or a violation is observed. The GP gate depends on calibrated confidence bounds. A Lipschitz gate depends on correct supplied constants and measurement error.
- property trials¶
Return attempts in dispatch order, including failed evaluations.
- class qdpy.algorithms.SafeIlluminationTrial(index: int, phase: str, fitness: float | None = None, margins: tuple[float, ...] | None = None)[source]¶
The phase is “seed”, “expansion”, or “illumination”.
- class qdpy.algorithms.DiffusionEvolution(container, budget, dimension, batch_size, *, ind_domain=(-1., 1.), diffusion_steps=20, temperature=.25, noise_scale=1., seed=0, **kwargs)[source]¶
Run bounded, population-only Diffusion Evolution with a reporting grid.
Shape Gaussian denoising estimates using the previous generation’s signed objective. The reporting archive fills from measured candidates and stays outside the proposal loop. Progress through a cosine schedule, then start another Gaussian population if more budget remains. Bounds and fitness scaling adapt the paper to the native fixed-generation evaluator API.
- Parameters:
container – Parentless best-only scalar Grid or CVTGrid.
budget – Number of attempted candidate evaluations.
dimension – Number of real genome coordinates.
batch_size – Maximum population size.
ind_domain – Shared finite lower and upper bounds.
diffusion_steps – Generations per cosine schedule, at least two.
temperature – Positive fitness temperature for denoising weights.
noise_scale – DDIM noise multiplier between zero and one.
seed – Private seed for Gaussian proposals and restart populations.
kwargs – Native optimizer options, such as optimisation_task.
- property diffusion_proposals¶
Return the number of candidates produced by completed denoising steps.
- class qdpy.algorithms.DiffusionMAPElites(container, budget, dimension, batch_size, *, max_elites=256, **kwargs)[source]¶
Use archive elites as references and seed particles across occupied niches.
Each reference is a genuinely measured elite. Draw an occupied cell for each particle and add forward noise at the current schedule stage. The same reverse update as DiffusionEvolution proposes offspring. Select a bounded uniform subset if the archive grows too large.
- Parameters:
max_elites – Maximum number of occupied cells in the denoising reference pool.
Execution and result files¶
- class qdpy.base.ParallelismManager(parallelism_type: str = 'multiprocessing', max_workers: int | None = None, toolbox: Any | None = None, force_worker_suicide: bool = True, *, ray_address: str | None = None)[source]¶
Open and close an evaluation executor as a context manager.
Use
noneorsequentialfor in-process evaluation,multithreadingfor a thread pool, andmultiprocessingorconcurrentfor a process pool. The process pool prefers forkserver when available and otherwise uses spawn. SCOOP and Ray require their optional runtime packages.- Parameters:
parallelism_type – Executor backend name.
max_workers – Optional worker count for the standard pools or CPU count for a local Ray runtime.
toolbox – Optional DEAP toolbox copied and bound to executor.map.
force_worker_suicide – Install the process worker’s interrupt handler.
ray_address – Optional cluster address for the Ray backend.
Process evaluation needs picklable evaluation functions and candidates. Protect executable entry points with the usual main guard.
- class qdpy.base.ExecutorLike(*args, **kwargs)[source]¶
Executor interface for submitting work, mapping a callable, and shutting down.
- class qdpy.base.FutureLike(*args, **kwargs)[source]¶
Future interface used to retrieve evaluator results and observe completion.
- qdpy.base.generic_as_completed(fs: Sequence[FutureLike], timeout: int | None = None) FutureLike[source]¶
Return the next completed future from a homogeneous nonempty sequence.
Sequential futures have already completed. Concurrent futures, SCOOP, and Ray use their respective completion mechanisms.
- Parameters:
fs – Pending futures from one backend.
timeout – Optional wait limit in seconds, passed to that backend.
- Raises:
ValueError – If the input is empty or the backend is unknown.