5"""Run three deterministic genealogy examples on CPU and save plots and measurements."""
8from itertools
import count
10from pathlib
import Path
12import matplotlib.pyplot
as plt
13from matplotlib.colors
import BoundaryNorm, ListedColormap
16from qdpy.algorithms import CuriosityMutPolyBounded, classifier_illumination, lexicase_index
19from qdpy.genealogy import (ancestor_archive, ancestry, goal_switches, lineage_trajectory_network,
20 plot_ancestry_archive, plot_stepping_stones)
21from qdpy.lineage import LineageNode, LineageRecorder, plot_lineage, read_lineage
26def map_elites_genealogy(output):
27 """Record six budget-matched curiosity runs and score selected ancestors."""
29 return Grid(shape=(8, 8), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),))
31 runs, targets, alternatives, endpoints = {}, {}, [], []
32 for seed
in (7, 11, 19, 29, 41, 59):
33 search = CuriosityMutPolyBounded(grid(), budget=384, batch_size=8, dimension=4,
34 init_pb=.12, mut_pb=.45, eta=6, optimisation_task=
"maximisation")
35 path = output / f
"rastrigin-{seed}.jsonl"
36 with LineageRecorder(path, record_measurements=
True).attach(search)
as recorder:
37 result = run(search, illumination_rastrigin_normalised, seed=seed)
38 elite = recorder.id_for(result.best)
39 retained = sorted(result.archive, key=
lambda item: item.fitness.values[0], reverse=
True)
40 candidates = [recorder.id_for(item)
for item
in retained[:5]]
41 nodes = read_lineage(path)
42 runs[seed], targets[seed] = nodes, (elite,)
43 for candidate
in candidates:
44 alternatives.append((len(goal_switches(nodes, elite=candidate)), seed, candidate))
45 for ancestor
in ancestry(nodes, elite, include_elite=
True).values():
46 if not ancestor.parents:
47 endpoints.append((ancestor.cell, nodes[elite].cell))
49 _, seed, elite = max(alternatives)
51 projected = ancestor_archive(runs[seed], elite, grid=reporting)
52 graph = lineage_trajectory_network(runs, targets=targets)
53 stones = graph.stepping_stones(endpoints)
54 positions = {cell: tuple((coordinate + .5) / 8
for coordinate
in cell)
for cell
in graph.states}
55 fig, axes = plt.subplots(1, 3, figsize=(13, 4.4), layout=
"constrained")
56 plot_lineage(runs[seed], elite=elite, ax=axes[0])
57 plot_ancestry_archive(runs[seed], elite, grid=reporting, ax=axes[1])
58 plot_stepping_stones(graph, analysis=stones, positions=positions, ax=axes[2])
59 axes[2].set(xlim=(0, 1), ylim=(0, 1), xlabel=
"Descriptor 1", ylabel=
"Descriptor 2",
60 title=
"Network of best elites' ancestries")
61 fig.savefig(output /
"archive-genealogy.png", dpi=125)
63 return {
"seed": seed,
"elite": elite,
"ancestor_cells": projected.filled_bins,
64 "ancestor_coverage": projected.filled_bins / 64,
"ancestor_qd_score": projected.qd_score(),
65 "network_states": len(graph.states),
"shortest_paths": stones.shortest_paths,
66 "stepping_stones": stones.stones,
"worsening_fraction": graph.worsening_fraction}
69def image_genealogy(output):
70 """Evolve a small image repertoire using a fixed procedural template classifier."""
71 x, y = np.meshgrid(np.linspace(-1., 1., 24), np.linspace(-1., 1., 24))
73 basis = np.array([np.sin(5 * x), np.sin(5 * y), np.cos(9 * r), np.cos(6 * x) * np.cos(6 * y)])
74 labels = (
"Vertical bands",
"Horizontal bands",
"Rings",
"Checker")
75 templates = (basis > 0).astype(float)
77 def render(candidate):
78 return .5 + .5 * np.tanh(np.tensordot(candidate, basis, axes=1))
80 def classify(candidate):
81 error = np.mean((render(candidate) - templates) ** 2, axis=(1, 2))
82 scores = np.exp(-10. * error)
83 return scores / scores.sum()
85 result = classifier_illumination(
lambda rng: rng.normal(0., .45, len(labels)),
86 lambda candidate, rng: candidate + rng.normal(0., .35, len(labels)),
87 classify, classes=len(labels), budget=180, initial_samples=5, seed=29)
88 elite = max(result.champions, key=
lambda champion: champion.lineage_id)
89 fig = plt.figure(figsize=(8, 4.2), layout=
"constrained")
90 grid = fig.add_gridspec(2, 3)
91 ax = fig.add_subplot(grid[:, 0])
93 switch = result.switches[0]
94 plot_lineage(result.nodes, elite=switch.child, highlight_edges=[(switch.parent, switch.child)], ax=ax)
95 ax.set_title(f
"Goal switch\n{labels[switch.source]} to {labels[switch.target]}", fontsize=10)
97 plot_lineage(result.nodes, elite=elite.lineage_id, ax=ax)
98 ax.set_title(f
"Ancestry of proposal {elite.lineage_id}")
99 for i, (label, champion)
in enumerate(zip(labels, result.champions, strict=
True)):
100 ax = fig.add_subplot(grid[i // 2, 1 + i % 2])
101 ax.imshow(render(champion.candidate), cmap=
"gray", vmin=0., vmax=1.)
102 ax.set_title(f
"{label} · {champion.score:.2f}", fontsize=10)
104 fig.savefig(output /
"classifier-goals.png", dpi=130)
106 return {
"evaluations": result.evaluations,
"champion_updates": result.champion_updates,
107 "goal_switches": len(result.switches),
"class_scores": [item.score
for item
in result.champions]}
110def phylogeny_example(output):
111 """Select candidates under two case sampling strategies and audit the final estimates."""
112 case_points = np.linspace(0., 1., 12)
114 fig, axes = plt.subplots(1, 2, figsize=(8.8, 3.8), layout=
"constrained")
115 cmap = ListedColormap((
"#3875a4",
"#f2b650",
"#ddd9d1"))
117 for ax, (label, sampling, mode)
in zip(
118 axes, ((
"Shared subset", {
"sample_size": 4},
"ancestor"), (
"Cohorts", {
"cohorts": 3},
"relative")),
120 rng = np.random.default_rng(19)
122 population = rng.random(size)
123 ids = [next(next_id)
for _
in population]
124 nodes = {node: LineageNode(node, (),
"initialise",
None)
for node
in ids}
125 measured, total_cases = {}, 0
126 for generation
in range(6):
127 groups = case_cohorts(size, len(case_points), rng, **sampling)
128 for group, cases
in groups:
130 observed = np.full(len(case_points), np.nan)
131 observed[cases] = np.square(population[row] - case_points[cases])
132 measured[ids[row]] = observed
133 total_cases += len(cases)
134 estimates = estimate_case_errors(nodes, measured, ids, mode=mode, max_distance=4, missing_error=1.)
137 for _
in range(size):
138 pool, _ = groups[rng.integers(len(groups))]
139 selected.append(pool[lexicase_index(estimates.errors[pool], rng)])
140 parents = [ids[row]
for row
in selected]
141 ids = [next(next_id)
for _
in population]
142 nodes.update((node, LineageNode(node, (parent,),
"mutation",
None))
143 for node, parent
in zip(ids, parents, strict=
True))
144 population = np.clip(population[selected] + rng.normal(0., .04, size), 0., 1.)
146 direct = estimates.donors == np.asarray(ids)[:,
None]
147 inherited = (estimates.donors >= 0) & ~direct
148 labels = np.where(direct, 0, np.where(inherited, 1, 2))
149 image = ax.imshow(labels, cmap=cmap, norm=BoundaryNorm((-.5, .5, 1.5, 2.5), cmap.N), aspect=
"auto")
150 ax.set(title=f
"{label} · {mode} donors", xlabel=
"Case index", ylabel=
"Candidate row")
151 full = np.square(population[:,
None] - case_points)
152 audit[label] = {
"measured_cases": total_cases,
"full_case_budget": 6 * size * len(case_points),
153 "final_estimates": int(inherited.sum()),
"final_fallbacks": int((labels == 2).sum()),
154 "inherited_mean_absolute_error": float(np.abs(estimates.errors - full)[inherited].mean())}
155 bar = fig.colorbar(image, ax=axes, ticks=(0, 1, 2), shrink=.86)
156 bar.ax.set_yticklabels((
"Measured",
"Relative's score",
"Fallback"))
157 fig.savefig(output /
"phylogenetic-estimation.png", dpi=125)
162if __name__ ==
"__main__":
163 parser = argparse.ArgumentParser(description=__doc__)
164 parser.add_argument(
"output", type=Path)
165 output = parser.parse_args().output
166 output.mkdir(parents=
True, exist_ok=
True)
167 report = {
"map_elites": map_elites_genealogy(output),
"classifier": image_genealogy(output),
168 "lexicase": phylogeny_example(output)}
169 (output /
"summary.json").write_text(json.dumps(report, indent=2) +
"\n", encoding=
"utf-8")
170 print(json.dumps(report, indent=2))