QDpy
Loading...
Searching...
No Matches
minimal_criterion.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Resource-limited Minimal Criterion Coevolution."""
7
8from collections import Counter, deque
9from dataclasses import dataclass
10from typing import Hashable
11
12import numpy as np
13
14from .modern import _positive_int
15from .sampling import _rollout_seed
16
17__all__ = ["MinimalCriterionCoevolution", "MCCTask", "MCCStats"]
18
19
20
21@dataclass(frozen=True)
22class MCCTask:
23 """Resource use follows the lifetime of the current environment entry."""
24
25 task: Hashable
26 used_resources: int
27
28
29
30@dataclass(frozen=True)
32 """Pairings are the only evaluator calls. First attempts count on error."""
33
34 proposals: int = 0
35 task_pairings: int = 0
36 solver_pairings: int = 0
37 task_admissions: int = 0
38 solver_admissions: int = 0
39 exhausted_task_skips: int = 0
40
41 @property
42 def evaluations(self):
43 """Return all attempted task-solver evaluations."""
44 return self.task_pairings + self.solver_pairings
45
46
47@dataclass
48class _Trial:
49 task_birth: bool
50 child: Hashable
51 partners: deque
52
53
54
56 """Alternate proposing task offspring and solver offspring.
57
58 A task offspring must be solved by at least one living solver.
59 A solver offspring must solve a living task that still has resources.
60 The first successful pairing admits the offspring and a solver
61 admission spends one resource on its supporting task. Test partners
62 in a seeded random order without replacement for each proposal.
63 Remove the oldest member of a population when it reaches capacity.
64
65 :param seed_tasks: Distinct immutable initial tasks, assumed viable.
66 :param seed_solvers: Distinct immutable initial solvers, assumed viable.
67 :param mutate_task: Callback taking (parent, rng) and returning a task or None.
68 :param mutate_solver: Callback taking (parent, rng) and returning a solver or None.
69 :param task_capacity: Maximum number of concurrent tasks.
70 :param solver_capacity: Maximum number of concurrent solvers.
71 :param task_resources: Number of solvers each task can admit while live.
72 None selects unlimited resources as a control.
73 :param seed: Private proposal and pair evaluation seed.
74 """
75
76 def __init__(self, seed_tasks, seed_solvers, *, mutate_task, mutate_solver,
77 task_capacity=32, solver_capacity=64, task_resources=4, seed=0):
78 if not callable(mutate_task) or not callable(mutate_solver):
79 raise TypeError("Supply task and solver mutation functions.")
80 self.task_capacity = _positive_int(task_capacity, "task_capacity")
81 self.solver_capacity = _positive_int(solver_capacity, "solver_capacity")
82 self.task_resources = None if task_resources is None else _positive_int(task_resources, "task_resources")
83 self._tasks = self._initial(seed_tasks, self.task_capacity)
84 self._solvers = self._initial(seed_solvers, self.solver_capacity)
85 self._mutate_task, self._mutate_solver = mutate_task, mutate_solver
86 proposals, pairings = np.random.SeedSequence(seed).spawn(2)
87 self._rng = np.random.default_rng(proposals)
88 self._evaluation_seed = int(pairings.generate_state(1, dtype=np.uint64)[0])
89 self._task_turn = False
90 self._counts = Counter()
91 self._pending = None
92
93 @staticmethod
94 def _initial(values, capacity):
95 values = tuple(values)
96 if not 1 <= len(values) <= capacity or any(value is None for value in values):
97 raise ValueError("Seed each population with viable non-None entries within capacity.")
98 data = dict.fromkeys(values, 0)
99 if len(data) != len(values):
100 raise ValueError("Seeds must be distinct within each population.")
101 return data
102
103 @property
104 def tasks(self):
105 """Return current environments and their use in oldest-first order."""
106 return tuple(MCCTask(task, used) for task, used in self._tasks.items())
107
108 @property
109 def solvers(self):
110 """Return living solvers in oldest-first order."""
111 return tuple(self._solvers)
112
113 @property
114 def stats(self):
115 """Return cumulative costs and admissions."""
116 return MCCStats(**self._counts)
117
118 def _propose(self):
119 task_birth = self._task_turn
120 self._task_turn = not task_birth
121 self._counts["proposals"] += 1
122 population = self._tasks if task_birth else self._solvers
123 mutate = self._mutate_task if task_birth else self._mutate_solver
124 parent = tuple(population)[int(self._rng.integers(len(population)))]
125 child = mutate(parent, self._rng)
126 if child is None or child in population:
127 return None
128 if task_birth:
129 partners = tuple(self._solvers)
130 else:
131 partners = tuple(task for task, used in self._tasks.items()
132 if self.task_resources is None or used < self.task_resources)
133 self._counts["exhausted_task_skips"] += len(self._tasks) - len(partners)
134 return _Trial(task_birth, child, deque(partners[i] for i in self._rng.permutation(len(partners))))
135
136 def _admit(self, trial, supporter):
137 if trial.task_birth:
138 population, capacity, metric = self._tasks, self.task_capacity, "task_admissions"
139 else:
140 population, capacity, metric = self._solvers, self.solver_capacity, "solver_admissions"
141 self._tasks[supporter] += 1
142 if len(population) == capacity:
143 del population[next(iter(population))]
144 population[trial.child] = 0
145 self._counts[metric] += 1
146
147
152 def run(self, evaluate, budget, *, proposal_limit=None):
153 """Save pending partner tests across a budget boundary and charge calls once."""
154 if not callable(evaluate):
155 raise TypeError("Supply a callable evaluator.")
156 budget = _positive_int(budget, "budget")
157 limit = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
158 end = self.stats.evaluations + budget
159 proposals_end = self._counts["proposals"] + limit
160 calls = end - budget
161 while calls < end:
162 if self._pending is None or not self._pending.partners:
163 self._pending = None
164 if self._counts["proposals"] >= proposals_end:
165 break
166 self._pending = self._propose()
167 continue
168 trial = self._pending
169 partner = trial.partners.popleft()
170 task, solver = (trial.child, partner) if trial.task_birth else (partner, trial.child)
171 seed = _rollout_seed(self._evaluation_seed, 0, calls)
172 calls += 1
173 self._counts["task_pairings" if trial.task_birth else "solver_pairings"] += 1
174 result = evaluate(task, solver, seed)
175 if not isinstance(result, (bool, np.bool_)):
176 raise TypeError("The evaluator must return a boolean viability decision.")
177 if result:
178 self._admit(trial, partner)
179 self._pending = None
180 return self.stats
Cumulative proposal, pairing, and admission counts.
An active environment and its number of admitted solver offspring.
Maintain two populations with binary selection and finite task resources.
run(self, evaluate, budget, *, proposal_limit=None)
Continue coevolution for an additional pair-evaluation budget.