Source code for qdpy.algorithms.adhoc_cooperation

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Self-play illumination and cross-play response tables for ad hoc cooperation.
# @see https://doi.org/10.1109/TG.2022.3169168

"""Evolve self-play strategies and select cooperative responses to observed partners."""

from dataclasses import dataclass
from math import isfinite
from operator import index

import numpy as np

from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid

__all__ = ["CooperativeQDResult", "PartnerResponseTable", "cooperative_map_elites", "build_partner_responses"]


## @brief Self-play repertoire and separate policy and match counts.
[docs] @dataclass(frozen=True) class CooperativeQDResult: """Every policy evaluation uses the same number of self-play matches.""" archive: object evaluations: int self_play_matches: int admissions: int
## @brief Snapshot of ordered cross-play and the response to each partner niche.
[docs] @dataclass(frozen=True) class PartnerResponseTable: """Rows are responding policies and columns are possible partner policies.""" niches: tuple[tuple[int, ...], ...] genomes: tuple[tuple, ...] payoffs: tuple[tuple[float, ...], ...] specialist_indices: tuple[int, ...] generalist_index: int matches: int ## @brief Pick the specialist for an observed niche or fall back to the generalist. # @param niche Grid index of the estimated partner behavior, or None. # @param observations Number of partner observations used by the caller. # @param min_observations Evidence required before use of a specialist. # @return Policy genome from the calibrated repertoire.
[docs] def select(self, niche=None, *, observations=0, min_observations=1): """Return a specialist after sufficient evidence for a calibrated cell.""" seen, threshold = _attempt_budget(observations), _attempt_budget(min_observations) if niche is None or seen < threshold: return self.genomes[self.generalist_index] niche = tuple(map(index, niche)) try: partner = self.niches.index(niche) except ValueError: return self.genomes[self.generalist_index] return self.genomes[self.specialist_indices[partner]]
## @brief Collect diverse cooperative policies using self-play. # @param archive Empty parentless, best-only Grid or CVTGrid with one objective. # @param play Callable (first_genome, second_genome, seed) returning (team_score, first_descriptor). # @param sample Callable (rng) returning an initial policy genome. # @param mutate Callable (genome, rng) returning an offspring. # @param budget Number of evaluated policy genomes. # @param repeats Number of common seeded matches per candidate. # @param initial_samples Number of unconditional sample calls. # @param seed Root variation and matchup seed. # @return CooperativeQDResult with native archive and match budget.
[docs] def cooperative_map_elites(archive, play, *, sample, mutate, budget, repeats=1, initial_samples=16, seed=0): """Measure each candidate against itself and admit by its measured behavior.""" _validate_grid(archive) if not all(map(callable, (play, sample, mutate))): raise TypeError("Supply callable play, sample and mutate functions.") budget, initial = _attempt_budget(budget), _attempt_budget(initial_samples) repeats = _positive_int(repeats, "repeats") if archive.fitness_weights is None: archive._set_fitness_weights((1.,)) if archive.fitness_weights[0] <= 0: raise ValueError("Cooperative team scores must be maximized.") rng, match_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2)) seeds = tuple(map(int, match_rng.integers(2**32, size=repeats))) before = archive.nb_added for step in range(budget): if step < initial or not archive: genome = tuple(sample(rng)) else: genome = tuple(mutate(tuple(archive[int(rng.integers(len(archive)))]), rng)) matches = [] for match_seed in seeds: score, descriptor = play(genome, genome, match_seed) matches.append(_finite_vector((score, *descriptor), "Match measurements", 1 + len(archive.features_domain))) mean = (np.asarray(matches) / repeats).sum(axis=0) _offer(archive, _measurement(archive, ((mean[0],), mean[1:]), genome)) return CooperativeQDResult(archive, budget, budget * repeats, archive.nb_added - before)
## @brief Calibrate the best generalist and one response per partner niche. # @param archive Nonempty self-play repertoire. # @param play Callable (first_genome, second_genome, seed) returning (team_score, first_descriptor). # @param budget Hard cap. Every ordered pair and repeat must fit before starting. # @param repeats Number of common seeded matches per ordered pair. # @param seed Cross-play seed, independent of self-play. # @return PartnerResponseTable with separate measurement counts.
[docs] def build_partner_responses(archive, play, *, budget, repeats=1, seed=0): """Score all ordered pairings and choose responses with maximum cooperative return.""" _validate_grid(archive, empty=False) if not archive or not callable(play): raise ValueError("Supply a nonempty repertoire and callable cross-play.") budget, repeats = _attempt_budget(budget), _positive_int(repeats, "repeats") entries = sorted((archive.index_grid(row), tuple(row)) for row in archive) needed = len(entries) ** 2 * repeats if needed > budget: raise ValueError(f"A complete response table needs {needed} cross-play matches.") niches, genomes = zip(*entries) seeds = tuple(map(int, np.random.default_rng(seed).integers(2**32, size=repeats))) values = np.empty((len(genomes), len(genomes))) for i, row in enumerate(genomes): for j, partner in enumerate(genomes): scores = tuple(float(play(row, partner, trial)[0]) for trial in seeds) if not all(map(isfinite, scores)): raise ValueError("Cross-play scores must be finite.") values[i, j] = sum(score / repeats for score in scores) generalist = int(np.argmax((values / len(genomes)).sum(axis=1))) return PartnerResponseTable(niches, genomes, tuple(tuple(map(float, row)) for row in values), tuple(map(int, values.argmax(axis=0))), generalist, needed)