49 """Alternate between two unstructured archives for opposing roles.
51 A sampled matchup gives the proposer context. If its candidate is
52 novel enough, the archive keeps it as a stepping stone. Otherwise the
53 candidate must beat its closest archived neighbor on a common panel
54 of opponents. Scores are interpreted in the current role's units and
55 larger is better for both roles. Archives hold the strategy and its
56 immutable embedding. Match outcomes are local to their comparison.
58 :param initial: One hashable immutable seed strategy per role.
59 :param play: Callable taking (role_0_strategy, role_1_strategy) and
60 returning a finite pair of scores in that order.
61 :param propose: Callable taking (QDSelfPlayContext, rng) and
62 returning a strategy or None to skip the proposal.
63 :param embed: Callable taking (role, strategy) and returning a finite vector.
64 :param novelty_radius: Candidate distance above which a strategy is considered novel.
65 :param neighbors: Maximum nearest strategies supplied to the proposer or novelty callback.
66 :param opponents: Maximum distinct opponents used in each local comparison.
67 :param is_novel: Optional callable taking (role, strategy, neighbors)
68 and returning a boolean, to replace the radius decision.
69 :param seed: Private random seed.
72 def __init__(self, initial, *, play, propose, embed, novelty_radius=.1,
73 neighbors=3, opponents=3, is_novel=None, seed=0):
75 if not all(map(callable, (play, propose, embed)))
or (is_novel
is not None and not callable(is_novel)):
76 raise TypeError(
"Provide callable match, proposal, and embedding functions.")
77 if not 0 <= novelty_radius < np.inf:
78 raise ValueError(
"novelty_radius must be finite and nonnegative.")
79 first, second = initial
80 if first
is None or second
is None:
81 raise ValueError(
"Provide one seed strategy per role.")
84 self.
neighbors = _positive_int(neighbors,
"neighbors")
85 self.
opponents = _positive_int(opponents,
"opponents")
86 self.
_rng = np.random.default_rng(seed)
92 """Return immutable snapshots of the strategies in role order."""
93 return tuple(tuple(archive)
for archive
in self.
_archives)
97 """Return cumulative accounting, including attempted callback calls."""
100 def _embedding(self, role, strategy, width=None):
101 vector = tuple(map(float, self.
_embed(role, strategy)))
102 if not vector
or (width
is not None and len(vector) != width)
or not all(map(isfinite, vector)):
103 raise ValueError(
"Supply a finite embedding with a fixed width per role.")
106 def _closest(self, archive, vector, exclude=None):
107 distances = [(dist(vector, other), strategy)
for strategy, other
in archive.items()
if strategy != exclude]
108 return sorted(distances, key=
lambda row: row[0])[:self.
neighbors]
110 def _match(self, pair):
112 first, second = map(float, self.
_play(*pair))
113 if not isfinite(first)
or not isfinite(second):
114 raise ValueError(
"Matches must return two finite payoffs.")
117 def _duel(self, role, candidate, incumbent, opponents, count):
118 chosen = self.
_rng.choice(len(opponents), size=min(len(opponents), count), replace=
False)
119 proposed, retained = [], []
121 opponent = opponents[index]
122 proposal_pair, incumbent_pair = (candidate, opponent), (incumbent, opponent)
124 proposal_pair, incumbent_pair = proposal_pair[::-1], incumbent_pair[::-1]
125 proposed.append(self.
_match(proposal_pair)[role])
126 retained.append(self.
_match(incumbent_pair)[role])
127 return fsum(value / len(chosen)
for value
in proposed) > fsum(value / len(chosen)
for value
in retained)
131 """Use the same sampled opponent panel for both members of a duel.
133 Each proposal costs one context match. A local update needs at
134 least two more calls. A run can leave up to two calls unused.
135 The final panel can be smaller than opponents when budget is low.
137 stop = self.
_matches + _positive_int(budget,
"budget")
140 self.
_role = 1 - role
143 parents = red[self.
_rng.integers(len(red))], blue[self.
_rng.integers(len(blue))]
144 scores = self.
_match(parents)
145 parent = parents[role]
147 tuple(item
for _, item
in self.
_closest(archive, archive[parent], parent)))
156 embedding = self.
_embedding(role, new, len(archive[parent]))
157 nearest = self.
_closest(archive, embedding)
158 distance, incumbent = nearest[0]
162 novel = self.
_is_novel(role, new, tuple(item
for _, item
in nearest))
163 if not isinstance(novel, (bool, np.bool_)):
164 raise ValueError(
"is_novel must return a boolean.")
166 archive[new] = embedding
168 elif self.
_duel(role, new, incumbent, blue
if role == 0
else red,
170 del archive[incumbent]
171 archive[new] = embedding
Information supplied to the strategy proposal callback.