Search algorithms¶
For candidate-based methods, match the evaluator and archive to the algorithm’s measurement format. See Core Python API for native ask/tell and search management.
Candidate generation¶
Use uniform or Sobol proposals as a baseline. Add a variation operator when you want new candidates to depend on the current archive. A genome can use different bounds from the descriptors returned by its evaluator.
- class qdpy.algorithms.Sobol(container: Container, budget: int, ind_domain: Tuple[float, float], **kwargs)[source]¶
Propose a deterministic low-discrepancy sequence within the genome bounds.
Skip the zero vector and scale the remaining Sobol points to
ind_domain. If a run needs more points than initially buffered, extend the sequence and preserve the already consumed prefix. Reinitialising resets candidate accounting and starts the sequence again.
- class qdpy.algorithms.Evolution(container: Container, budget: int, vary: Callable[[IndividualLike], IndividualLike], select: Callable[[Container], IndividualLike] | None = None, select_or_initialise: Callable[[Container], Tuple[IndividualLike, bool]] | None = None, tell: Callable | None = None, deepcopy_on_selection: bool = True, **kwargs)[source]¶
Build an ask/tell algorithm from selection and variation callables.
Supply either
selectorselect_or_initialise. Selection receives the archive. The combined callable can also receive the empty base candidate and reports whether variation should follow. Selected candidates are deep-copied by default so variation can mutate safely. The optional tell hook receives the evaluated individual and the archive’s update flag.
- class qdpy.algorithms.MutPolyBounded(container: Container, budget: int, dimension: int, ind_domain: Tuple[float, float] = (0., 1.), mut_pb: float = 0.2, eta: float = 20., **kwargs)[source]¶
Use bounded polynomial mutation after the archive has a parent to select.
- class qdpy.algorithms.MutGaussian(container: Container, budget: int, dimension: int, mut_pb: float = 0.2, mu: float = 0., sigma: float = 1.0, **kwargs)[source]¶
Use Gaussian mutation after the archive has a parent to select.
- class qdpy.algorithms.evolution.DGRandomSearchMutPolyBounded(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., **kwargs)[source]¶
Use uniform initialisation and grid-based roulette selection.
Selected genomes are varied by bounded polynomial mutation. Use a Grid as the archive because the selection operator draws from an occupied cell.
Recent QD methods¶
- qdpy.tools.iso_line_dd(first, second, *, iso_sigma=0.01, line_sigma=0.2, bounds=None, rng=None)[source]¶
Return an Iso+LineDD offspring as a new NumPy vector.
Each coordinate receives independent isotropic noise. One Gaussian draw scales the difference between the parents for the entire offspring.
- Parameters:
first – Base parent vector.
second – Parent defining the direction from the base.
iso_sigma – Standard deviation of independent coordinate noise.
line_sigma – Standard deviation of the shared direction coefficient.
bounds – Optional lower and upper coordinate bounds for clipping.
rng – Random generator. By default use NumPy’s global random stream.
- class qdpy.algorithms.IsoLineMAPElites(container, budget, dimension, ind_domain=(0.0, 1.0), *, batch_size=1, iso_sigma=0.01, line_sigma=0.2, **kwargs)[source]¶
MAP-Elites with uniform parent draws and bounded Iso+LineDD variation.
- Parameters:
container – One-elite grid or CVT grid.
budget – Candidate evaluations per run.
dimension – Genome length.
ind_domain – Common lower and upper genome bounds.
batch_size – Maximum number of in-flight candidates.
iso_sigma – Independent noise scale.
line_sigma – Shared direction noise scale.
- qdpy.tools.iso_line_cross(first, second, *, iso_sigma=0.005, line_sigma=0.05, crossover_probability=0.5, crossover_rate=0.1, bounds=None, rng=None)[source]¶
Return one IsoLineCross offspring without changing its parents.
Apply Iso+LineDD in both directions and alternate parental segments at the scaled cumulative exponential breakpoints. Set line_sigma to zero for IsoCross. A zero crossover probability consumes the same random draws as Iso+LineDD.
- Parameters:
first – Base parent vector.
second – Other parent vector with the same shape.
iso_sigma – Isotropic noise scale.
line_sigma – Directional noise scale.
crossover_probability – Probability of mixing the two varied vectors.
crossover_rate – Number of sampled breakpoints per gene, in [0, 1].
bounds – Optional clipping bounds.
rng – Generator or the default NumPy global stream.
- class qdpy.algorithms.IsoLineCrossMAPElites(container, budget, dimension, ind_domain=(0., 1.), *, crossover_probability=0.5, crossover_rate=0.1, iso_sigma=0.005, line_sigma=0.05, **kwargs)[source]¶
IsoLineCross MAP-Elites for a one-elite Grid or CVTGrid.
The two parents are drawn uniformly with replacement. Their varied coordinates form contiguous segments when crossover is selected.
- Parameters:
crossover_probability – Fraction of proposals using crossover.
crossover_rate – Number of sampled breakpoints per gene.
iso_sigma – Isotropic noise scale.
line_sigma – Directional noise scale. Zero selects IsoCross.
kwargs – Native IsoLineMAPElites configuration.
- class qdpy.algorithms.LearnedQD(selector, budget, dimension, population_size, batch_size, *, ind_domain=(0., 1.), fitness_domain=None, iso_sigma=.01, line_sigma=.2, seed=0, **kwargs)[source]¶
Evolve a population using Iso+LineDD and learned local competition.
The selector scores the concatenated parent and offspring population. Keep the highest-scoring distinct genomes with stable ties. Raw fitness and descriptors remain available for reporting and serialization.
- Parameters:
selector – LQDSelector for the evaluator’s descriptor width.
budget – Number of attempted evaluations.
dimension – Bounded real genome length.
population_size – Maximum retained population size.
batch_size – Number of offspring before survival selection.
ind_domain – Common clipping interval.
fitness_domain – Optional interval in raw objective units.
iso_sigma – Isotropic noise scale.
line_sigma – Directional noise scale.
seed – Local seed for parent draws and variation.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.LQDSelector(descriptor_size, *, width=16, heads=4, layers=4, parameters=None, seed=0)[source]¶
Produce one learned survival score per population member.
The model standardizes each input column across the population. Its attention blocks have a residual feed-forward layer and no positional encodings. The weights can be optimized by an external optimizer.
- Parameters:
descriptor_size – Number of measured descriptor coordinates.
width – Embedding width, divisible by the number of heads.
heads – Number of attention heads.
layers – Number of attention blocks.
parameters – Optional one-dimensional vector of model weights.
seed – Local initialization seed when weights are unspecified.
- classmethod load(path)[source]¶
Validate the format version and model geometry before constructing the selector.
- property parameters¶
Return a copy of the flat model weights.
- class qdpy.algorithms.CMAMAE(container, budget, x0, sigma0, batch_size, threshold_min, *, learning_rate=0.01, ind_domain=None, seed=None, **kwargs)[source]¶
Single-objective CMA-MAE with a best-only result grid and separate search state.
Install the optional
cmaextra. Each generation is ranked against the thresholds at its start. The final partial generation updates the grids.- Parameters:
container – Fixed, one-elite Grid or CVTGrid for reporting best solutions.
budget – Candidate evaluations per run.
x0 – Starting point in genome coordinates.
sigma0 – Initial CMA step size.
batch_size – CMA population size.
threshold_min – Initial threshold in signed, weighted quality units.
learning_rate – Archive learning rate between zero and one.
ind_domain – Optional common lower and upper genome bounds.
seed – Optional private seed for covariance search and restarts.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property search_elites¶
Return a mapping of threshold-qualified search representatives by cell.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.DominatedNoveltySearch(budget, dimension, population_size, batch_size, *, k=5, ind_domain=(0.0, 1.0), fitness_domain=None, iso_sigma=0.01, line_sigma=0.2, **kwargs)[source]¶
Keep candidates distant from their nearest strictly fitter neighbours.
Genome duplicates keep the first occurrence. Equal novelty scores keep incumbents ahead of offspring in proposal order. Fitness values stay raw.
- Parameters:
budget – Candidate evaluations per run.
dimension – Genome length.
population_size – Maximum number of survivors.
batch_size – Number of offspring per generation.
k – Maximum number of strictly fitter neighbours to score.
ind_domain – Shared genome bounds.
fitness_domain – Optional single objective interval.
iso_sigma – Independent noise scale.
line_sigma – Shared direction noise scale.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.MOME(container, budget, dimension, batch_size, *, ind_domain=(0.0, 1.0), iso_sigma=0.01, line_sigma=0.2, **kwargs)[source]¶
Multi-Objective MAP-Elites with uniform cell and front sampling.
The first generation uses uniform real-valued proposals. Later generations recombine parents with Iso+LineDD. Inspect cell fronts and hypervolume through the ParetoGrid.
- Parameters:
container – ParetoGrid for the search.
budget – Candidate evaluations per run.
dimension – Genome length.
batch_size – Number of candidates in a generation.
ind_domain – Shared genome bounds.
iso_sigma – Independent noise scale.
line_sigma – Shared direction noise scale.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.FeasibleMOME(container, budget, dimension, batch_size=1, *, constraint_names, infeasible_parent_probability=.25, seed=0, **kwargs)[source]¶
Apply explicit inequalities to MOME without changing its objective weights.
Evaluators return fitness, descriptors, and named constraint scores. Each residual g(x) must be finite, with g(x) <= 0 denoting feasibility. Only feasible candidates enter the reporting ParetoGrid. Infeasible candidates compete by the sum of their positive residuals in a separate slot per cell. Scale residuals in the evaluator when units differ.
- Parameters:
container – Empty ParetoGrid for feasible trade-offs.
budget – Exact evaluation attempts.
dimension – Number of real-valued genome coordinates.
batch_size – Number of proposals before committing feedback.
constraint_names – Score names holding the inequality residuals.
infeasible_parent_probability – Chance of drawing a least-violation breeder when both pools have entries. Zero disables these parents.
seed – Private mutation, selection, and truncation seed.
kwargs – MOME settings, including decision bounds and variation scales.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property infeasible_elites¶
Return an independent mapping of cells to their least-violation breeders.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.MOMEX(container, budget, dimension, *, samples=32, batch_size=8, estimator='median', ind_domain=(0., 1.), iso_sigma=.01, line_sigma=.2, seed=0)[source]¶
Search using fixed complete groups of ordinary scalar QD measurements.
- Parameters:
container – Empty crowding ParetoGrid with fitness and reproducibility objectives, in that order. Maximize the second objective.
budget – Raw rollout attempts. A remainder smaller than samples is left unused.
dimension – Number of bounded real decision variables.
samples – Rollouts per candidate, at least two.
batch_size – Maximum number of candidates before committing their fronts.
estimator – “median” or “mean” for fitness and descriptor coordinates.
ind_domain – Shared bounds on decision variables.
iso_sigma – Independent mutation scale for Iso+LineDD.
line_sigma – Directional mutation scale for Iso+LineDD.
seed – Private variation, selection, and evaluator seed.
- class qdpy.algorithms.NOAH(population_size, barrier, *, objective_generations=3, retain=None, patience=4, diversity_scale=1., maximize=False, seed=0)[source]¶
Find diverse alternatives whose fitness meets a requested quality barrier.
- Parameters:
population_size – Target number of distinct alternatives.
barrier – Largest admissible cost, or smallest reward when maximizing.
objective_generations – Quality-only generations between bound updates.
retain – Minimum survivors when tightening the bound. Defaults to half the population.
patience – Diversity generations without improvement before returning to quality search.
diversity_scale – Positive inverse length scale of the exponential distance kernel.
maximize – Use a reward floor in place of a cost ceiling.
seed – Private variation and parent selection seed.
- run(evaluate, *, budget, propose, mutate, distance)[source]¶
Return a bounded population and its acceptable subset.
Call propose(rng) for a fresh hashable genome, mutate(genome, rng) for an offspring, and evaluate(genome) for a finite scalar. The symmetric distance is evaluated once per pair. Every objective call counts, including repeated and infeasible proposals.
- class qdpy.algorithms.NOAHEntry(genome: object, fitness: float)[source]¶
A hashable genome and its raw scalar objective value.
- class qdpy.algorithms.NOAHResult(population: tuple[NOAHEntry, ...], acceptable: tuple[NOAHEntry, ...], evaluations: int, bound: float, diversity: float)[source]¶
The final population and the subset satisfying the requested quality barrier.
- class qdpy.algorithms.DeepSurrogateMAPElites(container, budget, *, propose, mutate, surrogate=None, encode=None, initial_samples=16, model_budget=128, seed=0)[source]¶
Run DSA-ME on a user-defined numeric genome with custom variation.
- Parameters:
container – Empty parentless, one-elite scalar Grid or CVTGrid.
budget – Hard cap on exact evaluator calls, including failures.
propose – Callback (rng) returning a fresh numeric genome.
mutate – Callback (parent_genome, rng) producing a varied genome.
surrogate – Optional model with fit(X, Y) and predict(X). Y has the scalar fitness followed by the descriptor coordinates. The default is a scaled, two-hidden-layer scikit-learn regressor.
encode – Optional genome-to-vector callback for the model.
initial_samples – Number of exact random measurements and random starts in each fresh inner archive.
model_budget – Prediction calls available per surrogate search.
seed – Private seed for proposals, evaluations, and the default model.
- class qdpy.algorithms.MedoidArchive(medoids, distance, *, maximize=True)[source]¶
A best-only archive over arbitrary immutable descriptor objects.
- Parameters:
medoids – Distinct ordered representatives in the descriptor space.
distance – Callable symmetric dissimilarity. It must be finite and nonnegative, with zero for identical objects.
maximize – Whether higher fitness is preferred.
- add(genome, fitness, descriptor)[source]¶
Return whether the candidate filled its niche or strictly improved its elite.
- property cells¶
Return a snapshot of occupied niche indices and their measured elites.
- classmethod fit(descriptors, count, distance, *, maximize=True, max_swaps=20)[source]¶
Use deterministic PAM build and swap passes on the reference panel.
Fitting uses a dense pairwise matrix. Equivalent descriptors at distance zero share the first representative.
- property medoids¶
Return the fixed niche anchors in tie-breaking order.
- class qdpy.algorithms.MedoidElite(genome: object, fitness: float, descriptor: object)[source]¶
An immutable record holding a candidate and its measurement.
- class qdpy.algorithms.MedoidMAPElites(archive, *, propose, mutate, seed=0)[source]¶
Search with a medoid archive and a scalar-fitness descriptor evaluator.
- Parameters:
archive – A MedoidArchive, optionally seeded with measured elites.
propose – Callback (rng) producing a fresh immutable genome.
mutate – Callback (parent_genome, rng) producing an immutable offspring.
seed – Independent proposal and parent selection seed.
- class qdpy.algorithms.NGramSequenceSpace(corpus, *, n, length)[source]¶
Fixed-length token sequences supported by an observed n-gram graph.
- Parameters:
corpus – Iterable of token sequences. Tokens must be hashable.
n – Number of tokens per n-gram, including its predicted token.
length – Length of each candidate, at least n.
Sampling uses corpus transition counts, restricted to edges that can complete the required length. Mutation and crossover use a shortest context bridge, then trim or extend the tail to length. A splice that cannot be completed returns the first parent.
- class qdpy.algorithms.GramElites(container, budget, space, *, initial_candidates=8, crossover_probability=1., mutation_probability=.02, batch_size=1, seed=0, **kwargs)[source]¶
MAP-Elites with corpus-sampled starts and n-gram variation.
- Parameters:
container – Best-only scalar Grid or CVTGrid.
budget – Candidate proposals to evaluate.
space – Fitted NGramSequenceSpace.
initial_candidates – Number of corpus-sampled proposals before variation.
crossover_probability – Probability of drawing a second parent and crossing.
mutation_probability – Probability of applying n-gram mutation to the child.
batch_size – Maximum proposals per native optimisation batch.
seed – Seed for proposals and parent selection.
kwargs – Native algorithm settings, including optimisation_task.
- class qdpy.algorithms.EmpiricalDistribution(samples)[source]¶
Store a nonempty sorted tuple of finite scalar observations.
Repeated values keep their multiplicity. The distance accepts distributions with unequal sample counts.
- qdpy.algorithms.wasserstein_descriptor_distance(first, second)[source]¶
Return the average transport cost with absolute distance in outcome units.
- class qdpy.algorithms.DistributionMAPElites(archive, *, propose, mutate, rollouts, seed=0)[source]¶
Use mean rollout fitness and the empirical distribution of scalar outcomes.
- Parameters:
archive – MedoidArchive with EmpiricalDistribution reference descriptors. Use wasserstein_descriptor_distance for one-dimensional Wasserstein niches.
propose – Callback (rng) producing an immutable genome.
mutate – Callback (parent, rng) producing an immutable offspring.
rollouts – Number of attempted calls per complete search measurement.
seed – Seed for variation and independent search and audit rollout streams.
The evaluator receives (genome, integer_seed) and returns (fitness, scalar_outcome). Fitness controls replacement. The outcome controls the niche. The evaluator can return the same value for both.
- class qdpy.algorithms.DistributionAudit(elite: MedoidElite, search_niche: int, audit_niche: int, fitness: float, descriptor: EmpiricalDistribution)[source]¶
Compare the search assignment and a held-out measurement of one elite.
- Parameters:
elite – Archive record containing the genome and search measurements.
search_niche – Niche index assigned during search.
audit_niche – Niche index from the audit descriptor.
fitness – Mean held-out fitness.
descriptor – Held-out outcome distribution.
- property stable¶
Return whether reassessment kept the elite in its original niche.
- class qdpy.algorithms.CounterexampleMAPElites(archive, scenarios, *, propose, mutate, measure, verify, initial_scenarios=(), seed=0)[source]¶
Run counterexample-guided MAP-Elites over a fixed finite scenario universe.
- Parameters:
archive – Empty, best-only scalar Grid or CVTGrid. This archive is owned by the search for the duration of verification.
scenarios – Nonempty ordered collection of distinct hashable cases.
propose – Callback (rng) producing an initial iterable genome.
mutate – Callback (parent_tuple, rng) producing an offspring genome.
measure – Callback (genome) returning ((fitness,), descriptors). The measurement fixes the candidate’s niche and its quality.
verify – Callback (genome, scenario) returning True on success, False on a counterexample, or None when the result is inconclusive.
initial_scenarios – Cases to check before unknown cases.
seed – Private proposal and parent selection seed.
Verification should be deterministic. Only candidates that can improve the archive are checked. A candidate enters the archive only after passing the complete scenario universe. A failed scenario moves ahead of unseen cases for later candidates. A candidate interrupted by the check budget or an inconclusive result resumes on the next run call.
- property counterexamples¶
Return discovered counterexamples in first-discovery order.
- property pending_genome¶
Return the genome awaiting verification, or None.
- run(*, proposals, checks)[source]¶
Return cumulative stats and retain a partial verification for the next call.
Zero proposals allows finishing the pending candidate. Reaching an inconclusive case pauses this call. A callback exception propagates after charging the attempted operation.
- property stats¶
Return an immutable snapshot of cumulative search work.
- class qdpy.algorithms.CounterexampleQDStats(proposals: int = 0, measurements: int = 0, checks: int = 0, rejected: int = 0, verified: int = 0, archive_updates: int = 0, counterexamples: int = 0, inconclusive_checks: int = 0)[source]¶
Counters checked independently against per-run proposal and verification budgets.
- Parameters:
proposals – Attempted proposals, including failures before measurement.
measurements – Attempts to measure nominal quality and descriptors.
checks – Attempts to verify a design on a single scenario.
rejected – Designs ruled out by a failing check.
verified – Designs that passed every scenario.
archive_updates – Insertions and improvements to the certified archive.
counterexamples – Newly discovered failing scenarios added to screening.
inconclusive_checks – Checks that returned None and need to be retried.
- class qdpy.algorithms.SymmetryAwareMAPElites(archive, *, canonicalize, propose, mutate, seed=0)[source]¶
Search only distinct canonical representatives in a best-only Grid or CVTGrid.
- Parameters:
archive – Empty reporting archive with scalar fitness.
canonicalize – Callback (genome_tuple) producing a canonical genome iterable with hashable entries. It must be deterministic and idempotent, and preserve fitness, descriptors, and feasibility.
propose – Callback (rng) producing an initial iterable genome.
mutate – Callback (parent_tuple, rng) producing an offspring genome.
seed – Private proposal and parent selection seed.
The search owns a cache of successfully evaluated representatives, including measurements outside the reporting domain. Keep the evaluator, geometry, and canonicalization fixed across calls.
- run(evaluate, *, proposals, max_evaluations=None)[source]¶
Return cumulative stats. The optional evaluation limit applies to this call.
Evaluate the canonical tuple and return ((fitness,), descriptors). Failed or invalid measurements propagate and leave the candidate eligible for a later attempt.
- property stats¶
Return an immutable snapshot of proposal and evaluation costs.
- class qdpy.algorithms.SymmetryQDStats(proposals: int = 0, evaluations: int = 0, duplicates: int = 0, archive_updates: int = 0)[source]¶
Cumulative proposals, evaluator attempts, repeats, and accepted archive updates.
- class qdpy.algorithms.PolicyManifoldSearch(container, budget, dimension, ind_domain=(0., 1.), *, batch_size=32, latent_size=4, hidden_size=64, min_elites=4, fit_interval=1, fit_epochs=5, fit_batch_size=64, learning_rate=1e-3, sigma=.05, seed=0, device='cpu', **kwargs)[source]¶
Bounded Policy Manifold Search (PoMS) using a native best-only grid.
Fit a deterministic autoencoder periodically on the occupied elite vectors. For a parent at or below the mean reconstruction error at the last fit, draw a Gaussian in normalized parameter coordinates and multiply it by the transpose of the decoder Jacobian. Add this perturbation to the parent’s latent code and decode the result. Less well-reconstructed parents receive direct parameter mutation.
- Parameters:
container – Best-only scalar Grid or CVTGrid.
budget – Total attempted candidate evaluations.
dimension – Number of bounded real coordinates in each policy vector.
ind_domain – Shared finite lower and upper bounds.
batch_size – Maximum candidates in one generation.
latent_size – Size of the autoencoder bottleneck.
hidden_size – Width of the encoder and decoder hidden layers.
min_elites – Minimum measured archive size before fitting.
fit_interval – Minimum number of generations between refits.
fit_epochs – Number of archive passes per fit.
fit_batch_size – Maximum number of training rows per update.
learning_rate – Positive Adam learning rate.
sigma – Gaussian standard deviation in normalized [0, 1] coordinates.
seed – Seed for initialization, parent selection and fitting.
device – PyTorch CPU or CUDA device.
kwargs – Native algorithm options such as optimisation_task.
Archive admission uses scalar fitness. For an exploration-only objective, return the same fitness in every niche.
- property model_fit_seconds¶
Return wall-clock time spent fitting the autoencoder and measuring training error.
- property model_fits¶
Return the number of completed archive autoencoder fits.
- property operator_counts¶
Return attempted proposals by random, parameter, or latent variation.
- class qdpy.algorithms.DecentralizedMAPElites(geometry, peers, *, propose, mutate, topology='ring', local_batch_size=1, exchange_period=1, migrants=1, seed=0)[source]¶
Simulate peer contacts in synchronous rounds using a shared evaluator.
- Parameters:
geometry – Empty parentless best-only scalar Grid or CVTGrid.
peers – Number of distinct local archives, at least two.
propose – Callback (peer, rng) producing a random genome.
mutate – Callback (peer, parent_genome, rng) producing an offspring.
topology – “ring” for two-way adjacent contacts or “complete”.
local_batch_size – Candidates proposed by each peer per round.
exchange_period – Completed rounds between exchange opportunities.
migrants – Maximum distinct entries sent along each directed edge per exchange.
seed – Root seed for independent proposal, contact, and rollout streams.
- optimise(evaluate, *, budget, message_budget, executor=None, seeded=False)[source]¶
Return the reporting union after one simulated run.
The evaluator is shared by peers. Each transferred elite consumes one message even if rejected by its recipient. The final partial round contributes local measurements, then exchanges if due. Supply seeded=True to receive an explicit rollout seed as a second argument.
- property peer_evaluations¶
Return exact evaluator attempts in peer order.
- class qdpy.algorithms.EntropyTourSearch(distances, cost_limit, population_size, *, segment_length=3, seed=0)[source]¶
Generate a biased and a uniform 2-opt child and compare them with their parent.
- Parameters:
distances – Square symmetric nonnegative matrix of finite edge costs.
cost_limit – Inclusive ceiling for each retained tour.
population_size – Maximum number of distinct tours to retain.
segment_length – Number of consecutive vertices in a segment.
seed – Private random stream for parent choice and cut locations.
- class qdpy.algorithms.TourPortfolio(tours: tuple[TourResult, ...], entropy: float, evaluations: int)[source]¶
Distinct tours, directed segment entropy, and all measured attempts.
- class qdpy.algorithms.TourResult(tour: tuple[int, ...], cost: float)[source]¶
The route starts at vertex zero and omits the repeated closing vertex.
- qdpy.algorithms.tour_segment_entropy(tours, segment_length=3)[source]¶
Count each segment in both directions and return its population entropy in nats.
- class qdpy.algorithms.MultiDescriptorNSLC(budget, dimension, population_size, batch_size=1, *, exploration_score_name='exploration', reference_capacity=128, k=15, ind_domain=(0., 1.), sigma=.1, mutate=None, seed=0, **kwargs)[source]¶
Use the NS–NSLC objectives described by Pugh, Soros, and Stanley.
The evaluator returns (fitness, reporting_descriptors, scores). A named score holds the independent exploration descriptor vector. The reporting view defines the neighbors for local competition. Each novelty view keeps a separate bounded memory. The objective direction for local competition is the raw scalar fitness direction.
- Parameters:
budget – Candidate evaluation attempts.
dimension – Number of real-valued genes.
population_size – Maximum size of the current breeding population.
batch_size – Number of offspring before committing feedback.
exploration_score_name – Score containing the exploration descriptor.
reference_capacity – Maximum entries in each novelty memory.
k – Number of nearest neighbors for novelty and local competition.
ind_domain – Shared bounds on genome coordinates.
sigma – Standard deviation of default bounded Gaussian variation.
mutate – Optional callback taking (parent_genome, rng).
seed – Private proposal and tie-breaking seed.
kwargs – Native settings including optimization direction.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property reference_sizes¶
Return the sizes of the exploration and reporting memories, in order.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.MEPGD(container, budget, dimension, *, replacement_probability=.3, sigma=.1, mutate=None, ind_domain=(0., 1.), batch_size=1, seed=0, **kwargs)[source]¶
Retain one reporting elite and at most one auxiliary breeder per cell.
A strict fitness improvement replaces the reporting elite. An otherwise eligible candidate may overwrite the auxiliary slot even when its fitness is lower. Parent selection samples an occupied cell uniformly and chooses between its two live occupants when both exist. All data in the reporting grid comes from elite competition.
- Parameters:
container – Empty parentless best-only Grid or CVTGrid with one objective.
budget – Candidate evaluation attempts.
dimension – Number of real-valued genome coordinates.
replacement_probability – Chance a non-improving candidate occupies the second slot.
sigma – Scale of default bounded Gaussian mutation.
mutate – Optional callback taking (parent_genome, rng).
ind_domain – Common bounds for all genome coordinates.
batch_size – Number of simultaneous proposals.
seed – Private seed for parent selection, mutation, and second-slot admission.
kwargs – Native QDAlgorithm settings.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property auxiliary_admissions¶
Return the cumulative number of second-slot updates.
- property breeding_slots¶
Return the second-slot occupants indexed by reporting cell.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.MOCMAMAE(container, budget, x0, sigma0, batch_size, reference, *, learning_rate=.1, ind_domain=None, seed=None, **kwargs)[source]¶
Two-objective MO-CMA-MAE with a dynamic threshold archive.
Each candidate is scored against its cell’s current threshold front, in proposal order. The learning rate determines how much hypervolume of an improvement is inserted into the threshold front. The reporting ParetoGrid stores original, nondominated measurements.
- Parameters:
container – Two-objective ParetoGrid with declared objective directions.
budget – Number of attempted candidate evaluations.
x0 – Initial genome centre, with at least two coordinates.
sigma0 – Initial CMA step size.
batch_size – Population size, at least two.
reference – Hypervolume reference in raw objective units. Candidate objectives must be at least as good as the reference in both coordinates.
learning_rate – Fraction of the hypervolume improvement applied to the threshold front, in [0, 1]. Zero freezes thresholds and one applies full gain.
ind_domain – Optional shared genome bounds.
seed – Optional private random seed for CMA and restarts.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.MOURQD(container, budget, dimension, batch_size=1, *, ind_domain=(0., 1.), iso_sigma=0.005, line_sigma=0.05, **kwargs)[source]¶
Draw parents uniformly from a LocalParetoArchive and apply Iso+LineDD.
A batch reads the current archive when drawing parents. Measurements update the archive in proposal order.
- Parameters:
container – LocalParetoArchive with the objective weights.
budget – Number of candidate evaluation attempts.
dimension – Number of real genome coordinates.
batch_size – Maximum number of proposals per batch.
ind_domain – Shared lower and upper genome bounds.
iso_sigma – Independent noise scale.
line_sigma – Shared direction noise scale.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.MixME(container, budget, role_sizes, *, role_bounds=None, batch_size=12, team_crossover=True, iso_sigma=0.01, line_sigma=0.2, polynomial_eta=20., mutation_probability=None, **kwargs)[source]¶
Use a flat genome and archive each evaluated team as one solution.
Once the archive has an elite, the three operators are used in turn across proposals. Team crossover draws an elite team with replacement for each role and copies only that team’s block for the role. Polynomial variation and Iso+LineDD preserve team membership during parent selection. A partial batch carries its position in the operator cycle into the next batch. The empty archive draws uniformly bounded genomes.
- Parameters:
container – Best-only Grid or CVTGrid for team measurements.
budget – Number of attempted evaluations of whole teams.
role_sizes – Positive genome lengths in role order, or a mapping from role names to lengths in insertion order.
role_bounds – One (lower, upper) interval per role, in role order. Defaults to (0, 1) for every role.
batch_size – Number of proposals between archive updates.
team_crossover – Include team mixing in the operator cycle.
iso_sigma – Independent Iso+LineDD noise scale.
line_sigma – Shared Iso+LineDD direction scale within a role.
polynomial_eta – Polynomial mutation distribution index.
mutation_probability – Polynomial mutation chance per gene. Defaults to the reciprocal of the total genome length.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- qdpy.algorithms.qdhf_search(evaluate, archive, *, feedback, budget, feedback_budget, dimension, raw_feature_size, ind_domain=(0., 1.), warmup=64, refit_every=112, feedback_batch=24, fit_steps=128, seed=0)[source]¶
Learn a descriptor on random trials and optionally on the evolving archive.
- Parameters:
evaluate – Function of a genome tuple returning scalar fitness and a raw feature vector in fixed units.
archive – Empty, parentless, one-elite rectangular Grid used as a template. Learned coordinates use its existing descriptor bounds.
feedback – Function of three QDHFTrial records. Return 0 for the second record, 1 for the third, or None to abstain.
budget – Hard budget of attempted evaluator calls, including warm-up.
feedback_budget – Hard budget of feedback calls, including abstentions.
dimension – Number of bounded real genome coordinates.
raw_feature_size – Length of the evaluator’s raw feature vector.
ind_domain – Shared lower and upper genome bounds.
warmup – Number of uniform candidate attempts before the first fit.
refit_every – Attempts between online feedback rounds. None requests the entire annotation budget at warm-up and freezes the projection.
feedback_batch – Maximum number of requests per online feedback round.
fit_steps – Adam update steps per fit.
seed – Root seed for independent variation and feedback streams.
- Returns:
Final archive, projector, attempted evaluations, failures, and labels.
- class qdpy.algorithms.TripletProjector(raw_feature_size, descriptor_size, *, margin=0.05, seed=0)[source]¶
Project fixed-width raw features into a lower-dimensional space.
For each labelled triplet, fit a linear map so the anchor is closer to the preferred point than to the other point by at least the margin. Distances in the training loss are squared Euclidean distances.
- Parameters:
raw_feature_size – Number of input coordinates after feature extraction.
descriptor_size – Number of learned descriptor coordinates.
margin – Positive target gap between squared distances.
seed – Seed for the initial projection.
- fit(raw_features, triplets, *, steps=128, batch_size=32, learning_rate=0.01, seed=0)[source]¶
Use Adam on the triplet hinge loss and return the fitted projector.
Each row of
tripletsgives three distinct row indices intoraw_features: anchor, preferred neighbor, other candidate. Training starts with the current projection and independent Adam moments. Commit the updated weights only after a finite fit.
- class qdpy.algorithms.QDHFTrial(attempt: int, genome: tuple[float, ...], fitness: float, raw_features: tuple[float, ...])[source]¶
One evaluated genome with a one-based attempt ID, fitness, and raw features.
- class qdpy.algorithms.TripletJudgment(attempts: tuple[int, int, int], choice: int | None)[source]¶
IDs are in anchor, first alternative, second alternative order.
- class qdpy.algorithms.QDHFResult(archive: Grid, projector: TripletProjector, attempts: int, failures: int, feedback: tuple[TripletJudgment, ...], fits: int)[source]¶
Feedback includes abstentions. Fits count successful projection updates.
- qdpy.algorithms.graph_path_qd(edges, *, budget, nodes=None, crossover_probability=0.5, crossover='feasible', seed=0)[source]¶
Explore routes with endpoint mutations and directed path crossover.
Initialize the repertoire with the direct edges. Each subsequent attempt changes one path or concatenates two paths. Mutation draws one plus a Poisson(1) number of incident-edge edits and ends the proposal at the first invalid edit. Crossover can select occupied pairs uniformly or draw the second pair from the first pair’s target row. Empty or incompatible pairs consume one attempt. A valid path replaces an equal-cost or higher-cost incumbent.
- Parameters:
edges – Iterable of (source, target, positive weight) triples. Nodes may be any hashable labels. Weights can be integers or floats.
budget – Nonnegative number of proposals after direct-edge initialization.
nodes – Optional node labels in sampling order, including isolated nodes. Omit to infer nodes in order of first occurrence in edges.
crossover_probability – Probability of a crossover attempt. Zero runs mutation-only QD-EA.
crossover – “feasible” for directed-row selection or “uniform” for two independent draws from occupied pairs.
seed – Local NumPy random seed.
- Returns:
A GraphPathRepertoire with routes and separate proposal counts.
- class qdpy.algorithms.GraphPathRepertoire(nodes: tuple[Hashable, ...], attempts: int, evaluations: int, initial_routes: int, _routes: dict[tuple[Hashable, Hashable], GraphPath])[source]¶
Attempts include invalid or unavailable offspring. Evaluations count valid offspring, including those that fail to improve the archive. Direct-edge initialization is reported separately.
- property routes¶
Mapping of discovered off-diagonal pairs to immutable routes.
Differentiable, Bayesian, and high-dimensional methods¶
- class qdpy.algorithms.GradientEvaluation(fitness: float, descriptors: Sequence[float], jacobian: ndarray)[source]¶
Measurements from a single gradient evaluation.
The Jacobian has one row for the objective followed by a row for each descriptor. Columns follow the order of the genome coordinates.
- class qdpy.algorithms.MEGIDE(container, budget, nvec, batch_size=32, *, entropy_fraction=.5, seed=None, **kwargs)[source]¶
MAP-Elites with the Gradient-Informed Discrete Emitter.
Return a
GradientEvaluationfor each integer candidate. Its Jacobian has rows for the objective followed by the descriptors, and columns for adjacent one-hot blocks of the configured category counts. Each call supplies the exact discrete measurements and derivatives of a caller-provided smooth relaxation at that one-hot point.Derivatives are cached for retained elites, so use a fixed evaluator throughout a run. The entropy is controlled separately for each proposal. Like the paper’s softmax, each current category is included in its block and may yield an unchanged proposal.
- Parameters:
container – Best-only single-objective Grid or CVTGrid.
budget – Number of candidate calls, including the initialization.
nvec – Sequence of positive category counts, with at least two alternatives in one coordinate. Categories are zero-indexed.
batch_size – Number of candidates selected from a frozen repertoire.
entropy_fraction – Desired entropy as a fraction of uniform entropy.
seed – Optional seed for initialization, parent sampling and edits.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.MBOA(repertoire, budget, *, length_scale=.4, kappa=.05, noise_variance=.001, signal_variance=1., allow_repeats=False)[source]¶
Map-based Bayesian optimization using original fitness as the prior mean.
The repertoire stays fixed. The posterior combines its nominal scores with measured residuals in the new conditions. Upper confidence bounds rank the available entries. All returned fitnesses use the raw units.
- Parameters:
repertoire – Live numeric container, numeric grid JSON export path, or the decoded JSON mapping.
budget – Maximum number of adaptation trials.
length_scale – Positive Matérn-5/2 length scale, in normalized descriptor coordinates. Axes without finite bounds use raw units.
kappa – Nonnegative exploration coefficient.
noise_variance – Positive observation variance in squared fitness units.
signal_variance – Positive GP variance in squared fitness units.
allow_repeats – Permit more than one new trial per repertoire entry.
- property best¶
Return the best genuine adaptation trial, or None before a success.
- property trials¶
Return the attempted trials in their original order.
- class qdpy.algorithms.MBOACandidate(index: int, genome: tuple, descriptor: tuple[float, ...], prior_fitness: float)[source]¶
- class qdpy.algorithms.MBOATrial(candidate: qdpy.algorithms.mboa.MBOACandidate, fitness: float | None)[source]¶
- class qdpy.algorithms.GoExplore(env_factory, *, cell, sample_action, exploration_steps=20, max_trajectory_steps=None, snapshot=None, restore=None, seed=0)[source]¶
Run the exploration phase of Go-Explore with a Gymnasium-style environment.
- Parameters:
env_factory – Factory for a single environment with seeded reset, five-value step, and close methods.
cell – Callable mapping observation and info to a stable hashable key.
sample_action – Callable given observation, info, and a seeded NumPy generator. Return a legal exploration action compatible with deepcopy.
exploration_steps – Maximum new actions per selected cell.
max_trajectory_steps – Optional cap on the length of any saved path.
snapshot – Optional callable taking the environment and returning its complete restorable state, including RNG and wrapper state.
restore – Paired callable receiving a fresh copy of that snapshot and the environment as
restore(env, snapshot). Return the restored observation and info. Without the pair, reset and replay each path.seed – Seed for cell selection, actions, and a fixed reset seed.
- property best¶
Return the highest-return path, with shorter paths winning ties.
- property cells¶
Return independent snapshots of the highest-return paths to each cell.
- explore(max_env_steps)[source]¶
Advance the archive by exactly this many calls to env.step on success.
- property stats¶
Return the current step totals and archive coverage as a cell count.
- class qdpy.algorithms.GoExploreCell(key: Hashable, reset_seed: int, actions: tuple, return_: float, ended: bool)[source]¶
Report a cell key, replay seed and path, cumulative return, and end flag.
- class qdpy.algorithms.GoExploreStats(exploration_steps: int, replay_steps: int, occupied_cells: int)[source]¶
Cumulative search costs and number of distinct reached cells.
- property env_steps¶
Return the total number of calls to the environment’s step method.
- qdpy.algorithms.squad_search(gradient_evaluate, initial_population, *, epochs, gamma, quality_floor, ind_domain=(0., 1.), batch_size=None, neighbors=None, learning_rate=0.02, maximize=True, archive=None, seed=0)[source]¶
Maximize the SQUAD objective with seeded minibatch Adam updates.
- Parameters:
gradient_evaluate – Callable returning a GradientEvaluation for one genome. Its Jacobian rows match raw fitness and descriptor order.
initial_population – Matrix of finite bounded genomes.
epochs – Number of complete passes after the initial evaluations. Every pass reevaluates each updated point once.
gamma – Positive distance scale in descriptor units.
quality_floor – Lower bound in signed fitness units. Each signed fitness must strictly exceed it for the square-root gradient.
ind_domain – Common bounds. Adam proposals are projected to this interval.
batch_size – Number of points per update. Defaults to the entire population.
neighbors – Maximum nearest neighbors per point. Defaults to all other points. Zero gives independent quality optimization.
learning_rate – Positive Adam step size.
maximize – False negates raw fitness and its derivative.
archive – Optional empty best-only Grid or CVTGrid for final reporting.
seed – Local seed for minibatch order.
- Returns:
Measured final population and optional reporting archive.
- qdpy.algorithms.soft_qd_score(qualities, descriptors, probes, *, sigma)[source]¶
Average the highest Gaussian-discounted quality at each probe.
Provide nonnegative qualities, one descriptor per solution, and a nonempty matrix of probe descriptors. For uniform probes in a box, multiplying by its volume estimates the integral over that box.
- class qdpy.algorithms.SQUADResult(population: tuple[Individual, ...], archive: Grid | None, evaluations: int, objective: float)[source]¶
The raw measurements, evaluation count and optimizer objective.
- qdpy.algorithms.set_scalarized_search(gradient_evaluate, initial_population, targets, *, epochs, bandwidth, smoothing=.05, scalarization='ssom', reference=None, quality_floor=0., learning_rate=.02, ind_domain=(0., 1.), maximize=True, archive=None)[source]¶
Use projected Adam on the SSoM or STCH-Set objective from Lin et al.
- Parameters:
gradient_evaluate – Callback returning one GradientEvaluation per point.
initial_population – Nonempty matrix of bounded genomes.
targets – Nonempty matrix of desired descriptors in measurement units.
epochs – Full-population updates after the initial measurements.
bandwidth – Gaussian distance scale in descriptor units.
smoothing – Positive log-sum-exp temperature in quality units.
scalarization – “ssom” or “stch-set”.
reference – Fixed target-wise ideal costs for STCH-Set. If omitted, use each target’s initial best cost minus smoothing.
quality_floor – Lower bound in signed fitness units. Shifted qualities must be nonnegative for distance discounting.
learning_rate – Projected Adam step in genome units.
ind_domain – Inclusive common genome interval.
maximize – Use higher raw fitness as better if true.
archive – Optional empty best-only Grid or CVTGrid for final reporting.
- class qdpy.algorithms.SetScalarizationResult(population: tuple[Individual, ...], archive: Grid | None, evaluations: int, objective: float, target_costs: tuple[float, ...])[source]¶
Report the measured final set and unsmoothed minimum cost at each target.
The objective is the final smooth loss and is minimized. Target costs retain probe order and are negative discounted qualities. A reporting archive, if supplied, contains the final set’s elites.
- class qdpy.algorithms.BayesianDeepQD(container, budget, variables, *, configurations, allocation='competitive', **kwargs)[source]¶
Use a feasibility-weighted Expected Improvement of the Deep Archive.
The exact archive holds the best feasible design for each configuration in every occupied cell. The supplied grid shows the best across configurations. Each surrogate prediction competes with the incumbent from its own configuration when present. A candidate for a missing configuration receives a more permissive reference based on estimated unfilled cells in the previous batch’s cheap pool.
Predictions are assigned by posterior-mean descriptor. At most one planned proposal per configuration and cell enters a batch. The default allocates the shared budget competitively. Equal allocation guarantees that configuration attempt counts differ by at most one, including warm-up and an incomplete final batch. Both modes use the same per-layer acquisition; callbacks follow ConditionalBayesianQD.
- Parameters:
container – Empty parentless Grid or CVTGrid with capacity for every cell.
budget – Budget in exact evaluation attempts.
variables – Mapping of conditional variable specifications.
configurations – Ordered ConditionalConfiguration sequence.
allocation –
competitive(default) orequalattempt allocation.kwargs – ConditionalBayesianQD proposal and surrogate settings.
- add_callback(event: str, fn: Callable) None¶
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()¶
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.
- ask_batch(size=None)¶
Issue a manual batch, shortening the default batch to fit the remaining budget.
- property batch_size: int¶
Configured candidate count per iteration, or the current budget when omitted.
- best() IndividualLike¶
Return the best retained candidate.
- Raises:
RuntimeError – If the container has no candidates.
- property configuration_attempts¶
Return exact proposals in configuration order, including failed evaluations.
- property configuration_observations¶
Return counts of finite observations used by each configuration model.
- property coverage_multipliers¶
Return the latest deep-archive coverage multipliers in configuration order.
- property current_iter¶
Number of committed generations, including partial generations.
- decode(candidate)¶
Return selector labels and typed active gene values in a new mapping.
- classmethod from_config(config: Mapping[str, Any], **kwargs: Any) Any¶
Create a class using the information from config to call the class constructor.
Parameters¶
- param config:
Mapping[str, Any] The configuration mapping used to create the class. For each entry, the key corresponds to the name of a parameter of the constructor of the class.
- param kwargs:
Any Additional information used to create the class. The configuration entries from kwargs take precedence over the entry in config.
- property model_fits¶
Return the number of per-configuration model refits.
- property modelled_proposals¶
Return exact proposals chosen by the surrogate.
- property nb_evaluations: int¶
Number of tell calls or candidate slots consumed by the managed scheduler.
- property nb_evaluations_in_iteration: int¶
Number of accounted evaluations since the last iteration ended.
- property nb_max_iter: int | float¶
Ceiling of the current budget divided by the batch size for a finite run.
- property nb_suggestions: int¶
Number of candidates returned by ask since initialisation or reinitialisation.
- property nb_suggestions_in_iteration: int¶
Number of asks recorded since the last managed iteration ended.
- property nb_updated: int¶
Number of evaluations for which the archive reported a local update.
- property nb_updated_in_iteration: int¶
Number of reported archive updates since the last iteration ended.
- property optimisation_task: str | Sequence[float]¶
The objective direction or explicit comparison weights.
- optimise(*args, **kwargs)¶
Schedule fixed generations via the native optimiser.
- 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.
- summary(max_depth: int | None = None, max_entry_length: int | None = 250) str¶
Return a summary description of the class. The summarised information is provided by the self.__get_summary_state__ method.
Parameters¶
- param max_depth:
Optional[int] The maximal recursion depth allowed. Used to summarise attributes of self that are also Summarisable. If the maximal recursion depth is reached, the attribute is only described with a reduced representation (repr(attribute)). If max_depth is set to None, there are no recursion limit.
- param max_entry_length:
Optional[int] If max_entry_length is not None, the description of a non-Summarisable entry exceeding max_entry_length is cropped to this limit.
- property surrogate_evaluations¶
Return the number of distinct cheap predictions across all batches.
- tell(individual, fitness=None, features=None, scores=None, elapsed=None, verbose=False, tell_container=True)¶
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_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- tell_container_entries(cont: Container | None = None) None¶
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.DescriptorAxis(name: str, bounds: tuple[float, float], bins: int)[source]¶
Use the same name in the evaluator’s measurement mapping.
- class qdpy.algorithms.DescriptorMutationMAPElites(axes, dimension, *, fitness_domain, maximize=True, ind_domain=(0., 1.), iso_sigma=.05, line_sigma=.2, seed=0)[source]¶
Search with interpretable descriptors and reuse historical elite measurements.
Evaluators receive a real-valued genome and private integer seed. Return scalar fitness and a mapping of named finite measurements. Include all active axes and optionally any measurements for future swaps. The search owns its Grid and replaces it after a successful rebuild. Retaining a reference to the old Grid gives a snapshot.
- Parameters:
axes – Nonempty sequence of distinct DescriptorAxis objects.
dimension – Number of real genome coordinates.
fitness_domain – Inclusive scalar reporting fitness bounds.
maximize – True to prefer higher fitness.
ind_domain – Shared finite interval for all genome coordinates.
iso_sigma – Independent mutation standard deviation.
line_sigma – Shared directional mutation standard deviation.
seed – Seed for proposals, evaluations, and separate refreshes.
- property archive¶
Return the active native grid.
- property axes¶
Return the active named axes in grid order.
- run(evaluate, budget)[source]¶
Return cumulative statistics. Evaluator errors propagate to the caller.
- property stats¶
Snapshot cumulative evaluation and switch counts.
- switch_axis(name, replacement, *, refresh=None, refresh_budget=0)[source]¶
Replace an axis and rebuild the active grid as one operation.
Keep the best elite in each cell of the unaffected projection. With one axis, keep the single best elite. Reuse cached values for the replacement axis. If a survivor lacks that measurement, refresh(genome, seed) must return its new scalar descriptor. The refresh budget must cover all missing values before any call is made. On failure the original grid remains active and attempted refreshes are still counted.
- class qdpy.algorithms.DescriptorMutationStats(evaluations: int, refresh_evaluations: int, switches: int)[source]¶
Evaluation counts include attempted callback calls.
- class qdpy.algorithms.DescriptorSwitch(previous: DescriptorAxis, replacement: DescriptorAxis, source_elites: int, projected_elites: int, transferred_elites: int, refresh_evaluations: int)[source]¶
Report source, projected, and transferred elite counts for one switch.
- class qdpy.algorithms.NeuralCellularMap(seed_map, *, iterations=3, hidden=3)[source]¶
Iterate shared local rules on a seed map using NumPy and SciPy.
Each hidden channel computes a 3x3 correlation and a ReLU. A pointwise sigmoid readout updates the map. Threshold the final map at one half. One denotes an obstacle and zero denotes open space.
- Parameters:
seed_map – Fixed binary starting map.
iterations – Number of full cellular updates.
hidden – Number of local correlation channels.
- property dimension¶
Return the total number of kernel and readout parameters.
- class qdpy.algorithms.ConnectedMapRepair(shape, obstacle_range, *, root=(0, 0), node_limit=None)[source]¶
Repair a binary map with a rooted single-commodity flow MILP.
The root is always open. Every other open cell consumes one unit of flow, and outgoing arcs have zero capacity on closed cells. Feasible input maps bypass the solver. If the solver cannot certify a minimum-edit repair within the supplied limits, return None.
- Parameters:
shape – Pair of positive map dimensions.
obstacle_range – Inclusive pair of obstacle-count bounds.
root – Fixed open cell, given as row and column.
node_limit – Optional positive number of MILP search nodes.
- class qdpy.algorithms.QDMapper(archive, dimension, *, generate, make_case, planners, describe, repair=None, panel_size=4, absolute_gap=False, ind_domain=(-2., 2.), iso_sigma=.2, line_sigma=.3, seed=0)[source]¶
Run the QD-MAPPER scenario workflow with bounded Iso+LineDD proposals.
A generator maps a real genome to a binary obstacle grid. Optionally repair the grid before evaluation. Each distinct layout is measured on the same seeded panel. All planners receive the same case per seed. Save the actual repaired layout under the elite’s “layout” score to audit it without calling the generator or solver again.
- Parameters:
archive – Empty parentless best-only Grid or CVTGrid maximizing the score.
dimension – Number of real genotype coordinates.
generate – Callable (genome) returning a rectangular binary layout.
make_case – Callable (layout, seed) returning an immutable planner instance.
planners – One or two callbacks (layout, case) -> finite costs, larger is harder.
describe – Callable (layout) returning the descriptor vector.
repair – Optional callable (layout) returning a valid layout or None.
panel_size – Number of training cases shared by the planners.
absolute_gap – Use absolute instead of signed cost difference for two planners.
ind_domain – Finite common genome bounds.
iso_sigma – Independent mutation deviation.
line_sigma – Directional mutation deviation.
seed – Independent proposal and training-panel seed.
- run(budget, *, proposal_budget=None, evolve=True)[source]¶
Return cumulative statistics, skipping duplicate repaired layouts.
Stop before exceeding either cap. Rejected maps spend proposals and repair attempts only. With evolve=False, sample uniformly as a matched-budget control.
- property stats¶
Snapshot cumulative search work.
- class qdpy.algorithms.MapEvaluation(objective: float, planner_costs: tuple[float, ...], descriptors: tuple[float, ...], planner_calls: int)[source]¶
Store quality, mean planner costs, descriptors, and total planner invocations.
- class qdpy.algorithms.QDMapperStats(proposals: int = 0, repair_calls: int = 0, failed_repairs: int = 0, duplicate_maps: int = 0, maps_evaluated: int = 0, planner_calls: int = 0, archive_updates: int = 0)[source]¶
Cumulative search counts. Independent audits return their own counts.
- class qdpy.algorithms.QDRec(items, item_embeddings, *, neighbors=3, exemplars=3, diversity_weight=1., prior_precision=1., noise_variance=.1, selection='thompson', seed=0)[source]¶
Run the QD-Rec search loop using caller-supplied scoring and generation.
Item embeddings guide the contextual bandit. Separate embeddings of item-hypothesis pairs determine the archive neighborhood. A novel recommendation enters the archive directly. Otherwise, a blind comparison with its nearest neighbor determines replacement. The bandit observes every scored and fully processed proposal, including rejected ones.
- Parameters:
items – Nonempty sequence of distinct hashable item identifiers.
item_embeddings – Aligned item embeddings, L2 normalized at construction.
neighbors – Number of recommendations passed to the novelty judge.
exemplars – Number of archive recommendations passed to the proposer.
diversity_weight – Weight of cosine novelty in the item acquisition.
prior_precision – Positive isotropic precision of the linear model’s prior.
noise_variance – Positive observation variance of normalized rewards.
selection – “thompson” or “uniform”. With zero exemplars, uniform selection gives the independent proposal control.
seed – Private random seed for item selection, exemplars, and comparisons.
- property archive¶
Return an immutable snapshot of the recommendation entries.
- property best¶
Return the highest pointwise score still in the archive.
- run(propose, score, embed, novel, compare, *, budget, initial=())[source]¶
Return cumulative statistics after a fixed number of proposals.
- Parameters:
propose – (item, exemplars, rng) -> hypothesis string.
score – Recommendation -> quality in [0, 1].
embed – Recommendation -> nonzero vector for cosine matching.
novel – (candidate, nearest_recommendations) -> Boolean.
compare – (first, second) -> index of the preferred recommendation. The order is randomized and scores are withheld.
budget – Number of proposer calls. Duplicates still consume calls.
initial – Optional Recommendation seeds, scored separately and admitted without local competition.
- property stats¶
Return cumulative callback and archive counters.
- class qdpy.algorithms.Recommendation(item: Hashable, hypothesis: str)[source]¶
Hold an immutable item identifier and a nonempty explanation.
- class qdpy.algorithms.QDRecEntry(recommendation: Recommendation, quality: float, embedding: tuple[float, ...])[source]¶
Store raw pointwise quality and a normalized cosine-search vector.
- class qdpy.algorithms.QDRecStats(proposals: int = 0, embeddings: int = 0, scores: int = 0, novelty_checks: int = 0, comparisons: int = 0, duplicates: int = 0, admissions: int = 0, replacements: int = 0, bandit_updates: int = 0)[source]¶
Count attempts, including callbacks that raise, and committed bandit updates.
- class qdpy.algorithms.CoME(archives, *, initialize, mutations, descriptors, evaluate, coupling='local-best', partners=2, radius=2., initial_samples=8, batch_size=16, seed=0)[source]¶
Mutate one component and evaluate it with neighbors of a chosen partner cell.
The two rectangular grids have identical shapes. Each is indexed by one component’s descriptors and stores the complete pair and its measured fitness. Each archive competes independently. Partner selection reads that side’s component from the pair at the chosen cell.
- Parameters:
archives – Two distinct empty, parentless, best-only grids with the same shape and the same finite, nonzero scalar fitness weight.
initialize – Two callbacks returning a component given the Generator.
mutations – Two callbacks taking (component, rng) and returning a component.
descriptors – Two callbacks taking a component and returning its finite, in-bounds descriptor vector. Components are immutable and hashable.
evaluate – Callback returning scalar fitness from a complete pair.
coupling – One of “local-best”, “global-best”, “identity”, “center”, or “random”.
partners – Maximum number of distinct neighbor cells sampled per mutation.
radius – Strict Euclidean radius in cell-index units around the partner cell.
initial_samples – Number of independently initialized pairs to score.
batch_size – Maximum number of scored pairs between archive updates.
seed – Private proposal seed.
- class qdpy.algorithms.CoMEStats(evaluations: int, generations: int, archive_updates: int)[source]¶
Count complete pair evaluations, evaluated generations, and archive insertions.
- Variables:
evaluations – Number of complete pairs scored, including initialization.
generations – Number of batches committed.
archive_updates – Number of successful insertions into either archive.
- class qdpy.algorithms.SPHEN(container, budget, dimension, ind_domain=(0., 1.), *, initial_samples=12, surrogate_budget=128, surrogate_batch_size=16, exploration=2., mutation_sigma=.1, length_scale=.25, batch_size=4, seed=0, **kwargs)[source]¶
Build acquisition and prediction maps on a fixed regular grid.
Each exact batch refits Gaussian processes for the objective and each descriptor. MAP-Elites perturbs observed points and predicted elites. An auxiliary cell retains the highest signed objective UCB within its predicted descriptor bounds. Sobol targets in descriptor space select cells for exact measurement. The supplied grid only receives measurements.
- Parameters:
container – Empty, parentless, best-only Grid with one signed objective.
budget – Exact evaluation attempts for optimise().
dimension – Length of the continuous decision vector.
ind_domain – Common lower and upper decision bounds.
initial_samples – Minimum successful measurements before fitting models.
surrogate_budget – Maximum number of predicted genomes per acquisition map.
surrogate_batch_size – Number of offspring per auxiliary MAP-Elites update.
exploration – Nonnegative objective standard deviation multiplier.
mutation_sigma – Gaussian variation scale in normalized decision space.
length_scale – Fixed RBF kernel length scale in normalized decision space.
batch_size – Maximum exact proposals per model update.
seed – Private Sobol and variation seed.
kwargs – Native QDAlgorithm settings.
- add_callback(event: str, fn: Callable) None¶
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()¶
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.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property batch_size: int¶
Configured candidate count per iteration, or the current budget when omitted.
- best() IndividualLike¶
Return the best retained candidate.
- Raises:
RuntimeError – If the container has no candidates.
- property current_iter¶
Number of committed generations, including partial generations.
- classmethod from_config(config: Mapping[str, Any], **kwargs: Any) Any¶
Create a class using the information from config to call the class constructor.
Parameters¶
- param config:
Mapping[str, Any] The configuration mapping used to create the class. For each entry, the key corresponds to the name of a parameter of the constructor of the class.
- param kwargs:
Any Additional information used to create the class. The configuration entries from kwargs take precedence over the entry in config.
- property misclassified¶
Return checked predictions assigned to a different cell, including out-of-grid measures.
- property modelled_proposals¶
Return the number of exact proposals promoted from an acquisition cell.
- property nb_evaluations: int¶
Number of tell calls or candidate slots consumed by the managed scheduler.
- property nb_evaluations_in_iteration: int¶
Number of accounted evaluations since the last iteration ended.
- property nb_max_iter: int | float¶
Ceiling of the current budget divided by the batch size for a finite run.
- property nb_suggestions: int¶
Number of candidates returned by ask since initialisation or reinitialisation.
- property nb_suggestions_in_iteration: int¶
Number of asks recorded since the last managed iteration ended.
- property nb_updated: int¶
Number of evaluations for which the archive reported a local update.
- property nb_updated_in_iteration: int¶
Number of reported archive updates since the last iteration ended.
- property optimisation_task: str | Sequence[float]¶
The objective direction or explicit comparison weights.
- optimise(*args, **kwargs)¶
Schedule fixed generations via the native optimiser.
- property prediction_checks¶
Return the number of promoted proposals with a valid measurement.
- prediction_map(budget=None, *, seed=0)[source]¶
Return immutable SPHENPrediction rows without calling the evaluator.
The budget counts model queries for this map alone. It defaults to surrogate_budget. The method uses the latest completed measurements and a local random stream. It leaves the measured archive, search streams, and acquisition counters intact.
- 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.
- summary(max_depth: int | None = None, max_entry_length: int | None = 250) str¶
Return a summary description of the class. The summarised information is provided by the self.__get_summary_state__ method.
Parameters¶
- param max_depth:
Optional[int] The maximal recursion depth allowed. Used to summarise attributes of self that are also Summarisable. If the maximal recursion depth is reached, the attribute is only described with a reduced representation (repr(attribute)). If max_depth is set to None, there are no recursion limit.
- param max_entry_length:
Optional[int] If max_entry_length is not None, the description of a non-Summarisable entry exceeding max_entry_length is cropped to this limit.
- property surrogate_evaluations¶
Return the number of predictions used to plan exact proposals.
- tell(individual, fitness=None, features=None, scores=None, elapsed=None, verbose=False, tell_container=True)¶
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_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- tell_container_entries(cont: Container | None = None) None¶
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.SPHENPrediction(cell: tuple, genome: tuple, fitness: float, features: tuple)[source]¶
Describe a model-selected design in raw units.
- Variables:
cell – Predicted cell in the supplied grid geometry.
genome – Proposed design in the original decision domain.
fitness – Predicted objective in its original optimisation direction.
features – Predicted descriptor vector used to assign the cell.
- class qdpy.algorithms.MOLE(bounds, *, step_size=None, min_step=None, gradient_tolerance=1e-6, max_descent_steps=256)[source]¶
Use joint descent, then trace each discovered set in both objective directions.
A callback supplies both objective values and their analytic Jacobian at each evaluated point. MOLE corrects secant predictions with local multi-objective descent and queues corrected points when continuation crosses into another basin. All calls share one evaluation budget.
- Parameters:
bounds – Sequence of finite increasing (lower, upper) pairs, one per coordinate.
step_size – Maximum spatial step for descent and tracing. Defaults to one hundredth of the decision box diagonal.
min_step – Smallest continuation and backtracking step. Defaults to one thousandth of step_size.
gradient_tolerance – Joint-gradient norm considered stationary.
max_descent_steps – Maximum accepted descent steps per correction.
- run(evaluate, starts, budget)[source]¶
Return approximate local curves from a bounded continuous problem.
evaluate receives a copy of a one-dimensional NumPy genome and returns (two costs, a 2-by-dimension Jacobian). Both costs are minimized. A run starts with empty traces. The result includes points already retained when a correction runs out of evaluations.
- class qdpy.algorithms.MOLEPoint(genome: tuple, objectives: tuple)[source]¶
Store a decision vector and its two measured objective values.
- class qdpy.algorithms.MOLEResult(sets: tuple, transitions: tuple, evaluations: int)[source]¶
Report the approximate local sets recovered within the callback budget.
- Variables:
sets – Curves of MOLEPoint records ordered by continuation.
transitions – Directed (source_set_index, destination_set_index) pairs.
evaluations – Number of joint objective and Jacobian evaluations.
- class qdpy.algorithms.QDHeuristicDesign(archive, *, structure, propose, evaluate, instance_features, descriptor_indices, neighbors=3, ridge=1., seed=0)[source]¶
Build a grid of heuristics that can be selected without scoring a new instance.
A ridge model fits signed mean performance against structural features of the calibration heuristics. Its interventional Shapley values are exact for the fitted linear predictor. The caller selects which attributions to map to grid coordinates, and all attributions inform the proposal callback. The calibration baseline and mapping are frozen before search so any two elites use the same niche definitions.
- Parameters:
archive – Empty parentless rectangular best-only Grid with a finite nonzero scalar fitness weight and (-1, 1) bounds on each descriptor.
structure – Callback returning a fixed-width finite vector from a hashable, immutable heuristic representation.
propose – Callback receiving (parent, attribution_tuple, rng) and returning a heuristic or None to reject a proposal.
evaluate – Callback returning raw scalar fitness for (heuristic, instance).
instance_features – Callback returning a finite vector for one instance.
descriptor_indices – Distinct structural feature indices, one per grid axis.
neighbors – Number of most similar training instances used for selection.
ridge – Positive ridge regularization used on standardized structural features.
seed – Private proposal seed.
- run(calibration, training_instances, budget, *, proposal_limit=None)[source]¶
Measure at least two distinct calibration heuristics, then evolve the repertoire.
Each complete panel costs one call per training instance. The budget must cover calibration. A remainder smaller than one panel stays unused. Duplicate and declined proposals count toward proposal_limit, which defaults to ten times the affordable panels. Create a fresh search to calibrate on a different panel.
- class qdpy.algorithms.HeuristicDesignStats(proposals: int, measured: int, evaluations: int, archive_updates: int)[source]¶
Count proposals, distinct measured heuristics, evaluations, and admissions.
- qdpy.algorithms.ast_node_counts(source, node_names)[source]¶
Return counts in the supplied AST class-name order.
SyntaxError from ast.parse lets callers reject malformed proposals before they submit them to a training evaluator.
- class qdpy.algorithms.MILPArchiveSearch(archive, objective, bounds, descriptor_matrix, *, descriptor_offset=None, integrality=None, constraints=(), time_limit=None, node_limit=None)[source]¶
Build one MILP per requested cell and verify its incumbent before admission.
Decision coordinates can be continuous or integer. Each descriptor is an integer affine function of integer decision coordinates. Cell constraints use the exact integer endpoints implied by Grid.index_grid. The supplied grid’s objective direction and objective bounds govern optimization. An “optimal” result means HiGHS reported optimality with zero requested relative gap and QDpy verified the incumbent.
- Parameters:
archive – Empty parentless rectangular one-elite Grid with room for every cell.
objective – One finite linear objective coefficient per coordinate.
bounds – Finite lower and upper scipy.optimize.Bounds for the decision vector.
descriptor_matrix – One integer coefficient row per descriptor.
descriptor_offset – Optional integer constant per descriptor (default zero).
integrality – Boolean mask with 1 for integer and 0 for continuous coordinates. Defaults to integer on every axis.
constraints – A LinearConstraint or sequence of shared constraints.
time_limit – Optional positive time limit in seconds per cell.
node_limit – Optional positive node limit per cell.
- class qdpy.algorithms.MILPCellResult(cell: tuple, status: str, genome: tuple | None = None, fitness: float | None = None, features: tuple | None = None, objective_bound: float | None = None, solver_status: int | None = None, message: str = '')[source]¶
Keep the verified incumbent and the original termination details.
- Variables:
cell – Rectangular cell index.
status – “optimal”, “infeasible”, or “unresolved”.
genome – Verified incumbent, if available.
fitness – Raw linear objective of the incumbent.
features – Integer-valued descriptors of the incumbent.
objective_bound – Solver bound in raw units, when reported.
solver_status – SciPy status code, or None if no solver call was needed.
message – Original termination or verification message.
- class qdpy.algorithms.CartesianGraphSpace(inputs, outputs, nodes, *, primitives=None, constants=(.1, 1.), operation_rate=None, connection_rate=None)[source]¶
Lay out graph nodes in one sequence, with the last nodes as outputs.
Every node has an operation gene and two predecessor genes. Operands may refer to observations, constants, or strictly earlier function nodes. Unary functions ignore the second connection. Inactive nodes can still mutate, so later connections can activate new computations.
- Parameters:
inputs – Number of observation coordinates.
outputs – Number of scalar outputs, beginning at the last outputs nodes.
nodes – Total number of function nodes in the genotype.
primitives – Ordered built-in operation names. Defaults to all operations.
constants – Finite scalar terminals available to every node.
operation_rate – Optional independent mutation rate for operation genes.
connection_rate – Optional independent mutation rate for operand genes. Unspecified rates default to the inverse genotype length.
- class qdpy.algorithms.CartesianGraphPolicy(space, genome)[source]¶
Evaluate an acyclic graph of built-in scalar operations on one observation.
Inputs and intermediate values are clipped to ±1e6. A protected division returns its numerator at a near-zero denominator. Above-zero, below-zero, and comparison primitives return 0 or 1. Output clipping to the environment’s action bounds belongs to the caller.
- Parameters:
space – CartesianGraphSpace defining the genotype.
genome – Flat sequence of validated integer genes.
- class qdpy.algorithms.GraphMAPElites(container, budget, space, *, seed=0, **kwargs)[source]¶
Illuminate behavioral, structural, or joint descriptors using CGP.
Native evaluators receive an integer genome. Use the space’s decode method to obtain a controller, and append structure_descriptors to the behavioral measurements for joint illumination. Each of those two axes reports the fraction of all genotype nodes occupied by active unary or binary functions.
Feedback is applied in proposal order within each generation. For manual evaluation, use ask_batch() and tell_batch().
- Parameters:
container – Best-only Grid or CVTGrid with one objective.
budget – Candidate evaluation attempts.
space – CartesianGraphSpace used for initialization and mutation.
seed – Private initialization and parent selection seed.
kwargs – Native QDAlgorithm settings, including batch_size.
- add_callback(event: str, fn: Callable) None¶
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()¶
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.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property batch_size: int¶
Configured candidate count per iteration, or the current budget when omitted.
- best() IndividualLike¶
Return the best retained candidate.
- Raises:
RuntimeError – If the container has no candidates.
- property current_iter¶
Number of committed generations, including partial generations.
- classmethod from_config(config: Mapping[str, Any], **kwargs: Any) Any¶
Create a class using the information from config to call the class constructor.
Parameters¶
- param config:
Mapping[str, Any] The configuration mapping used to create the class. For each entry, the key corresponds to the name of a parameter of the constructor of the class.
- param kwargs:
Any Additional information used to create the class. The configuration entries from kwargs take precedence over the entry in config.
- property nb_evaluations: int¶
Number of tell calls or candidate slots consumed by the managed scheduler.
- property nb_evaluations_in_iteration: int¶
Number of accounted evaluations since the last iteration ended.
- property nb_max_iter: int | float¶
Ceiling of the current budget divided by the batch size for a finite run.
- property nb_suggestions: int¶
Number of candidates returned by ask since initialisation or reinitialisation.
- property nb_suggestions_in_iteration: int¶
Number of asks recorded since the last managed iteration ended.
- property nb_updated: int¶
Number of evaluations for which the archive reported a local update.
- property nb_updated_in_iteration: int¶
Number of reported archive updates since the last iteration ended.
- property optimisation_task: str | Sequence[float]¶
The objective direction or explicit comparison weights.
- optimise(*args, **kwargs)¶
Schedule fixed generations via the native optimiser.
- 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.
- summary(max_depth: int | None = None, max_entry_length: int | None = 250) str¶
Return a summary description of the class. The summarised information is provided by the self.__get_summary_state__ method.
Parameters¶
- param max_depth:
Optional[int] The maximal recursion depth allowed. Used to summarise attributes of self that are also Summarisable. If the maximal recursion depth is reached, the attribute is only described with a reduced representation (repr(attribute)). If max_depth is set to None, there are no recursion limit.
- param max_entry_length:
Optional[int] If max_entry_length is not None, the description of a non-Summarisable entry exceeding max_entry_length is cropped to this limit.
- tell(individual, fitness=None, features=None, scores=None, elapsed=None, verbose=False, tell_container=True)¶
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_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- tell_container_entries(cont: Container | None = None) None¶
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.QDSelfPlay(initial, *, play, propose, embed, novelty_radius=.1, neighbors=3, opponents=3, is_novel=None, seed=0)[source]¶
Alternate between two unstructured archives for opposing roles.
A sampled matchup gives the proposer context. If its candidate is novel enough, the archive keeps it as a stepping stone. Otherwise the candidate must beat its closest archived neighbor on a common panel of opponents. Scores are interpreted in the current role’s units and larger is better for both roles. Archives hold the strategy and its immutable embedding. Match outcomes are local to their comparison.
- Parameters:
initial – One hashable immutable seed strategy per role.
play – Callable taking (role_0_strategy, role_1_strategy) and returning a finite pair of scores in that order.
propose – Callable taking (QDSelfPlayContext, rng) and returning a strategy or None to skip the proposal.
embed – Callable taking (role, strategy) and returning a finite vector.
novelty_radius – Candidate distance above which a strategy is considered novel.
neighbors – Maximum nearest strategies supplied to the proposer or novelty callback.
opponents – Maximum distinct opponents used in each local comparison.
is_novel – Optional callable taking (role, strategy, neighbors) and returning a boolean, to replace the radius decision.
seed – Private random seed.
- property archives¶
Return immutable snapshots of the strategies in role order.
- run(budget)[source]¶
Use the same sampled opponent panel for both members of a duel.
Each proposal costs one context match. A local update needs at least two more calls. A run can leave up to two calls unused. The final panel can be smaller than opponents when budget is low.
- property stats¶
Return cumulative accounting, including attempted callback calls.
- class qdpy.algorithms.QDSelfPlayContext(role: int, parents: tuple, payoffs: tuple, neighbors: tuple)[source]¶
Store one observed matchup and similar strategies for the side to mutate.
- Variables:
role – Index of the side for which a strategy is requested.
parents – Sampled pair, in fixed role-0, role-1 order.
payoffs – Observed scores for the sampled pair, in role order.
neighbors – Up to k other archived strategies near the active parent.
- class qdpy.algorithms.QDSelfPlayStats(matches: int, proposals: int, duplicates: int, novel_admissions: int, local_replacements: int)[source]¶
Count matches, proposals, duplicate strategies, admissions, and local wins.
- class qdpy.algorithms.YouthMAPElites(container, budget, dimension, *, parent_window=16, ind_domain=(0., 1.), sigma=.1, mutate=None, seed=0, **kwargs)[source]¶
Draw uniformly from the last parent_window current archive admissions.
Successful insertions and replacements appear at the end of the native Grid or CVTGrid storage. Rejected offspring leave that order unchanged. The list therefore reflects the youngest retained parents, including when starting from a prefilled archive. Each generation commits feedback in proposal order. Manual evaluations use ask_batch() and tell_batch().
- Parameters:
container – Best-only regular Grid or CVTGrid.
budget – Candidate evaluation attempts.
dimension – Number of real genome coordinates.
parent_window – Maximum number of recent elites eligible for sampling.
ind_domain – Common lower and upper bounds for each coordinate.
sigma – Standard deviation of default Gaussian mutation.
mutate – Optional callable taking (parent_tuple, rng) and returning a genome.
seed – Private seed.
kwargs – Native algorithm settings such as batch_size.
- add_callback(event: str, fn: Callable) None¶
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()¶
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.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property batch_size: int¶
Configured candidate count per iteration, or the current budget when omitted.
- best() IndividualLike¶
Return the best retained candidate.
- Raises:
RuntimeError – If the container has no candidates.
- property current_iter¶
Number of committed generations, including partial generations.
- classmethod from_config(config: Mapping[str, Any], **kwargs: Any) Any¶
Create a class using the information from config to call the class constructor.
Parameters¶
- param config:
Mapping[str, Any] The configuration mapping used to create the class. For each entry, the key corresponds to the name of a parameter of the constructor of the class.
- param kwargs:
Any Additional information used to create the class. The configuration entries from kwargs take precedence over the entry in config.
- property nb_evaluations: int¶
Number of tell calls or candidate slots consumed by the managed scheduler.
- property nb_evaluations_in_iteration: int¶
Number of accounted evaluations since the last iteration ended.
- property nb_max_iter: int | float¶
Ceiling of the current budget divided by the batch size for a finite run.
- property nb_suggestions: int¶
Number of candidates returned by ask since initialisation or reinitialisation.
- property nb_suggestions_in_iteration: int¶
Number of asks recorded since the last managed iteration ended.
- property nb_updated: int¶
Number of evaluations for which the archive reported a local update.
- property nb_updated_in_iteration: int¶
Number of reported archive updates since the last iteration ended.
- property optimisation_task: str | Sequence[float]¶
The objective direction or explicit comparison weights.
- optimise(*args, **kwargs)¶
Schedule fixed generations via the native optimiser.
- 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.
- summary(max_depth: int | None = None, max_entry_length: int | None = 250) str¶
Return a summary description of the class. The summarised information is provided by the self.__get_summary_state__ method.
Parameters¶
- param max_depth:
Optional[int] The maximal recursion depth allowed. Used to summarise attributes of self that are also Summarisable. If the maximal recursion depth is reached, the attribute is only described with a reduced representation (repr(attribute)). If max_depth is set to None, there are no recursion limit.
- param max_entry_length:
Optional[int] If max_entry_length is not None, the description of a non-Summarisable entry exceeding max_entry_length is cropped to this limit.
- tell(individual, fitness=None, features=None, scores=None, elapsed=None, verbose=False, tell_container=True)¶
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_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- tell_container_entries(cont: Container | None = None) None¶
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.
- qdpy.algorithms.select_youth(archive, count, *, rng=None)[source]¶
Return a live recent elite from a nonempty insertion-ordered archive.
A NumPy Generator can supply the draw. The default uses Python’s random stream, as do the native polynomial mutation operators.
- class qdpy.algorithms.FAERY(grid_factory, mutate, *, task_budget, offspring=4, tasks_per_generation=None, success_limit=None, seed=0)[source]¶
Meta-evolve a prior using mutation-only MAP-Elites as the inner search.
During training, the current prior and its mutated candidates are measured together on each task. A successful genome credits its original root, including a successful root at depth zero. Track successes by genome within each task, using their first successful evaluations. Pareto selection favors more successes and lower mean mutation depth.
- Parameters:
grid_factory – Callable taking a task and returning a fresh, empty best-only Grid or CVTGrid.
mutate – Callable taking (genome_tuple, rng) and returning a new immutable genome.
task_budget – Maximum evaluator calls for one inner task, including initial genomes.
offspring – Number of outer mutation proposals per generation.
tasks_per_generation – Number of tasks sampled without replacement. Defaults to all tasks.
success_limit – Optional stop after this many distinct successes. All initial genomes are measured.
seed – Seed for outer sampling, mutation, and tie-breaking.
- class qdpy.algorithms.FAERYResult(prior: tuple, history: tuple[FAERYGeneration, ...], evaluations: int)[source]¶
Hold selected genomes and total training evaluations across generations.
- class qdpy.algorithms.FAERYGeneration(candidates: tuple, success_counts: tuple[int, ...], mean_depths: tuple[float | None, ...], selected: tuple[int, ...], evaluations: int)[source]¶
Report counts and mean depths in candidate order, with selected indices.
Candidates with zero successes have a mean_depths entry of None.
- class qdpy.algorithms.FAERYTaskResult(archive: Grid, successes: tuple[FAERYSuccess, ...], evaluations: int, first_success: int | None)[source]¶
Store a native archive, distinct successes, and measured evaluation costs.
first_success is the one-based evaluation number, or None if no evaluated genome satisfied the task’s success predicate.
- class qdpy.algorithms.FAERYSuccess(genome: tuple, root: int, depth: int)[source]¶
Record a successful genome, its prior index, and its mutation depth.
- class qdpy.algorithms.HillVallEA(bounds, *, maximise=True, initial_samples=None, selection_fraction=.5, neighbors=None, max_probes=5, local_population=6, local_generations=12, fitness_tolerance=1e-3, seed=0)[source]¶
Cluster nearest-better candidates using line tests, then refine each basin.
This bounded variant uses CMA-ES for local search. Restart populations include the retained near-optima and grow when a restart finds no new basin. Every evaluation, including intermediate tests for clustering and duplicate-peak checks, reduces the same hard budget. Requires the optional cma extra at run time.
- Parameters:
bounds – Finite increasing (lower, upper) pairs per decision coordinate.
maximise – Maximize fitness if true, otherwise minimize it.
initial_samples – Number of random candidates at the first restart (default 16 per dimension).
selection_fraction – Fraction of sampled and retained points to cluster.
neighbors – Number of earlier nearest points to consider during clustering.
max_probes – Maximum interpolation points per line test.
local_population – Starting population size for each local CMA-ES.
local_generations – Maximum number of CMA-ES generations per cluster.
fitness_tolerance – Retain niche representatives within this fitness gap of the best retained peak.
seed – Private seed.
- class qdpy.algorithms.HillValleyResult(peaks: tuple[HillValleyPeak, ...], best: HillValleyPeak, samples: int, probes: int, local_evaluations: int, restarts: int)[source]¶
Keep the evaluated best point and the near-optimal niche representatives.
- property evaluations¶
Return the total number of objective calls.
- class qdpy.algorithms.HillValleyPeak(genome: tuple[float, ...], fitness: float)[source]¶
Store a decision vector and its raw scalar fitness.
- class qdpy.algorithms.QDEvo(*, propose, embed, evaluate, fitness_weights, similarity=.95, crossover_probability=.25, seed=0)[source]¶
Support QDEvo’s semantic survival and parent selection through callbacks.
Normalize each embedding before comparing cosine similarities. In insertion order, find the first cluster where the candidate matches every current member. A candidate competes only in that cluster. If no cluster qualifies, it starts another one. Clusters retain their identity after pruning. A callback can canonicalize its heuristic representation before proposing it to share the duplicate filter.
- Parameters:
propose – Callable taking (tuple_of_parent_entries, rng) and returning a hashable immutable heuristic or None to skip the proposal. The parent tuple is empty while bootstrapping. A dominating crossover parent is passed first.
embed – Callable mapping a valid heuristic to a finite nonzero vector.
evaluate – Callable returning a finite objective vector, or None for a failed heuristic.
fitness_weights – Two or more signed directions, positive for maximize and negative for minimize.
similarity – Minimum cosine similarity to every currently retained cluster member.
crossover_probability – Probability of drawing two distinct parents when available.
seed – Private proposal and parent selection seed.
- property clusters¶
Return immutable cluster snapshots, one local Pareto front per cluster.
- run(budget, *, initial=(), proposal_limit=None)[source]¶
Evaluate optional seeds first, then spend up to budget more exact calls.
Previously evaluated candidates and declined proposals consume no evaluation calls. Each generator invocation counts toward the proposal cap, which defaults to ten times budget. Evaluation returning None is counted as invalid, and callback errors propagate.
- property stats¶
Return counters across all completed or interrupted run calls.
- class qdpy.algorithms.QDEvoEntry(heuristic: object, objectives: tuple[float, ...], embedding: tuple[float, ...])[source]¶
Store a heuristic, its raw objective vector, and a unit embedding.
- class qdpy.algorithms.QDEvoStats(proposals: int, evaluations: int, invalid: int, duplicates: int, admissions: int)[source]¶
Count generator calls, evaluator calls, invalids, duplicates, and admissions.
- class qdpy.algorithms.CMAMAEGA(container, budget, x0, sigma0, batch_size, threshold_min, *, gradient_evaluate, step_size=1.0, **kwargs)[source]¶
CMA-MAE with a gradient arborescence over the current centre.
Install the optional
cmaextra. Each centre evaluation consumes one candidate slot. Subsequent offspring use the ordinary QDpy evaluator. The centre and offspring batches each emit an iteration callback.- Parameters:
gradient_evaluate – Callable returning a GradientEvaluation.
step_size – Multiplier for the rank-weighted centre displacement.
sigma0 – Initial step size in gradient coefficient coordinates.
kwargs – CMA-MAE options, including the reporting grid, bounds, budget, initial point, batch size, threshold and archive learning rate.
- property centre¶
Return a copy of the current gradient search point.
- property gradient_evaluations¶
Number of attempted centre evaluations, including failed calls.
- class qdpy.algorithms.CMAMEGA(container, budget, x0, sigma0, batch_size, *, gradient_evaluate, step_size=.05, centre_optimizer='adam', **kwargs)[source]¶
Analytic CMA-MEGA, with Adam for the centre update by default.
Each branch generation uses one measured Jacobian at the centre. New cells rank above same-cell improvements. Rejected offspring rank below both. Offspring use the ordinary QDpy evaluator.
- Parameters:
container – Empty best-only scalar Grid or CVTGrid without parents.
budget – Total candidate calls, including centre Jacobians.
x0 – Starting point in genome coordinates.
sigma0 – Initial standard deviation in coefficient space.
batch_size – Number of candidate branches per Jacobian.
gradient_evaluate – Callable returning a GradientEvaluation.
step_size – Learning rate for the centre update.
centre_optimizer – “adam” or the paper’s plain “gradient” update.
kwargs – Native algorithm settings, including ind_domain and seed.
- ask_batch(size=None)¶
Issue offspring after a successful centre evaluation.
- ask_dqd()¶
Return the centre, ready for a report through
tell_dqd().
- property centre¶
Return a copy of the current gradient search point.
- property gradient_evaluations¶
Number of attempted centre evaluations, including failed calls.
- tell_batch(results)¶
Commit the pending offspring in proposal order.
- tell_dqd(result)¶
Report a GradientEvaluation or
Nonefor a failed centre call.
- class qdpy.algorithms.OMGMEGA(container, budget, dimension, *, sigma=.1, batch_size=1, ind_domain=(0., 1.), seed=0, **kwargs)[source]¶
Draw Gaussian coefficients and use the absolute coefficient for fitness.
One combined evaluator call yields a GradientEvaluation for each candidate. Its normalized Jacobian is stored with the candidate if admitted, so future offspring reuse the measured basis. Descriptor coefficients remain signed. The fitness row follows the configured optimization direction.
- Parameters:
container – Empty parentless best-only Grid or CVTGrid with one objective.
budget – Combined fitness, descriptor, and Jacobian calls.
dimension – Number of decision variables.
sigma – Standard deviation of the sampled coefficients.
batch_size – Number of candidates proposed before a generation commits.
ind_domain – Shared decision bounds for sampling and clipping.
seed – Private seed for initialization, selection, and gradient coefficients.
kwargs – Native QDAlgorithm settings.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property gradient_evaluations¶
Return combined evaluation attempts, including failed gradient calls.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.CycleQD(base, experts, task_domains, *, bins=12, fitness_weights=None, task_order=None, parent_weight_bounds=(.1, 1.), merge_mean=1., merge_std=.3, svd_max=2., seed=0)[source]¶
Maintain one Grid for each objective role and score every checkpoint on all tasks.
Each archive maximizes or minimizes its active task. Other tasks supply the descriptor axes in the original order. Every measured candidate is offered to all archives. Parent probabilities follow the product of rescaled task performances in the active archive.
- Parameters:
base – Ordered real numeric tensors from the common base model.
experts – Nonempty checkpoints with the same ordered tensor shapes.
task_domains – One finite increasing interval for each task score.
bins – Common bin count or one bin count per task descriptor.
fitness_weights – Optional signed weights for task directions. All tasks maximize by default.
task_order – Optional sequence of breeding task indices. Defaults to all tasks in order. One task gives a fixed-role control.
parent_weight_bounds – Positive (low, high) range for the product score.
merge_mean – Mean of the two Gaussian crossover coefficients.
merge_std – Standard deviation of the Gaussian crossover coefficients.
svd_max – Upper bound for each singular-component multiplier. Set to None for crossover alone.
seed – Private seed for parent choice, crossover and mutation.
- class qdpy.algorithms.CycleQDStats(evaluations: int, expert_evaluations: int, archive_updates: int, out_of_domain: int, breeding_by_task: tuple[int, ...])[source]¶
Count each measured checkpoint once, independent of archive count.
- class qdpy.algorithms.BooleanConjunction(required: frozenset[int] = frozenset({}), excluded: frozenset[int] = frozenset({}))[source]¶
Match a subset containing every required index and no excluded index.
- class qdpy.algorithms.ConjunctionMAPElites(dimension, rules, *, max_items=None, mutation_probability=None, crossover_probability=0., fitness_domain=(-np.inf, np.inf), fitness_weight=1., seed=0)[source]¶
Optimize overlapping subset problems with one objective evaluation per proposal.
Give each rule a named cardinality archive. Try the required subset for every rule that still has an empty archive. Later choose parents uniformly across occupied rule/cardinality cells. Use independent bit flips and optional uniform crossover. A proposed subset matching several rules may improve all their archives.
- Parameters:
dimension – Number of available items.
rules – Mapping from nonempty names to BooleanConjunction objects.
max_items – Largest admissible subset size shared by the rules.
mutation_probability – Independent bit flip rate.
crossover_probability – Probability of choosing two parents and mixing their bits before mutation.
fitness_domain – Closed interval of admissible raw objective values.
fitness_weight – Signed objective weight. Positive maximizes.
seed – Private variation seed.
- class qdpy.algorithms.ConjunctionSearchStats(proposals: int, evaluations: int, over_limit: int, unmatched: int, archive_updates: int)[source]¶
Count measured subsets, rejected proposals, and updates across rule archives.
- class qdpy.algorithms.DivTuRBO1(genome_bounds, *, population_size, distance, phases=1, fitness_weight=-1., initial_samples=5, candidate_pool=64, seed=0)[source]¶
Implement the sequential and interleaved schedules of Perera et al.
Fit a local Matérn GP and sample from its posterior over a perturbed candidate pool. Fit only the current region’s measurements and keep all measurements for final selection. Choose the best feasible centre and prefer feasible candidates. If no point meets the separation requirement, favor the one farthest from its nearest reference. Check the returned minimum distance and violation count.
- Parameters:
genome_bounds – One finite increasing interval per decision coordinate.
population_size – Number of portfolio members to search for.
distance – Minimum Euclidean separation in the original decision units.
phases – One for the sequential method. Use more for interleaving.
fitness_weight – Sign of the objective direction. Positive maximizes.
initial_samples – Global Sobol calls when starting or restarting a region.
candidate_pool – Maximum number of local candidates per evaluation.
seed – Private seed for the independent trust regions.
- class qdpy.algorithms.DivTuRBOPoint(genome: tuple[float, ...], fitness: float)[source]¶
Store the evaluated design and its raw fitness.
- class qdpy.algorithms.DivTuRBOResult(solutions: tuple[DivTuRBOPoint, ...], evaluations_by_slot: tuple[int, ...], restarts_by_slot: tuple[int, ...], minimum_distance: float | None, violating_pairs: int)[source]¶
Minimum distance is None for a singleton portfolio.
- property evaluations¶
Return the total number of objective calls.
- qdpy.algorithms.qd_subgoal_mcts(start, *, actions, simulate, describe, budget, horizon, macro_steps=3, probes=8, subgoals=3, neighbors=3, reward_weight=.5, discount=.99, exploration=1.4, start_terminated=False, seed=0)[source]¶
Interleave local trajectory discovery with a high-level subgoal tree.
Each visit to an unexpanded macro node samples one path in its low-level tree. Local UCB uses discounted distance gains from that node. Once enough paths are available, keep a small set using novelty and local reward comparisons. High-level UCB backs up task rewards and uses the sampled endpoints for continuation rollouts. Return the best complete primitive path under discounted reward, or a measured prefix if the budget allowed only partial paths.
- Parameters:
start – Initial simulator snapshot.
actions – Callable yielding available actions for a snapshot.
simulate – Pure deterministic callback (state, action) returning (successor, finite reward, terminated). Treat snapshots as immutable.
describe – Callable returning a fixed nonempty numeric state descriptor.
budget – Maximum total calls to simulate, including low-level search.
horizon – Maximum primitive steps in any searched path.
macro_steps – Target primitive length of a subgoal trajectory. Terminal and dead-end paths can be shorter.
probes – Complete low-level samples before publishing subgoals, or fewer if the local tree is exhausted.
subgoals – Maximum number of macro-actions published per node.
neighbors – Nearest selected endpoints used in the local comparison.
reward_weight – Weight of local competition relative to novelty.
discount – Per-primitive-step reward and distance discount.
exploration – UCB exploration coefficient in both trees.
start_terminated – Whether the initial snapshot is already terminal.
seed – Private action-selection and rollout seed.
- qdpy.algorithms.primitive_mcts(start, *, actions, simulate, budget, horizon, discount=.99, exploration=1.4, start_terminated=False, seed=0)[source]¶
Run the primitive-action control with cached deterministic transitions.
See
qd_subgoal_mcts()for the simulator contract. The same horizon, reward discount, and simulator-call cap apply. Tree traversals pick an untried action uniformly or use UCB over existing children. Search ends early if the finite tree is exhausted.
- class qdpy.algorithms.MCTSPlan(actions: tuple, final_state: object, rewards: tuple[float, ...], terminated: bool)[source]¶
Hold the actual successor, reward sequence, and terminal flag.
- property return_¶
Return the undiscounted sum of rewards.
- class qdpy.algorithms.MCTSResult(plan: MCTSPlan, root_subgoals: tuple[MCTSPlan, ...], simulator_calls: int, low_level_calls: int, simulations: int, published_subgoals: int)[source]¶
Return the best observed path and the published subgoals at the root.
- class qdpy.algorithms.BayesianParetoIllumination(container, budget, dimension, ind_domain, *, reference, initial_samples=None, candidate_pool=128, restarts=8, seed=0)[source]¶
Sequential Bayesian illumination of measured two-objective Pareto fronts.
Fit independent fixed-kernel GP models for each objective and descriptor. For each candidate, sum per-cell expected hypervolume improvement multiplied by the probability of landing in that cell. Use actual evaluations for Pareto admission. Finite evaluations outside the archive bounds can still inform the models.
- Parameters:
container – A crowding ParetoGrid with two objectives and one or two descriptors. Use direct fitness and features.
budget – Number of true evaluation attempts.
dimension – Number of bounded real decision variables.
ind_domain – Shared finite decision bounds.
reference – Two raw objective coordinates weakly dominated by the worst objective corner of the declared fitness domain.
initial_samples – Number of initial Sobol proposals.
candidate_pool – Sobol candidates screened per acquisition.
restarts – Maximum number of local acquisition refinements.
seed – Seed for the scrambled Sobol proposal stream.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property n_observations¶
Number of finite observations available to the models.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.ASDelta(container, budget, dimension, *, delta_f, delta_r, sampling_size=128, initial_samples=2, estimator='median', reproducibility=None, ind_domain=(0., 1.), iso_sigma=.01, line_sigma=.2, seed=0)[source]¶
Maintain a preference-ordered depth in every occupied descriptor cell.
Refresh every incumbent once per generation before selecting new parents. An offspring requires a complete initial repeat group. Failed refreshes retain the last estimate and every attempted rollout counts. Rebuild the rankings from refreshed measurements, including changes of niche. A final generation needs room for all refreshes and one offspring group.
- Parameters:
container – Empty standalone Grid or CVTGrid with one objective. Its max_items_per_bin sets the depth. Leave it under the search’s control.
budget – Total raw rollout attempts, including incumbent refreshes.
dimension – Number of bounded real decision variables.
delta_f – Fitness tolerance in raw fitness units.
delta_r – Reproducibility improvement required to accept a performance loss.
sampling_size – Maximum raw rollout attempts per generation. It must allow a full archive refresh and at least one new candidate.
initial_samples – Number of repeated measurements for new candidates.
estimator – “mean” or “median” for both measurements, or a pair selecting the fitness and descriptor estimators independently.
reproducibility – Optional callable taking the matrix of raw descriptors and returning a finite scalar to maximize. Defaults to negative mean population standard deviation across the descriptor coordinates.
ind_domain – Shared decision bounds.
iso_sigma – Independent Iso+LineDD noise scale.
line_sigma – Directional Iso+LineDD noise scale.
seed – Seed for variation and the independent rollout stream.
- class qdpy.algorithms.CPDEA(genome_bounds, fitness_weights, *, population_size=60, neighbors=3, eta=2., seed=0)[source]¶
Run the steady-state algorithm of Liu et al. on bounded real decisions.
Penalize decision distances by the local presence of objective-space dominators. Update a separate nondominated archive using both decision and objective distances. Use population tournaments in the first half of the budget, then also mate sparse archive elites with nearby designs.
- Parameters:
genome_bounds – Finite increasing (lower, upper) intervals, one per variable.
fitness_weights – At least two signs. Positive maximizes and negative minimizes.
population_size – Size of the breeding population and cap of the archive.
neighbors – Number of nearest other solutions used in either density.
eta – Scale of the local-convergence bandwidth in Eq. 17.
seed – Private seed for initialization, mating, and variation.
- optimise(evaluate, budget)[source]¶
Call evaluate(genome) for raw objectives and return a
CPDEAResult.
- class qdpy.algorithms.CPDEAPoint(genome: tuple[float, ...], fitness: tuple[float, ...])[source]¶
Store a decision vector and its raw objective vector.
- class qdpy.algorithms.CPDEAResult(archive: tuple[CPDEAPoint, ...], population: tuple[CPDEAPoint, ...], evaluations: int)[source]¶
The final nondominated archive and final population are independent views.
- class qdpy.algorithms.BOPElites(container, budget, dimension, ind_domain, quality_floor, *, initial_samples=None, candidate_pool=128, restarts=8, seed=None, model_feasibility=False, descriptor_transform=None, latent_size=None, posterior_samples=256, **kwargs)[source]¶
Fit independent objective and descriptor Gaussian processes after each observation.
A scrambled Sobol sequence supplies initial points and acquisition restarts. The result grid contains genuine evaluations. Surrogates include finite observations that did not improve an elite or fell outside the grid. Powell search is bounded to the supplied decision domain.
With feasibility modelling enabled, return
(None, None, {"bop_valid": False})for a known infeasible design. Unsuccessful calls without explicit infeasibility teach neither the quality models nor the feasibility model.With a descriptor transform, return the measured sources as
(fitness, None, {"bop_latents": values}). The same transform sets measured descriptors and projects posterior samples during acquisition.- Parameters:
container – One-elite Grid with one or two descriptor axes.
budget – Maximum number of genuine evaluation attempts per run.
dimension – Number of continuous decision coordinates.
ind_domain – Common lower and upper decision bounds.
quality_floor – Empty-cell comparison value in signed quality units.
initial_samples – Number of Sobol proposals before modelling, default ten times the decision dimension.
candidate_pool – Number of Sobol points scored at each modelled step.
restarts – Maximum number of local acquisition searches per step.
seed – Optional seed for the Sobol sequence.
model_feasibility – Weight acquisition by a calibrated SVM after at least three valid and three explicitly infeasible observations.
descriptor_transform – Optional vectorized function of two arrays, raw genomes and measured or predicted latent rows. Return one descriptor row per input row. Use ordinary Grid features.
latent_size – Number of measured source values when a transform is set.
posterior_samples – Power-of-two number of shared normal draws for joint descriptor probabilities.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property n_invalid_observations¶
Number of explicit infeasibility labels received in this run.
- property n_observations¶
Number of finite observations available to the models.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.DiscountModelSearch(container, budget, x0, sigma0, batch_size, threshold_min, *, learning_rate=0.1, initial_anchors=256, empty_anchors=256, **kwargs)[source]¶
Native DMS with one CMA emitter and a CPU vector-descriptor model.
Install the optional
dmsextra. The fixed Grid or CVTGrid retains each cell’s best genuine evaluation. The MLP predicts a separate discount in signed quality units and trains once per committed generation.- Parameters:
container – One-elite reporting grid.
budget – Attempted evaluations per run.
x0 – Initial decision point.
sigma0 – Initial CMA search scale.
batch_size – Full CMA population size.
threshold_min – Initial discount in signed quality units within the model’s numeric range.
learning_rate – Archive target learning rate.
initial_anchors – Maximum sampled centres for model initialisation.
empty_anchors – Maximum sampled empty centres per generation.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- predict_discount(descriptors)[source]¶
Return one signed discount per row after the model has been initialised.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
Constrained search and coevolution¶
- class qdpy.algorithms.ConstrainedMAPElites(container, budget, variables, *, constraint_names, batch_size=1, real_sigma=0.1, infeasible_parent_probability=0.5, optimisation_task='minimisation')[source]¶
Keep the best feasible solution in each cell of a fixed result grid.
Return the native
(fitness, descriptors, scores)tuple from an evaluator and include one finite residual per named constraint. A residual of zero is feasible. Candidate genomes contain numeric coordinates and category indices. Usedecode()to recover labels.- Parameters:
container – Empty one-elite Grid or CVTGrid with one objective.
budget – Attempted evaluations per run.
variables – RealVariable, IntegerVariable, or CategoricalVariable instances in genome order.
constraint_names – Score names for inequality residuals g(x) <= 0.
batch_size – Number of proposals before updating either archive.
real_sigma – Gaussian mutation scale as a fraction of a real span.
infeasible_parent_probability – Probability of drawing a near-feasible parent when both archives have entries. Zero selects feasible parents exclusively and samples randomly until a feasible result is available.
optimisation_task – The usual single-objective direction or weight.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property infeasible_elites¶
Return the lowest-violation candidate currently held in each cell.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.WindowedMAPElites(container, budget, variables, *, window_radius, constraint_names=(), seed=0, batch_size=1, real_sigma=.1, optimisation_task=None)[source]¶
User-Controlled MAP-Elites for real, integer, and categorical variables.
Initially breed across the full archive. Call
choose()to display nearby feasible elites and center the window on the chosen elite. While focused, parents come from inside the window. Offspring may populate any descriptor cell. When both pools have eligible parents, alternate between feasible and infeasible elites.- Parameters:
container – Empty best-only Grid or CVTGrid with finite descriptor bounds.
budget – Evaluation budget for one managed optimisation call.
variables – Variable specifications in genome order.
window_radius – Positive half-width, scalar or one per archive descriptor.
constraint_names – Optional inequality residual names, where g(x) <= 0 is feasible.
seed – Private seed for parent sampling and variation.
batch_size – Number of proposals between archive updates.
real_sigma – Mutation scale as a fraction of each real variable’s width.
optimisation_task – Native scalar objective direction or weight.
- alternatives(count=4, *, sampling='medoids')[source]¶
Use descriptor distances scaled by window widths for display selection.
- choose(chooser, count=4, *, sampling='medoids')[source]¶
Call the chooser only when a feasible alternative is available.
- property window_center¶
Return the selected descriptor or None during global search.
- class qdpy.algorithms.RealVariable(lower: float, upper: float)[source]¶
Inclusive real interval. Equal endpoints fix the coordinate.
- class qdpy.algorithms.IntegerVariable(lower: int, upper: int)[source]¶
Inclusive integer interval. Equal endpoints fix the coordinate.
- class qdpy.algorithms.CategoricalVariable(choices: tuple)[source]¶
Ordered distinct hashable labels. A single label fixes the coordinate.
- class qdpy.algorithms.ConditionalConfiguration(selectors: tuple, active: tuple[str, ...], constraints: tuple[str, ...] = ())[source]¶
One allowed set of selector values in HiGeME.
- Parameters:
selectors – Mapping or pairs of selector names and hashable labels. Names and values are copied into a tuple of pairs.
active – Names from the shared variable schema visible in this branch.
constraints – Names of required residual scores. A value at most zero satisfies the constraint.
- class qdpy.algorithms.HiGeME(container, budget, variables, *, configurations, configuration_probability=0.4, gene_probability=0.5, real_sigma=0.3, seed=0, batch_size=1, optimisation_task='minimisation')[source]¶
Sample and mutate explicit configurations following Baraton et al.
Each genome contains a configuration index followed by one numeric gene per variable in mapping order. Hidden genes retain their stored values when a branch deactivates them. Use decode() to obtain only selectors and active parameters. The evaluator returns native fitness, descriptors, and named constraint scores.
- Parameters:
container – Empty best-only Grid or CVTGrid with one objective.
budget – Attempt budget including one initial sample per configuration.
variables – Ordered mapping from names to mixed-variable specifications.
configurations – Ordered sequence of ConditionalConfiguration objects.
configuration_probability – Chance of drawing a whole configuration uniformly for an offspring. The draw may retain the current branch.
gene_probability – Independent mutation probability of each active gene.
real_sigma – Gaussian mutation scale in units of the real interval.
seed – Seed for the search’s private random number generator.
batch_size – Number of candidates evaluated before archive feedback.
optimisation_task – Single objective direction or weight.
- ask_batch(size=None)[source]¶
Issue a manual batch, shortening the default batch to fit the remaining budget.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.ConditionalBayesianQD(container, budget, variables, *, configurations, initial_samples=4, surrogate_budget=96, quality_floor=None, exploration_probability=.1, real_length_scale=.25, discrete_correlation=.25, batch_size=1, seed=0, optimisation_task=None)[source]¶
Fit per-configuration surrogates and promote exact evaluations into a shared grid.
Each cheap pool uses a mix of uniform designs and perturbations of prior measurements from that configuration. Assign each predicted design to its posterior-mean descriptor cell. Rank proposals by feasibility-weighted expected improvement over the measured cell incumbent. Select at most one predicted winner per cell per batch before filling unused slots. Only measured feasible designs are offered to the reporting grid.
- Parameters:
container – Empty best-only Grid or CVTGrid with one objective.
budget – Total exact evaluation attempts.
variables – Ordered mapping from variable names to HiGeME gene specifications.
configurations – Allowed ConditionalConfiguration objects.
initial_samples – Space-filling draws per configuration before fitting.
surrogate_budget – Candidate prediction attempts per fitted configuration and batch.
quality_floor – Optional raw fitness reference for empty cells. By default use the worst signed fitness measured so far.
exploration_probability – Chance of a fresh random draw after warm-up.
real_length_scale – Gaussian length scale on normalized real genes.
discrete_correlation – Kernel factor for mismatched discrete genes.
batch_size – Total exact proposals per acquisition update.
seed – Private random seed.
optimisation_task – Single objective direction or weight. Defaults to the supplied archive’s direction when set.
- ask_batch(size=None)¶
Issue a manual batch, shortening the default batch to fit the remaining budget.
- property configuration_attempts¶
Return exact proposals in configuration order, including failed evaluations.
- property configuration_observations¶
Return counts of finite observations used by each configuration model.
- decode(candidate)¶
Return selector labels and typed active gene values in a new mapping.
- property model_fits¶
Return the number of per-configuration model refits.
- property modelled_proposals¶
Return exact proposals chosen by the surrogate.
- property surrogate_evaluations¶
Return the number of distinct cheap predictions across all batches.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- qdpy.algorithms.game_search(play, *, dimensions, rounds, matches_per_round, bounds=((0.0, 1.0), (0.0, 1.0)), task_count=4, cells_per_task=8, warmup_elites=8, seed=0, task_selection='behavior', match_budget=None)[source]¶
Coevolve two sides by alternating rounds of opponent-specific search.
An uncapped run completes
rounds * matches_per_roundsearch attempts. Between rounds, a separate tournament provides the new active side with measurements against its new opponents.- Parameters:
play – Callable taking immutable Red and Blue genomes in that order and returning a MatchResult. Each side maximises its fitness.
dimensions – Number of real coordinates for Red and Blue.
rounds – Alternating search rounds starting with Red.
matches_per_round – Search attempts in one round.
bounds – One shared coordinate interval for each side, Red first.
task_count – Initial number and later maximum number of opponents.
cells_per_task – Maximum retained niches per opponent, at least two.
warmup_elites – Minimum total elites before applying Iso+LineDD.
seed – Seed for proposals, opponent draws and clustering.
task_selection – “behavior” for the original selector, “ranking” for tournament matchup profiles, or “pareto” for NSGA-III selection over the raw matchup payoffs.
match_budget – Optional hard limit on search and tournament calls. If it cannot cover a selection tournament, the last round reports behavior-selected representatives. Inspect stopped_for_budget.
- Returns:
A GameResult with the round archives and attempt counts.
- Raises:
RuntimeError – If a round yields no valid elite.
- class qdpy.algorithms.MatchResult(fitness: tuple[float, float], descriptors: tuple[Sequence[float], Sequence[float]])[source]¶
Finite fitness and descriptor vectors in (Red, Blue) order.
- class qdpy.algorithms.GameResult(rounds: tuple[GameRound, ...], search_attempts: int, tournament_attempts: int, failed_attempts: int, stopped_for_budget: bool = False)[source]¶
Search and tournament attempts both include failed matches.
- class qdpy.algorithms.GameRound(side: str, opponents: tuple[tuple[float, ...], ...], elites_by_opponent: tuple[tuple[GameElite, ...], ...], representatives: tuple[GameElite, ...])[source]¶
Snapshot of one round.
The slots of
opponentsandelites_by_opponentcorrespond. Each representative retains the measurements used to select it.
Fixed-task and dynamic search¶
- qdpy.algorithms.mtmb_search(archives, evaluate, *, dimension, budget, ind_domain=(0, 1), seed=0, share_parents=True, on_step=None)[source]¶
Run fixed-task Multi-Task Multi-Behavior MAP-Elites.
Each proposal is evaluated for one task and can only enter that task’s grid. After warm-up, select each parent by first drawing a populated task and then drawing an elite from it.
- Parameters:
archives – Mapping from task IDs to distinct, empty best-only grids.
evaluate – Callable taking a task ID and a tuple of real coordinates. Return a one-value fitness tuple followed by the descriptors.
dimension – Number of genome coordinates.
budget – Total attempted evaluations across all tasks.
ind_domain – Shared inclusive genome bounds.
seed – Seed for independent task-selection and variation streams.
share_parents – Draw from all populated tasks. False limits the parent pool to the task being evaluated.
on_step – Optional callback receiving the task archives and the keyword arguments
iterationandevaluationsafter each attempt.
- Returns:
The live task archives and their attempt and failure counts.
- class qdpy.algorithms.MultiTaskResult(archives: dict, attempts_by_task: dict, failures_by_task: dict)[source]¶
Per-task attempt and failure counts alongside the supplied grids.
- qdpy.algorithms.parametric_task_map_elites(evaluate, *, genome_bounds, task_bounds, centroids, budget, seed=0, regression_probability=0.5, tournament_sizes=(1, 5, 10, 50, 100, 500))[source]¶
Run Parametric-Task MAP-Elites with CVT task cells and one fitness per trial.
- Parameters:
evaluate – Callable taking (genome, task) in physical units and returning a finite scalar fitness to maximize.
genome_bounds – Ordered finite intervals for real genes.
task_bounds – Ordered finite intervals for continuous task parameters.
centroids – CVT centers in physical task units. Supply distinct points.
budget – Total attempts, including one seed per centroid.
seed – Seed for variation and task selection.
regression_probability – Probability of proposing by local regression.
tournament_sizes – Positive task sample sizes available to UCB1.
- Returns:
A ParametricTaskResult with the CVT archive and evaluation records.
The first proposal at each center samples a genome uniformly. Subsequent evaluations draw tasks in the continuous domain. A regression fallback applies SBX at the already selected task without crediting the tournament. Each occupied cell keeps its highest recorded score. The incumbent wins ties.
- class qdpy.algorithms.ParametricTaskResult(archive: CVTGrid, evaluations: tuple[ParametricTaskEvaluation, ...], attempts: int, failures: int, task_bounds: tuple, tournament_attempts: dict[int, int], tournament_successes: dict[int, int], regression_proposals: int)[source]¶
A task repertoire and the evaluation data needed to change its resolution.
The archive stores genomes in physical units and feature coordinates in the normalized task box. Every successful measurement appears in order in evaluations. The attempts counter includes failed or invalid results.
- class qdpy.algorithms.ParametricTaskEvaluation(genome: tuple[float, ...], task: tuple[float, ...], fitness: float)[source]¶
Immutable observation in the caller’s genome and task coordinates.
- class qdpy.algorithms.CMOEA(task_count, *, sample, mutate, bin_capacity=8, batch_size=16, max_bins=None, subsets=None, aggregate='mean', seed=0)[source]¶
Combine task fitness and within-bin behavioral diversity.
Every evaluated offspring competes in each bin using its original vector of task scores. Survival uses NSGA-II front ranks and crowding for the aggregate task score and mean behavioral distance. Parent sampling is uniform over occupied bins and then their members.
- Parameters:
task_count – Number of task scores returned per evaluation.
sample – Callable (rng) returning an initial genome iterable.
mutate – Callable (genome, rng) returning an offspring genome. Treat genome elements as immutable.
bin_capacity – Maximum number of survivors in each task subset.
batch_size – New candidate evaluations before the next competition.
max_bins – Cap on automatically generated subsets, defaulting to max(64, 2 * task_count). Large families retain all singletons, the full task, and a seeded selection of other subsets.
subsets – Optional explicit collection of task index subsets. Include the full task subset. This overrides automatic bin selection.
aggregate – “mean” or “product” for fitness within each subset.
seed – Seed for selection, variation, and evaluator seeds.
- property best¶
Return the best measured candidate in the full subset, or None.
- property bins¶
Return a read-only live view of each subset and its survivors.
- property stats¶
Return cumulative attempts, failures, and generations.
- class qdpy.algorithms.CMOEARecord(genome: tuple, task_scores: tuple[float, ...], descriptor: tuple[float, ...])[source]¶
Store one measurement that can participate in multiple populations.
- class qdpy.algorithms.CMOEAStats(evaluations: int, failures: int, generations: int)[source]¶
Count each candidate once even when it competes in every bin.
- qdpy.algorithms.quality_environment_diversity(archive, evaluate, *, sample_environment, describe_environment, sample, mutate, budget, initial_samples=16, seed=0)[source]¶
Generate one training environment per candidate and retain its best trials.
The report grid uses environmental features such as friction or sensor noise. Separate random streams for environments, variation, and rollout seeds make the sequence of training conditions independent of parent selection. Export the native archive or pass it to MBOA for measured adaptation to new conditions.
- Parameters:
archive – Empty parentless best-only Grid or CVTGrid with one objective. Set fitness_weights explicitly to choose the objective direction.
evaluate – Callable (genome, environment, rollout_seed) returning one finite scalar fitness or None for a failed trial.
sample_environment – Callable (rng) drawing one environment specification.
describe_environment – Callable (environment) returning its finite grid coordinates.
sample – Callable (rng) returning an initial controller genome iterable.
mutate – Callable (genome, rng) returning the next controller genome. Treat genome elements as immutable.
budget – Total evaluator calls, including the initial phase.
initial_samples – Number of attempts before drawing parents from the archive.
seed – Seed for independent environment, controller, and rollout streams.
- class qdpy.algorithms.QEDResult(archive: Grid, evaluations: int, failures: int, out_of_domain: int, updates: int)[source]¶
Return the native archive and counts of trials, failures, and admissions.
- qdpy.algorithms.autoqd_search(evaluate, archive, *, budget, x0, sigma0, threshold_min, trajectory_width, batch_size=16, ind_domain=None, learning_rate=0.01, embedding_dim=128, bandwidth=1., gamma=0.99, update_interval=10, seed=0)[source]¶
Search for high-performing policies with trajectory-derived descriptors.
- Parameters:
evaluate – Callable taking a numeric genome tuple and a per-attempt seed. Return (fitness, trajectories), with one or more arrays of state-action rows. Fitness is maximized.
archive – Empty parentless one-elite Grid with feature bounds [-1.2, 1.2] on every axis and a domain for one maximizing objective.
budget – Hard budget in attempted candidate calls.
x0 – Initial CMA center with at least two real coordinates.
sigma0 – Initial step size for CMA-MAE and its restarts.
threshold_min – Initial CMA-MAE threshold in raw quality units.
trajectory_width – Number of state-action coordinates per step.
batch_size – CMA population size. The last batch may be partial.
ind_domain – Optional common lower and upper genome bounds.
learning_rate – CMA-MAE threshold update rate.
embedding_dim – Number of random Fourier features.
bandwidth – Gaussian kernel width in the caller’s fixed input units.
gamma – Discount applied within trajectories.
update_interval – Full generations between descriptor updates. None keeps the initial projection for a comparison at fixed coordinates.
seed – Root seed for independent descriptor, evaluator, and emitter streams.
- Returns:
AutoQDResult with the last grid, usable projector, and counts.
- class qdpy.algorithms.AutoQDResult(archive: Grid, projector: OccupancyDescriptor, attempts: int, failures: int, rollouts: int, trajectory_steps: int, boundary_evaluations: int, rebuilds: int, skipped_rebuilds: int)[source]¶
Rollout and boundary counts describe valid recorded evaluations.
Attempts include callbacks that failed or returned invalid values. Rebuilds and skipped rebuilds count scheduled descriptor updates.
- class qdpy.algorithms.OccupancyDescriptor(trajectory_width, descriptor_dim, *, embedding_dim=128, bandwidth=1., gamma=0.99, seed=0)[source]¶
A seeded random-feature map and its current linear descriptor projection.
Each trajectory is a finite matrix with one state-action row per transition. Input coordinates stay fixed across fits. The embedding averages discounted Fourier features across complete trajectories.
- Parameters:
trajectory_width – Number of numeric coordinates in each row.
descriptor_dim – Number of dimensions returned by transform().
embedding_dim – Number of random Fourier features.
bandwidth – Width of the Gaussian kernel in input units.
gamma – Discount in [0, 1).
seed – Seed for the random features and initial orthogonal projection.
- qdpy.algorithms.dynamic_map_elites(archive, evaluate, *, dimension, budget, ind_domain=(0, 1), seed=0, refresh='local', on_step=None)[source]¶
Run sequential Dynamic MAP-Elites with a shared attempt budget.
The evaluator receives a frozen tick for the offspring and its refresh chain. Publish a step only after all required refresh calls succeed. A finite measurement outside the archive domain is valid and unstorable.
- Parameters:
archive – Empty, parentless, best-only Grid or CVTGrid.
evaluate – Callable accepting a genome and the attempts already spent at the start of the step. Return
((fitness,), descriptors).dimension – Number of real genome coordinates.
budget – Attempt limit inclusive of incumbent refreshes.
ind_domain – Shared inclusive genome bounds.
seed – Seed for parent selection and mutation.
refresh – Use local cascading refresh, refresh all on a change, or perform no refresh (
"local","all","none").on_step – Optional callback receiving the archive and the keyword arguments
iterationandevaluationsafter each search step.
- Returns:
The live archive and counts for search, refreshes and failures.
Offline search and temporal planning¶
- class qdpy.algorithms.GradientAugmentedMAPElites(archive, genomes, fitnesses, descriptors, **kwargs)[source]¶
Build a surrogate prediction map following Kent’s GA-ME.
Target Sobol descriptor points from nearby logged designs. Alternate variation with local ascent on newly improved elites. Accept refinement moves that improve predicted fitness within the original cell. Drop random breeders between cycles and retain a separate result archive. Search charges every surrogate query, including gradients and rejected moves. Inherited verify() measures selected designs independently.
- Parameters:
archive – Empty best-only Grid or CVTGrid with finite descriptor bounds.
genomes – Matrix of real-valued logged genomes.
fitnesses – One scalar outcome per logged genome.
descriptors – One measured descriptor vector per logged genome.
kwargs – OfflineMAPElites genome, kernel, mutation, and seed settings. GA-ME searches posterior means. Use the default uncertainty_weight=0.
- run(budget, *, initial_samples=16, targeting_steps=3, mutation_steps=24, refinement_steps=3, dropout=.25, step_size=.08)[source]¶
Return an independently reproducible prediction map.
Target at most initial_samples descriptor points, each using up to targeting_steps gradient moves. Each cycle uses mutation_steps evaluated candidates, then up to refinement_steps moves for each new elite. Set either gradient phase to zero for ablation.
- static verify(result, evaluate, budget, *, seed=0, executor=None)¶
Keep measured outcomes separate. Observed descriptor cells decide placement.
- class qdpy.algorithms.GAMESearchResult(archive: Grid, predictions: int, targeting_predictions: int, refinement_predictions: int, dropped_elites: int)[source]¶
Keep the best predicted elites across all cycles and dropout events.
- class qdpy.algorithms.DynAMO(genomes, fitnesses, *, ind_domain=(0., 1.), maximize=True, temperature=1., beta=1., transport_limit=.03, max_multiplier=16., bandwidth=.15, batch_size=24, reference_size=64, proposal_sigma=.10, length_scale=.3, noise=1e-6, seed=0)[source]¶
Implement the continuous distribution-matching objective of Yao et al.
A frozen GP scores a bounded candidate pool. A Gaussian mixture smooths the reward-tilted empirical data distribution onto that pool. Each round solves finite optimal transport between the weighted reference and the new proposals to fit a Wasserstein critic. The reward surrogate, the categorical KL term, and the critic adjustment define the proposal probabilities. Draw the final batch without replacement using the final scores. There is no descriptor grid.
- Parameters:
genomes – Logged real design vectors within ind_domain.
fitnesses – One measured scalar objective per design.
ind_domain – Shared inclusive lower and upper genome bounds.
maximize – Maximize fitness if true, minimize it otherwise.
temperature – Positive tilt of the reference weights on scaled fitness.
beta – Positive KL penalty strength relative to the predicted objective.
transport_limit – Nonnegative target Wasserstein radius in normalized coordinates.
max_multiplier – Positive search cap for the transport dual variable.
bandwidth – Positive scale of the smoothing kernel in normalized coordinates.
batch_size – New designs per transport round.
reference_size – Maximum number of reference designs for each transport solve.
proposal_sigma – Positive local proposal scale in normalized coordinates.
length_scale – Fixed Matérn length scale for the frozen reward model.
noise – Positive covariance nugget for the frozen reward model.
seed – Seed for reference selection, variation, and batch sampling.
- class qdpy.algorithms.DynAMODesign(genome: tuple[float, ...], predicted_fitness: float, probability: float)[source]¶
Keep raw predicted fitness and the probability of this design in the final pool.
- class qdpy.algorithms.DynAMOResult(designs: tuple[DynAMODesign, ...], predictions: int, transport_solves: int, multiplier: float, source_distance: float)[source]¶
Report predictions, solved transport problems, and the final minibatch diagnostic.
- qdpy.algorithms.feature_based_planning(start, *, actions, simulate, goal, labels, monitors, max_plans, budget, max_depth=None, state_features=None, max_width=2)[source]¶
Search simulator states crossed with the temporal monitor memories.
Use a pure deterministic simulate(state, action) callback on immutable, hashable states. Return None for an illegal move. The planner stops expanding a path at its first goal, records its Boolean profile, and continues looking for new profiles. Reaching the same physical state with a different monitor memory can produce a different plan.
Supply state_features(state) to use iterative-width novelty pruning, repeating breadth-first passes with widths 1 through max_width. Novelty is tracked separately for each vector of monitor memories. Without state_features, a single exact product-state pass is used. Goal plans are shortest within the pass that discovered them.
- Parameters:
start – Initial simulator state.
actions – Callable (state) generating legal or attempted actions in stable order.
simulate – Pure callable (state, action) returning successor or None.
goal – Callable returning whether the state completes the task.
labels – Callable returning the true atomic propositions for a state.
monitors – Ordered mapping from feature names to TemporalMonitor objects.
max_plans – Stop after finding this many distinct profiles.
budget – Maximum simulator calls across all passes. Zero permits the initial goal check.
max_depth – Optional maximum action sequence length.
state_features – Optional callable returning hashable novelty atoms.
max_width – Maximum novelty tuple size when state_features is supplied.
- class qdpy.algorithms.DiversePlan(actions: tuple, profile: tuple[bool, ...], final_state: Hashable)[source]¶
Keep the simulator’s final state and one Boolean per named monitor.
- class qdpy.algorithms.DiversePlanningResult(plans: tuple[DiversePlan, ...], feature_names: tuple[str, ...], simulator_calls: int, expanded_states: int, width_passes: int, budget_exhausted: bool)[source]¶
Report goal plans in discovery order and simulator calls, including illegal actions.
- class qdpy.algorithms.TemporalMonitor(initial: Hashable, advance: Callable, accepts: Callable)[source]¶
Update one formula state for every observed label set.
Both the initial simulator state and successors contribute labels. Use a memory value that includes all information needed to compute future monitor updates and acceptance. Memory values must be immutable and hashable. Custom monitors can represent additional LTLf formulas.
Algorithm composition¶
Use an ask/tell wrapper when several children contribute proposals during one managed run. Use a sequence when each stage should complete its own optimisation. A shared archive lets the children contribute to the same cells. Separate archives let each child retain its own result.
An explicit wrapper container reports results across children with
matching objective weights. The wrapper’s constructor batch_mode
controls how frequently the active emitter changes. The separate
optimise(batch_mode=...) argument controls when the evaluator
scheduler refills the current batch.
- class qdpy.algorithms.base.QDAlgorithmLike(*args, **kwargs)[source]¶
Interface shared by native optimisers and algorithm sequences.
Callers may ask for a candidate and tell its result directly, or use optimise to manage evaluation and executor dispatch.
- class qdpy.algorithms.AlgWrapper(algorithms: Any, container: Container | None = None, budget: int | None = None, tell_container_when_switching: bool | str = False, name: str | None = None, batch_mode: bool = False, tell_all: bool = False, **kwargs)[source]¶
Coordinate child optimisers under one ask/tell interface.
The active child supplies each ask. Feedback follows the original proposer even if the active child changes before a result returns. With
tell_all, every child receives feedback and non-proposers receive copies. Child switching can warm-start the next child from its archive or the previous child’s best candidate.An explicit container collects all reported candidates and supplies the result. Otherwise report the active child’s archive, or the first populated child when the active archive is empty.
- switch_to(idx: int, verbose: bool = False)[source]¶
Switch to another algorithm of index idx in self.algorithms.
- 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]¶
Deliver an evaluation to the proposer, or to every child in tell-all mode.
A manually supplied candidate with no pending ask goes to the active child. Forward the optional evaluation arguments and update permission to the child. The wrapper accounts for one evaluation and reports an update if any child reports one.
- class qdpy.algorithms.AlternatingAlgWrapper(algorithms: Any, container: Container | None = None, budget: int | None = None, tell_container_when_switching: bool | str = False, name: str | None = None, batch_mode: bool = False, tell_all: bool = False, **kwargs)[source]¶
Cycle through child optimisers in order when the wrapper switches.
- class qdpy.algorithms.SqAlgWrapper(algorithms: Any, container: Container | None = None, budget: int | None = None, tell_container_when_switching: bool | str = False, name: str | None = None, batch_mode: bool = False, tell_all: bool = False, **kwargs)[source]¶
Advance to the next child when the active child has issued its budget of suggestions.
- class qdpy.algorithms.Sq(algorithms: Any, tell_container_when_switching: bool | str = True, name: str | None = None, **kwargs)[source]¶
Run complete child optimisations in a fixed sequence.
Switching can feed the next child from its archive or the previous child’s best candidate. A stage failure emits a warning and the next stage can still run. When every stage fails, the last error is raised.
- class qdpy.algorithms.FromArchive(container: Container, reference_data_files: List[str], **kwargs)[source]¶
Use genomes from trusted current result snapshots as suggestions.
Read the saved container entries in file order. The initial budget is the number of loaded genomes. Each ask copies a reference genome into a new base candidate and leaves fitness and descriptors to the next evaluation. Reinitialisation rewinds the cursor.
Surrogate-assisted illumination¶
SAIL uses a relatively cheap prediction to suggest candidates before spending more genuine evaluations. Configure an acquisition optimiser with compatible genome dimensions, objective counts, and descriptor ranges. Provide an initial genuine-evaluation budget that leaves training records in the illumination archive. Acquire and report genuine results through the wrapper as usual.
- class qdpy.algorithms.SurrogateAssistedAlg(illumination_algo: QDAlgorithm, acquisition_algo: QDAlgorithm, prediction_algo: QDAlgorithm | None = None, max_selected_acquisition_suggestions: float = np.inf, budget_not_suggested_by_surrogate: float = np.inf, **kwargs)[source]¶
Combine an evaluator-facing search with one or more surrogate searches.
The illumination algorithm provides initial and fallback candidates. The acquisition algorithm searches using surrogate predictions. The wrapper keeps evaluated candidates in the illumination archive and forwards feedback to the illumination algorithm.
- Parameters:
illumination_algo – Algorithm to receive genuine evaluations.
acquisition_algo – Search used to propose surrogate candidates.
prediction_algo – Predictor-side search. Defaults to a copy of the acquisition configuration.
max_selected_acquisition_suggestions – Cap on proposals selected from an acquisition result.
budget_not_suggested_by_surrogate – Number of initial evaluations supplied by the illumination algorithm.
- property acquisition_algo: QDAlgorithm¶
Search that explores the acquisition function.
- property illumination_algo: QDAlgorithm¶
Search that supplies native candidates and consumes true evaluation feedback.
- property prediction_algo: QDAlgorithm | None¶
Configured prediction-side search, if available.
- class qdpy.algorithms.SAIL(ucb_stddev: float = 1.0, **kwargs)[source]¶
Use a Gaussian process to propose candidates for expensive evaluation.
Fit the regressor on retained genomes and concatenate each genome’s objective and descriptor values as the training targets. For acquisition, combine each predicted mean with
ucb_stddevtimes its predictive standard deviation. Evaluate the selected acquisition proposals with the original evaluator before final admission.Supply enough genuine evaluations to populate the illumination archive before the first surrogate fit.
Repeated evaluation¶
A sampling decorator counts each observation against its budget. The base algorithm receives aggregated feedback after the requested observation count is reached. For example, a budget of twelve in a fixed sampler with three observations per proposal can complete four fresh genomes in a sequential run. Reserve enough budget for every repeat you need.
- class qdpy.algorithms.SamplingDecorator(base_alg: QDAlgorithm, *, seed=None, **kwargs)[source]¶
Schedule repeats independently of genome equality or worker completion order.
budgetandbatch_sizecount attempted rollouts. Ifseedis supplied, each evaluator input carries a deterministicevaluation_seed. One aggregated feedback event is sent to the base optimiser for each completed offspring. Incumbent reevaluation only updates the archive.- Parameters:
base_alg – Emitter that generates proposals and receives aggregate feedback.
seed – Nonnegative seed for rollout IDs, or None to leave seeding to the evaluator.
- Variables:
failed_evaluations – Number of failed or malformed rollout attempts.
- class qdpy.algorithms.FixedSamplingDecorator(base_alg: QDAlgorithm, nb_samples=1, **kwargs)[source]¶
Request
nb_samplesobservations per proposed genome.
- class qdpy.algorithms.TimeBasedSamplingDecorator(base_alg: QDAlgorithm, min_samples=5, max_samples=100, **kwargs)[source]¶
Interpolate from
min_samplestomax_samplesand round down.
- class qdpy.algorithms.AdaptiveSamplingDecorator(base_alg: QDAlgorithm, min_samples=5, max_samples=100, **kwargs)[source]¶
Perform local sample-count comparisons using the current cell’s best entry.
This decorator supplies the basic matching rule. Use
UncertainMAPEliteswithadaptivefor the drifting-elite race.
- class qdpy.algorithms.StandardErrorSamplingDecorator(base_alg, *, fitness_tolerance=0.02, descriptor_tolerance=0.01, min_samples=3, max_samples=10, **kwargs)[source]¶
Use separate absolute standard-error tolerances for fitness and descriptors.
- Parameters:
fitness_tolerance – Maximum objective standard error.
descriptor_tolerance – Maximum standard error in any descriptor coordinate.
min_samples – Minimum count needed to estimate standard error.
max_samples – Hard cap on observations for one proposal.
- class qdpy.algorithms.UncertainMAPElites(container, budget, dimension, *, policy='extract_me', sampling_size=128, base_alg=None, ind_domain=(0., 1.), optimisation_task='minimisation', initial_samples=None, extraction_fraction=0.25, max_samples=100, limit_descriptor_drift=True, seed=0)[source]¶
Run one published or experimental sampling and archive policy.
- Parameters:
container – A standalone fixed Grid or CVTGrid with one objective.
budget – Maximum search rollouts, inclusive of reevaluations.
sampling_size – Rollout slots available per generation.
dimension – Genome length used by the default polynomial emitter.
policy – Adaptive, Deep-Grid, Deep-Grid-Sampling, Archive-Sampling, Parallel-Adaptive-Sampling, Extract-ME, or fill-then-refine.
base_alg – Optional QDpy emitter using the same archive. Its selection rule replaces the default selector for the policy.
initial_samples – Override new-offspring repeats where applicable.
extraction_fraction – Fraction of a generation reserved for Extract-ME.
max_samples – Per-solution cap for the local adaptive race.
limit_descriptor_drift – Apply the cell-visit stopping rule in adaptive races.
seed – Seed for rollout IDs and the extraction RNG. Seed the caller’s Python and NumPy RNGs separately for emitter reproduction.
- class qdpy.algorithms.ArchiveAudit(archive: Grid, corrected_qd_score: float, corrected_coverage: float, cell_drift: float, rollout_cell_change: float, rollouts: int, failed_rollouts: int)[source]¶
Hold corrected metrics independently of search measurements and budget.
- qdpy.algorithms.reevaluate_archive(archive, evaluate, *, samples=32, seed=0, estimator='median', representative='best', selector=None, executor=None)[source]¶
Build a new depth-one archive without changing the input archive.
The selector-based audit draws a member on each rollout. Its aggregate describes a source cell’s deployment policy. The corrected coverage denominator is the number of cells in the source geometry.
See MAP-Elites with noisy evaluations for supported policies and Audit a noisy archive for examples of independent auditing.
- class qdpy.algorithms.SampledIndividual(iterable: Iterable | None = None, name: str | None = None, fitness: FitnessLike | None = None, features: FeaturesLike | None = None)[source]¶
Represent one genome evaluated several times.
Fitness and features are independent sample accumulators. The sampling decorator tracks the total expected observations on each proposal before reporting aggregated feedback to the base search.
- property nb_samples: int¶
Count fitness observations. The scheduling interface uses a minimum count of one.
- class qdpy.algorithms.SampledFitness(sampling_strategy: SampleAveragingStrategy = ExplicitSampleAveragingStrategy(), values: Sequence[Any] | ndarray = (), weights: Sequence[Any] | ndarray | None = None)[source]¶
Keep individual fitness observations and expose their mean as Fitness.
Setting values appends a raw observation. Dominance applies comparison weights to the aggregate. Changing weights leaves the observations unchanged. Reset before gathering an independent estimate.
- property nb_samples: int¶
Number of contributing fitness observations.
- property samples: Sequence[Sequence[Any] | ndarray]¶
Return a new list containing the raw objective observations.
- class qdpy.algorithms.SampledFeatures(sampling_strategy: SampleAveragingStrategy = ExplicitSampleAveragingStrategy(), *args, **kwargs)[source]¶
Keep descriptor observations and expose their coordinate-wise aggregate.
- property nb_samples: int¶
Number of retained descriptor observations.
- property samples: List[Sequence[Any] | ndarray]¶
Return a new list containing the observed descriptor vectors.
CMA-based algorithms¶
Install the cma extra to construct CMA-ES and its emitters. These
entries describe the functionality with that backend installed.
- class qdpy.algorithms.CMAES(container, budget, dimension, ind_domain=None, sigma0=1.0, separable_cma=False, ignore_if_not_added_to_container=False, **kwargs)¶
Adapt a Gaussian distribution using one scalar objective. The optimiser sends one loss per evaluated candidate to pycma, buffering until the strategy’s population is ready. A positive objective weight means maximisation in QDpy and produces a negated loss for the backend.
Set
ind_domainto constrain the genome,sigma0to set the initial standard deviation, andseparable_cmato use diagonal covariance.
- class qdpy.algorithms.CMAMEOptimizingEmitter(*args, **kwargs)[source]¶
Run single-objective CMA-ES and restart from an archive entry.
Use the
cmaextra. When the backend reaches a stopping condition, select a centre uniformly from the retained genomes. An empty archive uses the zero genome. The objective and loss conventions are the same as those of CMAES.
- class qdpy.algorithms.CMAMEImprovementEmitter(*args, **kwargs)[source]¶
Adapt search using cell coverage and signed fitness gains.
Read the previous cell representative before insertion. A candidate that fills an empty cell receives priority. For a filled cell, use the difference between candidate and previous weighted objectives. Sum weighted objectives into scalar feedback for pycma.
- class qdpy.algorithms.CMAMERandomDirectionEmitter(*args, **kwargs)[source]¶
Use a projection of behaviour descriptors as scalar CMA feedback.
A restart samples a direction using the descriptor domain. The feedback population is formed from locally admitted candidates and passed to pycma after projection. This emitter uses descriptor values on the individuals and supports a multiobjective archive.
- class qdpy.algorithms.MEMAPElitesUCB1(algorithms: Any, zeta: float = 0.0005, nb_active_emitters: int = 1, initial_expected_rwds: float = 1., shuffle_emitters: bool = True, **kwargs)[source]¶
Choose active child emitters with an upper confidence bound.
The reward estimate combines each emitter’s fraction of evaluations that updated the archive with an exploration term based on evaluation counts. Untried emitters receive
initial_expected_rwds.- Parameters:
algorithms – Available child emitters.
zeta – Coefficient of the UCB1 exploration term.
nb_active_emitters – Number of emitters retained per selection.
initial_expected_rwds – Reward estimate for a child with no evaluations.
shuffle_emitters – Shuffle the candidate order before ranking.
Multifidelity and open-ended search¶
- class qdpy.algorithms.QDHyperband(archive, dimension, fidelities, *, eta=3, ind_domain=(0., 1.), seed=0)[source]¶
Search designs over increasing evaluation fidelities.
- Parameters:
archive – Best-only Grid or CVTGrid with one signed objective.
dimension – Number of real design coordinates.
fidelities – Increasing positive integer resource units. Rungs are charged their total cost, including evaluations of promotions.
eta – Integer successive-halving factor, at least two.
ind_domain – Common lower and upper bounds for design coordinates.
seed – Private seed for new proposals and promotion.
- run(evaluate, budget)[source]¶
Return the archive after spending at most budget additional units.
The evaluator accepts (genome, fidelity) and returns (scalar fitness, descriptors) or None. Only results at the highest fidelity can enter the reporting archive. A promotion uses its most recent descriptor.
- property spent¶
Return cumulative resource units including failed calls.
- property trials¶
Return attempted evaluations in their submission order.
- class qdpy.algorithms.BOPElitesHyperband(archive, dimension, fidelities, *, quality_floor, model_after=12, pool_size=256, random_fraction=.1, trees=32, **kwargs)[source]¶
Rank proposals by expected joint improvement over regular grid cells.
Forests train on all successful observations with the fidelity as an input. Their predictions and incumbent comparisons use the first rung of the planned bracket. A uniform fraction can be reserved for exploration.
- Parameters:
quality_floor – Raw comparison value for a cell without observations.
model_after – Number of successful observations before fitting.
pool_size – Minimum number of candidates ranked at bracket start.
random_fraction – Fraction of each bracket reserved for uniform draws.
trees – Number of trees per output prediction.
kwargs – Arguments accepted by QDHyperband.
- class qdpy.algorithms.FidelityTrial(genome: tuple[float, ...], fidelity: int, fitness: float | None, descriptors: tuple[float, ...] | None)[source]¶
A failed evaluation has fitness and descriptors set to None.
- class qdpy.algorithms.MonteCarloElites(container, budget, dimension, *, arms='individual', exploration=1 / np.sqrt(2), sigma=.05, ind_domain=(0., 1.), mutate=None, seed=0, **kwargs)[source]¶
Run MAP-Elites with UCB parent selection and one-parent variation.
- Parameters:
container – Grid with one retained elite per cell.
budget – Candidate evaluation budget.
dimension – Number of real genome coordinates.
arms – Use an independent history per “individual” or retain counts by “cell” as elites are replaced.
exploration – Nonnegative coefficient of the UCB exploration term.
mutate – Optional callable taking an immutable parent genome and the private generator. The default adds bounded Gaussian noise.
seed – Seed for initialization, mutation and tie breaks.
- class qdpy.algorithms.MEES(archive, x0, *, pairs=16, block_steps=5, mode='explore-exploit', evaluations_per_center=1, sigma=.05, learning_rate=.03, l2=.005, novelty_neighbors=10, ind_domain=None, seed=0)[source]¶
Black-box MAP-Elites with Evolution Strategies.
Perturbation measurements guide an Adam update. Independently evaluate the resulting center before offering it to the grid. Novelty uses the descriptors of previously evaluated centers, including rejected ones.
- Parameters:
archive – Best-only Grid or CVTGrid with one finite nonzero fitness weight.
x0 – Initial parameter vector.
pairs – Number of antithetic Gaussian pairs per ES step.
block_steps – Number of ES steps before selecting a new elite.
mode – “exploit”, “explore”, or “explore-exploit” (alternating blocks).
evaluations_per_center – Number of rollouts averaged per center.
sigma – Gaussian standard deviation.
learning_rate – Adam step size.
l2 – Parameter decay included in the ascent gradient.
novelty_neighbors – Number of nearest center descriptors for novelty.
ind_domain – Optional common lower and upper parameter bounds.
seed – Private random seed.
- property center_evaluations¶
Return attempted center rollouts, including initialization.
- property evaluations¶
Return attempted perturbation and center evaluations combined.
- run(evaluate, budget, *, executor=None)[source]¶
Return the result archive after using at most budget evaluator calls.
Return (scalar fitness, descriptors) or None for a failed rollout. A caller-owned executor must support submit and Future.result. Feedback order follows submission order.
- property updates¶
Return the number of completed ES steps.
- class qdpy.algorithms.NoveltyES(initial_population, *, mode='nsra-es', archive=None, pairs=16, sigma=.05, learning_rate=.02, l2=.005, neighbors=10, distance=dist, history_capacity=None, patience=10, weight_step=.05, ind_domain=None, seed=0)[source]¶
Use Conti et al.’s shared novelty memory and three search objectives.
Each step selects one member with probability proportional to its novelty. Separately rank the probe rewards and novelty scores, then combine their gradient estimates. NS-ES uses only novelty. NSR-ES averages both signals. NSRA-ES starts with reward and lowers its weight as best measured center reward stagnates.
- Parameters:
initial_population – Nonempty matrix of finite parameter vectors.
mode –
ns-es,nsr-es, ornsra-es.archive – Optional parentless best-only reporting Grid or CVTGrid. It uses reward maximization and does not affect selection.
pairs – Number of antithetic Gaussian perturbation pairs per step.
sigma – Gaussian standard deviation.
learning_rate – Step size of the per-member Adam update.
l2 – Nonnegative weight decay in the parameter gradient.
neighbors – Number of nearest measured center descriptors.
distance – Symmetric nonnegative descriptor distance, default Euclidean.
history_capacity – Optional maximum number of recent center descriptors.
patience – Stagnant steps before reducing NSRA-ES reward weight.
weight_step – Amount to change that weight on a plateau or new best.
ind_domain – Optional common parameter interval for clipped ES.
seed – Private seed for selection, perturbations, and evaluations.
- property best¶
Return the historically best measured center, or None before a successful call.
- property history¶
Return shared descriptors from committed center measurements.
- property population¶
Return measured centers in population order.
- run(evaluate, budget, *, executor=None)[source]¶
Retry initialization if all centers fail and reserve full ES steps.
- property stats¶
Return a snapshot of cumulative costs and current reward weight.
- property step_cost¶
Return evaluator calls reserved for a probe batch and its center.
- class qdpy.algorithms.NoveltyESPolicy(genome: tuple[float, ...], reward: float, descriptor: tuple[float, ...])[source]¶
Keep a parameter vector, its return, and its observed descriptor.
- class qdpy.algorithms.NoveltyESStats(center_evaluations: int, perturbation_evaluations: int, failures: int, updates: int, reward_weight: float, selection_counts: tuple[int, ...])[source]¶
Count attempted rollouts and committed center updates.
- property evaluations¶
Return total evaluator calls.
- class qdpy.algorithms.QQD(archive, *, sample, operators, batch_size=16, initial_samples=None, controller='q-learning', learning_rate=.5, discount=.9, epsilon=.3, epsilon_decay=.999, anneal_batches=None, improvement_scale=1e-12, seed=0)[source]¶
Run Qin et al.’s tabular operator selector with user-defined variation.
Select a parent uniformly from the archive and learn from admission to its offspring’s destination cell. A new cell yields one unit of reward, improvement yields a scaled quality gain, and rejection yields zero. The controller advances through batch positions cyclically. Each operator call proposes one candidate.
- Parameters:
archive – Parentless best-only Grid or CVTGrid with native scalar fitness.
sample – Callable (rng) returning a fresh genome.
operators – Ordered mapping of names to callbacks (genome, rng).
batch_size – Number of positions in the cyclic controller state.
initial_samples – Warm-up attempts, defaulting to batch_size.
controller –
q-learning,uniform, orbandit.learning_rate – Initial Q-table step size in (0, 1].
discount – Bootstrapping coefficient in [0, 1].
epsilon – Initial exploration probability.
epsilon_decay – Multiplier applied after each local proposal.
anneal_batches – Optional batch count for annealing learning_rate toward .01.
improvement_scale – Positive denominator floor for relative improvement.
seed – Seed for selection, variation, and evaluator calls.
- property q_values¶
Return a copy of the table in batch position and operator order.
- property stats¶
Return cumulative work and operator counts.
- class qdpy.algorithms.QQDStats(evaluations: int, failures: int, archive_updates: int, q_updates: int, operator_attempts: tuple[tuple[str, int], ...])[source]¶
Count failed evaluations, archive admissions, and operator attempts.
- class qdpy.algorithms.MultiDescriptorMAPElites(container, budget, dimension, *, selection_size, selection_score='selection', mode='novelty', neighbors=15, clusters=12, surprise_neighbors=2, novelty_weight=.6, ind_domain=(0., 1.), iso_sigma=.05, line_sigma=.2, seed=0, batch_size=16, **kwargs)[source]¶
Independently measure selection and archive descriptors.
The third item of the evaluator result is a score mapping. Store the numeric selection vector under
selection_score. The archive uses the ordinary feature vector and scalar fitness. All parents in a batch come from the same measured archive snapshot.- Parameters:
container – Parentless best-only Grid or CVTGrid.
budget – Managed evaluation attempts.
dimension – Length of each real vector.
selection_size – Number of coordinates in the selection vector.
selection_score – Name of the vector in candidate scores.
mode –
uniform,novelty,surprise,blend, orpareto.neighbors – Number of closest other elites for novelty.
clusters – Maximum number of cluster centers for forecasting surprise.
surprise_neighbors – Forecast centers averaged in the surprise score.
novelty_weight – Weight of novelty in the blended score.
ind_domain – Common interval for all genome coordinates.
iso_sigma – Independent Gaussian variation per coordinate.
line_sigma – Gaussian variation along the difference of two parents.
seed – Private seed for selection, variation, and forecasting.
batch_size – Evaluations per archive snapshot.
kwargs – Native optimiser options such as the objective direction.
- add_callback(event: str, fn: Callable) None¶
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()¶
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.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property batch_size: int¶
Configured candidate count per iteration, or the current budget when omitted.
- best() IndividualLike¶
Return the best retained candidate.
- Raises:
RuntimeError – If the container has no candidates.
- property current_iter¶
Number of committed generations, including partial generations.
- property forecasts¶
Return the number of forecasts with two observed archive snapshots.
- classmethod from_config(config: Mapping[str, Any], **kwargs: Any) Any¶
Create a class using the information from config to call the class constructor.
Parameters¶
- param config:
Mapping[str, Any] The configuration mapping used to create the class. For each entry, the key corresponds to the name of a parameter of the constructor of the class.
- param kwargs:
Any Additional information used to create the class. The configuration entries from kwargs take precedence over the entry in config.
- property nb_evaluations: int¶
Number of tell calls or candidate slots consumed by the managed scheduler.
- property nb_evaluations_in_iteration: int¶
Number of accounted evaluations since the last iteration ended.
- property nb_max_iter: int | float¶
Ceiling of the current budget divided by the batch size for a finite run.
- property nb_suggestions: int¶
Number of candidates returned by ask since initialisation or reinitialisation.
- property nb_suggestions_in_iteration: int¶
Number of asks recorded since the last managed iteration ended.
- property nb_updated: int¶
Number of evaluations for which the archive reported a local update.
- property nb_updated_in_iteration: int¶
Number of reported archive updates since the last iteration ended.
- property optimisation_task: str | Sequence[float]¶
The objective direction or explicit comparison weights.
- optimise(*args, **kwargs)¶
Schedule fixed generations via the native optimiser.
- 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.
- summary(max_depth: int | None = None, max_entry_length: int | None = 250) str¶
Return a summary description of the class. The summarised information is provided by the self.__get_summary_state__ method.
Parameters¶
- param max_depth:
Optional[int] The maximal recursion depth allowed. Used to summarise attributes of self that are also Summarisable. If the maximal recursion depth is reached, the attribute is only described with a reduced representation (repr(attribute)). If max_depth is set to None, there are no recursion limit.
- param max_entry_length:
Optional[int] If max_entry_length is not None, the description of a non-Summarisable entry exceeding max_entry_length is cropped to this limit.
- tell(individual, fitness=None, features=None, scores=None, elapsed=None, verbose=False, tell_container=True)¶
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_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- tell_container_entries(cont: Container | None = None) None¶
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.GSEMOD(dimension, *, diversity='total', initial=None, seed=0)[source]¶
Run Antipov et al.’s GSEMO with diversity-aware tie replacement.
Sample a parent uniformly and flip each bit independently with probability 1/dimension. For a previously seen objective vector, replace its incumbent if population imbalance improves or ties. For other vectors, use Pareto dominance on maximization objectives.
- Parameters:
dimension – Number of bits per solution.
diversity –
totalminimizes summed imbalance andlexicographicminimizes the sorted imbalance vector.noneis the GSEMO control.initial – Optional binary starting genome.
seed – Seed for variation, parent selection, and evaluator calls.
- property population¶
Return the nondominated representatives in admission order.
- property stats¶
Return a snapshot of attempted evaluations and population diversity.
- class qdpy.algorithms.BinaryParetoPoint(genome: tuple[int, ...], objectives: tuple[float, ...])[source]¶
An immutable snapshot of one Pareto representative.
- class qdpy.algorithms.GSEMODStats(evaluations: int, failures: int, admissions: int, tie_replacements: int, population_size: int, imbalance: tuple[int, ...])[source]¶
Unevaluated or failed candidates do not contribute to imbalance.
- property total_imbalance¶
Return the sum of absolute zero/one count differences.
- class qdpy.algorithms.EnhancedPOET(initial_task, initial_policy, *, mutate_task, improve, minimal_criterion, reproduction_threshold, active_limit=8, proposals=8, new_tasks=2, mutate_every=4, transfer_every=4, novelty_neighbors=5, seed=0)[source]¶
Run the generic Enhanced POET curriculum and transfer loop.
- Parameters:
initial_task – Immutable hashable encoding of the starting task.
initial_policy – One finite real vector.
mutate_task – Callable (task, rng) returning a new task or None.
improve – Callable (task, policy, score, rng) returning a policy. Its score callback takes one policy and charges the current budget.
minimal_criterion – Inclusive (too hard, too easy) raw score bounds.
reproduction_threshold – Minimum score at which a task can reproduce.
active_limit – Maximum simultaneously trained pairs.
proposals – Number of task mutations per reproduction round.
new_tasks – Maximum newly admitted tasks per reproduction round.
mutate_every – Interval between task reproduction rounds.
transfer_every – Interval between transfer checks. Use None to disable.
novelty_neighbors – Number of nearest task profiles used for novelty.
seed – Private seed for evaluation, mutation and optimization order.
- property active¶
Return currently trained pairs in their admission order.
- property archived¶
Return retired pairs still used as references in PATA-EC.
- run(evaluate, budget, *, rounds)[source]¶
Return cumulative stats with a hard evaluator-call budget.
The evaluator accepts (task, policy, seed) and returns a scalar to maximize. An interrupted round can leave completed pair updates in place. Use the score callback for every evaluation in improve.
- property stats¶
Return cumulative evaluation and event counts.
- class qdpy.algorithms.POETPair(task: Hashable, policy: tuple[float, ...], score: float, parent: Hashable | None)[source]¶
Track a task, the policy paired with it, and its source task.
- class qdpy.algorithms.POETStats(rounds: int = 0, training_evaluations: int = 0, criterion_evaluations: int = 0, novelty_evaluations: int = 0, transfer_evaluations: int = 0, admitted_tasks: int = 0, transfers: int = 0, fine_tuning_attempts: int = 0)[source]¶
- property evaluations¶
Return all score calls, including task and transfer screening.
Scalable and learned variation¶
- class qdpy.algorithms.LMMAMAE(container, budget, x0, sigma0, batch_size, threshold_min, *, memory_size=None, **kwargs)[source]¶
LM-MA-MAE for fixed one-elite grids and CVT grids.
Uses the CMA-MAE annealed thresholds and reporting archive with the LM-MA-ES optimizer from Loshchilov et al. The optimizer stores direction vectors instead of a square covariance matrix. No CMA extra is needed.
- Parameters:
container – Fixed, one-elite Grid or CVTGrid.
budget – Candidate evaluations per run.
x0 – Finite center vector in genome coordinates.
sigma0 – Positive initial search step size.
batch_size – Population size (at least two).
threshold_min – Initial threshold in weighted quality units.
memory_size – Number of direction vectors, at most the genome length. The default is the smaller of that length and four plus the floor of three times the natural logarithm of the length.
kwargs – CMA-MAE threshold, seed, and native QD options.
Bounded candidates are clipped to the genome domain. On small problems the path learning rates are capped at one. Incomplete trailing batches update the archives only. Failed slots are excluded from adaptation.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- threshold(cell)¶
Return the current admission threshold for a descriptor cell.
- class qdpy.algorithms.DDEElites(container, budget, dimension, ind_domain=(0., 1.), *, batch_size=32, mixtures=((1., 0., 0.), (0., 1., 0.), (0., 0., 1.), (.5, .5, 0.), (.5, 0., .5)), window_size=50, min_elites=4, fit_interval=1, fit_epochs=5, fit_batch_size=64, hidden_size=64, latent_size=8, learning_rate=1e-3, beta=0.01, iso_sigma=.01, line_sigma=.2, seed=0, device='cpu', **kwargs)[source]¶
DDE-Elites for bounded real genomes and a fixed, best-only archive.
A variational autoencoder learns from the current elites. Reconstructive crossover averages a parent with its decoded latent mean. A sliding window UCB1 bandit chooses a mixture of this operator, Iso+LineDD, and isotropic mutation once per generation. Successful offspring are those still present after the whole generation has been committed.
- Parameters:
container – Fixed, one-elite Grid or CVTGrid.
budget – Candidate evaluations.
dimension – Length of the real genome.
ind_domain – Shared finite lower and upper genome bounds.
batch_size – Candidate proposals per generation.
mixtures – Rows of probabilities in reconstruction, line, isotropic order. Include a mixture without reconstruction for warm-up. The default tries the three pure operators and two mixed arms.
window_size – Number of recent arm rewards kept by UCB1.
min_elites – Elites required before training a model.
fit_interval – Generations between fits, starting at the first eligible batch.
fit_epochs – Passes over the archive per fit.
fit_batch_size – Genome minibatch size.
hidden_size – Width of the encoder and decoder hidden layers.
latent_size – Width of the Gaussian latent representation.
learning_rate – VAE Adam learning rate.
beta – KL term weight.
iso_sigma – Isotropic mutation scale in genome units.
line_sigma – Relative Iso+LineDD direction scale.
seed – Private search and model seed.
device – PyTorch training device.
kwargs – Native QDAlgorithm options.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property model_fits¶
Return the number of completed archive VAE fits.
- property operator_counts¶
Return cumulative proposals by variation operator, including random starts.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
Targeted and tournament search¶
- class qdpy.algorithms.JEDi(container, budget, dimension, ind_domain=(0., 1.), *, batch_size=16, warmup=32, targets_per_cycle=3, generations_per_target=4, sigma0=.1, proximity_weight=.5, length_scale=.25, noise=.01, seed=0, **kwargs)[source]¶
Quality with Just Enough Diversity, following Templier et al. (GECCO 2024).
A Matérn Gaussian process models elite fitness over normalized descriptor coordinates. Each occupied cell’s noise is inversely proportional to its number of visits. Sample target cells without replacement from the posterior mean and deviation Pareto front. Start one LM-MA-ES per target from the closest elite and rank proposals by normalized fitness and target proximity. Every valid measurement can enter the reporting grid.
- Parameters:
container – Fixed best-only Grid or CVTGrid with a scalar objective.
budget – Number of evaluation attempts.
dimension – Length of the real genome, at least two.
ind_domain – Common lower and upper genome bounds.
batch_size – Population size per target.
warmup – Minimum initialization attempts before using the GP.
targets_per_cycle – Maximum concurrent target strategies.
generations_per_target – Complete generations attempted per target.
sigma0 – Initial genome step size.
proximity_weight – Weight of target proximity in [0, 1].
length_scale – Fixed Matérn kernel length in normalized descriptor units.
noise – Positive base observation variance in scaled fitness units.
seed – Private search seed.
kwargs – Common QDAlgorithm options, including optimisation_task.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- property cell_visits¶
Return a copy of the per-cell counts of valid evaluations.
- property target_history¶
Return the cell indices selected for each completed target draw.
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- qdpy.algorithms.game_cross_play(play, red, blue, *, repeats=1)[source]¶
Evaluate all Red and Blue pairings. Missing matchup scores are NaN.
- Parameters:
play – Match evaluator with the same contract as game_search.
red – Red strategy genomes in input order.
blue – Blue strategy genomes in input order.
repeats – Matches to average for each pair. A failed replicate makes that pair incomplete and removes the affected profile from metric calculations.
- class qdpy.algorithms.GameTournament(fitness: ndarray, attempts: int, failed_attempts: int)[source]¶
A read-only payoff matrix indexed by Red, Blue, and scoring side.
- metrics(side, strategies=None, *, win_threshold=.5, clusters=4, seed=0)[source]¶
Use all opponents. Fit coverage clusters over all complete rows on this side.
- Parameters:
side – Either “red” or “blue”.
strategies – Optional indices into that side’s strategies.
win_threshold – A score must exceed this threshold to win.
clusters – Maximum number of reference behavior clusters.
seed – Seed for the reference clustering.
Interactive search and repertoire reuse¶
- class qdpy.algorithms.BOIL(container, budget, dimension, ind_domain, quality_floor, *, entropy_weight=1., target_samples=64, **kwargs)[source]¶
Bayesian Optimization with Interactive Illumination (Kent and Branke, 2023).
Reuse the measured design and descriptor posteriors across all three phases. Use a fixed one- or two-dimensional rectangular reporting grid. Model building multiplies expected joint improvement by one plus the normalized entropy of posterior region membership. Focused illumination considers only selected cells. Target search uses common Monte Carlo draws to estimate the expected improvement in target utility.
- Parameters:
container – Best-only Grid with one objective and one or two descriptors.
budget – Total measurement attempts across repeated optimise calls and manual batches.
dimension – Length of a real-valued genome.
ind_domain – Common lower and upper decision bounds.
quality_floor – Empty-cell threshold in weighted fitness units.
entropy_weight – Nonnegative multiplier on normalized descriptor entropy.
target_samples – Power-of-two count of fixed, scrambled Sobol posterior draws.
kwargs – Native optimizer arguments and BOP-Elites initialization and search settings.
- best_target()[source]¶
Return a BOILTargetResult for the active target, or None before any observations.
- focus(cells=None)[source]¶
Select a nonempty sequence of grid indices, or pass None to use the full map.
- optimise(evaluate, budget=None, **kwargs)[source]¶
Run an additional phase, using the remaining budget if none is given.
- prediction_map(*, samples=512, min_probability=.5, seed=0)[source]¶
Return up to one provisional solution per cell, ranked by predicted weighted fitness.
- property remaining_evaluations¶
Return the number of attempts still available, including future phases.
- class qdpy.algorithms.BOILPrediction(cell: tuple[int, ...], genome: tuple[float, ...], fitness_mean: float, descriptor_mean: tuple[float, ...], probability: float)[source]¶
A surrogate estimate for inspection before running a real evaluation.
- class qdpy.algorithms.BOILTargetResult(genome: tuple[float, ...], fitness: float, descriptors: tuple[float, ...], utility: float)[source]¶
Report measured fitness, descriptors and target utility in their original units.
- class qdpy.algorithms.QDGP(sequencing, routing, *, sequencing_probes, routing_probes, initial_samples=24, max_depth=6, tournament_size=3, crossover_probability=.75, maximize=False, seed=0)[source]¶
QDGPf from Xu et al. (GECCO 2025), with caller-defined scheduling instances.
An evaluation receives two compiled priority functions. Lower scores take precedence at each probe. Encode the rank of the chosen candidate under fixed reference rules in two mixed-radix cell coordinates. A sparse archive stores the best measured rule pair per coordinate. Use the same training instances whenever you call run on this search.
- Parameters:
sequencing – Untyped DEAP PrimitiveSet for sequencing rules.
routing – Untyped DEAP PrimitiveSet for routing rules.
sequencing_probes – Sequence of DecisionProbe instances.
routing_probes – Sequence of DecisionProbe instances.
initial_samples – Number of randomly initialized candidates.
max_depth – Maximum height of either tree.
tournament_size – Number of randomly sampled elites per parent tournament.
crossover_probability – Probability of using subtree crossover instead of mutation.
maximize – Whether the caller’s fitness is higher-is-better.
seed – Search seed. Use fixed literal terminals for deterministic initialization.
- property archive¶
Return a dictionary snapshot of the current elites.
- class qdpy.algorithms.DecisionProbe(candidates: tuple[tuple[float, ...], ...], reference_order: tuple[int, ...])[source]¶
Define candidate feature rows and a best-first permutation of candidate indices.
- class qdpy.algorithms.SchedulingRules(sequencing: str, routing: str)[source]¶
Store two trees in the text representation of the corresponding primitive sets.
- class qdpy.algorithms.SchedulingElite(rules: SchedulingRules, fitness: float, cell: tuple[int, int])[source]¶
Describe a measured elite, with one mixed-radix index per decision kind.
- class qdpy.algorithms.ResetFreeTrialAndError(repertoire, *, horizon=4, simulations=128, goal_tolerance=.15, prior_std=.12, observation_noise=.02, length_scale=.4, model_capacity=128, exploration=.7, discount=.95, collision_penalty=6., seed=0)[source]¶
Reset-free Trial-and-Error following Chatzilygeroudis et al.
The first implementation assumes additive, stationary displacements in fixed numeric state coordinates. A residual GP updates the nominal skill effects from live outcomes. MCTS uses UCB and progressive widening for skills and their possible successor states. The caller supplies the environment and handles execution.
- Parameters:
repertoire – Nonempty sequence of RTESkill records, live numeric repertoire, or its portable grid export. For a grid, each descriptor must be the skill’s nominal displacement in state coordinates.
horizon – Number of skill applications planned per simulated path.
simulations – Monte Carlo rollouts per planning call.
goal_tolerance – Distance at which the goal is reached.
prior_std – Standard deviation of the nominal transition error.
observation_noise – Positive observation standard deviation for the GP.
length_scale – GP kernel scale in normalized skill coordinates.
model_capacity – Number of recent live outcomes retained by the GP.
exploration – UCB exploration coefficient for simulated actions.
discount – Discount on future distance improvements.
collision_penalty – Positive cost of a forbidden simulated transition.
seed – Random seed for planning.
- observe(state, skill, successor)[source]¶
Add a measured displacement from an executed skill to the rolling model dataset.
- plan(state, goal, *, traversable=None)[source]¶
Return an RTESkill or None if the state is already within goal_tolerance.
traversable, if supplied, tests the whole predicted transition as (before, after). A blocked result receives the collision cost and ends that simulated path.
- run(state, goal, execute, *, max_trials, traversable=None, adapt=True)[source]¶
Return an RTEPath by calling execute(current_state, genome) at most max_trials times.
- property stats¶
Return the current count of live actions, observations, and simulated paths.
- class qdpy.algorithms.RTESkill(genome: tuple[float, ...], displacement: tuple[float, ...])[source]¶
A numeric genome and a finite displacement in the planner’s state coordinates.
- class qdpy.algorithms.RTEPath(states: tuple[tuple[float, ...], ...], skills: tuple[RTESkill, ...], goal_reached: bool)[source]¶
A path has one more state than skill and includes the caller’s initial state.
- class qdpy.algorithms.RTEStats(real_attempts: int, observations: int, planning_rollouts: int)[source]¶
Cumulative counts over any number of replanning calls.
- class qdpy.algorithms.QDMeta(dimension, base_domain, shape, *, ind_domain=(0., 1.), maximize=True, initial_samples=32, inner_evaluations=16, population_size=6, database_capacity=4096, sigma0=.45, iso_sigma=.05, line_sigma=.2, seed=0)[source]¶
QD Meta-Evolution following Bossens and Tarapore.
Each generation samples a population of linear feature maps. It rebuilds a best-only grid for each map from the same shared database snapshot and runs a fixed number of MAP-Elites proposals. Newly evaluated genomes join the database for the next generation. Meta fitness ranks the maps for a limited-memory evolution strategy.
- Parameters:
dimension – Length of the real-valued genome.
base_domain – Finite bounds for each measured base feature.
shape – Target grid shape, with one output of the projection per axis.
ind_domain – Common lower and upper genome bounds.
maximize – Whether greater inner fitness should be retained.
initial_samples – Number of real evaluations for initial shared records.
inner_evaluations – Number of fresh attempts per projection and generation.
population_size – Number of feature maps per outer generation.
database_capacity – Capacity of the shared FIFO measurement database.
sigma0 – Initial step size for the outer limited-memory ES.
iso_sigma – Inner isotropic mutation scale.
line_sigma – Inner directional mutation scale.
seed – Seed for the database initialization, inner searches and outer ES.
- property result¶
Return the best learned archive and cumulative cost counters.
- run(evaluate, meta_fitness, *, generations=1)[source]¶
Run fresh inner searches. Both callbacks may return None for a failed measurement.
evaluate takes a genome and returns (scalar fitness, base_features). meta_fitness takes a completed Grid and returns a scalar to maximize. The latter should treat the supplied Grid as read-only. Its own simulator interactions can be tracked in the callback.
- class qdpy.algorithms.FeatureProjection(weights: tuple[tuple[float, ...], ...], base_domain: tuple[tuple[float, float], ...])[source]¶
Project bounded features into [0, 1] using signed, L1-normalized rows.
- class qdpy.algorithms.QDMetaResult(projection: FeatureProjection | None, archive: Grid | None, meta_fitness: float | None, evaluations: int, meta_evaluations: int, generations: int, database_size: int)[source]¶
Describe the best archive by meta-fitness. An unsuccessful search has no archive.
Parent selection, surrogates, and skill composition¶
- qdpy.algorithms.lexicase_index(errors, rng, *, epsilon=0.)[source]¶
Minimize errors one case at a time among the remaining candidates.
Zero tolerance implements exact lexicase. With epsilon=”mad”, a case’s median absolute deviation is computed over the original pool. The best error is recomputed among the survivors for every case. Choose uniformly if several candidates remain after the last case.
- class qdpy.algorithms.QualityEvolvabilityES(x0, *, pairs=16, sigma=.1, learning_rate=.03, l2=.005, maximize=True, quality_only=False, ind_domain=None, seed=0)[source]¶
Run mirrored ES with centered Pareto ranks and an Adam ascent step.
Evolvability is squared descriptor distance from the current offspring mean. Normalize descriptor axes in the evaluator if their units differ. Search optimizes the mutation distribution with one fixed sigma. It maintains a single center and evaluates offspring around it.
- Parameters:
x0 – Finite initial parameter vector.
pairs – Number of mirrored perturbation pairs per ES update.
sigma – Gaussian standard deviation for mutation.
learning_rate – Adam ascent step size.
l2 – Nonnegative L2 coefficient applied to the gradient.
maximize – Maximize fitness if true, minimize otherwise.
quality_only – Run the matched fitness-only ES control if true.
ind_domain – Optional common inclusive parameter bounds.
seed – Private seed for mirrored noise and evaluator seeds.
- property center¶
Return a copy of the center, which can be used with a new evaluator.
- run(evaluate, budget)[source]¶
Use up to budget calls. Any remainder smaller than 2*pairs stays unspent.
- sample_offspring(evaluate, count, *, seed)[source]¶
Measure an independent sample around the current center using the training sigma.
- property stats¶
Return cumulative search statistics.
- class qdpy.algorithms.EvolvabilityESStats(evaluations: int, updates: int)[source]¶
Count training evaluator calls, including attempts that raise.
- class qdpy.algorithms.OffspringSample(fitness: tuple[float, ...], descriptors: tuple[tuple[float, ...], ...])[source]¶
Keep quality scores and corresponding descriptors in sampling order.
- qdpy.algorithms.nss_fronts(qualities, descriptors)[source]¶
Rank finite scalar qualities (larger is better) and descriptor rows.
A candidate is surrounded if, for every sign direction, some strictly fitter candidate weakly improves every signed coordinate and strictly improves at least one. Remove each front before determining the next. The returned ranks follow input order.
Exact direction enumeration is intended for low-dimensional descriptors.
- class qdpy.algorithms.NSSMAPElites(container, budget, dimension, *, batch_size=16, ind_domain=(0., 1.), sigma=.1, seed=None, **kwargs)[source]¶
Run NSS-ME on a one-elite Grid or CVTGrid with one fitness objective.
Parents come from the highest-ranking fronts of the measured archive. A partial boundary front is sampled uniformly without replacement. If the archive has fewer members than the generation size, select every member and fill the remaining slots from the first front. Offspring use clipped Gaussian mutation and native grid admission. Use ask_batch and tell_batch for manual evaluation.
- ask_batch(size=None)¶
Return a generation of candidates to evaluate.
The default is the configured batch size. Pass a smaller size for a final partial generation. Send its results to
tell_batch().
- tell_batch(results)¶
Commit one result per candidate, in the order returned by ask_batch.
Use any native evaluator result or
Nonefor a failed slot. Every slot counts as an attempt. A cardinality error leaves the batch pending.
- class qdpy.algorithms.DSAGE(archive, dimension, *, ind_domain=(0., 1.), initial_samples=24, surrogate_evaluations=256, simulation_batch_size=8, prediction_batch_size=32, downsample_shape=None, encoder=None, surrogate=None, seed=0, maximise=True)[source]¶
Deep Surrogate Assisted Generation of Environments on fixed grids.
A bounded real genome can parameterize any caller-provided simulator. The optional encoder builds a fixed-width vector for the surrogate. For custom models, supply fit(X, targets, auxiliary) and predict(X), with target columns ordered as fitness followed by descriptors.
Admit measured results to archive. The inner search illuminates a separate predicted grid. Before simulation, uniformly pick an elite from each selected occupied region of a coarser descriptor grid.
- run(evaluate, *, budget)[source]¶
Run initial and promoted measurements and return cumulative counters.
- property stats¶
Return the actual cumulative search costs.
- class qdpy.algorithms.DSAGESurrogate(*, width=64, epochs=30, learning_rate=.003, auxiliary_weight=1., seed=0)[source]¶
Train a PyTorch MLP on encoded genome rows.
With ancillary targets, a first network predicts them. A second network consumes the encoded genome and those predictions to predict fitness and descriptors. Both losses train the first network. When auxiliary targets are absent, train only the second network.
- class qdpy.algorithms.DSAGEMeasurement(fitness: float, features: tuple[float, ...], auxiliary: object = None)[source]¶
Supply scalar fitness, descriptor coordinates, and optional ancillary targets.
- class qdpy.algorithms.DSAGEStats(evaluations: int, surrogate_evaluations: int, model_fits: int)[source]¶
Cumulative search costs.
- class qdpy.algorithms.HierarchicalRepertoire(primitives)[source]¶
Grow a hierarchy from finite low-level RTESkill records.
Each new layer evolves sequences of indices into the layer below. Candidates are executed during construction by a caller-supplied simulator or scorer. Its returned displacement and secondary descriptors identify the cell used for scalar fitness competition.
- add_layer(evaluate, *, shape, features_domain, sequence_length, budget, seed=None)[source]¶
Return a new layer of evaluated HTESkill records.
Evaluate receives the expanded tuple of primitive RTESkills and returns (fitness, displacement, secondary). The first descriptor axes in the native Grid are the displacement coordinates. Use at least one secondary descriptor axis to retain alternatives.
- property evaluations¶
Count calls to layer evaluators, including failed calls.
- property layers¶
Return all constructed layers, from lowest to highest.
- property primitives¶
Return the immutable primitive layer.
- class qdpy.algorithms.HTESkill(program: tuple[int, ...], primitive_indices: tuple[int, ...], displacement: tuple[float, ...], secondary: tuple[float, ...], fitness: float, primary_cell: tuple[int, ...])[source]¶
Store a program, nominal displacement, and secondary descriptor.
- class qdpy.algorithms.HierarchicalTrialAndError(repertoire, *, secondary_exploration=1., secondary_prior=.5, secondary_noise=.03, model_capacity=128, seed=0, **planning)[source]¶
Deploy a built hierarchy using RTE and a secondary error model.
Each occupied primary cell supplies one nominal displacement from its highest-quality composition. The primary planner uses online residual GPs and MCTS. A second GP predicts error relative to that nominal displacement from primary and secondary descriptors. Its lower confidence bound chooses a measured composition in the cell.
- run(state, goal, execute, *, max_trials, traversable=None, adapt=True)[source]¶
Return an HTEPath on a budget of macro trials.
Execute receives (state, primitive_genome) and returns the new state. Traversable tests predicted primary transitions in the planner. The caller may enforce its own rules during execution.
- property stats¶
Return costs for construction-independent online deployment.
- class qdpy.algorithms.HTEPath(states: tuple[tuple[float, ...], ...], skills: tuple[HTESkill, ...], goal_reached: bool)[source]¶
One more state than skill, beginning at the given initial state.
- class qdpy.algorithms.HTEStats(macro_trials: int, primitive_steps: int, observations: int, planning_rollouts: int)[source]¶
Cumulative costs for online deployment.
- class qdpy.algorithms.QDAIF(archive, *, parent_count=1, seed=None)[source]¶
QDAIF with caller-supplied generation and grading.
Use a one-elite Grid or CVTGrid with one maximized objective. Each archived individual contains one string. Propose receives a tuple of parent texts and this search’s NumPy generator. Judge returns a scalar quality and a descriptor vector. Exact text matches reuse the first successful judgment. Keep the rubric fixed across calls.
Set parent_count to zero for independent sampling. Otherwise parents are sampled uniformly from occupied cells without replacement, up to the requested number.
- property best¶
Return the best archived text, or None for an empty archive.
- run(propose, judge, *, proposal_budget, judgment_budget, initial=())[source]¶
Evaluate seed texts first, then propose and judge new texts.
Seeds spend judgment calls only. Duplicate proposals still spend proposal calls. Stop when either call budget is exhausted. Malformed feedback or a callback error propagates to the caller.
- property stats¶
Return immutable accounting through the latest callback.
Binary swarms, geometric policies, and budgeted archives¶
- class qdpy.algorithms.NoveltyBinaryPSO(archive, dimension, *, population_size=16, neighbors=5, memory_size=256, inertia=.7, cognitive=1.4, social=1.4, velocity_limit=6., temperature=(5., 1.), seed=0)[source]¶
Evaluate binary topologies and report their measured fitness and descriptors.
Recompute the novelty of current positions and personal leaders against a common memory at each swarm iteration. The most novel personal leader provides the social signal. A temperature schedule controls the sigmoid used to sample bit values from their velocities. The reporting archive receives real measurements and stays independent of the novelty memory. Use deterministic measurements for a given bit vector.
- Parameters:
archive – Empty parentless best-only scalar Grid or CVTGrid.
dimension – Number of bits.
population_size – Particle count, up to the available evaluation budget.
neighbors – Number of previous designs used for novelty.
memory_size – Maximum number of distinct recent designs.
inertia – Previous-velocity coefficient in the swarm update.
cognitive – Pull toward each particle’s personal leader.
social – Pull toward the swarm’s most novel leader.
velocity_limit – Absolute velocity cap.
temperature – Positive starting and ending sigmoid temperatures.
seed – Private seed for initial positions and velocity draws.
- class qdpy.algorithms.BinarySwarmResult(archive: Grid, positions: tuple[tuple[int, ...], ...], memory: tuple[tuple[int, ...], ...], evaluations: int, archive_updates: int, out_of_domain: int)[source]¶
The archive retains measured fitness. The memory guides swarm novelty.
- class qdpy.algorithms.GENEEncoding(layer_sizes: tuple[int, ...], coordinate_size: int = 3)[source]¶
Decode a flat genome to alternating row-major weights and biases.
A genome stores all neuron coordinates in layer order followed by the biases of all non-input layers. A weight is the L2 distance between connected neurons multiplied by the coordinate difference product clipped to [-1, 1]. Biases use direct encoding.
- Parameters:
layer_sizes – Width of each layer, including input and output.
coordinate_size – Number of geometric coordinates per neuron.
- property genome_size¶
Return the number of evolved coordinates and bias values.
- property parameter_count¶
Return the number of parameters in the decoded dense actor.
- class qdpy.algorithms.LUCIEMAPElites(archive, dimension, *, delta=.05, epsilon=0., initial_samples=2, max_pairs=16, ind_domain=(0., 1.), iso_sigma=.03, line_sigma=.2, seed=0)[source]¶
Assume deterministic descriptors and independent bounded fitness observations.
Race against an incumbent only within the challenger’s predetermined cell. Reuse the incumbent’s earlier observations. Once the outsider’s upper bound is within epsilon of the leader’s lower bound, the leader is an epsilon-accurate choice under the confidence event. If the rollout or pair budget ends first, use the empirical leader and record an unresolved race. Exact ties retain the incumbent.
- Parameters:
archive – Empty standalone best-only Grid or CVTGrid, with one finite fitness interval covering the support of every observation. Unweighted archives maximize fitness.
dimension – Real genome length.
delta – Total confidence error allowance across arms and sample counts.
epsilon – Additive fitness tolerance in original units.
initial_samples – Number of fitness observations for a new arm.
max_pairs – Maximum extra pairs per local race.
ind_domain – Shared finite, increasing genome bounds.
iso_sigma – Isotropic mutation scale.
line_sigma – Directional mutation scale.
seed – Private variation and evaluator seed.
- class qdpy.algorithms.LUCIESearchStats(evaluations: int, incumbent_evaluations: int, proposals: int, out_of_domain: int, certified_races: int, unresolved_races: int, replacements: int)[source]¶
Counters refer to an individual run call.
- class qdpy.algorithms.TravelingThiefItem(city: int, weight: int, profit: float)[source]¶
City zero is the depot. Item indices are their positions in the input sequence.
- class qdpy.algorithms.TravelingThiefProblem(distances, items, capacity, *, min_speed=.1, max_speed=1., rent=1.)[source]¶
Travel speed decreases linearly with the current carried weight.
Pick up items before leaving their cities and include the final edge back to the depot. The objective maximizes packed profit minus the rental cost of travel time. Both tour directions retain their own load order.
- Parameters:
distances – Square finite nonnegative distance matrix.
items – Sequence of TravelingThiefItem objects.
capacity – Positive integer weight capacity.
min_speed – Speed at capacity.
max_speed – Speed when empty.
rent – Nonnegative cost per travel-time unit.
- evaluate(tour, packing)[source]¶
Return the score and archive descriptors for the supplied item IDs.
- solve_packing(tour)[source]¶
Return (solution, item_transitions) for one exact packing solve.
Keep the best partial net profit for each reachable weight. Apply the next travel cost once all items at the current city have been considered. Count each candidate item addition that stays within capacity, including candidates discarded by the DP.
- class qdpy.algorithms.TravelingThiefMAPElites(problem, archive, *, initial_tours=8, seed=0)[source]¶
Store the highest measured net profit per tour-length/item-profit cell.
This small-instance bilevel variant uses 2-opt mutation and exact packing. A tour evaluation includes one packing solve and one measured route-and-packing pair. An out-of-domain result still spends its tour evaluation and packing work.
- Parameters:
problem – TravelingThiefProblem with integer item weights.
archive – Empty parentless maximizing scalar Grid or CVTGrid with descriptors for unloaded tour length and item profit.
initial_tours – Number of random initial route evaluations.
seed – Private seed for initialization and 2-opt.
Reference niches and repertoire selection¶
- qdpy.algorithms.reference_cvt(targets, *, features_domain=None, fitness_domain=((0., inf),), fitness_weights=(1.,))[source]¶
Use raw or embedded examples as nearest-neighbour archive targets.
Pass the same representation for every reference and candidate. The default descriptor domain is unbounded. Use explicit finite intervals if the search algorithm needs a bounded model, as DMS does. Each input row has a stable zero-based target ID. Deterministic distance ties go to the first matching row.
- qdpy.algorithms.audit_reference_cvt(archive, *, distance_limit=None)[source]¶
Read each incumbent’s fitness and displacement from its target.
- class qdpy.algorithms.ReferenceTarget(target_id: int, fitness: float | None, distance: float | None)[source]¶
Distance is in the same Euclidean space that defines archive cells.
- class qdpy.algorithms.ReferenceAudit(targets: tuple[ReferenceTarget, ...], occupied: int, coverage: float, mean_distance: float | None, matched_coverage: float | None)[source]¶
Mean distance uses occupied cells. The coverage denominator is all targets.
- qdpy.algorithms.select_dpp(candidates, size, *, embedding=None, quality=None, bandwidth=1., quality_strength=1., ridge=1e-8)[source]¶
Select a compact repertoire without modifying or reevaluating candidates.
The defaults use each elite’s feature vector and its scalar weighted fitness, resolving named scores and weights when given a container. Rescale features before selection when axes have different units. The maximum quality gets zero log penalty and the minimum gets a penalty of quality_strength. Set quality_strength to zero for diversity-only selection. An incremental Cholesky update needs only one kernel column per selected member.
- class qdpy.algorithms.DPPRepertoire(indices: tuple[int, ...], members: tuple, similarity_logdet: float, objective_logdet: float)[source]¶
Members reference the input objects. Indices retain greedy selection order.
- class qdpy.algorithms.ScheduledCVTMAPElites(archives, dimension, *, phase_evaluations, shared_feedback=False, ind_domain=(0., 1.), iso_sigma=.03, line_sigma=.2, seed=0)[source]¶
Use the active CVT archive as the parent pool for one phase.
At a phase boundary, re-bin each current elite into the incoming archive using the measurements cached on the original evaluation. The incoming archive also keeps any elites already found in earlier phases. Transfer costs zero evaluator calls. Each view owns its fitness weights and descriptor geometry.
- Parameters:
archives – Ordered mapping of names to empty, distinct scalar CVT grids.
dimension – Number of real decision coordinates.
phase_evaluations – Number of evaluation attempts per active view.
shared_feedback – Also offer each evaluation to inactive views for a control.
ind_domain – Increasing finite genome bounds shared by all coordinates.
iso_sigma – Independent Iso+LineDD mutation scale.
line_sigma – Directional Iso+LineDD mutation scale.
seed – Seed for private variation and evaluator streams.
- property archives¶
Return a mapping of names to the live CVT grids owned by the search.
- property current_archive¶
Return the active parent pool.
- run(evaluate, budget)[source]¶
Return a scalar fitness and one descriptor vector per configured view.
- property stats¶
Return cumulative evaluator and phase counts.
- class qdpy.algorithms.ScheduledCVTStats(evaluations: int, active_view: str, evaluations_by_view: tuple[tuple[str, int], ...], switches: tuple[CVTViewSwitch, ...])[source]¶
Report cumulative attempts and the current view.
Case rarity, linked variation, and coevolution¶
- qdpy.algorithms.novelty_case_counts(outputs, *, history=())[source]¶
Count an output’s occurrences in the current population and history.
Choose hashable labels before calling this function. For continuous outputs, a caller can discretize values to determine what counts as the same behavior. History participates in counts and stays outside the selection pool.
- qdpy.algorithms.novelty_lexicase_index(errors, outputs, rng, *, history=())[source]¶
Shuffle original error columns and output counts together as cases.
- qdpy.algorithms.learn_categorical_linkage(genomes)[source]¶
Cluster variables by normalized empirical mutual information.
Return singleton groups and all non-root merges, in tree construction order. Use at least two encoded genomes. Invariant columns have zero similarity to other columns. Ties follow SciPy’s deterministic linkage.
- class qdpy.algorithms.GOMMAPElites(archive, nvec, *, initial_samples=16, random_injection=.05, linkage_period=32, learn_linkage=True, seed=0)[source]¶
Search a product of integer categories using measured block recombination.
Groups are inferred from archived genomes. Each mix chooses donors from a snapshot so admissions during the mix do not change its gene pool. Offer every measured intermediate to the archive. Continue mixing from a trial if it preserves or improves the parent’s scalar fitness, using the archive’s comparison direction.
- Parameters:
archive – Empty parentless scalar best-only Grid or CVTGrid.
nvec – Number of categories for each variable, starting at zero.
initial_samples – Minimum number of initial proposals before mixing.
random_injection – Probability of a random instead of a mixing proposal.
linkage_period – Minimum number of measurements between linkage fits.
learn_linkage – Learn groups or use only singleton groups for a control.
seed – Private seed for sampling and selecting genomes.
- class qdpy.algorithms.GOMSearchStats(evaluations: int, random_evaluations: int, block_evaluations: int, accepted_blocks: int, linkage_fits: int, archive_updates: int, out_of_domain: int)[source]¶
Every measured intermediate proposal contributes to evaluations.
- class qdpy.algorithms.MinimalCriterionCoevolution(seed_tasks, seed_solvers, *, mutate_task, mutate_solver, task_capacity=32, solver_capacity=64, task_resources=4, seed=0)[source]¶
Alternate proposing task offspring and solver offspring.
A task offspring must be solved by at least one living solver. A solver offspring must solve a living task that still has resources. The first successful pairing admits the offspring and a solver admission spends one resource on its supporting task. Test partners in a seeded random order without replacement for each proposal. Remove the oldest member of a population when it reaches capacity.
- Parameters:
seed_tasks – Distinct immutable initial tasks, assumed viable.
seed_solvers – Distinct immutable initial solvers, assumed viable.
mutate_task – Callback taking (parent, rng) and returning a task or None.
mutate_solver – Callback taking (parent, rng) and returning a solver or None.
task_capacity – Maximum number of concurrent tasks.
solver_capacity – Maximum number of concurrent solvers.
task_resources – Number of solvers each task can admit while live. None selects unlimited resources as a control.
seed – Private proposal and pair evaluation seed.
- run(evaluate, budget, *, proposal_limit=None)[source]¶
Save pending partner tests across a budget boundary and charge calls once.
- property solvers¶
Return living solvers in oldest-first order.
- property stats¶
Return cumulative costs and admissions.
- property tasks¶
Return current environments and their use in oldest-first order.
- class qdpy.algorithms.MCCTask(task: Hashable, used_resources: int)[source]¶
Resource use follows the lifetime of the current environment entry.
- class qdpy.algorithms.MCCStats(proposals: int = 0, task_pairings: int = 0, solver_pairings: int = 0, task_admissions: int = 0, solver_admissions: int = 0, exhausted_task_skips: int = 0)[source]¶
Pairings are the only evaluator calls. First attempts count on error.
- property evaluations¶
Return all attempted task-solver evaluations.
Portfolios, novelty–surprise, and policy transfer¶
- qdpy.algorithms.solve_binary_portfolio(objective, size, *, quality_loss=0., maximize=True, constraints=(), time_limit=None, node_limit=None)[source]¶
First certify the quality reference, then optimize the portfolio jointly.
Both solves request zero relative MIP gap. Constraint verification uses absolute tolerance 1e-7. Solver certificates retain the solver’s numerical tolerances. Solver calls and their limits apply separately to the reference optimum and the joint problem.
- class qdpy.algorithms.MILPPortfolioResult(status: str, designs: tuple[tuple[int, ...], ...] = (), qualities: tuple[float, ...] = (), optimum: float | None = None, quality_cutoff: float | None = None, minimum_distance: int | None = None, distance_upper_bound: float | None = None, solver_calls: int = 0, message: str = '')[source]¶
Report raw objective values and a bound in units of Hamming distance.
A status of optimal requires solver optimality and independent checks on the rounded incumbent. An unresolved portfolio may still contain a complete, verified set from a limited solve. A certified single-design optimum is required before solving the portfolio problem.
- class qdpy.algorithms.NoveltySurpriseSearchLC(archive, dimension, *, novelty_weight=.5, novelty_neighbors=15, novelty_threshold=.1, novelty_history=512, **kwargs)[source]¶
Use the same forecasts and steady-state variation as SurpriseSearchLC.
With a real-valued novelty_weight, NSGA-II maximizes the weighted sum of novelty and surprise beside local wins. With novelty_weight=None, it treats all three signals as separate objectives. Novelty and local wins consider both the live population and past novel offspring. Distances are Euclidean in descriptor coordinates, as in SS-LC.
- Parameters:
archive – Passive reporting grid, as in SurpriseSearchLC.
dimension – Number of decision coordinates.
novelty_weight – Novelty fraction of the aggregated divergence score. Use None for three-objective NS-SS-LC.
novelty_neighbors – Number of neighbors for the novelty score.
novelty_threshold – Add measured offspring whose novelty meets this threshold.
novelty_history – Maximum number of older novel offspring retained in FIFO order.
kwargs – Search, forecast, and variation settings accepted by SurpriseSearchLC.
- qdpy.algorithms.fit_tabular_successor_features(continuation, features, policies, *, gamma=.99)[source]¶
Solve each source policy’s Bellman system exactly up to float precision.
Missing transition mass denotes termination. Include immediate features from the terminal outcomes in the expected input features. Observations and actions are integer indices. All policies transfer within the same dynamics and reward is linear in the features.
- class qdpy.algorithms.SuccessorFeatureRepertoire(successor_features: ndarray)[source]¶
The values array is indexed by policy, state, first action, and feature.
Feature returns predict continuing with the source policy after the first action. GPI chooses the action with the highest value across all source policies independently at each visited state.
Guided variation and reward coverage¶
- qdpy.algorithms.tabular_sfols(continuation, features, start, *, gamma=.99, max_policy_solves=32, tolerance=1e-7)[source]¶
Solve the most promising corner of the current policy envelope next.
The search first solves unit reward weights. For each corner of the current piecewise-linear value envelope, a linear program bounds the value of any unknown policy using the solved tasks. Numerical roundoff in policy evaluation is tracked through a Bellman residual bound. Corner enumeration is intended for small reward spaces. Auditing uses the supplied start distribution.
- qdpy.algorithms.tabular_optimal_policy(continuation, features, reward_weights, *, gamma=.99)[source]¶
Return the integer action table for a fixed linear reward.
- class qdpy.algorithms.SFOLSResult(repertoire: SuccessorFeatureRepertoire, policies: tuple[tuple[int, ...], ...], feature_returns: tuple[tuple[float, ...], ...], solved_weights: tuple[tuple[float, ...], ...], upper_gap: float | None, converged: bool, bound_solves: int)[source]¶
Coverage and the gap refer to the supplied start-state distribution.
upper_gap is None if the budget was too small to solve every unit reward. Read the finite gap with the policy and LP solver tolerances. Each row of feature_returns reports one retained policy’s start value.
- property policy_solves¶
Count supported weights sent to the scalar policy solver.
- class qdpy.algorithms.PriorGuidedOfflineMAPElites(archive, genomes, fitnesses, descriptors, *, nvec, prior=None, prior_weight=1., uncertainty_scale=None, uncertainty_penalty=0., mutation_choices=4, proposal_strength=3., length_scale=1.8, noise=1e-6, seed=0)[source]¶
Use a frozen Matérn GP and a caller-supplied categorical prior.
Mutation samples single-locus changes and optionally chooses among them using prior scores. At admission, increasing model uncertainty increases the contribution of the prior to a normalized quality score. The returned archive stores raw predicted quality and descriptors. Disagreement is an acquisition signal and carries no coverage guarantee.
- Parameters:
archive – Empty parentless best-only Grid or CVTGrid with one signed objective.
genomes – Integer training designs, one row per measurement.
fitnesses – Measured scalar qualities for the training designs.
descriptors – Measured descriptors for the training designs.
nvec – Number of zero-based categories in each locus.
prior – Callable scoring a design on [0, 1], with higher being more plausible.
prior_weight – Maximum fraction of the acquisition score determined by the prior.
uncertainty_scale – Predicted deviation at which the prior receives half its maximum weight. Defaults to one quarter of the logged quality span.
uncertainty_penalty – Fixed standard-deviation penalty in quality units.
mutation_choices – Number of prior-scored edits per mutation.
proposal_strength – Inverse temperature applied to prior scores on edits.
length_scale – Fixed Matérn length scale on one-hot genomes.
noise – Positive GP covariance regularization.
seed – Private seed for seed selection and mutations.
- run(budget, *, initial_samples=16)[source]¶
Make a new predicted archive and count every prior call.
- static verify(result, evaluate, budget, *, seed=0, executor=None)¶
Keep measured outcomes separate. Observed descriptor cells decide placement.
- class qdpy.algorithms.PriorGuidedSearchResult(archive: Grid, predictions: int, prior_queries: int)[source]¶
Each elite’s scores include its selection score, uncertainty, and prior weight.
- class qdpy.algorithms.OperatorMOME(archive, *, initializer, operators, controller='uniform', initial_samples=16, seed=0)[source]¶
Use uniform or UCB1 operator choices with native two-objective fronts.
Sample descriptor cells uniformly and then parents uniformly within their fronts. An admitted child earns 1 for space in its target front or .8 for entering a full front. A rejected child earns zero. Keep cumulative evaluation accounting and resume with the same next parent context when another search budget is supplied.
- Parameters:
archive – Empty two-objective ParetoGrid with hypervolume truncation.
initializer – Callback returning a genome from a private generator.
operators – Mapping of names to callbacks taking (parent, donor, rng). Parents and donors are tuples copied from the archive.
controller – Uniform or bandit.
initial_samples – Minimum number of warm-up evaluations.
seed – Private seed for decisions, mutations, and evaluations.
- property stats¶
Return costs, per-operator outcomes, and archive updates.
- class qdpy.algorithms.OperatorMOMEStats(evaluations: int, initial_evaluations: int, archive_updates: int, out_of_domain: int, operator_attempts: tuple[tuple[str, int], ...], operator_admissions: tuple[tuple[str, int], ...], optimizer_steps: int, target_syncs: int)[source]¶
The operator tuples follow the supplied mapping’s iteration order.
Batch acquisition, benchmark instances, feasibility, and scenario risk¶
- class qdpy.algorithms.BatchBOPElites(container, budget, dimension, ind_domain, quality_floor, *, batch_size=4, candidates=96, samples=128, selection='joint', initial_samples=None, seed=None, **kwargs)[source]¶
Fit objective and descriptor models once per generation.
Draw correlated samples across the Sobol candidate pool for each independent output GP. Greedily select a batch that maximizes the expected sum of the largest improvement in each cell. Outside-grid samples have zero gain. Only measured candidates can update the archive. This variant works with native scalar fitness and one or two direct descriptors.
- Parameters:
container – Parentless best-only rectangular Grid.
budget – Maximum true-evaluation attempts.
dimension – Number of bounded decision variables.
ind_domain – Common finite decision interval.
quality_floor – Empty-cell threshold in signed weighted quality units.
batch_size – Maximum number of candidates in a generation.
candidates – Number of Sobol proposals scored jointly.
samples – Number of joint normal posterior draws per generation.
selection – Joint marginal improvement or independent top-k.
initial_samples – Minimum number of initial Sobol proposals.
seed – Seed for Sobol proposals and posterior draws.
kwargs – Native optimiser options.
- class qdpy.algorithms.DiscriminatoryInstanceSearch(archive, *, solvers, initializer, mutate, describe, performance_archive=None, maximize=True, target_solver=None, novelty_weight=.5, gap_novelty_weight=.5, gap_scale=1., min_gap=0., population_size=32, history_size=128, neighbors=5, initial_samples=16, seed=0)[source]¶
Evolve a population using instance and gap novelty beside discrimination.
A solver returns a single comparable performance value. Its advantage is measured against the best competing solver, with optional focusing on a fixed target solver. Every complete panel is scored using the same seed across its solvers. A passive grid keeps the largest positive margin, raw panel scores, and the winner for independent analysis.
- Parameters:
archive – Empty best-only maximizing Grid or CVTGrid with native scores.
performance_archive – Optional second maximizing grid with (winner index, raw margin) descriptors.
solvers – Ordered mapping from names to callbacks (instance, seed).
initializer – Callback (rng) generating an immutable instance sequence.
mutate – Callback (instance, rng) generating a new instance sequence.
describe – Callback (instance) computing finite instance descriptors.
maximize – Whether a larger panel score indicates a better solver.
target_solver – Optional fixed solver whose signed margin guides search.
novelty_weight – Fraction of the search score allocated to novelty.
gap_novelty_weight – Fraction of novelty allocated to performance gaps.
gap_scale – Positive reference scale for solver advantages.
min_gap – Minimum positive advantage accepted by the reporting grid.
population_size – Maximum number of live instances.
history_size – Number of distinct recent genomes in novelty history.
neighbors – Number of nearest neighbors used for novelty.
initial_samples – Number of random instances before variation.
seed – Private seed for search and complete solver panels.
- run(budget) DiscriminatorySearchStats[source]¶
Leave any remainder smaller than a panel unspent.
- property stats¶
Return cumulative solver-panel accounting.
- class qdpy.algorithms.DiscriminatorySearchStats(instances: int, solver_calls: int, discriminatory_instances: int, archive_updates: int, wins: tuple[tuple[str, int], ...], performance_updates: int)[source]¶
The winner counts exclude draws and follow the solver mapping’s order.
- class qdpy.algorithms.FeasibleInfeasibleNoveltySearch(archive, *, initializer, mutate, mode='fins', population_size=32, history_size=128, neighbors=5, feasible_parent_probability=.5, initial_samples=16, seed=0)[source]¶
Keep independent bounded populations and novelty histories.
FINS chooses feasible parents by novelty and infeasible parents by low total positive violation. FI2NS uses novelty in both populations. An offspring enters the pool appropriate to its measured constraints. Only feasible measurements are offered to the independent native grid.
- Parameters:
archive – Empty parentless best-only Grid or CVTGrid.
initializer – Callable (rng) returning an immutable genome sequence.
mutate – Callable (genome, rng) returning a new genome sequence.
mode – FINS or FI2NS, specified as “fins” or “fi2ns”.
population_size – Capacity of each breeding population.
history_size – Number of distinct recent genomes per novelty history.
neighbors – Nearest-neighbor count for novelty.
feasible_parent_probability – Fraction of births allocated to feasible breeders when both populations are available.
initial_samples – Number of initial proposals from initializer.
seed – Seed for variation, selection, and evaluation calls.
- property feasible_population¶
Return immutable active feasible genomes.
- property infeasible_population¶
Return immutable active infeasible genomes.
- run(evaluate, budget) FeasibleNoveltyStats[source]¶
Use residuals at or below zero for feasible admission and propagate invalid evaluations.
- property stats¶
Return cumulative measured search costs and outcomes.
- class qdpy.algorithms.FeasibleNoveltyStats(evaluations: int = 0, feasible_evaluations: int = 0, feasible_from_infeasible: int = 0, infeasible_from_feasible: int = 0, archive_updates: int = 0, first_feasible: int | None = None)[source]¶
Evaluations count attempted calls, with one-based first-feasible indexing.
- class qdpy.algorithms.ScenarioRiskMAPElites(archive, scenarios, *, initializer, mutate, tail_fraction=.2, objective='cvar', probabilities=None, initial_samples=16, seed=0)[source]¶
Measure the same scenario panel for every design before archive admission.
Use mean performance, empirical CVaR, or a Pareto front with mean and CVaR in that order. Average descriptors over the same panel with the supplied weights. Report raw performance and propagate errors when a scenario yields invalid data.
- Parameters:
archive – Empty best-only Grid or CVTGrid, or a native two-objective ParetoGrid.
scenarios – Nonempty fixed sequence of scenario inputs.
initializer – Callable (rng) generating a design.
mutate – Callable (genome, rng) generating a new design.
tail_fraction – Worst probability mass used for CVaR.
objective – Mean, CVaR, or Pareto, specified in lowercase.
probabilities – Optional weights aligned with the scenario panel.
initial_samples – Number of proposals drawn from the initializer.
seed – Private selection, initialization, and variation seed.
- audit(evaluate, scenarios, *, probabilities=None, budget=None) ScenarioRiskAudit[source]¶
Reassign audited designs by measured behaviour while preserving the source archive.
- run(evaluate, budget) ScenarioRiskStats[source]¶
Reuse the common panel and leave a partial panel unspent.
- property stats¶
Return cumulative scenario attempts and archive changes.
- class qdpy.algorithms.ScenarioRiskStats(scenario_calls: int = 0, candidates: int = 0, archive_updates: int = 0, out_of_domain: int = 0)[source]¶
A budget can have a remainder too short to compare another complete design.
- class qdpy.algorithms.ScenarioRiskAudit(archive: Grid, stats: ScenarioRiskStats, measurements: tuple[Individual, ...])[source]¶
The result records each candidate’s mean, tail, and descriptor before archive truncation.
Objective voting, structural diversity, and transfer¶
- class qdpy.algorithms.MOVE(objective_count, *, sample, mutate, slots=50, subset_size=None, subsets=None, maximize=True, seed=0)[source]¶
Run Dean and Cheney’s MOVE with caller-supplied genomes and objective functions.
The initial population assigns one candidate to each slot. Within a generation, all offspring use the incumbent snapshot, then compete in slot order. Each objective casts a vote only for a strict improvement. Slots keep their incumbent on a tied or losing vote.
- Parameters:
objective_count – Number of values returned by the evaluator.
sample – Callable (rng) returning a genome iterable.
mutate – Callable (parent_genome, rng) returning an offspring iterable.
slots – Number of independently sampled subsets if subsets is omitted.
subset_size – Number of distinct indices per sampled subset. Defaults to five or the full objective count, whichever is smaller.
subsets – Optional explicit nonempty objective index subsets in slot order.
maximize – One Boolean direction for all objectives or one per objective.
seed – Seed for geometry, variation, and independent evaluations.
- property champions¶
Return the current champions in slot order, with None for empty slots.
- run(evaluate, budget)[source]¶
Spend the additional budget. A subsequent call continues the current generation.
- property stats¶
Return cumulative telemetry.
- property subsets¶
Return the objective indices in each slot, including repeated subsets.
- class qdpy.algorithms.MOVEEntry(genome: tuple, objectives: tuple[float, ...], evaluation_id: int, parent_id: int | None, parent_slot: int | None)[source]¶
Store raw objective values and lineage back to the breeding slot.
- class qdpy.algorithms.MOVEStats(evaluations: int, failures: int, generations: int, replacements: int, goal_switches: int)[source]¶
Count each evaluation once even if it replaces several champions.
- class qdpy.algorithms.DiversityEnhancingNSGAII(objective_count, *, sample, mutate, distance, crowding_distance=None, population_size=32, maximize=True, standard_crowding=False, seed=0)[source]¶
Apply DE-NSGA-II to encodings with an application-defined distance.
Each merged population receives an extra objective equal to mean behavioral dissimilarity. Its Pareto ranks guide survival and tournament selection. To break rank ties, the default uses average behavioral dissimilarity. A separate callback can use the genomes.
- Parameters:
objective_count – Number of raw objectives.
sample – Callable (rng) returning a genome.
mutate – Callable (parent_genome, rng) returning an offspring.
distance – Symmetric nonnegative callable over two behavior objects. Treat the genome elements and observed behavior as immutable.
crowding_distance – Optional symmetric callable over two DissimilarityEntry instances. Omit it to share the diversity objective’s distance matrix.
population_size – Parent and offspring population capacity.
maximize – A Boolean or one Boolean direction per objective.
standard_crowding – Use standard objective-space NSGA-II crowding for an ablation.
seed – Private sampling and evaluation seed.
- property population¶
Return survivors from the last completed selection, in tournament order.
- run(evaluate, budget)[source]¶
Spend the budget and keep an unfinished offspring batch for a later call.
- property stats¶
Return cumulative evaluation attempts and completed selections.
- class qdpy.algorithms.DissimilarityEntry(genome: tuple, objectives: tuple[float, ...], behavior: object)[source]¶
The behavior object is passed to user-supplied dissimilarity functions.
- class qdpy.algorithms.DissimilarityStats(evaluations: int, failures: int, generations: int)[source]¶
Separate failed measurement attempts from committed generations.
- class qdpy.algorithms.EDOCS(dimension, *, archive_size=32, clusters=5, top_per_cluster=2, sample=None, ind_domain=None, novelty_neighbors=10, novelty_threshold=.05, probes=16, es_steps=5, sigma=.05, learning_rate=.02, weights=(0., .5), ucb_scale=1., seed=0)[source]¶
Implement EDO-CS over numeric policy vectors and a seeded evaluator.
Cluster the current archive with k-means at each round. Always breed the best archived policy, then sample uniformly among the top policies of each other cluster. Estimate raw ES gradients from Gaussian probes against a frozen archive. Use UCB1 on each diversity weight’s measured improvement in return. Each accepted offspring is the newest archive entry for FIFO capacity enforcement.
- Parameters:
dimension – Number of parameters in each policy vector.
archive_size – Number of random initialization attempts and maximum live policies.
clusters – Maximum number of behavioral clusters.
top_per_cluster – Number of high-reward policies eligible in each other cluster.
sample – Optional callable (rng) returning initial parameters. The default is uniform within ind_domain or [-1, 1] if unbounded.
ind_domain – Optional shared finite bounds for clipped ES.
novelty_neighbors – Number of nearest archived policies in the ES novelty term.
novelty_threshold – Descriptor radius within which reward decides replacement.
probes – Independent Gaussian probes per ES update.
es_steps – ES updates per selected policy before evaluating its final center.
sigma – Standard deviation of Gaussian perturbations.
learning_rate – Step size of the raw ES gradient estimator.
weights – Diversity weights made available as UCB arms. Pass a single value for a fixed-weight ablation.
ucb_scale – Nonnegative scale of the confidence bonus.
seed – Seed for initialization, selection, perturbations, and rollouts.
- property archive¶
Return measured policies from oldest to newest.
- property next_round_cost¶
Return evaluator calls required by the next round, or zero if empty.
- property stats¶
Return cumulative attempts and counts of observed arm rewards.
- class qdpy.algorithms.EDOCSPolicy(genome: tuple[float, ...], reward: float, descriptor: tuple[float, ...])[source]¶
Archive only measurements from initialization and evaluated ES centers.
- class qdpy.algorithms.EDOCSStats(policy_evaluations: int, perturbation_evaluations: int, failures: int, rounds: int, arm_counts: tuple[int, ...])[source]¶
Report attempts, failed slots, completed outer rounds, and UCB feedback counts.
- property evaluations¶
Return total evaluator calls.
- class qdpy.algorithms.CosineMAPElites(targets, *, sample, mutate, crossover=None, crossover_probability=.5, shape=(8, 8), population_size=32, alpha=.1, retain_fraction=.5, maximize=False, seed=0)[source]¶
Implement the semantic search of Zhang et al. with caller-defined model encodings.
Fit a cosine-kernel projection using symmetric reference predictions around the target vector. Preserve the best fraction of offspring and incumbents before rebuilding the archive in the new coordinates. Evaluators should provide out-of-fold or other training-only predictions. Use held-out observations only for final comparison.
- Parameters:
targets – Supervised target vector in evaluator prediction order.
sample – Callable (rng) returning a model genome iterable.
mutate – Callable (genome, rng) returning an offspring genome.
crossover – Optional callable (genome, donor, rng) returning a recombinant genome.
crossover_probability – Probability of crossing before mutation when supplied.
shape – Number of cells along each projected axis.
population_size – Initial sample and offspring batch size.
alpha – Reference displacement along the target-to-prediction vector.
retain_fraction – Fraction of the merged pool considered for the new archive.
maximize – Compare larger fitness when True and smaller fitness otherwise.
seed – Seed for parent selection, variation, and model evaluation.
- property archive¶
Return the native Grid from the most recent fit. Its geometry can change at a rebuild.
- run(evaluate, budget)[source]¶
Retain any incomplete batch so a later call continues the same trajectory.
- property stats¶
Return model evaluation and archive rebuild counts.
- class qdpy.algorithms.CosineElitesStats(evaluations: int, failures: int, rebuilds: int)[source]¶
Count attempted fits, failed evaluations, and completed archive projections.
- class qdpy.algorithms.TBREvolution(*, sample, mutate, population_size=24, neighbors=15, novelty_threshold=.1, transfer_threshold=.2, transfer_period=4, maximize=True, seed=0)[source]¶
Maintain a simulator repertoire with occasional measurements on a target system.
Periodically sample one candidate from the combined population and repertoire, observe its target descriptor, and update a linear nu-SVR discrepancy model. Novelty and local quality and error ranks determine NSGA-II survival. A locally competing archive candidate wins on quality when both errors meet the transfer threshold. If either misses that threshold, the lower predicted error wins.
- Parameters:
sample – Callable (rng) returning a genome iterable.
mutate – Callable (parent_genome, rng) returning an offspring.
population_size – Initial and offspring batch size and survivor capacity.
neighbors – Number of neighbors in the population and repertoire union.
novelty_threshold – Novelty needed to enter without replacing a neighbor.
transfer_threshold – Maximum acceptable predicted target descriptor error.
transfer_period – Number of completed simulator batches between transfer attempts.
maximize – Prefer larger quality when True and smaller quality otherwise.
seed – Random seed for variation, transfer selection, and both evaluators.
- property archive¶
Return the current repertoire with simulated quality and descriptors.
- property population¶
Return the last selected breeding population.
- predict_error(descriptors)[source]¶
Use an optimistic zero before transfer data and the observed constant for one pair.
- run(simulate, simulation_budget, *, evaluate_target=None, target_budget=0)[source]¶
Spend simulator attempts and skip scheduled transfers when the target budget is exhausted.
- property stats¶
Return attempts and failures by evaluation source.
- property transfers¶
Return measured simulator–target pairs used for fitting.
- class qdpy.algorithms.TBREntry(genome: tuple, quality: float, descriptor: tuple[float, ...], evaluation_id: int)[source]¶
Store predicted-system measurements and the simulator attempt ID.
Density guidance, design portfolios, and planning¶
See Learned density, design portfolios, and shared controllers for examples and resource accounting.
- qdpy.algorithms.dds_cnf(archive, evaluate, *, x0, budget, reservoir_size=1024, sigma0=.15, batch_size=16, ind_domain=(0., 1.), seed=0, executor=None, on_step=None, model_width=32, fit_period=4, fit_steps=20, fit_batch_size=32, integration_steps=8, learning_rate=.003)[source]¶
Run DDS with a CPU PyTorch flow trained by conditional flow matching.
Fit only on earlier descriptor batches. Score a candidate by mapping its descriptor back to a standard Gaussian and integrating the velocity divergence. A fixed affine normalization is learned from the first nonempty reservoir. Its log determinant cancels in the ranking. Fitness still controls only admission to the reporting archive.
Requires pycma and PyTorch, available through the existing
dmsextra.
- class qdpy.algorithms.DDSCNFResult(archive: Grid, attempts: int, failures: int, reservoir_size: int, model_fits: int, optimizer_steps: int, density_evaluations: int, fit_seconds: float, density_seconds: float)[source]¶
The first generation uses equal density ranks until measurements exist.
- qdpy.algorithms.evolutionary_portfolios(evaluate, *, dimension, portfolio_size, budget, population_size=20, quality='mean', method='nsga2', crossover_probability=.8, mutation_probability=None, descriptor=None, repair=None, seed=0)[source]¶
Treat a concatenation of member bit strings as a single evolutionary individual.
Uniform crossover shuffles the second parent’s member order before exchanging bits. Mutation flips bits independently. The optional descriptor changes the space where Hamming distances are computed, for example from vertex indicators to cut-edge indicators.
Every member slot is evaluated. Repeated designs are allowed and contribute zero pair distance to an identical descriptor. A failed member excludes its portfolio from selection. Pass a repair callback to enforce constraints before evaluation, or handle them in the evaluator. The uniform control uses random proposals and the same bounded NSGA-II survival rule.
- class qdpy.algorithms.EvolutionaryPortfolio(members: tuple[tuple[int, ...], ...], member_qualities: tuple[float, ...], quality: float, diversity: int)[source]¶
The diversity is the sum of Hamming distances over unordered member pairs.
- class qdpy.algorithms.EvolutionaryPortfolioResult(portfolios: tuple[EvolutionaryPortfolio, ...], member_evaluations: int, failed_members: int, portfolio_attempts: int, generations: int)[source]¶
The evaluation budget counts calls for each member, including failures and repeats.
- qdpy.algorithms.solve_diversitree(objective, bounds, size, *, budget, integrality=None, constraints=(), binary_indices=None, quality_loss=0., maximize=True, alpha=.7, beta=.1, seed_solutions=2, time_limit=None)[source]¶
Use DiversiTree’s bound, partial diversity, and depth priorities.
The outer tree branches over binary projections. Each node uses SciPy MILP as an exact subproblem oracle. A verified node optimum contributes one representative. Partition the remaining node by the first bit where its projection differs from that representative. Open nodes inherit their parent’s valid objective bound. The method returns a bounded collection, with a certificate for the reference fitness.
- class qdpy.algorithms.DiversiTreeResult(status: str, designs: tuple[tuple[int | float, ...], ...], qualities: tuple[float, ...], binary_indices: tuple[int, ...], solver_calls: int, optimum: float | None, quality_cutoff: float | None, message: str = '')[source]¶
Keep one mixed-integer point per distinct selected binary projection.
- property mean_binary_distance¶
Return the mean pairwise Hamming distance divided by the binary dimension.
- qdpy.algorithms.forbid_iterative_planning(start, *, actions, simulate, goal, size, max_depth, budget, pool_size=64, cost_ceiling=np.inf, distinct='multiset', selection='diverse', diversity='mean', distance=action_multiset_distance, distance_floor=None)[source]¶
Adapt the forbid-and-select method to a bounded deterministic simulator.
A shared uniform-cost frontier enumerates goal plans and forbids duplicate sequences or action multisets during collection. Plans may visit the same state via different prefixes. Expansion ends at the first goal of a path. Select a diverse subset from that pool by growing the most distant pair, or solve the paper’s clique formulation to enforce a minimum pairwise separation.
- qdpy.algorithms.action_multiset_distance(left, right)[source]¶
Count repeated actions and ignore their ordering.
- class qdpy.algorithms.CostedPlan(actions: tuple, cost: float, final_state: Hashable)[source]¶
Action sequences are immutable tuples of hashable action identifiers.
- class qdpy.algorithms.ForbidPlanningResult(plans: tuple[CostedPlan, ...], candidates: tuple[CostedPlan, ...], simulator_calls: int, solver_calls: int, stop_reason: str, selection_status: str, minimum_distance: float | None, mean_distance: float | None)[source]¶
A diversity-bound certificate applies to the recorded candidate pool.
- property total_cost¶
Return the sum of selected plan costs.
Seeded refinement and coupled archives¶
- qdpy.algorithms.qd_seeded_refinement(seed_archive, archive, evaluate, refine, *, dimension, search_budget, starts, refinement_budget_per_start, ind_domain=(0., 1.), initial_samples=8, seed_selection='archive', propose=None, seed=0)[source]¶
Use the local solver’s measured trials to choose one result per start.
The solver receives a scalar minimization objective and a measured start. Return values from the solver are advisory. Selection uses the best feasible measured point, including the start, so a failed or worse trial cannot erase it. The objective raises a private stop signal before exceeding its call cap. A rejected measurement returns positive infinity.
The random control samples seed designs independently and retains a uniform reservoir of valid points for refinement. Both modes start up to the configured number of solves without extra seed evaluations.
- class qdpy.algorithms.QDIDStart(seed: tuple[float, ...], solution: tuple[float, ...], initial_fitness: float, fitness: float, evaluations: int, failures: int)[source]¶
The reported seed remains available if all refinements are worse.
- class qdpy.algorithms.QDIDResult(seeds: object, archive: object, starts: tuple[QDIDStart, ...], search_evaluations: int, search_failures: int, refinement_evaluations: int, refinement_failures: int)[source]¶
Keep exact evaluator calls for the seed search and for local refinement.
- qdpy.algorithms.llmatic(archive, prompt_archive, *, initial, prompts, generate, evaluate, proposal_budget, evaluation_budget, batch_size=8, crossover_probability=.3, crossover_prompt='Combine the parents.', crossover_neighbors=2, prompt_exploration=.2, initial_temperature=.6, temperature_step=.1, seed=0)[source]¶
Reward prompts that produce good measured architectures.
Curiosity is tracked per template. A new archive entry earns one point, rejection costs half a point, and a failed mutation costs one point. Only measured models can earn credit for exceeding the previous batch’s best architecture. The prompt grid stores cumulative credits and uses normalized template index and temperature as descriptors. The network grid stores measured validation quality.
The evaluator is assumed stationary and deterministic for an immutable architecture (including rejected ones). Each payload is measured at most once. The initial architecture supplies a parent without using a measurement call. It can enter the archive if a generator proposes it.
- class qdpy.algorithms.LLMaticRequest(parents: tuple[Hashable, ...], prompt: str, temperature: float, crossover: bool)[source]¶
Mutation has one parent, while crossover starts from nearby elites.
- class qdpy.algorithms.LLMaticResult(architectures: object, prompts: object, proposals: int, evaluations: int, invalid: int, duplicates: int, mutations: int, crossovers: int, admissions: int, prompt_curiosity: tuple[float, ...], prompt_credits: tuple[int, ...])[source]¶
Keep callback counts, unique architecture evaluations and prompt feedback.
- qdpy.algorithms.acdc(initial_models, initial_tasks, *, vary_model, propose_task, evaluate, task_descriptor, budget, rounds, model_capacity=8, offspring_size=8, active_task_capacity=16, task_period=2, task_proposals=4, task_novelty=.05, passing_score=.5, difficulty_target=.5, novelty_neighbors=3, selection='novelty', valid_model=None, valid_task=None, team_size=3, team_budget=0, seed=0)[source]¶
Select models for unique skills and keep novel, solvable assessments.
Measure every active model on new tasks before admitting them. Retain the best model and rank the others by difficulty-weighted solved tasks missed by fitter models. Task proposals receive the parent’s pass rate and direction. The active task panel rolls forward as novel tasks enter.
A proposal is measured only when its whole assessment panel fits the search budget. Scores for identical pairs are reused across generations. For final team selection, score the historical panel if its missing pairs fit the separate team budget. Otherwise score coverage on the fully observed active panel. Both stages use caller-owned evaluators.
- class qdpy.algorithms.ACDCTaskRequest(parent: Hashable, references: tuple[Hashable, ...], pass_rate: float, direction: str)[source]¶
Use the current pass rate, parent and reference tasks to create an assessment.
- class qdpy.algorithms.ACDCResult(models: tuple[Hashable, ...], tasks: tuple[Hashable, ...], skill_vectors: tuple[tuple[float, ...], ...], historical_models: tuple[Hashable, ...], historical_tasks: tuple[Hashable, ...], team: tuple[Hashable, ...], team_tasks: tuple[Hashable, ...], team_coverage: float, team_assessments: int, team_uses_history: bool, assessments: int, model_proposals: int, task_proposals: int, accepted_tasks: int, rounds: int)[source]¶
Keep active scores in model-major order and report task-force selection costs.
Task relevance, checkpoint fusion, and local adaptation¶
- qdpy.algorithms.ruda_search(evaluate, solve_task, *, dimension, budget, capacity=128, descriptor_size=2, ind_domain=(0., 1.), novelty_threshold=.12, task_period=32, useful_capacity=64, neighbors=5, distance_floor=.02, guidance=True, fit_period=64, training_capacity=1024, encoder_factory=None, initial_samples=16, seed=0)[source]¶
Use directed distances from each candidate to the current archive.
Scale distance by the inverse mean distance to the closest useful behaviors. The task solver returns indices from the provided immutable snapshot. Retrain a fresh PCA encoder by default, then re-encode the entire repertoire and useful buffer from raw observations. Supply an encoder factory to use a different representation learner.
Before fitting, use the first descriptor_size observation coordinates. An exact-size bound uses directed spacing to evict a crowded incumbent. Fitness is maximized when a close proposal competes with a neighbor.
- class qdpy.algorithms.RUDAEntry(genome: tuple[float, ...], fitness: float, observation: tuple[float, ...], descriptor: tuple[float, ...])[source]¶
Preserve the raw observation so descriptor refits can use it directly.
- class qdpy.algorithms.RUDAResult(archive: tuple[RUDAEntry, ...], useful_observations: tuple[tuple[float, ...], ...], encoder: object | None, evaluations: int, failures: int, admissions: int, solver_calls: int, encoder_fits: int)[source]¶
The useful observations can outlive their archived individuals.
- qdpy.algorithms.m2n2(checkpoints, evaluate, *, budget, population_size=8, competition='continuous', attraction=True, schedule_power=1., seed=0)[source]¶
Evolve an aligned checkpoint population under per-example competition.
Sample the first parent by shared fitness, then the second by its directional improvements on the first parent’s evaluation panel. Apply complementary SLERP ratios on the two sides of a flattened split. The eligible range of each parameter grows around its midpoint as the budget progresses. Rank prospective survivor pools with a common resource weight for each example.
- class qdpy.algorithms.M2N2Model(checkpoint: tuple[ndarray, ...], scores: tuple[float, ...])[source]¶
Each checkpoint preserves the common ordered tensor shapes.
- property quality¶
Return mean unshared performance for reporting.
- class qdpy.algorithms.M2N2Result(population: tuple[M2N2Model, ...], best: M2N2Model, shared_fitness: tuple[float, ...], evaluations: int, seed_evaluations: int, replacements: int)[source]¶
Keep the best raw-scoring model even if resource selection discards it.
- qdpy.algorithms.portfolio_mcts(start, *, scripts, weights, simulate, budget, horizon, simulations=None, initial_fraction=.5, unprune_at=4, unprune_rate=2., exploration=1.414, progressive_bias=1., discount=1., seed=0)[source]¶
Rank duplicate suggestions by their strongest weighted score.
At each node, start with the most preferred fraction of actions and gradually expose the rest as visits accumulate. Score visited actions by UCB with a decaying script bias. Cache deterministic tree edges, and charge every actual simulator call, including rollouts.
- class qdpy.algorithms.PortfolioMCTSResult(plan: MCTSPlan, simulator_calls: int, simulations: int, root_actions: tuple, root_open: int, root_expanded: int)[source]¶
The root action list is in weighted script priority order.
- qdpy.algorithms.portfolio_map_elites(archive, scenarios, *, scripts, simulate, summarize, budget, plan_budget, horizon, random_initial=8, planner_options=None, seed=0)[source]¶
Seed with one active script at a time and then mutate one weight per proposal.
- class qdpy.algorithms.PortfolioQDResult(archive: object, evaluations: int, plans: int, simulator_calls: int, admissions: int)[source]¶
A measurement attempt evaluates the whole scenario panel.
- class qdpy.algorithms.HebbianPolicy(layer_sizes: tuple[int, ...], genome: tuple[float, ...], initial_scale: float = 0.1, weight_limit: float = 4.0, learning_scale: float = 0.1)[source]¶
Each layer has ordered rows of (A, B, C, D, eta).
A policy describes a dense bias-free tanh network and update rule. Its weights are initialized separately for every rollout.
- Parameters:
layer_sizes – Input, hidden and output widths.
genome – Flat layer-major coefficient vector in [-1, 1].
initial_scale – Uniform half-width for synapse initialization.
weight_limit – Symmetric per-synapse clip after the update.
learning_scale – Global multiplier for the local update.
- class qdpy.algorithms.HebbianSession(policy, *, seed=0, plastic=True)[source]¶
Return tanh actions and update the local synapses after each forward pass.
- act(observation)[source]¶
Use the current weights for inference and the activations for the next update.
- property weights¶
Return a copy of each layer’s current synapse matrix.
- class qdpy.algorithms.HebbianEvaluator(layer_sizes, evaluate, *, initial_scale=.1, weight_limit=4., learning_scale=.1)[source]¶
Use this callable with a native optimizer such as CMA-ME or CMA-MAE.
The supplied rollout function receives a HebbianPolicy. It returns objective values and descriptors in the optimizer’s normal format. Start a fresh session for each episode in your evaluator.
- property dimension¶
Return five times the total number of neurons.
Classifiers, schedules, and cooperative responses¶
- qdpy.algorithms.neuro_map_elites(targets, predict, *, sample, mutate, structural, mining_archive, budget, mining_budget, initial_samples=16, shape=(8, 8), min_mining_accuracy=.5, fit_steps=128, hidden=32, fit_batch=32, beta=.3, seed=0)[source]¶
Run structural and learned-descriptor searches over the same training panel.
Use balanced accuracy in both phases. Retain the error masks of qualifying mining elites and fit a beta-VAE to the binary masks. Seed the learned archive from cached mining measurements. Normal quantiles partition each learned axis into bins of equal mass under the latent prior.
- qdpy.algorithms.nme_ensemble(archive, predict, targets, *, classes=None, max_members=None, size=None)[source]¶
Try quality-ranked vote prefixes and keep the smallest best-scoring one.
- class qdpy.algorithms.NMEResult(archive: Grid, mining_archive: Grid, encoder: object, evaluations: int, mining_evaluations: int, encoder_updates: int, training_masks: int)[source]¶
The encoder maps binary error masks to descriptors in the unit cube.
- class qdpy.algorithms.NMEEnsemble(genomes: tuple[tuple, ...], classes: tuple, validation_accuracy: float, validation_evaluations: int)[source]¶
Preserve vote order and break vote ties by the order of classes.
- qdpy.algorithms.sade_qd(archive, evaluate, critical_edit, *, block_sizes, budget, initial_samples=16, stall=12, edge_pool=20, scale=.5, guided_probability=.75, seed=0)[source]¶
Search one native grid with the paper’s three guided DE formulas.
A genome contains three contiguous blocks of keys in [0, 1]. Begin with random keys, then ask the caller to edit a critical component of a measured archive member. When admissions stall, use a random elite and donors with low transport or idle time. The measured DE proposal supplies the next critical edit even when it has not entered the archive. Both calls count toward budget.
- class qdpy.algorithms.SADEQDResult(archive: object, evaluations: int, samples: int, critical_edits: int, guided_steps: int, admissions: int)[source]¶
Report evaluations by proposal type, including guided DE followed by a critical edit.
- class qdpy.algorithms.FlexibleJobShop(jobs, machine_factories, *, travel=None)[source]¶
Assign jobs to a factory and pick machine choices with random keys.
The order block supplies a key for each operation. Only the next unscheduled operation of each job competes in priority selection. Decoding appends to the selected machine and honors both job precedence and travel from the previous machine. Transportation delays allow concurrent travel and require no extra vehicle resource.
- Parameters:
jobs – Jobs containing operations with (machine, duration) alternatives.
machine_factories – Factory label for each zero-based machine index.
travel – Optional nonnegative matrix of delays from machine to machine.
- property block_sizes¶
Return the lengths of the factory, order, and machine key blocks.
- class qdpy.algorithms.JobShopSchedule(operations: tuple[ScheduledOperation, ...], makespan: float, transport: float, idle: float, critical: tuple[int, ...])[source]¶
Critical indices refer to the job-major operation order used by the genome.
- class qdpy.algorithms.ScheduledOperation(index: int, job: int, operation: int, machine: int, start: float, finish: float)[source]¶
Order in the schedule is the priority decoder’s dispatch order.
- qdpy.algorithms.cooperative_map_elites(archive, play, *, sample, mutate, budget, repeats=1, initial_samples=16, seed=0)[source]¶
Measure each candidate against itself and admit by its measured behavior.
- qdpy.algorithms.build_partner_responses(archive, play, *, budget, repeats=1, seed=0)[source]¶
Score all ordered pairings and choose responses with maximum cooperative return.
- class qdpy.algorithms.CooperativeQDResult(archive: object, evaluations: int, self_play_matches: int, admissions: int)[source]¶
Every policy evaluation uses the same number of self-play matches.
- class qdpy.algorithms.PartnerResponseTable(niches: tuple[tuple[int, ...], ...], genomes: tuple[tuple, ...], payoffs: tuple[tuple[float, ...], ...], specialist_indices: tuple[int, ...], generalist_index: int, matches: int)[source]¶
Rows are responding policies and columns are possible partner policies.
- qdpy.algorithms.divhf_search(evaluate, archive, *, feedback, budget, feedback_budget, dimension, raw_feature_size, ind_domain=(0., 1.), warmup=64, refit_every=None, feedback_batch=24, fit_steps=128, temperature=.1, regularization=1e-3, seed=0)[source]¶
Compare the two labeled extremes and fit a probabilistic projection.
For example, (1, 0) says records 0 and 2 are closest and records 0 and 1 are farthest apart. A skipped query still consumes one annotation. Reuse QDHF’s cached archive rebuild when refitting.
- class qdpy.algorithms.DivHFProjector(raw_feature_size, descriptor_size, *, temperature=.1, regularization=1e-3, seed=0)[source]¶
Train on anchor, near, far index triples using log likelihood.
Two distinct pairs in a triplet share one anchor. Similarity is negative squared Euclidean distance in the projected coordinates. A small weight penalty regularizes otherwise separable comparisons.
- Parameters:
raw_feature_size – Input width.
descriptor_size – Learned coordinate width.
temperature – Positive divisor for the difference in similarities.
regularization – Nonnegative squared-weight penalty.
seed – Initial projection seed.
- fit(raw_features, triplets, *, steps=128, batch_size=32, learning_rate=.01, seed=0)[source]¶
Fit probabilities for anchor, closer, farther labels by minimizing cross-entropy.
- transform(raw_features)¶
Return descriptor coordinates in the units of the trained projection.
- class qdpy.algorithms.DivHFResult(archive: Grid, projector: DivHFProjector, attempts: int, failures: int, feedback: tuple[DivHFJudgment, ...], fits: int)[source]¶
Each query stores the original pair ranking or an abstention.
Age layers, alternative decoders, and sensor prediction¶
- qdpy.algorithms.age_layered_map_elites(archives, evaluate, *, sample, mutate, max_ages, budget, immigrant_interval=8, seed=0)[source]¶
Inherit the parent’s birth evaluation and compete in the current age layer.
At the first evaluation whose age reaches a layer limit, move or expire the individual using its cached measurement. Promotions count successful arrivals and expirations include rejected moves. The last layer has no age limit.
- class qdpy.algorithms.AgeLayeredResult(archives: tuple, evaluations: int, immigrants: int, admissions: tuple[int, ...], promotions: tuple[int, ...], expired: int)[source]¶
Admission and promotion counts are reported separately for each layer.
- qdpy.algorithms.multi_decoder_map_elites(archive, evaluate, *, sample, emitters, decoders, budget, initial_samples=8, rule='round_robin', exploration=1., epsilon=.3, seed=0)[source]¶
Try each decoder on the emitted genome and reward successful admissions.
Each decode consumes a budget slot, including a refusal to decode. Rotate decoder order each proposal. Each arm earns the fraction of attempted decodings that filled or improved a cell. The decoder index prefixes archived genomes to preserve alternative phenotypes.
- class qdpy.algorithms.MultiDecoderResult(archive: object, proposals: int, decoder_calls: tuple[int, ...], objective_calls: int, failed_decodes: int, emitter_calls: tuple[int, ...], emitter_rewards: tuple[float, ...])[source]¶
An archive genome is the decoder index followed by the original genotype.
- qdpy.algorithms.minimize_surprise_map_elites(archive, rollout, *, describe, sample, mutate, budget, repeats=3, initial_samples=16, seed=0)[source]¶
Use the minimum prediction accuracy over repeats and average observed descriptors.
Dynamic mutation and learned novelty¶
- class qdpy.algorithms.DynamicMutationMAPElites(container, budget, dimension, *, mode='coverage', ind_domain=(0., 1.), sigma_start=.2, sigma_stop=.025, coverage_target=1., adaptation_rate=None, seed=0, batch_size=1, **kwargs)[source]¶
Use fixed, coverage-based, annealed, or log-normal inherited mutation.
Scales are in unit-genome coordinates, multiplied by the domain span and divided by the square root of the active dimension minus one (one for a single coordinate). Both global schedules use committed feedback when generating a proposal. Inherited scales travel with survivors and remain independent of the genome itself.
- Parameters:
container – Native one-elite Grid or CVTGrid.
budget – Nominal number of evaluations, also the annealing horizon.
dimension – Number of real-valued genome variables.
mode – “fixed”, “coverage”, “anneal”, or “self_adaptive”.
ind_domain – Common finite coordinate bounds.
sigma_start – Initial Gaussian strength, or the fixed strength.
sigma_stop – Final Gaussian strength, or the inherited scale floor.
coverage_target – Occupied fraction of the grid at which coverage annealing ends.
adaptation_rate – Log-normal learning rate, defaulting to one over the square root of the dimension.
seed – Private initialization and mutation seed.
batch_size – Maximum proposals before feedback. The default updates after each evaluation.
kwargs – Native QDAlgorithm configuration, including the optimization direction.
- property scheduled_sigma¶
Return the current global mutation scale before domain scaling.
- class qdpy.algorithms.TAXONS(dimension, *, ind_domain=(0., 1.), population_size=16, offspring=16, mutation_sigma=.12, latent_size=3, neighbors=8, novelty_capacity=128, archive_additions=2, training_capacity=128, epochs=2, batch_size=32, learning_rate=1e-3, seed=0, device='cpu')[source]¶
Use latent k-nearest-neighbor novelty and reconstruction error.
Choose one criterion with equal probability for each generation. Add the strongest novel offspring to a bounded archive. Fit on a bounded cache of measured observations between generations.
- Parameters:
dimension – Number of real parameters per genome.
ind_domain – Common inclusive genome bounds.
population_size – Maximum number of breeding policies.
offspring – Number of evaluations per generation after initialization.
mutation_sigma – Gaussian strength as a fraction of the bounds’ span.
latent_size – Learned descriptor width.
neighbors – Neighbors contributing to each novelty score.
novelty_capacity – Maximum number of retained novelty records.
archive_additions – Maximum new records retained per generation.
training_capacity – Maximum number of recent training observations.
epochs – Reconstruction training epochs per completed generation.
batch_size – Maximum observations per training minibatch.
learning_rate – Adam learning rate.
seed – Private rollout, variation and training seed.
device – PyTorch device.
- encode(observation)[source]¶
Return the current latent descriptor of one previously measurable observation.
- property novelty_archive¶
Return measured observations retained for latent novelty.
- property population¶
Return the most recent committed exploration population.
- run(evaluate, budget)¶
Continue from the last generation, including any pending measurements.
- property stats¶
Return cumulative search costs and completed generations.
- class qdpy.algorithms.STAX(dimension, *, reward_threshold=0., emitter_budget=16, emitter_sigma=.03, emitter_size=4, bootstrap_calls=4, stagnation_calls=20, max_emitters=8, reward_capacity=128, **kwargs)[source]¶
Learn behavior from observations while exploiting sparse reward discoveries.
A successful evaluation can seed an emitter with reward-only survival. Promising bootstrap emitters continue on a novelty/improvement Pareto front. Model refits reuse measured observations. The reward archive stores observations and genomes independently of the current latent coordinates.
- Parameters:
dimension – Number of real parameters per genome.
reward_threshold – Seed and retain policies with reward strictly above this value.
emitter_budget – Maximum reward-search calls after each exploration generation.
emitter_sigma – Local mutation strength as a fraction of the genome span.
emitter_size – Maximum number of parents per emitter.
bootstrap_calls – Calls before accepting an improving emitter.
stagnation_calls – Nonimproving calls before retiring an active emitter.
max_emitters – Bound on each queue and the active emitter pool.
reward_capacity – Maximum retained reward records.
kwargs – TAXONS representation and exploration settings.
- property reward_archive¶
Return the bounded reward archive in measurement order.
- run(evaluate, budget)¶
Continue from the last generation, including any pending measurements.
- class qdpy.algorithms.BRNS(dimension, *, ind_domain=(0., 1.), population_size=16, offspring=16, mutation_sigma=.12, embedding_size=32, hidden_size=64, epochs=2, batch_size=32, learning_rate=1e-3, seed=0, device='cpu')[source]¶
Run archive-free Behavior Recognition Novelty Search.
Score candidates with squared embedding prediction error before training on the generation’s newly measured observations. Use a slightly deeper predictor with leaky ReLU and a linear output layer. The retained population and the unfinished generation bound memory.
- Parameters:
dimension – Number of real parameters per genome.
ind_domain – Common inclusive genome bounds.
population_size – Maximum breeding population.
offspring – Candidate evaluations in subsequent generations.
mutation_sigma – Gaussian strength as a fraction of the bounds’ span.
embedding_size – Width of the fixed random embedding.
hidden_size – Width of the target and predictor hidden layers.
epochs – Prediction training epochs per generation.
batch_size – Maximum observations per optimization step.
learning_rate – Adam learning rate.
seed – Private rollout, variation and training seed.
device – PyTorch device.
- property population¶
Return the most recent committed exploration population.
- run(evaluate, budget)¶
Continue from the last generation, including any pending measurements.
- property stats¶
Return cumulative search costs and completed generations.
- class qdpy.algorithms.LearnedBehavior(genome: tuple[float, ...], reward: float, observation: ndarray)[source]¶
Keep the numeric genome, reward, and a read-only observation array.
- class qdpy.algorithms.LearnedExplorationStats(exploration_evaluations: int = 0, bootstrap_evaluations: int = 0, emitter_evaluations: int = 0, failed_evaluations: int = 0, model_updates: int = 0, generations: int = 0, emitters_started: int = 0, first_reward_evaluation: int | None = None)[source]¶
Candidate attempts include failures and prefixes of pending generations.
Encodings, behavior spaces, and design prototypes¶
- class qdpy.algorithms.GenomeEncoding(name: str, sample: Callable[[Generator], Iterable], mutate: Callable[[tuple, Generator], Iterable], decode: Callable[[tuple], object])[source]¶
The genotype is a sequence. The decoded phenotype can be any object.
- class qdpy.algorithms.MultiEncodingMAPElites(archive, encodings, *, initial_samples=8, seed=0)[source]¶
Sample each encoding evenly, then mutate uniformly drawn archive elites.
Archived genotypes start with the zero-based encoding index, followed by the encoding’s genome. All encodings compete in the same descriptor cells.
- class qdpy.algorithms.MultiEncodingStats(proposals: tuple[int, ...], failed_decodes: tuple[int, ...], objective_calls: tuple[int, ...], admissions: tuple[int, ...])[source]¶
Counter tuples follow the configured encoding order.
- class qdpy.algorithms.NSMBS(descriptor_sizes, *, sample, mutate, population_size=32, offspring=32, neighbors=15, archive_capacity=256, archive_additions=4, seed=0)[source]¶
Each view supplies a novelty ranking over its defined descriptors.
Survivors are selected one at a time, without replacement. Draw uniformly among views with remaining eligible candidates. If those views are exhausted, draw any remaining candidates uniformly. Past records use a bounded FIFO.
- class qdpy.algorithms.MultiBehaviorRecord(genome: tuple, fitness: float, descriptors: tuple[tuple[float, ...] | None, ...])[source]¶
Fitness is available for reporting and plays no part in selection.
- class qdpy.algorithms.NSMBSStats(evaluations: int, failures: int, generations: int, measured_views: tuple[int, ...], selected_views: tuple[int, ...], fallback_selections: int)[source]¶
Measured views and selections are counted in descriptor order.
- qdpy.algorithms.spirit_descriptor(states, actions, *, state_count, action_count)[source]¶
Build the paper’s SPIRIT-o behavior descriptor from a discrete trajectory.
- class qdpy.algorithms.BehaviorCharacterization(weights: tuple[float, ...], bounds: tuple[tuple[float, float], ...] | None = None)[source]¶
Fit on training tasks, then apply the same transform to every search candidate.
- class qdpy.algorithms.PRODUQD(archive, dimension, describe, *, ind_domain=(0., 1.), initial_samples=16, acquisition_steps=128, prediction_steps=256, evaluations_per_fit=4, kappa=2., mutation_sigma=.08, embedding='pca', cluster_eps=.2, min_samples=2, seed=0)[source]¶
The supplied grid only stores measured elites. All valid measurements train the GP.
Inspect predictions and prototypes after each run, then select any number of prototype families before resuming. Selecting families sets breeding seeds in both surrogate maps. Mutation may still visit other parts of the domain.
- class qdpy.algorithms.Prototype(representative: PrototypePrediction, members: tuple[PrototypePrediction, ...])[source]¶
The representative is a member of the cluster. All members can seed search.
Editable archives, preference drift, and component credit¶
- class qdpy.algorithms.InteractiveConstrainedMAPElites(axes, *, fitness_domain, sample, mutate, crossover=None, maximize=True, cell_capacity=4, initial_samples=8, anchor_probability=.2, seed=0)[source]¶
Keep separate subpopulations for good designs and near-feasible ones.
Positive constraint residuals indicate violations. Feasible individuals compete on user-provided fitness, infeasible individuals on total positive residual. Both grids retain the configured number of breeders per cell. Use hashable genome sequences and emit measurements for prospective axes.
- class qdpy.algorithms.InteractiveConstrainedStats(evaluations: int, edits: int, failures: int, feasible_evaluations: int, feasible_admissions: int, infeasible_admissions: int, reprojections: int)[source]¶
Admissions count new measurements. Reprojecting existing rows has its own counter.
- class qdpy.algorithms.ConstrainedSurpriseSearch(archive, *, initializer, mutate, forecast_interval=None, feasibility_score=None, clip_forecast=True, **kwargs)[source]¶
A steady-state adaptation of Constrained Surprise Search.
Freeze a forecast between fixed-size blocks. Use Euclidean deviation from the forecast to select feasible breeders. Before the first forecast, use the inherited feasible novelty score. Positive residuals indicate violations. The reporting archive stores measured feasible quality.
- property feasible_population¶
Return immutable active feasible genomes.
- property infeasible_population¶
Return immutable active infeasible genomes.
- run(evaluate, budget) FeasibleNoveltyStats¶
Use residuals at or below zero for feasible admission and propagate invalid evaluations.
- property stats¶
Return cumulative measured search costs and outcomes.
- class qdpy.algorithms.ConstrainedSurpriseStats(evaluations: int = 0, feasible_evaluations: int = 0, feasible_from_infeasible: int = 0, infeasible_from_feasible: int = 0, archive_updates: int = 0, first_feasible: int | None = None, forecasts: int = 0)[source]¶
Each forecast uses a snapshot of the feasible breeding population.
- class qdpy.algorithms.UserDecisionModel(points, embedded, selected, model)[source]¶
Build a positional preference model from selected and deselected reference designs.
- class qdpy.algorithms.UserDrivenQD(archive, *, sample, mutate, initial_samples=8, seed=0)[source]¶
Fit a new decision model from the active panel at each user feedback round.
The active archive ranks by preference-adjusted fitness and records the underlying measurement and drift in the scores udqd_raw_fitness and udqd_drift. The measured archive always ranks by raw fitness.
- class qdpy.algorithms.UserDrivenQDStats(evaluations: int, failures: int, measured_admissions: int, preference_admissions: int, feedback_rounds: int)[source]¶
Admissions include replacements. Reseeding contributes to the feedback counter.
- class qdpy.algorithms.MORTAR(archive, *, sample, mutate, describe, partners=(), generate_partner=None, initial_samples=8, composition_budget=20, max_components=4, branching=3, selection='ucb', exploration=1.4, seed=0)[source]¶
Fit a MAP-Elites repertoire of components using their CITS scores.
Provide callbacks for representation-specific variation and composition evaluation. All nodes are complete designs. Each transition adds one component and measures the resulting design. The root is a singleton candidate whose measured value can inform marginal contributions.
- class qdpy.algorithms.MORTARStats(proposals: int, composition_evaluations: int, failed_compositions: int, partner_proposals: int, admissions: int)[source]¶
A proposal can take up to composition_budget complete-design evaluations.
- class qdpy.algorithms.MORTARRound(candidate: tuple, compositions: tuple[tuple[tuple, float], ...], credit: tuple[tuple[tuple, float], ...], evaluations: int, failures: int)[source]¶
Failed measurements are omitted from compositions and counted separately.
- qdpy.algorithms.mortar_credit(compositions, *, root=())[source]¶
Treat unmeasured subsets as zero-valued. The root can provide a baseline value.
A composition is an unordered set of hashable component IDs. Each nonroot measured composition contributes one estimate for each member. Iterating measured subsets yields the same sum as enumeration over all subsets with nonzero values.