6"""Send measured lineages through archive layers as they age."""
8from bisect
import bisect_right
9from dataclasses
import dataclass
10from heapq
import heappop, heappush
14from ._population
import _attempt_budget, _finite_vector
15from .modern
import _positive_int
16from .task_search
import _measurement, _offer, _validate_grid
18__all__ = [
"AgeLayeredResult",
"age_layered_map_elites"]
22@dataclass(frozen=True)
24 """Admission and promotion counts are reported separately for each layer."""
29 admissions: tuple[int, ...]
30 promotions: tuple[int, ...]
44def age_layered_map_elites(archives, evaluate, *, sample, mutate, max_ages, budget, immigrant_interval=8, seed=0):
45 """Inherit the parent's birth evaluation and compete in the current age layer.
47 At the first evaluation whose age reaches a layer limit, move or
48 expire the individual using its cached measurement. Promotions
49 count successful arrivals and expirations include rejected moves.
50 The last layer has no age limit.
52 archives = tuple(archives)
53 limits = tuple(_positive_int(age,
"max_ages")
for age
in max_ages)
54 if (len(archives) < 2
or len({id(archive)
for archive
in archives}) != len(archives)
55 or len(limits) != len(archives) - 1
or any(a >= b
for a, b
in zip(limits, limits[1:]))):
56 raise ValueError(
"Supply distinct archives and strictly increasing ages for the bounded layers.")
57 if not all(map(callable, (sample, mutate, evaluate))):
58 raise TypeError(
"Supply callable sampling, mutation and evaluation.")
59 for archive
in archives:
60 _validate_grid(archive)
61 if {
"alme_birth",
"alme_descriptors"}.intersection((*archive.fitness_score_names, *archive.features_score_names)):
62 raise ValueError(
"Use score names distinct from the ALME age and descriptor metadata.")
63 direction = next((archive.fitness_weights[0]
for archive
in archives
if archive.fitness_weights), 1.)
64 if any(archive.fitness_weights
and (archive.fitness_weights[0] > 0) != (direction > 0)
65 for archive
in archives):
66 raise ValueError(
"Every layer must use the same objective direction.")
67 budget = _attempt_budget(budget)
68 interval = _positive_int(immigrant_interval,
"immigrant_interval")
69 for archive
in archives:
70 if archive.fitness_weights
is None:
71 archive._set_fitness_weights((direction,))
72 rng = np.random.default_rng(seed)
73 admissions, promotions = [0] * len(archives), [0] * len(archives)
74 immigrants = expired = 0
75 queue, pending = [], {}
77 def place(layer, token, genome, fitness, descriptions, birth):
78 archive = archives[layer]
79 measurement = _measurement(archive, ((fitness,), descriptions[layer]), genome)
80 candidate, cell = measurement
83 previous = archive.solutions[cell][0]
if archive.solutions[cell]
else None
84 candidate.name = str(token)
85 candidate.scores[
"alme_birth"] = birth
86 candidate.scores[
"alme_descriptors"] = descriptions
87 before = archive.nb_added
88 _offer(archive, measurement)
89 if archive.nb_added == before:
91 if layer < len(limits):
92 if previous
is not None:
93 pending.pop(int(previous.name),
None)
94 pending[token] = layer, candidate
95 heappush(queue, (birth + limits[layer], token))
98 for step
in range(budget):
99 while queue
and queue[0][0] <= step:
100 _, token = heappop(queue)
101 entry = pending.pop(token,
None)
104 source, elite = entry
105 birth = elite.scores[
"alme_birth"]
106 destination = bisect_right(limits, step - birth)
107 moved = place(destination, token, tuple(elite), elite.fitness.values[0],
108 elite.scores[
"alme_descriptors"], birth)
109 archives[source].discard(elite)
110 promotions[destination] += moved
112 occupied = [layer
for layer
in archives
if layer]
113 if step % interval == 0
or not occupied:
114 genome, birth = tuple(sample(rng)), step
117 source = occupied[int(rng.integers(len(occupied)))]
118 parent = source[int(rng.integers(len(source)))]
119 genome, birth = tuple(mutate(tuple(parent), rng)), parent.scores[
"alme_birth"]
120 fitness, descriptions = evaluate(genome)
121 descriptions = tuple(descriptions)
122 if len(descriptions) != len(archives):
123 raise ValueError(
"Return a descriptor vector for every layer.")
124 measured = tuple(_finite_vector(point,
"Layer descriptors", len(archive.features_domain))
125 for archive, point
in zip(archives, descriptions))
126 layer = bisect_right(limits, step - birth)
127 admissions[layer] += place(layer, step, genome, fitness, measured, birth)
128 return AgeLayeredResult(archives, budget, immigrants, tuple(admissions), tuple(promotions), expired)
Report the live layers, measurement budget, and age-driven migrations.