# 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.
[docs]
def game_search(play, *, dimensions, rounds, matches_per_round,
bounds=((0.0, 1.0), (0.0, 1.0)), task_count=4,
cells_per_task=8, warmup_elites=8, seed=0,
task_selection="behavior", match_budget=None):
"""Coevolve two sides by alternating rounds of opponent-specific search.
An uncapped run completes ``rounds * matches_per_round`` search
attempts. Between rounds, a separate tournament provides the new
active side with measurements against its new opponents.
:param play: Callable taking immutable Red and Blue genomes in that
order and returning a MatchResult. Each side maximises its fitness.
:param dimensions: Number of real coordinates for Red and Blue.
:param rounds: Alternating search rounds starting with Red.
:param matches_per_round: Search attempts in one round.
:param bounds: One shared coordinate interval for each side, Red first.
:param task_count: Initial number and later maximum number of opponents.
:param cells_per_task: Maximum retained niches per opponent, at least two.
:param warmup_elites: Minimum total elites before applying Iso+LineDD.
:param seed: Seed for proposals, opponent draws and clustering.
:param task_selection: "behavior" for the original selector, "ranking"
for tournament matchup profiles, or "pareto" for NSGA-III selection
over the raw matchup payoffs.
:param match_budget: Optional hard limit on search and tournament calls.
If it cannot cover a selection tournament, the last round reports
behavior-selected representatives. Inspect stopped_for_budget.
:returns: A GameResult with the round archives and attempt counts.
:raises RuntimeError: If a round yields no valid elite.
"""
red_dim, blue_dim = dimensions
dimensions = (_positive_int(red_dim, "Red dimension"), _positive_int(blue_dim, "Blue dimension"))
red_bounds, blue_bounds = bounds
bounds = (_bounds(tuple(map(float, red_bounds))), _bounds(tuple(map(float, blue_bounds))))
if any(not isfinite(upper - lower) for lower, upper in bounds):
raise ValueError("Each genome interval must have a finite span.")
rounds = _positive_int(rounds, "rounds")
matches_per_round = _positive_int(matches_per_round, "matches_per_round")
task_count = _positive_int(task_count, "task_count")
cells_per_task = _positive_int(cells_per_task, "cells_per_task")
if cells_per_task < 2:
raise ValueError("cells_per_task must be at least two.")
warmup_elites = _positive_int(warmup_elites, "warmup_elites")
if not callable(play):
raise TypeError("play must be callable.")
if task_selection not in ("behavior", "ranking", "pareto"):
raise ValueError("task_selection must be behavior, ranking or pareto.")
if match_budget is not None:
match_budget = _positive_int(match_budget, "match_budget")
if match_budget < matches_per_round:
raise ValueError("match_budget must cover one search round.")
rng = np.random.default_rng(seed)
expected_sizes = None
failed_attempts = 0
def sample(side):
return tuple(map(float, rng.uniform(*bounds[side], size=dimensions[side])))
def attempt(candidate, opponent, active_side):
nonlocal expected_sizes, failed_attempts
genomes = (candidate, opponent) if active_side == 0 else (opponent, candidate)
try:
elites = _checked_match(play(*genomes), genomes, expected_sizes)
except Exception as error:
failed_attempts += 1
warnings.warn(f"GAME match failed: {error}", stacklevel=3)
return None
if expected_sizes is None:
expected_sizes = tuple(len(elite.descriptors) for elite in elites)
return elites
opponents = tuple(sample(1) for _ in range(task_count))
bootstrap = ()
history = []
tournament_attempts = 0
search_attempts = 0
stopped_for_budget = False
def affordable(extra):
return match_budget is None or search_attempts + tournament_attempts + extra <= match_budget
def tournament(candidates):
nonlocal tournament_attempts
table = []
for elite in candidates:
row = []
for opponent in opponents:
tournament_attempts += 1
row.append(attempt(elite.genome, opponent, active))
table.append(row)
return table
for round_index in range(rounds):
active = round_index % 2
archives = [_GrowingArchive(cells_per_task) for _ in opponents]
for task, elite in bootstrap:
archives[task].add(elite)
for _ in range(matches_per_round):
search_attempts += 1
task = int(rng.integers(len(opponents)))
live_elites = [elite for archive in archives for elite in archive.elites]
if len(live_elites) < warmup_elites:
candidate = sample(active)
else:
parents = rng.integers(len(live_elites), size=2)
first, second = (live_elites[parent].genome for parent in parents)
lower, upper = bounds[active]
child = iso_line_dd(first, second, bounds=(lower, upper),
iso_sigma=0.01 * (upper - lower), rng=rng)
candidate = tuple(map(float, child))
match = attempt(candidate, opponents[task], active)
if match is not None:
archives[task].add(match[active])
elites_by_opponent = tuple(tuple(archive.elites) for archive in archives)
elites = [elite for group in elites_by_opponent for elite in group]
if not elites:
raise RuntimeError(f"GAME round {round_index + 1} has no valid elite.")
last = round_index + 1 == rounds
if task_selection == "behavior":
representatives = _select_representatives(elites, task_count, rng)
rows = ()
if not last and affordable(len(representatives) * len(opponents) + matches_per_round):
rows = tournament(representatives)
else:
unique = {}
for elite in sorted(elites, key=lambda entry: -entry.fitness):
unique.setdefault(elite.genome, elite)
candidates = tuple(unique.values())
rows = ()
if affordable(len(candidates) * len(opponents)):
table = tournament(candidates)
complete = [i for i, row in enumerate(table) if all(match is not None for match in row)]
if complete:
fitness = np.asarray([[match[active].fitness for match in table[i]] for i in complete])
select = _rank_selection if task_selection == "ranking" else _nsga3_selection
positions = [complete[i] for i in select(fitness, min(task_count, len(complete)), rng)]
representatives = tuple(candidates[i] for i in positions)
rows = [table[i] for i in positions]
else:
representatives = _select_representatives(elites, task_count, rng)
by_genome = {elite.genome: row for elite, row in zip(candidates, table)}
rows = [by_genome[elite.genome] for elite in representatives]
else:
representatives = _select_representatives(elites, task_count, rng)
stopped_for_budget = True
history.append(GameRound(("red", "blue")[active], opponents, elites_by_opponent, representatives))
if last:
break
if not rows or not affordable(matches_per_round):
stopped_for_budget = True
break
bootstrap = [(slot, match[1 - active]) for slot, row in enumerate(rows)
for match in row if match is not None]
opponents = tuple(elite.genome for elite in representatives)
return GameResult(tuple(history), search_attempts, tournament_attempts, failed_attempts, stopped_for_budget)