Replay a saved search ===================== Use :func:`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``. .. code-block:: python 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. .. code-block:: sh 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. .. code-block:: 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_.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 :func:`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 :doc:`tutorial_visualization` 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 :doc:`tutorial_run_bundles`. :func:`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. .. code-block:: sh 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. .. code-block:: sh 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 :func:`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. .. code-block:: sh 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. .. code-block:: sh 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. .. code-block:: python 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 :doc:`tutorial_offline_vq` for independent verification of predicted elites. .. autofunction:: qdpy.journal.export_evaluation_dataset Load and analyse a portable archive ----------------------------------- Use the numeric export when you only need the saved elites and their geometry. :func:`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 :doc:`choose_algorithm` for examples that save, restore, and plot Grid and ParetoGrid. .. code-block:: python 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. .. autofunction:: qdpy.results.read_run_manifest .. autofunction:: qdpy.results.export_grid .. autofunction:: qdpy.results.load_grid .. autofunction:: qdpy.results.grid_to_dataframe .. autofunction:: qdpy.results.write_run_manifest .. autofunction:: qdpy.checkpoints.run_checkpointed .. autofunction:: qdpy.journal.read_evaluation_journal