Plot archive geometry and evolution =================================== Plot a single archive with :func:`qdpy.plots.plot_archive`, or give :func:`qdpy.plots.plot_archives` a named collection for a side-by-side figure. The functions return Matplotlib objects you can customise and save. Choose a view ------------- Regular grids use a strip or rectangular heatmap. Sliding Boundaries grids draw their measured bin edges, including in recorded frames. Two-dimensional CVT grids draw Voronoi cells bounded by the descriptor domain. Higher-dimensional archives display a scatter projection unless you supply a slice. To plot a slice through a three-descriptor CVT, fix the third descriptor. Each polygon uses the full distance to its centroid, including the fixed coordinate. .. code-block:: python from qdpy.plots import plot_archive ax = plot_archive(cvt_3d, dimensions=(0, 1), slice_at={2: 0.5}) ax.figure.savefig("cvt-slice.pdf") Use ``view="sphere"`` to display elite directions on a globe. Choose three Cartesian descriptors with ``dimensions`` and set the origin with ``sphere_center``. A CVT whose centroids lie on a common sphere inside its descriptor domain gets spherical Voronoi cells. .. code-block:: sh python examples/spherical_archive.py results/sphere.png The default colour scale shows raw fitness. Use ``objective=1`` for the second objective, ``metric="occupancy"`` for the count in each cell, or ``metric="activity"`` for grid insertions. A grid export supports fitness and occupancy. Record a history to retain activity. Empty cells are grey. The planar rendering follows the archive geometry illustrated in Figure 1 of the `CVT-MAP-Elites paper `__. The plotting convention is also used by `pyribs `__ and `QDax `__. Spherical cells use `SciPy's spherical Voronoi geometry `__. Compare several archives ------------------------ Use the archive mapping returned by :func:`qdpy.algorithms.mtmb_search` directly. For :doc:`tutorial_mc_aurora`, pass the learned archive decorators so each panel uses its own descriptors after a refit. Share a colourbar when the panels measure comparable quantities. .. code-block:: python from qdpy.plots import plot_archives fig, axes = plot_archives(task_result.archives, shared_scale=True) fig.savefig("tasks.png") learned = {f"Encoder {i}": archive for i, archive in enumerate(aurora.archives, 1)} fig, axes = plot_archives(learned, shared_scale=True, columns=2) fig.savefig("learned-archives.png") Use ``panel_options={label: {"view": "sphere"}}`` to change the view of one named panel. Compare paired runs cell by cell -------------------------------- Run both methods on the same seeds and at the same evaluation budget. Give :func:`qdpy.reporting.compare_archive_cells` the final archives keyed by seed and a common reporting grid. The source archives can be live containers or portable archive JSON. The reporting grid can have a different resolution or tessellation, as long as the descriptors in both runs have the same meaning and units. .. code-block:: python from qdpy.containers import Grid from qdpy.plots import plot_archive_difference from qdpy.reporting import compare_archive_cells reporting = Grid(shape=(8, 8), features_domain=((0., 1.), (0., 1.)), fitness_domain=((0., 1.),), fitness_weights=(1.,)) comparison = compare_archive_cells(uniform_by_seed, isoline_by_seed, reporting_grid=reporting, objective=0) fig, axes = plot_archive_difference(comparison, labels=("Uniform", "Iso+LineDD")) fig.savefig("archive-differences.png") The top panels show how many paired seeds reached each cell with only one method. The bottom right counts seeds where both reached it. Only those jointly occupied pairs contribute to the bottom-left median. Its values are in raw fitness units, with positive values favoring the contender for either maximisation or minimisation. Grey indicates no paired fitness differences. Check ``unmatched_reference`` and ``unmatched_contender`` for seeds excluded from the comparison. .. figure:: benchmarks/archive-differences-example.png :alt: Four heatmaps showing exclusive occupancy, joint occupancy, and fitness differences by cell. Six paired seeds on normalized Rastrigin, with 144 evaluations per run. Some cells are reached more often by Uniform, while some jointly reached cells have higher fitness under Iso+LineDD. The reporting calculation works with a fixed ``Grid`` or ``CVTGrid``. The plot supports 1D and 2D rectangular grids and 2D CVT cells. Trace a retained elite's ancestry --------------------------------- Attach :class:`qdpy.lineage.LineageRecorder` before the search starts. It records the actual parents selected for each proposal and whether the archive accepted or rejected it. Managed evaluation failures are also recorded. With a manual ask/tell loop, call ``mark_failed()`` if your evaluator fails and manage the failed attempt's budget yourself. .. code-block:: python from qdpy.lineage import LineageRecorder, read_lineage from qdpy.plots import plot_lineage with LineageRecorder("lineage.jsonl").attach(search) as recorder: search.optimise(evaluate) elite_id = recorder.id_for(search.best()) nodes = read_lineage("lineage.jsonl") if elite_id is not None: ax = plot_lineage(nodes, elite=elite_id) ax.figure.savefig("elite-ancestry.png") Both the mutation forest and the crossover graph are generated by the example below. Use the full view for a small run and ``elite=`` to focus on one proposal's ancestors in a larger log. Accepted means the candidate entered the archive at that evaluation. It may have been replaced later. .. code-block:: sh python examples/map_elites_lineage.py results/lineage-demo .. figure:: benchmarks/map-elites-lineage-example.png :alt: A mutation forest and the multi-parent ancestry of one retained crossover elite. Each edge follows a recorded parent selection. In the right panel, the ring identifies the retained elite and the graph shows only its ancestors. Recording supports native polynomial and Gaussian mutation emitters, Iso+LineDD, and IsoLineCross with a grid or CVT archive. Evaluators that return a replacement candidate must return a fresh object. Existing archive entries become founders when the recorder attaches, including when restarting from a checkpoint. Use a fresh path for each trace. See :doc:`tutorial_genealogy` to project measured ancestry onto an archive and compare stepping stones across runs. Capture and animate a run ------------------------- Attach :class:`qdpy.plots.ArchiveRecorder` after callbacks that update your archives, such as MC-AURORA training. Choose an iteration interval with ``every``. The recorder also captures the initial and final states. Pass a mapping or a callable that returns your current archives. .. code-block:: python from qdpy.plots import ArchiveRecorder, animate_archives recorder = ArchiveRecorder("history", every=10).attach(search, archives=learned) search.optimise(evaluate) animate_archives("history", "evolution.gif", frames_dir="frames", shared_scale=True) For fixed-task and dynamic search, pass ``on_step=recorder.capture`` to record after each step. To record less often, call ``capture()`` inside a callback that checks the iteration or evaluation count. The seeded example records a rectangular grid and a CVT on the same evaluations. It writes the history, a final comparison figure, and the PNG frames used for the GIF. .. code-block:: sh python examples/archive_animation.py results/archive-demo Align separate histories by evaluation budget --------------------------------------------- When runs use different batch or recording intervals, align by evaluations with :func:`qdpy.plots.align_archive_histories`. The time-lapse uses the union of recorded budgets inside the interval shared by all runs. At each budget, a run displays its most recent snapshot at or before that budget. A panel can stay unchanged while another advances. .. code-block:: python from qdpy.plots import align_archive_histories, animate_archives histories = {"Uniform": "uniform/history", "Iso+LineDD": "isoline/history"} animate_archives(align_archive_histories(histories), "comparison.gif", frames_dir="frames", fps=4, shared_scale=True, show_progress=True, highlight_changes=True) Circles mark newly occupied cells and triangles mark strict fitness improvements since the preceding frame. Highlights require unchanged planar cell geometry across those two frames. The charts show coverage and normalized QD score for the selected objective, using one best value per cell and the recorded fitness bounds. Archives without cells have no coverage value. The dashed line marks the current budget. Each recorded step has equal screen time. Read the evaluation axis to compare intervals, which can differ in length. .. code-block:: sh python examples/compare_archive_histories.py results/comparison-demo --mp4 The example saves the paired difference plot, both histories, and the numbered PNGs. It writes a GIF using Pillow. ``--mp4`` also writes an H.264 video and requires FFmpeg with the ``libx264`` encoder on ``PATH``. You can :download:`download the example time-lapse `. .. figure:: benchmarks/archive-progress-example.png :alt: Two MAP-Elites archives at 72 evaluations above QD score and coverage curves. One frame of the paired Rastrigin run. Uniform has a new capture at 72 evaluations, while Iso+LineDD displays its capture from evaluation 64. The markers show the changes in the Uniform archive. Render saved runs or PNGs ------------------------- The CLI renders grid exports, run manifests, and recorded histories. An animation uses the same layout and colour limits in every frame. Choose an encoder with ``--encoder``, or let QDpy try gifski, FFmpeg, and Pillow in order. .. code-block:: sh python -m qdpy.visualization plot results/archive-demo/history -o final.pdf --shared-scale python -m qdpy.visualization frames results/archive-demo/history -o replay --shared-scale python -m qdpy.visualization gif replay -o evolution.gif --fps 8 python -m qdpy.visualization mp4 replay -o evolution.mp4 --fps 8 Pass ``--show-progress`` and ``--highlight-changes`` when rendering frames from a history. Saved PNGs already include any overlays drawn during rendering. Use ``--trusted-pickle`` to read your own :class:`qdpy.algorithms.AlgorithmLogger` checkpoints. Python pickle files can run code during loading. QDpy processes iteration filenames numerically and adds the final archive when it differs from the last checkpoint. .. code-block:: sh python -m qdpy.visualization gif checkpoints -o checkpoints.gif --trusted-pickle