QDpy
Loading...
Searching...
No Matches
game.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Coevolve two sets of strategies with one behaviour archive per opponent."""
6
7from dataclasses import dataclass
8from math import isfinite
9from numbers import Real
10from operator import index
11from typing import Sequence
12import warnings
13
14import numpy as np
15from scipy.spatial.distance import cdist
16from sklearn.cluster import KMeans
17
18from qdpy.tools import iso_line_dd
19from .modern import _bounds, _positive_int
20from ._game_selection import _cluster_profiles, _nsga3_selection, _rank_selection
21
22__all__ = ["MatchResult", "GameElite", "GameRound", "GameResult", "game_search",
23 "GameTournament", "GameTournamentMetrics", "game_cross_play"]
24
25
26
27@dataclass(frozen=True)
29 """Finite fitness and descriptor vectors in (Red, Blue) order."""
30
31 fitness: tuple[float, float]
32 descriptors: tuple[Sequence[float], Sequence[float]]
33
34
35
36@dataclass(frozen=True)
38 """Store the measurements of a strategy against one opponent."""
39
40 genome: tuple[float, ...]
41 fitness: float
42 descriptors: tuple[float, ...]
43
44
45
46@dataclass(frozen=True)
48 """Snapshot of one round.
49
50 The slots of ``opponents`` and ``elites_by_opponent`` correspond.
51 Each representative retains the measurements used to select it.
52 """
53
54 side: str
55 opponents: tuple[tuple[float, ...], ...]
56 elites_by_opponent: tuple[tuple[GameElite, ...], ...]
57 representatives: tuple[GameElite, ...]
58
59
60
61@dataclass(frozen=True)
63 """Search and tournament attempts both include failed matches."""
64
65 rounds: tuple[GameRound, ...]
66 search_attempts: int
67 tournament_attempts: int
68 failed_attempts: int
69 stopped_for_budget: bool = False
70
71 @property
72 def total_attempts(self):
73 """Return the combined search and task-selection match cost."""
74 return self.search_attempts + self.tournament_attempts
75
76
77
78@dataclass(frozen=True)
80 """Describe the best win rate, worst-case payoff, collective expertise, and coverage."""
81
82 win_rate: float
83 robustness: float
84 expertise: float
85 coverage: float
86
87
88
89@dataclass(frozen=True)
91 """A read-only payoff matrix indexed by Red, Blue, and scoring side."""
92
93 fitness: np.ndarray
94 attempts: int
95 failed_attempts: int
96
97
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.
100
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.
106 """
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:
113 selected[:] = False
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)),
125 )
126
127
128def _scaled(points):
129 # Uniform scaling retains Euclidean comparisons and avoids overflow in
130 # squared distances and clustering for large finite descriptor values.
131 scale = np.max(np.abs(points))
132 return points / scale if scale else points
133
134
136 """Track a bounded set of centroids and the anchor elite of each cell."""
137
138 def __init__(self, capacity):
139 self.capacity = capacity
140 self.anchors = []
141 self.elites = []
142
143 def add(self, elite):
144 if not self.anchors:
145 self.anchors.append(elite)
146 self.elites.append(elite)
147 return
148
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]
154 if distance > 0 and len(self.anchors) < self.capacity:
155 self.anchors.append(elite)
156 self.elites.append(elite)
157 return
158 if distance > 0:
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]:
163 # Compare each member with the centroids outside the pair.
164 distances[first, second] = distances[second, first] = np.inf
165 replace = first if distances[first].min() < distances[second].min() else second
166 self.anchors[replace] = elite
167 self.elites[replace] = elite
168 self._restore_backups()
169 return
170 if elite.fitness > self.elites[closest].fitness:
171 self.elites[closest] = elite
172
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)):
177 if nearest != slot:
178 self.elites[slot] = self.anchors[slot]
179
180
181def _select_representatives(elites, count, rng):
182 # Stable sorting also keeps the first measurement on exact fitness ties.
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)))
186 if n_clusters == 1:
187 labels = np.zeros(len(points), dtype=int)
188 else:
189 seed = int(rng.integers(2**32))
190 labels = KMeans(n_clusters=n_clusters, n_init=10, random_state=seed).fit_predict(points)
191 clusters = {}
192 for label, elite in zip(labels, ranked):
193 clusters.setdefault(label, elite)
194 selected = {}
195 for elite in clusters.values():
196 selected.setdefault(elite.genome, elite)
197 for elite in ranked:
198 if len(selected) == count:
199 break
200 selected.setdefault(elite.genome, elite)
201 return tuple(selected.values())
202
203
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.")
207 elites = []
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))))
216 return tuple(elites)
217
218
219
220def game_cross_play(play, red, blue, *, repeats=1):
221 """Evaluate all Red and Blue pairings. Missing matchup scores are NaN.
222
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.
228 """
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):
239 scores = []
240 for _ in range(repeats):
241 try:
242 elites = _checked_match(play(first, second), (first, second), sizes)
243 except Exception as error:
244 failures += 1
245 warnings.warn(f"GAME cross-play match failed: {error}", stacklevel=2)
246 else:
247 sizes = tuple(len(elite.descriptors) for elite in elites)
248 scores.append([elite.fitness for elite in elites])
249 if len(scores) == repeats:
250 # Divide first to keep large finite payoffs representable.
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)
254
255
256
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.
262
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.
266
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.
285 """
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.")
307
308 rng = np.random.default_rng(seed)
309 expected_sizes = None
310 failed_attempts = 0
311
312 def sample(side):
313 return tuple(map(float, rng.uniform(*bounds[side], size=dimensions[side])))
314
315 def attempt(candidate, opponent, active_side):
316 nonlocal expected_sizes, failed_attempts
317 genomes = (candidate, opponent) if active_side == 0 else (opponent, candidate)
318 try:
319 elites = _checked_match(play(*genomes), genomes, expected_sizes)
320 except Exception as error:
321 failed_attempts += 1
322 warnings.warn(f"GAME match failed: {error}", stacklevel=3)
323 return None
324 if expected_sizes is None:
325 expected_sizes = tuple(len(elite.descriptors) for elite in elites)
326 return elites
327
328 opponents = tuple(sample(1) for _ in range(task_count))
329 bootstrap = ()
330 history = []
331 tournament_attempts = 0
332 search_attempts = 0
333 stopped_for_budget = False
334
335 def affordable(extra):
336 return match_budget is None or search_attempts + tournament_attempts + extra <= match_budget
337
338 def tournament(candidates):
339 nonlocal tournament_attempts
340 table = []
341 for elite in candidates:
342 row = []
343 for opponent in opponents:
344 tournament_attempts += 1
345 row.append(attempt(elite.genome, opponent, active))
346 table.append(row)
347 return table
348
349 for round_index in range(rounds):
350 active = round_index % 2
351 archives = [_GrowingArchive(cells_per_task) for _ in opponents]
352 for task, elite in bootstrap:
353 archives[task].add(elite)
354 for _ in range(matches_per_round):
355 search_attempts += 1
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)
360 else:
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]
372 if not elites:
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)
377 rows = ()
378 if not last and affordable(len(representatives) * len(opponents) + matches_per_round):
379 rows = tournament(representatives)
380 else:
381 unique = {}
382 for elite in sorted(elites, key=lambda entry: -entry.fitness):
383 unique.setdefault(elite.genome, elite)
384 candidates = tuple(unique.values())
385 rows = ()
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)]
389 if complete:
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]
395 else:
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]
399 else:
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))
403 if last:
404 break
405 if not rows or not affordable(matches_per_round):
406 stopped_for_budget = True
407 break
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.
Definition game.py:37
Completed GAME rounds and separately counted matches.
Definition game.py:62
The opponent-specific archives and selected strategies from one round.
Definition game.py:47
Compare a strategy group against an identical panel of opponents.
Definition game.py:79
Store all directional payoffs from a common Red versus Blue tournament.
Definition game.py:90
metrics(self, side, strategies=None, *, win_threshold=.5, clusters=4, seed=0)
Score a group of strategies using the whole tournament's reference panel.
Definition game.py:98
Record one match from both players' perspectives.
Definition game.py:28