Replay a saved search¶

Use qdpy.simple.run() with output_dir to save run.json and, for a supported numeric grid, an archive snapshot. The manifest records the evaluator, seed, execution options, and candidate counts. Keep the Python code that constructs the optimiser and evaluator to repeat a run that used the shortcuts. Pass a configuration mapping to include constructor settings or other experiment parameters in the manifest. QDpy records the actual runner seed under seed.

from qdpy.algorithms import IsoLineMAPElites
from qdpy.benchmarks import illumination_rastrigin_normalised
from qdpy.containers import Grid
from qdpy.simple import run

settings = {"budget": 24, "dimension": 3, "iso_sigma": 0.02}
grid = Grid(shape=(4, 4), features_domain=((0, 1), (0, 1)),
            fitness_domain=((0, 1),))
search = IsoLineMAPElites(grid, **settings)
run(search, illumination_rastrigin_normalised, seed=42,
    configuration=settings, output_dir="results.isoline")

The runner’s seed controls coordinator randomness during execution. If you fit a CVT before calling run(), seed NumPy before construction or supply fixed centroids. Give a stochastic worker its own evaluation seed.

The Rastrigin example writes a run manifest with its resolved YAML configuration. Start two searches in separate output directories from the repository root.

python examples/rastrigin.py --seed 42 --outputDir results.first
python examples/rastrigin.py --replay results.first/run.json --outputDir results.replay

Compare the two manifests with Python.

from qdpy.results import read_run_manifest

first = read_run_manifest("results.first/run.json")
replay = read_run_manifest("results.replay/run.json")
assert replay["evaluation"]["attempted"] == first["evaluation"]["attempted"]
assert replay["archive"]["sha256"] == first["archive"]["sha256"]

The archive fingerprint covers storage order, genomes, cell coordinates, measurements, and geometry. Use the same QDpy and dependency versions when comparing fingerprints. The default sequential evaluator replays the recorded seed. Worker completion order can affect a parallel search, even if each individual evaluation uses reproducible randomness.

The Rastrigin and NSLC examples write run.json. YAML-based QDExperiment.run() writes run_<timestamp>.json alongside its timestamped pickle. Each manifest records the QDpy version and source revision when available, relevant dependencies, the seed and settings, the evaluator, and the configured and attempted evaluation counts. The attempt count includes evaluation failures. Use QDPY_SOURCE_REVISION to supply an explicit revision for a locally built package whose metadata lacks one.

Grid, CVTGrid, ParetoGrid, SlidingBoundariesGrid, and TDominOGrid archives with numeric genomes get a companion JSON file. The manifest records its name and SHA-256 hash. Each row stores effective fitness, descriptors, and a cell index. CVT exports include centroid coordinates. Sliding Boundaries exports include physical edge positions. Pareto, Sliding Boundaries, and T-DominO exports include admission settings. Bounds such as infinity use objects like {"$qdpy_float": "inf"} so the files remain valid JSON. The manifest records an export error when the archive or genome uses an unsupported type. Use the existing trusted pickle workflow for custom objects and archive-based warm starts.

Trusted QDpy 0.1.3 pickles that refer to qdpy.algorithms.sampling.SampledScores can be read with qdpy.tools.open_pickle_file(). The deprecated class keeps both the named values and the original sample history. Use ScoresDict and a sampling decorator for new experiments.

Use Plot archive geometry and evolution to plot numeric exports, play back periodic checkpoints, or record plot data during future runs.

Resume a search in a new process¶

For an integrated run directory with a verified manifest, history, and genealogy across restart, see Save and resume a portable run.

