51 """Maintain one Grid or CVTGrid per class and one team population per task.
53 Each mainland team has exactly one member of every class. Island
54 search uses bounded numeric variation and caller-defined descriptors.
55 Mainlands use elitism, tournament selection and within-class crossover.
56 On migration rounds, remeasure the members of the best mainland teams
57 on their islands. Then allocate new island exports to mainland slots
58 using a role-specific softmax learned from measured contributions.
60 :param islands: Mapping of role names to distinct empty native grids
61 with one explicit signed fitness objective.
62 :param tasks: Ordered iterable of at least two distinct mainland task IDs.
63 :param role_sizes: Mapping from the same roles to their genome lengths.
64 :param role_bounds: Optional mapping of roles to finite genome bounds.
65 The default is [0, 1] for each role.
66 :param population_size: Maximum teams per mainland.
67 :param elite_size: Teams retained in each mainland before selecting new offspring.
68 :param island_offspring: Local search evaluations per role and generation.
69 :param migration_period: Mainland generations between migration rounds.
70 :param migrants_per_role: Island exports per role on each migration round.
71 Defaults to population_size minus elite_size.
72 :param allocation_rate: Positive learning rate for mainland allocation logits.
73 :param entropy: Nonnegative regularization toward spread-out task allocation.
74 :param iso_sigma: Independent Gaussian variation scale on islands.
75 :param line_sigma: Shared Iso+LineDD direction scale on islands.
76 :param seed: Root seed for proposal, crossover and migration streams.
79 def __init__(self, islands, tasks, *, role_sizes, role_bounds=None, population_size=8,
80 elite_size=2, island_offspring=4, migration_period=3, migrants_per_role=None,
81 allocation_rate=.1, entropy=.01, iso_sigma=.05, line_sigma=.2, seed=0):
82 if (
not isinstance(islands, Mapping)
or len(islands) < 2
83 or len({id(grid)
for grid
in islands.values()}) != len(islands)):
84 raise ValueError(
"Supply at least two role names with distinct island archives.")
85 if not isinstance(role_sizes, Mapping)
or role_sizes.keys() != islands.keys():
86 raise ValueError(
"Supply a genome length for every island role.")
87 if role_bounds
is not None and (
not isinstance(role_bounds, Mapping)
or role_bounds.keys() != islands.keys()):
88 raise ValueError(
"Supply bounds for every island role.")
89 if isinstance(tasks, (str, bytes)):
90 raise ValueError(
"Supply an ordered collection of task IDs.")
91 self.
tasks = tuple(tasks)
93 raise ValueError(
"Supply at least two distinct mainland tasks.")
94 for archive
in islands.values():
95 _validate_grid(archive)
96 if not archive.fitness_weights
or archive.fitness_score_names
or archive.features_score_names:
97 raise ValueError(
"Use direct island fitness and descriptors with explicit objective weights.")
99 self.
roles = tuple(islands)
101 self.
_sizes = tuple(_positive_int(role_sizes[r],
"role size")
for r
in self.
roles)
102 bounds = ((0., 1.)
for _
in self.
roles)
if role_bounds
is None else (role_bounds[r]
for r
in self.
roles)
103 self.
_bounds = tuple(_variation_settings(interval, iso_sigma, line_sigma)
for interval
in bounds)
104 if not all(np.isfinite(high - low)
for low, high
in self.
_bounds):
105 raise ValueError(
"Genome bounds must have finite spans.")
106 self.
_population = _positive_int(population_size,
"population_size")
107 self.
_elites = _positive_int(elite_size,
"elite_size")
109 raise ValueError(
"elite_size must be smaller than population_size.")
110 self.
_local = _positive_int(island_offspring,
"island_offspring")
111 self.
_period = _positive_int(migration_period,
"migration_period")
113 self.
_migrants = available
if migrants_per_role
is None else _positive_int(migrants_per_role,
116 raise ValueError(
"Exports per role must fit the available mainland slots.")
117 if not (0 < allocation_rate < np.inf
and 0 <= entropy < np.inf):
118 raise ValueError(
"Use finite positive allocation_rate and finite nonnegative entropy.")
125 np.random.default_rng(stream)
for stream
in np.random.SeedSequence(seed).spawn(3))
129 """Return a shallow copy mapping role names to live island archives."""
134 """Return the measured teams for each task in descending fitness order."""
139 """Return the current mainland selection probabilities for each island."""
140 return {role: dict(zip(self.
tasks, map(float, values)))
141 for role, values
in zip(self.
roles, softmax(self.
_logits, axis=1))}
145 """Return cumulative attempted evaluation counts and migrations."""
148 def _elites_by_task(self):
151 def _migration_due(self):
152 n = self.
_counts[
"generations"]
153 return n > 0
and n % self.
_period == 0
155 def _costs(self, retained, migrate):
156 incumbents = sum(map(len, retained.values()))
157 return (self.
_local * len(self.
roles) + (incumbents * len(self.
roles)
if migrate
else 0),
162 """Return the island and team budget needed for one further generation."""
165 def _sample_role(self, role_index, rng):
168 return tuple(archive[rng.integers(len(archive))])
169 return tuple(map(float, rng.uniform(*self.
_bounds[role_index], size=self.
_sizes[role_index])))
171 def _measure_role(self, evaluate, role, genome, *, returning=False):
172 self.
_counts[
"island_evaluations"] += 1
173 self.
_counts[
"returning_evaluations"] += returning
174 result = evaluate(role, genome)
176 self.
_counts[
"failed_island_evaluations"] += 1
179 value, descriptor = (np.asarray(field, dtype=float)
for field
in result)
180 if (value.shape
not in ((), (1,))
or not np.isfinite(value).all()
181 or descriptor.shape != (len(archive.features_domain),)
or not np.isfinite(descriptor).all()):
182 raise ValueError(
"Island evaluations must supply finite scalar fitness and a matching descriptor.")
183 fitness, features = (float(value.item()),), tuple(map(float, descriptor))
184 if (archive.in_bounds(fitness, archive.fitness_domain)
185 and archive.in_bounds(features, archive.features_domain)):
186 cell = archive.index_grid(features)
187 if archive.solutions[cell]
or archive.free >= 1:
191 def _advance_islands(self, evaluate):
192 for i, role
in enumerate(self.
roles):
194 for _
in range(self.
_local):
198 child = iso_line_dd(first, second, bounds=self.
_bounds[i], iso_sigma=self.
_iso_sigma,
200 first = tuple(map(float, child))
203 def _update_allocation(self):
204 estimates = [np.mean([team.contributions
for team
in teams], axis=0)
if teams
else None
206 present = [estimate
for estimate
in estimates
if estimate
is not None]
209 average = np.mean(present, axis=0)
210 credit = np.stack([estimate
if estimate
is not None else average
for estimate
in estimates], axis=1)
211 log_probabilities = log_softmax(self.
_logits, axis=1)
212 probabilities = np.exp(log_probabilities)
213 utility = credit - self.
_entropy * log_probabilities
214 gradient = probabilities * (utility - (utility * probabilities).sum(axis=1, keepdims=
True))
216 if not np.isfinite(logits).all():
217 raise ValueError(
"Role contributions made the allocation logits nonfinite.")
220 def _migration_slots(self, asks):
222 for role_index
in range(len(self.
roles)):
224 available = [list(range(count))
for count
in asks]
226 eligible = [i
for i, slot
in enumerate(available)
if slot]
227 task_index = rng.choice(eligible, p=softmax(self.
_logits[role_index, eligible]))
228 selected = available[task_index].pop(rng.integers(len(available[task_index])))
229 slots.add((task_index, selected, role_index))
232 def _offspring(self, task, elites, slots):
237 champion = elites[rng.integers(len(elites))]
239 contender = population[min(rng.integers(len(population), size=2))]
241 tuple(map(float, np.where(rng.random(self.
_sizes[i]) < .5, first, second)))
242 for i, (first, second)
in enumerate(zip(champion.genomes, contender.genomes)))
244 def _measure_team(self, evaluate, task, genomes):
245 self.
_counts[
"team_evaluations"] += 1
246 result = evaluate(task, genomes)
248 self.
_counts[
"failed_team_evaluations"] += 1
250 fitness, contributions = (np.asarray(field, dtype=float)
for field
in result)
251 if (fitness.shape
not in ((), (1,))
or not np.isfinite(fitness).all()
252 or contributions.shape != (len(self.
roles),)
or not np.isfinite(contributions).all()):
253 raise ValueError(
"Team evaluations must supply finite scalar fitness and one contribution per role.")
254 return AIMTeam(genomes, float(fitness.item()), tuple(map(float, contributions)))
256 def _advance_mainlands(self, evaluate, retained, migrate):
260 for task_index, (task, count)
in enumerate(zip(self.
tasks, asks)):
261 survivors = list(retained[task])
262 for slot
in range(count):
263 exports = {i
for i, role
in enumerate(self.
roles)
264 if (task_index, slot, i)
in migration
and len(self.
_islands[role])}
265 genomes = self.
_offspring(task, retained[task], exports)
266 self.
_counts[
"exported_roles"] += len(exports)
268 if measured
is not None:
269 survivors.append(measured)
270 populations[task] = tuple(sorted(survivors, key=
lambda team: team.fitness, reverse=
True))
274 def run(self, evaluate_role, evaluate_team, *, island_budget, team_budget):
275 """Continue training and return cumulative AIMStats.
277 evaluate_role(role, genome) returns (fitness, descriptors).
278 evaluate_team(task, genomes) returns (fitness, role contributions).
279 Either evaluator can return None to report a failed call. The team
280 fitness is maximized. Retained teams keep their original measurements.
282 island_budget = _positive_int(island_budget,
"island_budget")
283 team_budget = _positive_int(team_budget,
"team_budget")
284 if not callable(evaluate_role)
or not callable(evaluate_team):
285 raise TypeError(
"Supply both island and team evaluators.")
288 island_cost, team_cost = self.
_costs(retained, migrate)
289 if island_cost > island_budget
or team_cost > team_budget:
292 for elites
in retained.values():
294 for role, genome
in zip(self.
roles, elite.genomes):
295 self.
_measure_role(evaluate_role, role, genome, returning=
True)
299 island_budget -= island_cost
300 team_budget -= team_cost
301 self.
_counts[
"generations"] += 1
302 self.
_counts[
"migration_rounds"] += migrate