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, anddescriptors, with aligned unsigned 64-bitevaluation_idsandseeds. Repeated genomes get separate rows. Optional named scores use one JSON string per row. The JSONmetadataincludes 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_weightsanddescriptors. Each stores a tuple per elite. The DataFrame’sattrshold 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
bundleincludes 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_everycounts full batches.stop_afteris 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=Truewith 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. Withpacked=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. Withjournal_path, supply a scalar evaluator taking a numeric individual and a stable seed. Useevaluation_keyto identify the simulator and settings, and optionally a caller-ownedjournal_executor. The evaluator should use the supplied seed with a local random generator. The journal reuses returned measurements in proposal order on resume. Ifstop_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.