6"""Evolve self-play strategies and select cooperative responses to observed partners."""
8from dataclasses
import dataclass
9from math
import isfinite
10from operator
import index
14from ._population
import _attempt_budget, _finite_vector
15from .modern
import _positive_int
16from .task_search
import _measurement, _offer, _validate_grid
18__all__ = [
"CooperativeQDResult",
"PartnerResponseTable",
"cooperative_map_elites",
"build_partner_responses"]
22@dataclass(frozen=True)
24 """Every policy evaluation uses the same number of self-play matches."""
28 self_play_matches: int
33@dataclass(frozen=True)
35 """Rows are responding policies and columns are possible partner policies."""
37 niches: tuple[tuple[int, ...], ...]
38 genomes: tuple[tuple, ...]
39 payoffs: tuple[tuple[float, ...], ...]
40 specialist_indices: tuple[int, ...]
49 def select(self, niche=None, *, observations=0, min_observations=1):
50 """Return a specialist after sufficient evidence for a calibrated cell."""
51 seen, threshold = _attempt_budget(observations), _attempt_budget(min_observations)
52 if niche
is None or seen < threshold:
53 return self.
genomes[self.generalist_index]
54 niche = tuple(map(index, niche))
56 partner = self.
niches.index(niche)
58 return self.
genomes[self.generalist_index]
72def cooperative_map_elites(archive, play, *, sample, mutate, budget, repeats=1, initial_samples=16, seed=0):
73 """Measure each candidate against itself and admit by its measured behavior."""
74 _validate_grid(archive)
75 if not all(map(callable, (play, sample, mutate))):
76 raise TypeError(
"Supply callable play, sample and mutate functions.")
77 budget, initial = _attempt_budget(budget), _attempt_budget(initial_samples)
78 repeats = _positive_int(repeats,
"repeats")
79 if archive.fitness_weights
is None:
80 archive._set_fitness_weights((1.,))
81 if archive.fitness_weights[0] <= 0:
82 raise ValueError(
"Cooperative team scores must be maximized.")
83 rng, match_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
84 seeds = tuple(map(int, match_rng.integers(2**32, size=repeats)))
85 before = archive.nb_added
86 for step
in range(budget):
87 if step < initial
or not archive:
88 genome = tuple(sample(rng))
90 genome = tuple(mutate(tuple(archive[int(rng.integers(len(archive)))]), rng))
92 for match_seed
in seeds:
93 score, descriptor = play(genome, genome, match_seed)
94 matches.append(_finite_vector((score, *descriptor),
"Match measurements",
95 1 + len(archive.features_domain)))
96 mean = (np.asarray(matches) / repeats).sum(axis=0)
97 _offer(archive, _measurement(archive, ((mean[0],), mean[1:]), genome))
108def build_partner_responses(archive, play, *, budget, repeats=1, seed=0):
109 """Score all ordered pairings and choose responses with maximum cooperative return."""
110 _validate_grid(archive, empty=
False)
111 if not archive
or not callable(play):
112 raise ValueError(
"Supply a nonempty repertoire and callable cross-play.")
113 budget, repeats = _attempt_budget(budget), _positive_int(repeats,
"repeats")
114 entries = sorted((archive.index_grid(row), tuple(row))
for row
in archive)
115 needed = len(entries) ** 2 * repeats
117 raise ValueError(f
"A complete response table needs {needed} cross-play matches.")
118 niches, genomes = zip(*entries)
119 seeds = tuple(map(int, np.random.default_rng(seed).integers(2**32, size=repeats)))
120 values = np.empty((len(genomes), len(genomes)))
121 for i, row
in enumerate(genomes):
122 for j, partner
in enumerate(genomes):
123 scores = tuple(float(play(row, partner, trial)[0])
for trial
in seeds)
124 if not all(map(isfinite, scores)):
125 raise ValueError(
"Cross-play scores must be finite.")
126 values[i, j] = sum(score / repeats
for score
in scores)
127 generalist = int(np.argmax((values / len(genomes)).sum(axis=1)))
129 tuple(map(int, values.argmax(axis=0))), generalist, needed)
Self-play repertoire and separate policy and match counts.
Snapshot of ordered cross-play and the response to each partner niche.
select(self, niche=None, *, observations=0, min_observations=1)
Pick the specialist for an observed niche or fall back to the generalist.