# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Run a custom evaluator, reload the numeric archive, and reproduce its metrics. """Save a MAP-Elites or MOME search and plot the saved measurements.""" import argparse import json from pathlib import Path import matplotlib from qdpy.algorithms import MOME from qdpy.containers import ParetoGrid from qdpy.results import load_grid, read_run_manifest from qdpy.simple import map_elites, run def evaluate_map(candidate): """Minimise cost and fill cells along the second genome coordinate.""" x, behaviour = candidate return (x**2,), (behaviour,) def evaluate_mome(candidate): """Return competing costs on the same descriptor axis.""" x, behaviour = candidate return (x**2, (1. - x)**2), (behaviour,) def metrics(archive): """Measure occupancy and the quality statistic for the selected archive.""" result = {"cells": archive.filled_bins, "retained": len(archive)} if isinstance(archive, ParetoGrid): result["qd_hypervolume"] = archive.qd_hypervolume((1., 1.)) result["global_hypervolume"] = archive.global_hypervolume((1., 1.)) else: result["qd_score"] = archive.qd_score() return result def main(): """Write a manifest, numeric archive, and PNG under the output directory.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("method", choices=("map-elites", "mome")) parser.add_argument("output_dir", type=Path) args = parser.parse_args() unit = (0., 1.) if args.method == "mome": archive = ParetoGrid(shape=8, max_items_per_bin=4, fitness_domain=(unit, unit), features_domain=(unit,), truncation="crowding") search, evaluate = MOME(archive, 64, dimension=2, batch_size=8), evaluate_mome else: search = map_elites(dimension=2, budget=64, batch_size=8, shape=8, fitness_domain=(unit,), features_domain=(unit,)) evaluate = evaluate_map result = run(search, evaluate, seed=42, output_dir=args.output_dir) manifest = read_run_manifest(result.manifest_path) snapshot = manifest["archive"] archive_path = result.manifest_path.with_name(snapshot["file"]) restored = load_grid(archive_path, expected_sha256=snapshot["sha256"]) measured = metrics(restored) if measured != metrics(result.archive): raise RuntimeError("Restored archive metrics differ from the live search.") matplotlib.use("Agg") from matplotlib import pyplot as plt from qdpy.plots import plot_archive ax = plot_archive(archive_path, metric="occupancy" if args.method == "mome" else "fitness") ax.figure.savefig(args.output_dir / "archive.png", dpi=140, bbox_inches="tight") plt.close(ax.figure) print(json.dumps(dict(evaluations=result.evaluations, **measured), sort_keys=True)) if __name__ == "__main__": main()