# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Demonstrate archive ancestry, class switches, and phylogenetic case estimation. """Run three deterministic genealogy examples on CPU and save plots and measurements.""" import argparse from itertools import count import json from pathlib import Path import matplotlib.pyplot as plt from matplotlib.colors import BoundaryNorm, ListedColormap import numpy as np from qdpy.algorithms import CuriosityMutPolyBounded, classifier_illumination, lexicase_index from qdpy.benchmarks import illumination_rastrigin_normalised from qdpy.containers import Grid from qdpy.genealogy import (ancestor_archive, ancestry, goal_switches, lineage_trajectory_network, plot_ancestry_archive, plot_stepping_stones) from qdpy.lineage import LineageNode, LineageRecorder, plot_lineage, read_lineage from qdpy.phylogeny import case_cohorts, estimate_case_errors from qdpy.simple import run def map_elites_genealogy(output): """Record six budget-matched curiosity runs and score selected ancestors.""" def grid(): return Grid(shape=(8, 8), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),)) runs, targets, alternatives, endpoints = {}, {}, [], [] for seed in (7, 11, 19, 29, 41, 59): search = CuriosityMutPolyBounded(grid(), budget=384, batch_size=8, dimension=4, init_pb=.12, mut_pb=.45, eta=6, optimisation_task="maximisation") path = output / f"rastrigin-{seed}.jsonl" with LineageRecorder(path, record_measurements=True).attach(search) as recorder: result = run(search, illumination_rastrigin_normalised, seed=seed) elite = recorder.id_for(result.best) retained = sorted(result.archive, key=lambda item: item.fitness.values[0], reverse=True) candidates = [recorder.id_for(item) for item in retained[:5]] nodes = read_lineage(path) runs[seed], targets[seed] = nodes, (elite,) for candidate in candidates: alternatives.append((len(goal_switches(nodes, elite=candidate)), seed, candidate)) for ancestor in ancestry(nodes, elite, include_elite=True).values(): if not ancestor.parents: endpoints.append((ancestor.cell, nodes[elite].cell)) _, seed, elite = max(alternatives) reporting = grid() projected = ancestor_archive(runs[seed], elite, grid=reporting) graph = lineage_trajectory_network(runs, targets=targets) stones = graph.stepping_stones(endpoints) positions = {cell: tuple((coordinate + .5) / 8 for coordinate in cell) for cell in graph.states} fig, axes = plt.subplots(1, 3, figsize=(13, 4.4), layout="constrained") plot_lineage(runs[seed], elite=elite, ax=axes[0]) plot_ancestry_archive(runs[seed], elite, grid=reporting, ax=axes[1]) plot_stepping_stones(graph, analysis=stones, positions=positions, ax=axes[2]) axes[2].set(xlim=(0, 1), ylim=(0, 1), xlabel="Descriptor 1", ylabel="Descriptor 2", title="Network of best elites' ancestries") fig.savefig(output / "archive-genealogy.png", dpi=125) plt.close(fig) return {"seed": seed, "elite": elite, "ancestor_cells": projected.filled_bins, "ancestor_coverage": projected.filled_bins / 64, "ancestor_qd_score": projected.qd_score(), "network_states": len(graph.states), "shortest_paths": stones.shortest_paths, "stepping_stones": stones.stones, "worsening_fraction": graph.worsening_fraction} def image_genealogy(output): """Evolve a small image repertoire using a fixed procedural template classifier.""" x, y = np.meshgrid(np.linspace(-1., 1., 24), np.linspace(-1., 1., 24)) r = np.hypot(x, y) basis = np.array([np.sin(5 * x), np.sin(5 * y), np.cos(9 * r), np.cos(6 * x) * np.cos(6 * y)]) labels = ("Vertical bands", "Horizontal bands", "Rings", "Checker") templates = (basis > 0).astype(float) def render(candidate): return .5 + .5 * np.tanh(np.tensordot(candidate, basis, axes=1)) def classify(candidate): error = np.mean((render(candidate) - templates) ** 2, axis=(1, 2)) scores = np.exp(-10. * error) return scores / scores.sum() result = classifier_illumination(lambda rng: rng.normal(0., .45, len(labels)), lambda candidate, rng: candidate + rng.normal(0., .35, len(labels)), classify, classes=len(labels), budget=180, initial_samples=5, seed=29) elite = max(result.champions, key=lambda champion: champion.lineage_id) fig = plt.figure(figsize=(8, 4.2), layout="constrained") grid = fig.add_gridspec(2, 3) ax = fig.add_subplot(grid[:, 0]) if result.switches: switch = result.switches[0] plot_lineage(result.nodes, elite=switch.child, highlight_edges=[(switch.parent, switch.child)], ax=ax) ax.set_title(f"Goal switch\n{labels[switch.source]} to {labels[switch.target]}", fontsize=10) else: plot_lineage(result.nodes, elite=elite.lineage_id, ax=ax) ax.set_title(f"Ancestry of proposal {elite.lineage_id}") for i, (label, champion) in enumerate(zip(labels, result.champions, strict=True)): ax = fig.add_subplot(grid[i // 2, 1 + i % 2]) ax.imshow(render(champion.candidate), cmap="gray", vmin=0., vmax=1.) ax.set_title(f"{label} · {champion.score:.2f}", fontsize=10) ax.axis("off") fig.savefig(output / "classifier-goals.png", dpi=130) plt.close(fig) return {"evaluations": result.evaluations, "champion_updates": result.champion_updates, "goal_switches": len(result.switches), "class_scores": [item.score for item in result.champions]} def phylogeny_example(output): """Select candidates under two case sampling strategies and audit the final estimates.""" case_points = np.linspace(0., 1., 12) size = 10 fig, axes = plt.subplots(1, 2, figsize=(8.8, 3.8), layout="constrained") cmap = ListedColormap(("#3875a4", "#f2b650", "#ddd9d1")) audit = {} for ax, (label, sampling, mode) in zip( axes, (("Shared subset", {"sample_size": 4}, "ancestor"), ("Cohorts", {"cohorts": 3}, "relative")), strict=True): rng = np.random.default_rng(19) next_id = count() population = rng.random(size) ids = [next(next_id) for _ in population] nodes = {node: LineageNode(node, (), "initialise", None) for node in ids} measured, total_cases = {}, 0 for generation in range(6): groups = case_cohorts(size, len(case_points), rng, **sampling) for group, cases in groups: for row in group: observed = np.full(len(case_points), np.nan) observed[cases] = np.square(population[row] - case_points[cases]) measured[ids[row]] = observed total_cases += len(cases) estimates = estimate_case_errors(nodes, measured, ids, mode=mode, max_distance=4, missing_error=1.) if generation < 5: selected = [] for _ in range(size): pool, _ = groups[rng.integers(len(groups))] selected.append(pool[lexicase_index(estimates.errors[pool], rng)]) parents = [ids[row] for row in selected] ids = [next(next_id) for _ in population] nodes.update((node, LineageNode(node, (parent,), "mutation", None)) for node, parent in zip(ids, parents, strict=True)) population = np.clip(population[selected] + rng.normal(0., .04, size), 0., 1.) direct = estimates.donors == np.asarray(ids)[:, None] inherited = (estimates.donors >= 0) & ~direct labels = np.where(direct, 0, np.where(inherited, 1, 2)) image = ax.imshow(labels, cmap=cmap, norm=BoundaryNorm((-.5, .5, 1.5, 2.5), cmap.N), aspect="auto") ax.set(title=f"{label} · {mode} donors", xlabel="Case index", ylabel="Candidate row") full = np.square(population[:, None] - case_points) audit[label] = {"measured_cases": total_cases, "full_case_budget": 6 * size * len(case_points), "final_estimates": int(inherited.sum()), "final_fallbacks": int((labels == 2).sum()), "inherited_mean_absolute_error": float(np.abs(estimates.errors - full)[inherited].mean())} bar = fig.colorbar(image, ax=axes, ticks=(0, 1, 2), shrink=.86) bar.ax.set_yticklabels(("Measured", "Relative's score", "Fallback")) fig.savefig(output / "phylogenetic-estimation.png", dpi=125) plt.close(fig) return audit if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("output", type=Path) output = parser.parse_args().output output.mkdir(parents=True, exist_ok=True) report = {"map_elites": map_elites_genealogy(output), "classifier": image_genealogy(output), "lexicase": phylogeny_example(output)} (output / "summary.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print(json.dumps(report, indent=2))