qdpy.checkpoints.run_checkpointed() supports polynomial-mutation MAP-Elites and CMA-MAE with a parentless, one-elite Grid or CVTGrid. It also supports MOME with a native parentless ParetoGrid. It saves the live archive, its admission history, search counters, and both global random generators. A periodic checkpoint is written after a completed batch. A controlled stop also writes the final completed chunk. Keep the same evaluator, Python, QDpy, NumPy, and search settings when resuming. Evaluator-owned random streams and mutable simulator state remain the caller’s responsibility. Optimisation start and finish callbacks should avoid changing the search or evaluator’s random streams. CMA-MAE checkpoints also hold the covariance strategy, emitter RNG, archive thresholds, and search representatives. Resume with the same pycma version and optimiser settings. MOME checkpoints preserve each cell’s front order, truncation policy, and completed-generation count. Recreate the same ParetoGrid and variation settings before restoring the checkpoint. For NSLC, supply a fixed Euclidean NoveltyArchive with plain, parentless Container histories. The checkpoint restores the active archive and each parent in place and rebuilds the exact neighbour index as needed. This also preserves histories when ordinary archive pickles are configured to omit parents.

Run these commands from a checkout with QDpy installed. The first process stops at 32 of 67 evaluations. The second restores the search and spends the remaining 35. Each command exports a portable result and prints a summary of its elites.

python examples/resume_map_elites.py build/resume-example --kind cvt --stop-after 32
python examples/resume_map_elites.py build/resume-example --kind cvt --resume-trusted
python examples/resume_map_elites.py build/resume-reference --kind cvt

For MOME, these three commands compare a resumed search with one that runs in a single process. The saved archive checksums should match.

python examples/resume_map_elites.py build/mome-resume --method mome --journal --stop-after 32
python examples/resume_map_elites.py build/mome-resume --method mome --journal --resume-trusted
python examples/resume_map_elites.py build/mome-reference --method mome --journal
cmp build/resume-example/archive.json build/resume-reference/archive.json

The checkpoint is a Python pickle. Use --resume-trusted, or resume=True, trusted=True from Python, only with your own checkpoint or one from a source you trust. Atomic replacement keeps the previous checkpoint readable if the process stops during a write. On an unexpected interruption, the next run repeats work after the last saved boundary. Use one writer per checkpoint path and keep it on a filesystem that persists across jobs.

By default the driver evaluates each candidate itself. Pass packed=True to submit an entire batch to an evaluator that returns results in proposal order. The example’s --ray-address local option uses an ordered Ray map. Use the same flag on both commands and install the ray extra. For independent Rundra runs, give each search its own persistent output directory. For exact replay, parallel worker measurements need to be deterministic or use stable seeds assigned by the evaluator.

Recover evaluations from an interrupted batch¶

Pass journal_path and an evaluation_key to save an initial checkpoint and append each evaluation dispatch and response to a durable JSON Lines journal. The key identifies your simulator and measurement settings. Update it when starting a run with changed settings. The evaluator takes (candidate, seed) and returns numeric fitness and descriptors plus an optional JSON-compatible named score mapping. Use the supplied seed to initialize a local random generator. Each candidate slot has a distinct ID and seed across repeated evaluations.

The resumed driver regenerates the proposals from the last checkpoint. It verifies their genomes and seeds, reuses committed responses, and dispatches the remaining slots. An evaluator exception becomes a recorded failed response. A broken worker or transport interrupts the driver and leaves unconfirmed dispatches available for retry. In qdpy.journal.read_evaluation_journal(), returned_calls includes successes and recorded evaluator failures. uncertain_calls counts dispatches with no durable response, including earlier attempts at retried slots. A simulator may have already executed those calls. Use one writer per checkpoint and journal pair.

python -m pip install ".[cma]"
python examples/resume_map_elites.py build/cma-resume --method cma-mae --journal --stop-after 32
python examples/resume_map_elites.py build/cma-resume --method cma-mae --journal --resume-trusted

python examples/resume_map_elites.py build/nslc-resume --method nslc --journal --stop-after 32
python examples/resume_map_elites.py build/nslc-resume --method nslc --journal --resume-trusted

The journal works with caller-owned executors through journal_executor. The example uses an ordered Ray executor when passed --ray-address. Per-response synchronization is intended for expensive evaluations. The driver keeps an in-memory index of journal records while the run is open.

