QDpy
Loading...
Searching...
No Matches
faery.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Learn which initial genomes yield many successful descendants at low depth."""
7
8from dataclasses import dataclass
9from math import isfinite
10
11import numpy as np
12
13from qdpy.containers import Grid
14from qdpy.phenotype import Features, Fitness, Individual
15from .constrained import _validate_grid
16from .evolvability_es import _pareto_utilities
17from .modern import _positive_int
18
19__all__ = ["FAERY", "FAERYSuccess", "FAERYTaskResult", "FAERYGeneration", "FAERYResult"]
20
21
22
23@dataclass(frozen=True)
25 """Record a successful genome, its prior index, and its mutation depth."""
26
27 genome: tuple
28 root: int
29 depth: int
30
31
32
33@dataclass(frozen=True)
35 """Store a native archive, distinct successes, and measured evaluation costs.
36
37 first_success is the one-based evaluation number, or None if no
38 evaluated genome satisfied the task's success predicate.
39 """
40
41 archive: Grid
42 successes: tuple[FAERYSuccess, ...]
43 evaluations: int
44 first_success: int | None
45
46
47
48@dataclass(frozen=True)
50 """Report counts and mean depths in candidate order, with selected indices.
51
52 Candidates with zero successes have a mean_depths entry of None.
53 """
54
55 candidates: tuple
56 success_counts: tuple[int, ...]
57 mean_depths: tuple[float | None, ...]
58 selected: tuple[int, ...]
59 evaluations: int
60
61
62
63@dataclass(frozen=True)
65 """Hold selected genomes and total training evaluations across generations."""
66
67 prior: tuple
68 history: tuple[FAERYGeneration, ...]
69 evaluations: int
70
71
72def _prior_population(prior):
73 genomes = tuple(tuple(genome) for genome in prior)
74 if not genomes or any(not genome for genome in genomes) or len(set(genomes)) != len(genomes):
75 raise ValueError("Provide distinct, nonempty, immutable prior genomes.")
76 return genomes
77
78
79
80class FAERY:
81 """Meta-evolve a prior using mutation-only MAP-Elites as the inner search.
82
83 During training, the current prior and its mutated candidates are
84 measured together on each task. A successful genome credits its
85 original root, including a successful root at depth zero. Track
86 successes by genome within each task, using their first successful
87 evaluations. Pareto selection favors more successes and lower
88 mean mutation depth.
89
90 :param grid_factory: Callable taking a task and returning a fresh, empty best-only Grid or CVTGrid.
91 :param mutate: Callable taking (genome_tuple, rng) and returning a new immutable genome.
92 :param task_budget: Maximum evaluator calls for one inner task, including initial genomes.
93 :param offspring: Number of outer mutation proposals per generation.
94 :param tasks_per_generation: Number of tasks sampled without replacement. Defaults to all tasks.
95 :param success_limit: Optional stop after this many distinct successes. All initial genomes are measured.
96 :param seed: Seed for outer sampling, mutation, and tie-breaking.
97 """
98
99 def __init__(self, grid_factory, mutate, *, task_budget, offspring=4,
100 tasks_per_generation=None, success_limit=None, seed=0):
101 if not callable(grid_factory) or not callable(mutate):
102 raise TypeError("Provide a grid factory and a mutation callback.")
103 self._grid_factory, self._mutate = grid_factory, mutate
104 self.task_budget = _positive_int(task_budget, "task_budget")
105 self.offspring = _positive_int(offspring, "offspring")
106 self.tasks_per_generation = (None if tasks_per_generation is None else
107 _positive_int(tasks_per_generation, "tasks_per_generation"))
108 self.success_limit = None if success_limit is None else _positive_int(success_limit, "success_limit")
109 self.seed = seed
110
111
112 def adapt(self, prior, task, evaluate, budget=None, *, seed=0):
113 """Run mutation-only MAP-Elites under a separate evaluation budget.
114
115 evaluate(task, genome) returns (scalar fitness, descriptors, success).
116 The success flag is independent of archive admission.
117 """
118 prior = _prior_population(prior)
119 budget = self.task_budget if budget is None else _positive_int(budget, "budget")
120 if budget < len(prior) or not callable(evaluate):
121 raise ValueError("Provide an evaluator and a budget that covers all prior genomes.")
122 archive = self._grid_factory(task)
123 _validate_grid(archive)
124 weights = tuple(archive.fitness_weights or ())
125 if (archive.parents or len(weights) != 1 or not isfinite(weights[0]) or weights[0] == 0
126 or archive.fitness_score_names or archive.features_score_names):
127 raise ValueError("Use a parentless archive with a finite signed scalar fitness weight and native scores.")
128 rng = np.random.default_rng(seed)
129 successes = {}
130 first_success = None
131
132 for attempt in range(budget):
133 if attempt < len(prior):
134 root, depth, genome = attempt, 0, prior[attempt]
135 else:
136 if self.success_limit is not None and len(successes) >= self.success_limit:
137 break
138 if archive:
139 parent = archive[rng.integers(len(archive))]
140 root, depth = parent.scores["faery_root"], parent.scores["faery_depth"] + 1
141 else:
142 root = int(rng.integers(len(prior)))
143 parent, depth = prior[root], 1
144 genome = tuple(self._mutate(tuple(parent), rng))
145 if not genome:
146 raise ValueError("Mutation must return a nonempty genome.")
147 hash(genome)
148 quality, features, solved = evaluate(task, genome)
149 quality, features = float(quality), tuple(map(float, features))
150 if (not isfinite(quality) or len(features) != len(archive.features_domain)
151 or not all(map(isfinite, features)) or not isinstance(solved, (bool, np.bool_))):
152 raise ValueError("Return finite fitness and descriptors, and a boolean success flag.")
153 if solved:
154 if first_success is None:
155 first_success = attempt + 1
156 successes.setdefault(genome, FAERYSuccess(genome, root, depth))
157 if (archive.in_bounds((quality,), archive.fitness_domain)
158 and archive.in_bounds(features, archive.features_domain)):
159 cell = archive.index_grid(features)
160 if archive.free or archive.solutions[cell]:
161 individual = Individual(list(genome), fitness=Fitness((quality,), weights=weights),
162 features=Features(features))
163 individual.scores["faery_root"] = root
164 individual.scores["faery_depth"] = depth
165 archive.add(individual)
166 else:
167 return FAERYTaskResult(archive, tuple(successes.values()), budget, first_success)
168 return FAERYTaskResult(archive, tuple(successes.values()), attempt, first_success)
169
170
171 def fit(self, initial, tasks, evaluate, *, generations):
172 """Reassess the combined parent and offspring candidates on shared task panels."""
173 prior = _prior_population(initial)
174 tasks = tuple(tasks)
175 generations = _positive_int(generations, "generations")
176 sample_size = len(tasks) if self.tasks_per_generation is None else self.tasks_per_generation
177 if not 0 < sample_size <= len(tasks) or not callable(evaluate):
178 raise ValueError("Provide enough training tasks and an evaluator.")
179 if len(prior) + self.offspring > self.task_budget:
180 raise ValueError("task_budget must cover the prior and all outer offspring.")
181 size = len(prior)
182 rng = np.random.default_rng(self.seed)
183 history = []
184 for _ in range(generations):
185 pool = dict.fromkeys(prior)
186 for _ in range(self.offspring):
187 child = tuple(self._mutate(prior[rng.integers(size)], rng))
188 if not child:
189 raise ValueError("Mutation must return a nonempty genome.")
190 pool.setdefault(child)
191 genomes = tuple(pool)
192 count = [0] * len(genomes)
193 depth_sum = [0] * len(genomes)
194 calls = 0
195 for task_index in rng.choice(len(tasks), size=sample_size, replace=False):
196 result = self.adapt(genomes, tasks[task_index], evaluate, seed=int(rng.integers(2**32)))
197 calls += result.evaluations
198 for success in result.successes:
199 count[success.root] += 1
200 depth_sum[success.root] += success.depth
201 depths = tuple(total / number if number else None for total, number in zip(depth_sum, count))
202 speed = np.asarray([-depth if depth is not None else -self.task_budget for depth in depths])
203 utility = _pareto_utilities(np.asarray(count), speed)
204 selected = tuple(map(int, np.lexsort((rng.random(len(genomes)), -utility))[:size]))
205 prior = tuple(genomes[i] for i in selected)
206 history.append(FAERYGeneration(genomes, tuple(count), depths, selected, calls))
207 return FAERYResult(prior, tuple(history), sum(row.evaluations for row in history))
Lineage credit used in one outer FAERY selection.
Definition faery.py:49
A learned prior and its training history.
Definition faery.py:64
A successful evaluated genome and its lineage in an adaptation run.
Definition faery.py:24
The result of adapting one prior population to one task.
Definition faery.py:34
Fit an initialization prior using successful descendants and mutation depth.
Definition faery.py:80
fit(self, initial, tasks, evaluate, *, generations)
Learn a fixed-size population from training tasks.
Definition faery.py:171
adapt(self, prior, task, evaluate, budget=None, *, seed=0)
Evaluate one prior on a task without modifying it.
Definition faery.py:112
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405