5"""Coevolve two sets of strategies with one behaviour archive per opponent."""
7from dataclasses
import dataclass
8from math
import isfinite
9from numbers
import Real
10from operator
import index
11from typing
import Sequence
15from scipy.spatial.distance
import cdist
16from sklearn.cluster
import KMeans
19from .modern
import _bounds, _positive_int
20from ._game_selection
import _cluster_profiles, _nsga3_selection, _rank_selection
22__all__ = [
"MatchResult",
"GameElite",
"GameRound",
"GameResult",
"game_search",
23 "GameTournament",
"GameTournamentMetrics",
"game_cross_play"]
27@dataclass(frozen=True)
29 """Finite fitness and descriptor vectors in (Red, Blue) order."""
31 fitness: tuple[float, float]
32 descriptors: tuple[Sequence[float], Sequence[float]]
36@dataclass(frozen=True)
38 """Store the measurements of a strategy against one opponent."""
40 genome: tuple[float, ...]
42 descriptors: tuple[float, ...]
46@dataclass(frozen=True)
48 """Snapshot of one round.
50 The slots of ``opponents`` and ``elites_by_opponent`` correspond.
51 Each representative retains the measurements used to select it.
55 opponents: tuple[tuple[float, ...], ...]
56 elites_by_opponent: tuple[tuple[GameElite, ...], ...]
57 representatives: tuple[GameElite, ...]
61@dataclass(frozen=True)
63 """Search and tournament attempts both include failed matches."""
65 rounds: tuple[GameRound, ...]
67 tournament_attempts: int
69 stopped_for_budget: bool =
False
73 """Return the combined search and task-selection match cost."""
74 return self.search_attempts + self.tournament_attempts
78@dataclass(frozen=True)
80 """Describe the best win rate, worst-case payoff, collective expertise, and coverage."""
89@dataclass(frozen=True)
91 """A read-only payoff matrix indexed by Red, Blue, and scoring side."""
98 def metrics(self, side, strategies=None, *, win_threshold=.5, clusters=4, seed=0):
99 """Use all opponents. Fit coverage clusters over all complete rows on this side.
101 :param side: Either "red" or "blue".
102 :param strategies: Optional indices into that side's strategies.
103 :param win_threshold: A score must exceed this threshold to win.
104 :param clusters: Maximum number of reference behavior clusters.
105 :param seed: Seed for the reference clustering.
107 if side
not in (
"red",
"blue")
or not isfinite(win_threshold):
108 raise ValueError(
"Use a valid side and a finite win_threshold.")
109 clusters = _positive_int(clusters,
"clusters")
110 matrix = self.
fitness[:, :, 0]
if side ==
"red" else self.
fitness[:, :, 1].T
111 selected = np.ones(len(matrix), dtype=bool)
112 if strategies
is not None:
114 selected[[index(strategy)
for strategy
in strategies]] =
True
115 valid = np.isfinite(matrix).all(axis=1)
116 if not np.any(valid & selected):
117 raise ValueError(
"The group needs at least one complete matchup profile.")
118 labels = _cluster_profiles(matrix[valid], clusters, np.random.default_rng(seed))
119 group = matrix[valid & selected]
121 float((group > win_threshold).mean(axis=1).max()),
122 float(group.min(axis=1).max()),
123 float(group.max(axis=0).min()),
124 len(np.unique(labels[selected[valid]])) / len(np.unique(labels)),
131 scale = np.max(np.abs(points))
132 return points / scale
if scale
else points
136 """Track a bounded set of centroids and the anchor elite of each cell."""
138 def __init__(self, capacity):
143 def add(self, elite):
149 points = _scaled(np.array([anchor.descriptors
for anchor
in self.
anchors] + [elite.descriptors]))
150 centres, new = points[:-1], points[-1:]
151 distance_to_new = cdist(new, centres)[0]
152 closest = int(np.argmin(distance_to_new))
153 distance = distance_to_new[closest]
159 distances = cdist(centres, centres)
160 np.fill_diagonal(distances, np.inf)
161 first, second = np.unravel_index(distances.argmin(), distances.shape)
162 if distance > distances[first, second]:
164 distances[first, second] = distances[second, first] = np.inf
165 replace = first
if distances[first].min() < distances[second].min()
else second
167 self.
elites[replace] = elite
170 if elite.fitness > self.
elites[closest].fitness:
171 self.
elites[closest] = elite
173 def _restore_backups(self):
174 points = _scaled(np.array([entry.descriptors
for entry
in self.
anchors + self.
elites]))
175 centres, descriptors = np.split(points, 2)
176 for slot, nearest
in enumerate(cdist(descriptors, centres).argmin(axis=1)):
181def _select_representatives(elites, count, rng):
183 ranked = sorted(elites, key=
lambda elite: -elite.fitness)
184 points = _scaled(np.asarray([elite.descriptors
for elite
in ranked]))
185 n_clusters = min(count, len(np.unique(points, axis=0)))
187 labels = np.zeros(len(points), dtype=int)
189 seed = int(rng.integers(2**32))
190 labels = KMeans(n_clusters=n_clusters, n_init=10, random_state=seed).fit_predict(points)
192 for label, elite
in zip(labels, ranked):
193 clusters.setdefault(label, elite)
195 for elite
in clusters.values():
196 selected.setdefault(elite.genome, elite)
198 if len(selected) == count:
200 selected.setdefault(elite.genome, elite)
201 return tuple(selected.values())
204def _checked_match(result, genomes, expected_sizes):
205 if not isinstance(result, MatchResult)
or len(result.fitness) != 2
or len(result.descriptors) != 2:
206 raise ValueError(
"Return a MatchResult containing the fitness and descriptors of both players.")
208 for side, (genome, fitness, features)
in enumerate(zip(genomes, result.fitness, result.descriptors)):
209 features = np.asarray(features)
210 if (features.ndim != 1
or not features.size
or not np.isfinite(features).all()
211 or np.iscomplexobj(features)
or not isinstance(fitness, Real)
or not isfinite(fitness)):
212 raise ValueError(
"Each side needs finite scalar fitness and a finite nonempty descriptor vector.")
213 if expected_sizes
is not None and features.size != expected_sizes[side]:
214 raise ValueError(
"The descriptor dimension for each side must stay fixed across matches.")
215 elites.append(
GameElite(genome, float(fitness), tuple(map(float, features))))
220def game_cross_play(play, red, blue, *, repeats=1):
221 """Evaluate all Red and Blue pairings. Missing matchup scores are NaN.
223 :param play: Match evaluator with the same contract as game_search.
224 :param red: Red strategy genomes in input order.
225 :param blue: Blue strategy genomes in input order.
226 :param repeats: Matches to average for each pair. A failed replicate makes
227 that pair incomplete and removes the affected profile from metric calculations.
229 if not callable(play):
230 raise TypeError(
"play must be callable.")
231 repeats = _positive_int(repeats,
"repeats")
232 red, blue = tuple(map(tuple, red)), tuple(map(tuple, blue))
233 if not red
or not blue:
234 raise ValueError(
"Supply at least one strategy for each side.")
235 fitness = np.full((len(red), len(blue), 2), np.nan)
236 failures, sizes = 0,
None
237 for i, first
in enumerate(red):
238 for j, second
in enumerate(blue):
240 for _
in range(repeats):
242 elites = _checked_match(play(first, second), (first, second), sizes)
243 except Exception
as error:
245 warnings.warn(f
"GAME cross-play match failed: {error}", stacklevel=2)
247 sizes = tuple(len(elite.descriptors)
for elite
in elites)
248 scores.append([elite.fitness
for elite
in elites])
249 if len(scores) == repeats:
251 fitness[i, j] = (np.asarray(scores) / repeats).sum(axis=0)
252 fitness.setflags(write=
False)
253 return GameTournament(fitness, len(red) * len(blue) * repeats, failures)
257def game_search(play, *, dimensions, rounds, matches_per_round,
258 bounds=((0.0, 1.0), (0.0, 1.0)), task_count=4,
259 cells_per_task=8, warmup_elites=8, seed=0,
260 task_selection=
"behavior", match_budget=
None):
261 """Coevolve two sides by alternating rounds of opponent-specific search.
263 An uncapped run completes ``rounds * matches_per_round`` search
264 attempts. Between rounds, a separate tournament provides the new
265 active side with measurements against its new opponents.
267 :param play: Callable taking immutable Red and Blue genomes in that
268 order and returning a MatchResult. Each side maximises its fitness.
269 :param dimensions: Number of real coordinates for Red and Blue.
270 :param rounds: Alternating search rounds starting with Red.
271 :param matches_per_round: Search attempts in one round.
272 :param bounds: One shared coordinate interval for each side, Red first.
273 :param task_count: Initial number and later maximum number of opponents.
274 :param cells_per_task: Maximum retained niches per opponent, at least two.
275 :param warmup_elites: Minimum total elites before applying Iso+LineDD.
276 :param seed: Seed for proposals, opponent draws and clustering.
277 :param task_selection: "behavior" for the original selector, "ranking"
278 for tournament matchup profiles, or "pareto" for NSGA-III selection
279 over the raw matchup payoffs.
280 :param match_budget: Optional hard limit on search and tournament calls.
281 If it cannot cover a selection tournament, the last round reports
282 behavior-selected representatives. Inspect stopped_for_budget.
283 :returns: A GameResult with the round archives and attempt counts.
284 :raises RuntimeError: If a round yields no valid elite.
286 red_dim, blue_dim = dimensions
287 dimensions = (_positive_int(red_dim,
"Red dimension"), _positive_int(blue_dim,
"Blue dimension"))
288 red_bounds, blue_bounds = bounds
289 bounds = (_bounds(tuple(map(float, red_bounds))), _bounds(tuple(map(float, blue_bounds))))
290 if any(
not isfinite(upper - lower)
for lower, upper
in bounds):
291 raise ValueError(
"Each genome interval must have a finite span.")
292 rounds = _positive_int(rounds,
"rounds")
293 matches_per_round = _positive_int(matches_per_round,
"matches_per_round")
294 task_count = _positive_int(task_count,
"task_count")
295 cells_per_task = _positive_int(cells_per_task,
"cells_per_task")
296 if cells_per_task < 2:
297 raise ValueError(
"cells_per_task must be at least two.")
298 warmup_elites = _positive_int(warmup_elites,
"warmup_elites")
299 if not callable(play):
300 raise TypeError(
"play must be callable.")
301 if task_selection
not in (
"behavior",
"ranking",
"pareto"):
302 raise ValueError(
"task_selection must be behavior, ranking or pareto.")
303 if match_budget
is not None:
304 match_budget = _positive_int(match_budget,
"match_budget")
305 if match_budget < matches_per_round:
306 raise ValueError(
"match_budget must cover one search round.")
308 rng = np.random.default_rng(seed)
309 expected_sizes =
None
313 return tuple(map(float, rng.uniform(*bounds[side], size=dimensions[side])))
315 def attempt(candidate, opponent, active_side):
316 nonlocal expected_sizes, failed_attempts
317 genomes = (candidate, opponent)
if active_side == 0
else (opponent, candidate)
319 elites = _checked_match(play(*genomes), genomes, expected_sizes)
320 except Exception
as error:
322 warnings.warn(f
"GAME match failed: {error}", stacklevel=3)
324 if expected_sizes
is None:
325 expected_sizes = tuple(len(elite.descriptors)
for elite
in elites)
328 opponents = tuple(sample(1)
for _
in range(task_count))
331 tournament_attempts = 0
333 stopped_for_budget =
False
335 def affordable(extra):
336 return match_budget
is None or search_attempts + tournament_attempts + extra <= match_budget
338 def tournament(candidates):
339 nonlocal tournament_attempts
341 for elite
in candidates:
343 for opponent
in opponents:
344 tournament_attempts += 1
345 row.append(attempt(elite.genome, opponent, active))
349 for round_index
in range(rounds):
350 active = round_index % 2
352 for task, elite
in bootstrap:
353 archives[task].add(elite)
354 for _
in range(matches_per_round):
356 task = int(rng.integers(len(opponents)))
357 live_elites = [elite
for archive
in archives
for elite
in archive.elites]
358 if len(live_elites) < warmup_elites:
359 candidate = sample(active)
361 parents = rng.integers(len(live_elites), size=2)
362 first, second = (live_elites[parent].genome
for parent
in parents)
363 lower, upper = bounds[active]
364 child = iso_line_dd(first, second, bounds=(lower, upper),
365 iso_sigma=0.01 * (upper - lower), rng=rng)
366 candidate = tuple(map(float, child))
367 match = attempt(candidate, opponents[task], active)
368 if match
is not None:
369 archives[task].add(match[active])
370 elites_by_opponent = tuple(tuple(archive.elites)
for archive
in archives)
371 elites = [elite
for group
in elites_by_opponent
for elite
in group]
373 raise RuntimeError(f
"GAME round {round_index + 1} has no valid elite.")
374 last = round_index + 1 == rounds
375 if task_selection ==
"behavior":
376 representatives = _select_representatives(elites, task_count, rng)
378 if not last
and affordable(len(representatives) * len(opponents) + matches_per_round):
379 rows = tournament(representatives)
382 for elite
in sorted(elites, key=
lambda entry: -entry.fitness):
383 unique.setdefault(elite.genome, elite)
384 candidates = tuple(unique.values())
386 if affordable(len(candidates) * len(opponents)):
387 table = tournament(candidates)
388 complete = [i
for i, row
in enumerate(table)
if all(match
is not None for match
in row)]
390 fitness = np.asarray([[match[active].fitness
for match
in table[i]]
for i
in complete])
391 select = _rank_selection
if task_selection ==
"ranking" else _nsga3_selection
392 positions = [complete[i]
for i
in select(fitness, min(task_count, len(complete)), rng)]
393 representatives = tuple(candidates[i]
for i
in positions)
394 rows = [table[i]
for i
in positions]
396 representatives = _select_representatives(elites, task_count, rng)
397 by_genome = {elite.genome: row
for elite, row
in zip(candidates, table)}
398 rows = [by_genome[elite.genome]
for elite
in representatives]
400 representatives = _select_representatives(elites, task_count, rng)
401 stopped_for_budget =
True
402 history.append(
GameRound((
"red",
"blue")[active], opponents, elites_by_opponent, representatives))
405 if not rows
or not affordable(matches_per_round):
406 stopped_for_budget =
True
408 bootstrap = [(slot, match[1 - active])
for slot, row
in enumerate(rows)
409 for match
in row
if match
is not None]
410 opponents = tuple(elite.genome
for elite
in representatives)
411 return GameResult(tuple(history), search_attempts, tournament_attempts, failed_attempts, stopped_for_budget)
A strategy with fitness and behaviour against a single opponent.
Completed GAME rounds and separately counted matches.
The opponent-specific archives and selected strategies from one round.
Compare a strategy group against an identical panel of opponents.
Store all directional payoffs from a common Red versus Blue tournament.
metrics(self, side, strategies=None, *, win_threshold=.5, clusters=4, seed=0)
Score a group of strategies using the whole tournament's reference panel.
Record one match from both players' perspectives.