On Slurm, arrange for the warning signal to reach the Python driver and set a flag in the signal handler. Pass a callable that reads it as stop_requested. The search checkpoints and returns at the next committed batch. The example option --slurm-signal listens for SIGUSR1. A batch wrapper can use exec python ... --slurm-signal with sbatch --signal=B:USR1@35. Allow enough time for an in-flight batch to complete. Use the same output path from the next allocation. See the Slurm job signal documentation.

Export journal measurements for offline QD¶

After the journal writer exits, export the committed successful measurements to a pickle-free NumPy dataset.

python -m qdpy.journal build/nslc-resume/evaluations.jsonl build/nslc-dataset.npz

Each row contains a genome, fitness vector, descriptor vector, evaluation ID, seed, and a JSON string for named scores. Rows follow proposal order and keep repeats of the same genome. The JSON metadata contains the journal’s run ID, SHA-256 of the complete source prefix, and counts of returned, failed, and unconfirmed calls. Save the journal and metadata with the dataset for provenance. Failed and unconfirmed calls contribute to the counts and have no measurement row.

For the scalar Rastrigin data above, the following fits a surrogate and uses a separate budget of 32 surrogate predictions.

import json
import numpy as np
from qdpy.algorithms import OfflineMAPElites
from qdpy.containers import Grid

grid = Grid(shape=(8, 8), fitness_domain=((0., 1.),), fitness_weights=(-1.,),
            features_domain=((0., 1.),) * 2)
with np.load("build/nslc-dataset.npz", allow_pickle=False) as data:
    print(json.loads(data["metadata"].item())["journal_sha256"])
    search = OfflineMAPElites(grid, data["genomes"], data["fitness"][:, 0],
                              data["descriptors"], seed=7)
result = search.run(32)
print(len(result.archive))

See Offline search, learned niches, and cooperating policy parts for independent verification of predicted elites.

qdpy.journal.export_evaluation_dataset(journal_path, output_path)[source]¶

Write a pickle-free NPZ dataset of successful responses in slot order.

Archives contain two-dimensional float arrays named genomes, fitness, and descriptors, with aligned unsigned 64-bit evaluation_ids and seeds. Repeated genomes get separate rows. Optional named scores use one JSON string per row. The JSON metadata includes the evaluator key, run ID, coordinator seed, digest of the complete journal prefix, and omitted-call counts. Export after the writer exits to capture the final run dataset.

Load and analyse a portable archive¶

Use the numeric export when you only need the saved elites and their geometry. qdpy.results.load_grid() verifies cell assignment, capacity per cell, and the effective measurements of each stored elite. Pass the digest from the original manifest to verify the file before parsing. The returned archive retains the original grid type, geometry, and storage order. Earlier Sliding Boundaries and T-DominO exports load with default constructor settings. Adaptive remapping buffers and tournament anchors start empty. Exact continuation requires the original search state. See Choose your first QDpy search for examples that save, restore, and plot Grid and ParetoGrid.

from qdpy.results import grid_to_dataframe, load_grid

archive = load_grid("build/resume-example/archive.json")
table = grid_to_dataframe(archive)
table["cost"] = table["fitness"].map(lambda values: values[0])
print(table.sort_values("cost")[["cell", "cost", "descriptors"]])

The table keeps a tuple for each cell, genome, fitness vector, fitness weight vector, and descriptor vector. Its attrs include the export metadata such as centroid coordinates and named score order. Portable archives restore effective named measurements; checkpoint files also retain native admission history and candidate metadata from the original run.

qdpy.results.read_run_manifest(path)[source]¶

Read JSON result metadata, checking the schema version.

qdpy.results.export_grid(grid, path)[source]¶

Export a built-in grid and return its SHA-256 fingerprint.

Rows follow archive storage order. They contain the numeric genome, effective fitness and descriptors, and the stored cell. A CVT file includes centroid coordinates and a Sliding Boundaries file records its current bin edges. Specialized grids include admission settings. The snapshot is for inspection, comparison, and plotting. Custom objects, historical offers, and optimiser state use other formats.

