QDpy
Loading...
Searching...
No Matches
archive_roundtrip.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Save a MAP-Elites or MOME search and plot the saved measurements."""
6
7import argparse
8import json
9from pathlib import Path
10
11import matplotlib
12
13from qdpy.algorithms import MOME
14from qdpy.containers import ParetoGrid
15from qdpy.results import load_grid, read_run_manifest
16from qdpy.simple import map_elites, run
17
18
19def evaluate_map(candidate):
20 """Minimise cost and fill cells along the second genome coordinate."""
21 x, behaviour = candidate
22 return (x**2,), (behaviour,)
23
24
25def evaluate_mome(candidate):
26 """Return competing costs on the same descriptor axis."""
27 x, behaviour = candidate
28 return (x**2, (1. - x)**2), (behaviour,)
29
30
31def metrics(archive):
32 """Measure occupancy and the quality statistic for the selected archive."""
33 result = {"cells": archive.filled_bins, "retained": len(archive)}
34 if isinstance(archive, ParetoGrid):
35 result["qd_hypervolume"] = archive.qd_hypervolume((1., 1.))
36 result["global_hypervolume"] = archive.global_hypervolume((1., 1.))
37 else:
38 result["qd_score"] = archive.qd_score()
39 return result
40
41
42def main():
43 """Write a manifest, numeric archive, and PNG under the output directory."""
44 parser = argparse.ArgumentParser(description=__doc__)
45 parser.add_argument("method", choices=("map-elites", "mome"))
46 parser.add_argument("output_dir", type=Path)
47 args = parser.parse_args()
48 unit = (0., 1.)
49 if args.method == "mome":
50 archive = ParetoGrid(shape=8, max_items_per_bin=4, fitness_domain=(unit, unit),
51 features_domain=(unit,), truncation="crowding")
52 search, evaluate = MOME(archive, 64, dimension=2, batch_size=8), evaluate_mome
53 else:
54 search = map_elites(dimension=2, budget=64, batch_size=8, shape=8,
55 fitness_domain=(unit,), features_domain=(unit,))
56 evaluate = evaluate_map
57
58 result = run(search, evaluate, seed=42, output_dir=args.output_dir)
59 manifest = read_run_manifest(result.manifest_path)
60 snapshot = manifest["archive"]
61 archive_path = result.manifest_path.with_name(snapshot["file"])
62 restored = load_grid(archive_path, expected_sha256=snapshot["sha256"])
63 measured = metrics(restored)
64 if measured != metrics(result.archive):
65 raise RuntimeError("Restored archive metrics differ from the live search.")
66
67 matplotlib.use("Agg")
68 from matplotlib import pyplot as plt
69 from qdpy.plots import plot_archive
70
71 ax = plot_archive(archive_path, metric="occupancy" if args.method == "mome" else "fitness")
72 ax.figure.savefig(args.output_dir / "archive.png", dpi=140, bbox_inches="tight")
73 plt.close(ax.figure)
74 print(json.dumps(dict(evaluations=result.evaluations, **measured), sort_keys=True))
75
76
77if __name__ == "__main__":
78 main()