5"""Resume a trusted MAP-Elites, NSLC, CMA-MAE, or MOME checkpoint."""
8from contextlib
import nullcontext
9from pathlib
import Path
18from qdpy.results import export_grid, grid_to_dataframe, load_grid
22def create_search(kind, budget, *, method="map", seed=17):
23 """Recreate the search settings in both processes."""
25 settings = dict(dimension=3, batch_size=8, budget=budget)
26 bounds = dict(fitness_domain=(unit,), features_domain=(unit, unit))
29 raise ValueError(
"MOME uses a rectangular ParetoGrid. Choose --kind grid.")
30 archive = ParetoGrid(shape=(2, 2), max_items_per_bin=4, fitness_domain=(unit, unit),
31 features_domain=(unit, unit), truncation=
"crowding")
32 return MOME(archive, **settings)
34 search = nslc(threshold_novelty=0.12, k=5, **bounds, **settings)
35 search.container.indexed =
True
37 if kind ==
"grid" and method ==
"map":
38 return map_elites(shape=(2, 2), **bounds, **settings)
40 centroids = [(0.15, 0.20), (0.45, 0.75), (0.75, 0.25), (0.90, 0.80)]
41 grid = Grid(shape=(2, 2), **bounds)
if kind ==
"grid" else CVTGrid(shape=4, centroids=centroids, **bounds)
42 if method ==
"cma-mae":
43 return CMAMAE(grid, budget=budget, x0=[0.5] * 3, sigma0=0.15, threshold_min=-1.0,
44 batch_size=8, ind_domain=unit, seed=seed)
45 return RandomSearchMutPolyBounded(grid, **settings)
48def seeded_rastrigin(genome, _seed):
49 """Evaluate deterministic Rastrigin through the seeded journal interface."""
50 return illumination_rastrigin_normalised(genome)
53def evaluate_tradeoff(genome, _seed=None):
54 """Evaluate two competing costs and use the remaining genes as descriptors."""
56 return (x**2, (1. - x)**2), (y, z)
60 """Read CLI settings and publish a portable result at the chosen boundary."""
61 parser = argparse.ArgumentParser(description=__doc__)
62 parser.add_argument(
"output", type=Path)
63 parser.add_argument(
"--kind", choices=(
"grid",
"cvt"), default=
"grid")
64 parser.add_argument(
"--method", choices=(
"map",
"nslc",
"cma-mae",
"mome"), default=
"map")
65 parser.add_argument(
"--budget", type=int, default=67)
66 parser.add_argument(
"--seed", type=int, default=17, help=
"Coordinator seed for a fresh search.")
67 parser.add_argument(
"--stop-after", type=int)
68 parser.add_argument(
"--resume-trusted", action=
"store_true")
69 parser.add_argument(
"--ray-address", help=
"Use ordered Ray evaluations. Pass local for a local runtime.")
70 parser.add_argument(
"--workers", type=int, default=2, help=
"Number of workers for local Ray.")
71 parser.add_argument(
"--journal", action=
"store_true", help=
"Keep a durable evaluation journal.")
72 parser.add_argument(
"--slurm-signal", action=
"store_true", help=
"Checkpoint and pause after SIGUSR1.")
73 args = parser.parse_args(argv)
75 search = create_search(args.kind, args.budget, method=args.method, seed=args.seed)
76 except ValueError
as error:
77 parser.error(str(error))
78 evaluate = evaluate_tradeoff
if args.method ==
"mome" else illumination_rastrigin_normalised
81 def on_time_limit(_signum, _frame):
86 signal.signal(signal.SIGUSR1, on_time_limit)
87 manager = (nullcontext()
if args.ray_address
is None
88 else ParallelismManager(
"ray", max_workers=args.workers, ray_address=args.ray_address))
89 with manager
as parallelism:
90 def evaluate_batch(batch):
91 return list(parallelism.executor.map(evaluate, batch))
93 evaluator = evaluate
if parallelism
is None else evaluate_batch
94 options = {
"packed": parallelism
is not None}
96 evaluator = evaluate_tradeoff
if args.method ==
"mome" else seeded_rastrigin
97 evaluation_key =
"mome-tradeoff-v1" if args.method ==
"mome" else "rastrigin-v1"
98 options = {
"journal_path": args.output /
"evaluations.jsonl",
"evaluation_key": evaluation_key,
99 "journal_executor":
None if parallelism
is None else parallelism.executor}
100 result = run_checkpointed(search, evaluator,
101 checkpoint_path=args.output /
"checkpoint.pkl", checkpoint_every=2,
102 stop_after=args.stop_after, seed=args.seed, resume=args.resume_trusted,
103 trusted=args.resume_trusted, stop_requested=
lambda: stop, **options)
104 if args.method ==
"nslc":
105 print(f
"{result.evaluations} new evaluations, {search.nb_evaluations} total, "
106 f
"{len(result.archive)} active, {len(result.archive.parents[0])} parent entries")
108 path = args.output /
"archive.json"
109 digest = export_grid(result.archive, path)
110 archive = load_grid(path, expected_sha256=digest)
111 print(f
"{result.evaluations} new evaluations, {search.nb_evaluations} total, SHA-256 {digest}")
112 print(grid_to_dataframe(archive)[[
"cell",
"fitness",
"descriptors"]].to_string(index=
False))
114 journal = read_evaluation_journal(args.output /
"evaluations.jsonl")
115 print(f
"{journal['returned_calls']} returned calls, {journal['failed_calls']} failed, "
116 f
"{journal['uncertain_calls']} uncertain dispatches")
119if __name__ ==
"__main__":