Source code for qdpy.algorithms.game

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Generational Adversarial MAP-Elites for two-player games.

"""Coevolve two sets of strategies with one behaviour archive per opponent."""

from dataclasses import dataclass
from math import isfinite
from numbers import Real
from operator import index
from typing import Sequence
import warnings

import numpy as np
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans

from qdpy.tools import iso_line_dd
from .modern import _bounds, _positive_int
from ._game_selection import _cluster_profiles, _nsga3_selection, _rank_selection

__all__ = ["MatchResult", "GameElite", "GameRound", "GameResult", "game_search",
           "GameTournament", "GameTournamentMetrics", "game_cross_play"]


## @brief Record one match from both players' perspectives.
[docs] @dataclass(frozen=True) class MatchResult: """Finite fitness and descriptor vectors in (Red, Blue) order.""" fitness: tuple[float, float] descriptors: tuple[Sequence[float], Sequence[float]]
## @brief A strategy with fitness and behaviour against a single opponent.
[docs] @dataclass(frozen=True) class GameElite: """Store the measurements of a strategy against one opponent.""" genome: tuple[float, ...] fitness: float descriptors: tuple[float, ...]
## @brief The opponent-specific archives and selected strategies from one round.
[docs] @dataclass(frozen=True) class GameRound: """Snapshot of one round. The slots of ``opponents`` and ``elites_by_opponent`` correspond. Each representative retains the measurements used to select it. """ side: str opponents: tuple[tuple[float, ...], ...] elites_by_opponent: tuple[tuple[GameElite, ...], ...] representatives: tuple[GameElite, ...]
## @brief Completed GAME rounds and separately counted matches.
[docs] @dataclass(frozen=True) class GameResult: """Search and tournament attempts both include failed matches.""" rounds: tuple[GameRound, ...] search_attempts: int tournament_attempts: int failed_attempts: int stopped_for_budget: bool = False @property def total_attempts(self): """Return the combined search and task-selection match cost.""" return self.search_attempts + self.tournament_attempts
## @brief Compare a strategy group against an identical panel of opponents.
[docs] @dataclass(frozen=True) class GameTournamentMetrics: """Describe the best win rate, worst-case payoff, collective expertise, and coverage.""" win_rate: float robustness: float expertise: float coverage: float
## @brief Store all directional payoffs from a common Red versus Blue tournament.
[docs] @dataclass(frozen=True) class GameTournament: """A read-only payoff matrix indexed by Red, Blue, and scoring side.""" fitness: np.ndarray attempts: int failed_attempts: int ## @brief Score a group of strategies using the whole tournament's reference panel.
[docs] def metrics(self, side, strategies=None, *, win_threshold=.5, clusters=4, seed=0): """Use all opponents. Fit coverage clusters over all complete rows on this side. :param side: Either "red" or "blue". :param strategies: Optional indices into that side's strategies. :param win_threshold: A score must exceed this threshold to win. :param clusters: Maximum number of reference behavior clusters. :param seed: Seed for the reference clustering. """ if side not in ("red", "blue") or not isfinite(win_threshold): raise ValueError("Use a valid side and a finite win_threshold.") clusters = _positive_int(clusters, "clusters") matrix = self.fitness[:, :, 0] if side == "red" else self.fitness[:, :, 1].T selected = np.ones(len(matrix), dtype=bool) if strategies is not None: selected[:] = False selected[[index(strategy) for strategy in strategies]] = True valid = np.isfinite(matrix).all(axis=1) if not np.any(valid & selected): raise ValueError("The group needs at least one complete matchup profile.") labels = _cluster_profiles(matrix[valid], clusters, np.random.default_rng(seed)) group = matrix[valid & selected] return GameTournamentMetrics( float((group > win_threshold).mean(axis=1).max()), float(group.min(axis=1).max()), float(group.max(axis=0).min()), len(np.unique(labels[selected[valid]])) / len(np.unique(labels)), )
def _scaled(points): # Uniform scaling retains Euclidean comparisons and avoids overflow in # squared distances and clustering for large finite descriptor values. scale = np.max(np.abs(points)) return points / scale if scale else points class _GrowingArchive: """Track a bounded set of centroids and the anchor elite of each cell.""" def __init__(self, capacity): self.capacity = capacity self.anchors = [] self.elites = [] def add(self, elite): if not self.anchors: self.anchors.append(elite) self.elites.append(elite) return points = _scaled(np.array([anchor.descriptors for anchor in self.anchors] + [elite.descriptors])) centres, new = points[:-1], points[-1:] distance_to_new = cdist(new, centres)[0] closest = int(np.argmin(distance_to_new)) distance = distance_to_new[closest] if distance > 0 and len(self.anchors) < self.capacity: self.anchors.append(elite) self.elites.append(elite) return if distance > 0: distances = cdist(centres, centres) np.fill_diagonal(distances, np.inf) first, second = np.unravel_index(distances.argmin(), distances.shape) if distance > distances[first, second]: # Compare each member with the centroids outside the pair. distances[first, second] = distances[second, first] = np.inf replace = first if distances[first].min() < distances[second].min() else second self.anchors[replace] = elite self.elites[replace] = elite self._restore_backups() return if elite.fitness > self.elites[closest].fitness: self.elites[closest] = elite def _restore_backups(self): points = _scaled(np.array([entry.descriptors for entry in self.anchors + self.elites])) centres, descriptors = np.split(points, 2) for slot, nearest in enumerate(cdist(descriptors, centres).argmin(axis=1)): if nearest != slot: self.elites[slot] = self.anchors[slot] def _select_representatives(elites, count, rng): # Stable sorting also keeps the first measurement on exact fitness ties. ranked = sorted(elites, key=lambda elite: -elite.fitness) points = _scaled(np.asarray([elite.descriptors for elite in ranked])) n_clusters = min(count, len(np.unique(points, axis=0))) if n_clusters == 1: labels = np.zeros(len(points), dtype=int) else: seed = int(rng.integers(2**32)) labels = KMeans(n_clusters=n_clusters, n_init=10, random_state=seed).fit_predict(points) clusters = {} for label, elite in zip(labels, ranked): clusters.setdefault(label, elite) selected = {} for elite in clusters.values(): selected.setdefault(elite.genome, elite) for elite in ranked: if len(selected) == count: break selected.setdefault(elite.genome, elite) return tuple(selected.values()) def _checked_match(result, genomes, expected_sizes): if not isinstance(result, MatchResult) or len(result.fitness) != 2 or len(result.descriptors) != 2: raise ValueError("Return a MatchResult containing the fitness and descriptors of both players.") elites = [] for side, (genome, fitness, features) in enumerate(zip(genomes, result.fitness, result.descriptors)): features = np.asarray(features) if (features.ndim != 1 or not features.size or not np.isfinite(features).all() or np.iscomplexobj(features) or not isinstance(fitness, Real) or not isfinite(fitness)): raise ValueError("Each side needs finite scalar fitness and a finite nonempty descriptor vector.") if expected_sizes is not None and features.size != expected_sizes[side]: raise ValueError("The descriptor dimension for each side must stay fixed across matches.") elites.append(GameElite(genome, float(fitness), tuple(map(float, features)))) return tuple(elites) ## @brief Evaluate two strategy pools against one another for cross-variant reporting.
[docs] def game_cross_play(play, red, blue, *, repeats=1): """Evaluate all Red and Blue pairings. Missing matchup scores are NaN. :param play: Match evaluator with the same contract as game_search. :param red: Red strategy genomes in input order. :param blue: Blue strategy genomes in input order. :param repeats: Matches to average for each pair. A failed replicate makes that pair incomplete and removes the affected profile from metric calculations. """ if not callable(play): raise TypeError("play must be callable.") repeats = _positive_int(repeats, "repeats") red, blue = tuple(map(tuple, red)), tuple(map(tuple, blue)) if not red or not blue: raise ValueError("Supply at least one strategy for each side.") fitness = np.full((len(red), len(blue), 2), np.nan) failures, sizes = 0, None for i, first in enumerate(red): for j, second in enumerate(blue): scores = [] for _ in range(repeats): try: elites = _checked_match(play(first, second), (first, second), sizes) except Exception as error: failures += 1 warnings.warn(f"GAME cross-play match failed: {error}", stacklevel=2) else: sizes = tuple(len(elite.descriptors) for elite in elites) scores.append([elite.fitness for elite in elites]) if len(scores) == repeats: # Divide first to keep large finite payoffs representable. fitness[i, j] = (np.asarray(scores) / repeats).sum(axis=0) fitness.setflags(write=False) return GameTournament(fitness, len(red) * len(blue) * repeats, failures)
## @brief Run GAME with caller-supplied fitness and descriptors.