qdpy.results.load_grid(path, *, expected_sha256=None)[source]¶

Load a numeric archive from export_grid() or a run manifest.

Pass the manifest’s archive SHA-256 to verify the file before parsing. The archive owns newly created individuals and preserves storage order, geometry, effective named scores and fitness weights. Offer history, T-DominO anchors, and custom candidate attributes are outside the portable format. Use a checkpoint for exact continuation.

qdpy.results.grid_to_dataframe(grid)[source]¶

Return an independent DataFrame of numeric elite records in storage order.

The columns are cell, genome, fitness, fitness_weights and descriptors. Each stores a tuple per elite. The DataFrame’s attrs hold the snapshot header, including the descriptor bounds, named score order and any CVT centroids.

qdpy.results.write_run_manifest(path, algorithm, *, configuration, evaluate, execution, initial_evaluations=0, final_pickle=None, bundle=None)[source]¶

Publish a manifest for the search’s current evaluation count.

Supply the resolved configuration and execution settings. When reusing an optimiser, pass its initial evaluation count to report only attempts from this run. A built-in numeric grid gets a sibling JSON export. Unsupported archive and configuration values are recorded with a reason. Sweep reports mark a run as incomplete until its attempted count reaches the configured budget. An optional bundle includes portable artifact links and their checksums.

qdpy.checkpoints.run_checkpointed(algorithm, evaluate, *, checkpoint_path, seed=0, checkpoint_every=10, stop_after=None, resume=False, trusted=False, packed=False, journal_path=None, evaluation_key=None, journal_executor=None, stop_requested=None, _observer=None)[source]¶

Run MAP-Elites, fixed Euclidean NSLC, CMA-MAE, or MOME with atomic checkpoints.

Supply a fresh supported optimiser for either a new run or a resume. Its budget is the total search budget. MOME saves its ordered Pareto fronts and generation count. NSLC checkpoints save the active novelty archive and its plain parent histories. The exact index is rebuilt on the next query. checkpoint_every counts full batches. stop_after is a cumulative evaluation count and must be a batch boundary or the total budget. The last completed chunk is also saved.

To resume, pass resume=True, trusted=True with the same optimiser settings, evaluator and runtime. Checkpoints contain the native archive, counters and Python and NumPy global random generator states. Supply only checkpoints you trust. The seed initializes a fresh run and the checkpoint supplies the generator states when resuming. Use one writer per path. External simulator state, callback state, user-owned random generators, and side effects need caller management. With packed=True, the evaluator receives a whole batch and returns one result per candidate in proposal order. It can use remote workers for deterministic measurements or assign stable seeds itself. With journal_path, supply a scalar evaluator taking a numeric individual and a stable seed. Use evaluation_key to identify the simulator and settings, and optionally a caller-owned journal_executor. The evaluator should use the supplied seed with a local random generator. The journal reuses returned measurements in proposal order on resume. If stop_requested() returns true, pause at the next completed batch. A signal handler can set the flag that this callable observes. Resume mutates the supplied empty archive in place. The result’s evaluation count is the number of attempts in this invocation.

qdpy.journal.read_evaluation_journal(path)[source]¶

Return ordered records and actual returned calls plus dispatch counts.

A dispatch without a recorded response is uncertain. A worker may have run that call before the driver lost its response. Such calls are counted as uncertain separately from confirmed success and evaluator failure.

qdpy

Navigation

Contents:

  • Choose your first QDpy search
  • Run your first searches from PyPI
  • Validation for recommended methods
  • Run a seeded MAP-Elites search
  • Run a seeded NSLC search
  • Choose a QD method
  • Choose a QD algorithm
  • Compare three QD baselines
  • Run reference QD benchmarks
  • Reference QD benchmark results
  • MAP-Elites with Iso+LineDD
  • CMA-MAE with a best-only result grid
  • Dominated Novelty Search
  • Multi-Objective MAP-Elites
  • CMA-MAEGA with analytic gradients
  • Bayesian optimisation of elites
  • Discount Model Search
  • Constrained MAP-Elites with mixed variables
  • Conditional design search with HiGeME
  • Generational Adversarial MAP-Elites
  • Multi-Task Multi-Behavior MAP-Elites
  • Parametric-Task MAP-Elites
  • Learn descriptors from trajectories with AutoQD
  • MOUR-QD for unbounded descriptors
  • Mix-ME for cooperative teams
  • Quality diversity through human feedback
  • Graph-path quality diversity
  • Dynamic MAP-Elites
  • Multiple descriptors and CMA-based search
  • Case-wise selection and policy repertoires
  • Case-wise search and policy repertoire benchmarks
  • Conditional designs and task repertoires
  • Conditional designs and task repertoire benchmarks
  • Offline search and diverse plans
  • Offline search and diverse planning benchmarks
  • Compact repertoires and skill composition
  • Compact repertoire benchmarks
  • Deep archives and scenario discovery
  • Deep archives and scenario discovery benchmarks
  • Adaptive exploration, operator selection, and phased diversity
  • Residual regression and focused QD search
  • Learned density, design portfolios, and shared controllers
  • Refine diverse starts and coevolve complementary solutions
  • Guide search with task feedback and local adaptation
  • Build repertoires for classifiers, schedules, and skills
  • Search across age layers, decoders, and learned behaviors
  • Dynamic mutation and learned novelty
  • Encodings, behavior spaces, and design prototypes
  • Editable archives, preference drift, and component credit
  • Composite designs, surrogate niching, and heuristics
  • Composite design and heuristic search benchmarks
  • Solver-backed archives, graph policies, and self-play
  • Solver-backed archives, graph controllers, and parent selection
  • Few-shot priors, basin search, and semantic trade-offs
  • Language models for context rewrites, ideas, and benchmark tasks
  • Changing constraints, structured niches, fidelity, and replay
  • Changing constraints, structured niches, fidelity, and replay
  • Hierarchical archives, counterfactuals, and generative QD
  • Hierarchical archives, counterfactuals, and generative QD
  • Constraint programming, safe exploration, and diffusion search
  • Constraint programming, safe exploration, and diffusion search
  • Sequence search, outcome distributions, and continuing control
  • Sequence search, outcome distributions, and continuing control
  • Counterexamples, design symmetries, and learned policy variation
  • Counterexamples, design symmetries, and learned policy variation
  • Few-shot priors, basin search, and semantic trade-offs
  • Feasible Pareto fronts, analytic gradients, and diverse breeding
  • Feasible fronts, gradients, and diverse breeding
  • Quality thresholds, measured surrogates, and comparable policies
  • Quality thresholds, measured surrogates, and comparable policies
  • Metric archives, peer exchange, and structured variation
  • Metric archives, peer exchange, and structured variation
  • Pareto fronts, noisy elites, and policy gradients
  • Pareto fronts, noisy elites, and policy gradients on CPU
  • Model merging, subset selection, and planning
  • CPU comparisons for model merging, subset selection, and planning
  • Binary swarms, geometric policies, and budgeted archives
  • CPU pilots for binary, geometric, and budgeted search
  • Reference niches, repertoire selection, and model-based skills
  • CPU pilots for reference repertoires and model-based skills
  • Case novelty, linked variation, and discovered skills
  • CPU pilots for case novelty, linked variation, and discovered skills
  • Near-optimal portfolios, novelty, and policy reuse
  • CPU pilots for portfolios, novelty–surprise search, and policy reuse
  • Guided variation, reward coverage, and offline priors
  • Objective voting, structural diversity, and transfer
  • CPU pilots for guided search
  • Batch acquisition, benchmark instances, feasibility, and scenario risk
  • CPU pilots for batch acquisition, benchmark instances, feasibility, and risk
  • Discrete policy search with PPO and MAP-Elites
  • Continuous control with PPO, TD3, and PGA-MAP-Elites
  • Batched neural MAP-Elites
  • Quality-diversity policy gradient
  • Descriptor-conditioned MAP-Elites
  • Quality-Diversity Actor-Critic
  • Discrete QDAC variants
  • Control evaluation with ask and tell
  • Run a QDpy seed sweep with Rundra
  • Evaluate a MAP-Elites search with Ray
  • Replay a saved search
    • Resume a search in a new process
    • Recover evaluations from an interrupted batch
    • Export journal measurements for offline QD
    • Load and analyse a portable archive
  • Save and resume a portable run
  • Compare multi-seed runs
  • Plot archive geometry and evolution
  • Genealogy and stepping stones
  • MC-AURORA with learned descriptors
  • MAP-Elites with noisy evaluations
  • Audit a noisy archive
  • Shared noisy Rastrigin validation
  • How QDpy runs a search
  • Core Python API
  • QDpy source reference
  • QDpy release notes
  • Run the release preflight
  • Benchmark search throughput
  • QDpy parallelism benchmarks
  • Compare MAP-Elites, CVT-MAP-Elites, and CMA-MAE
  • Shared QD benchmark panels
  • Modern QD pilot results
  • Differentiable, Bayesian, and high-dimensional QD pilots
  • Constrained search and GAME pilots
  • Fixed-task and dynamic QD pilots
  • Local Pareto, team, feedback, graph, and Bayesian QD pilots
  • Joint population optimization with SQUAD
  • Segment crossover in MAP-Elites
  • Learned competition rules
  • Share policy representations with RefQD
  • Co-design bodies and controllers with Pollination
  • Population objectives, learned selection, and policy transfer
  • Adapt a repertoire with M-BOA
  • Two-objective MO-CMA-MAE
  • Gradient-informed search on categorical genomes
  • Behavior-regulated policy gradients
  • Return to promising states with Go-Explore
  • Repertoire adaptation, gradient search, and exploration benchmarks
  • Multifidelity search, adaptive grids, and curricula
  • Train controllers for objective trade-offs
  • Multifidelity search, adaptive grids, and curricula benchmarks
  • Scalable covariance search and learned genome variation
  • Gradient, imitation, and dynamics-aware policy search
  • Scalable emitters and continuous policy search benchmarks
  • Targeted search, balanced designs, and adversarial tournaments
  • SAC populations and search over frozen policy latents
  • Targeted search and policy population benchmarks
  • Interactive search, scheduling rules, and repertoire reuse
  • Distill a repertoire with the Quality-Diversity Transformer
  • Interactive and repertoire workflow benchmarks
  • Symbolic regression with MAP-Elites
  • Symbolic regression benchmark
  • Parent selection, surrogate search, and diverse skills
  • Parent selection, surrogate search, and skill pilots
  • Archive repair, ensembles, and policy reuse
  • Archive repair, ensembles, and policy reuse benchmarks
  • Differential evolution, mixed variables, and learned preferences
  • Differential evolution, mixed variables, and learned preferences
  • Solver repair, repertoire selection, and cross-component search
  • Solver repair, repertoire selection, and cross-component search
  • Offline search, learned niches, and cooperating policy parts
  • Offline search, learned niches, and cooperating policies benchmarks
  • Trace-Elites, MEMES, and asymmetric islands
  • Trace-Elites, MEMES, and AIM benchmarks
  • Deep QD, Voronoi-Elites, and occupancy CVT-MAP-Elites
  • Deep QD, Voronoi-Elites, and occupancy benchmarks
  • Sparse rewards, interpretable trees, and population diversity
  • Sparse rewards, decision trees, and determinant diversity
  • Ordered trajectories and model-guided variation
  • Ordered trajectories and model-guided variation

Related Topics

  • Documentation overview
    • Previous: Evaluate a MAP-Elites search with Ray
    • Next: Save and resume a portable run
©2018, Leo Cazenille. | Powered by Sphinx 9.2.0 & Alabaster 1.0.0 | Page source