# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Co-evolve viable tasks and solvers with limited task resources.
# @see https://doi.org/10.1145/3377930.3389809
"""Resource-limited Minimal Criterion Coevolution."""
from collections import Counter, deque
from dataclasses import dataclass
from typing import Hashable
import numpy as np
from .modern import _positive_int
from .sampling import _rollout_seed
__all__ = ["MinimalCriterionCoevolution", "MCCTask", "MCCStats"]
## @brief An active environment and its number of admitted solver offspring.
[docs]
@dataclass(frozen=True)
class MCCTask:
"""Resource use follows the lifetime of the current environment entry."""
task: Hashable
used_resources: int
## @brief Cumulative proposal, pairing, and admission counts.
[docs]
@dataclass(frozen=True)
class MCCStats:
"""Pairings are the only evaluator calls. First attempts count on error."""
proposals: int = 0
task_pairings: int = 0
solver_pairings: int = 0
task_admissions: int = 0
solver_admissions: int = 0
exhausted_task_skips: int = 0
@property
def evaluations(self):
"""Return all attempted task-solver evaluations."""
return self.task_pairings + self.solver_pairings
@dataclass
class _Trial:
task_birth: bool
child: Hashable
partners: deque
## @brief Maintain two populations with binary selection and finite task resources.
[docs]
class MinimalCriterionCoevolution:
"""Alternate proposing task offspring and solver offspring.
A task offspring must be solved by at least one living solver.
A solver offspring must solve a living task that still has resources.
The first successful pairing admits the offspring and a solver
admission spends one resource on its supporting task. Test partners
in a seeded random order without replacement for each proposal.
Remove the oldest member of a population when it reaches capacity.
:param seed_tasks: Distinct immutable initial tasks, assumed viable.
:param seed_solvers: Distinct immutable initial solvers, assumed viable.
:param mutate_task: Callback taking (parent, rng) and returning a task or None.
:param mutate_solver: Callback taking (parent, rng) and returning a solver or None.
:param task_capacity: Maximum number of concurrent tasks.
:param solver_capacity: Maximum number of concurrent solvers.
:param task_resources: Number of solvers each task can admit while live.
None selects unlimited resources as a control.
:param seed: Private proposal and pair evaluation seed.
"""
def __init__(self, seed_tasks, seed_solvers, *, mutate_task, mutate_solver,
task_capacity=32, solver_capacity=64, task_resources=4, seed=0):
if not callable(mutate_task) or not callable(mutate_solver):
raise TypeError("Supply task and solver mutation functions.")
self.task_capacity = _positive_int(task_capacity, "task_capacity")
self.solver_capacity = _positive_int(solver_capacity, "solver_capacity")
self.task_resources = None if task_resources is None else _positive_int(task_resources, "task_resources")
self._tasks = self._initial(seed_tasks, self.task_capacity)
self._solvers = self._initial(seed_solvers, self.solver_capacity)
self._mutate_task, self._mutate_solver = mutate_task, mutate_solver
proposals, pairings = np.random.SeedSequence(seed).spawn(2)
self._rng = np.random.default_rng(proposals)
self._evaluation_seed = int(pairings.generate_state(1, dtype=np.uint64)[0])
self._task_turn = False
self._counts = Counter()
self._pending = None
@staticmethod
def _initial(values, capacity):
values = tuple(values)
if not 1 <= len(values) <= capacity or any(value is None for value in values):
raise ValueError("Seed each population with viable non-None entries within capacity.")
data = dict.fromkeys(values, 0)
if len(data) != len(values):
raise ValueError("Seeds must be distinct within each population.")
return data
@property
def tasks(self):
"""Return current environments and their use in oldest-first order."""
return tuple(MCCTask(task, used) for task, used in self._tasks.items())
@property
def solvers(self):
"""Return living solvers in oldest-first order."""
return tuple(self._solvers)
@property
def stats(self):
"""Return cumulative costs and admissions."""
return MCCStats(**self._counts)
def _propose(self):
task_birth = self._task_turn
self._task_turn = not task_birth
self._counts["proposals"] += 1
population = self._tasks if task_birth else self._solvers
mutate = self._mutate_task if task_birth else self._mutate_solver
parent = tuple(population)[int(self._rng.integers(len(population)))]
child = mutate(parent, self._rng)
if child is None or child in population:
return None
if task_birth:
partners = tuple(self._solvers)
else:
partners = tuple(task for task, used in self._tasks.items()
if self.task_resources is None or used < self.task_resources)
self._counts["exhausted_task_skips"] += len(self._tasks) - len(partners)
return _Trial(task_birth, child, deque(partners[i] for i in self._rng.permutation(len(partners))))
def _admit(self, trial, supporter):
if trial.task_birth:
population, capacity, metric = self._tasks, self.task_capacity, "task_admissions"
else:
population, capacity, metric = self._solvers, self.solver_capacity, "solver_admissions"
self._tasks[supporter] += 1
if len(population) == capacity:
del population[next(iter(population))]
population[trial.child] = 0
self._counts[metric] += 1
## @brief Continue coevolution for an additional pair-evaluation budget.
# @param evaluate Boolean viability callback taking (task, solver, seed).
# @param budget Maximum additional pairing calls.
# @param proposal_limit Maximum new proposals, including duplicates and None.
# @return Cumulative costs and admissions.
[docs]
def run(self, evaluate, budget, *, proposal_limit=None):
"""Save pending partner tests across a budget boundary and charge calls once."""
if not callable(evaluate):
raise TypeError("Supply a callable evaluator.")
budget = _positive_int(budget, "budget")
limit = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
end = self.stats.evaluations + budget
proposals_end = self._counts["proposals"] + limit
calls = end - budget
while calls < end:
if self._pending is None or not self._pending.partners:
self._pending = None
if self._counts["proposals"] >= proposals_end:
break
self._pending = self._propose()
continue
trial = self._pending
partner = trial.partners.popleft()
task, solver = (trial.child, partner) if trial.task_birth else (partner, trial.child)
seed = _rollout_seed(self._evaluation_seed, 0, calls)
calls += 1
self._counts["task_pairings" if trial.task_birth else "solver_pairings"] += 1
result = evaluate(task, solver, seed)
if not isinstance(result, (bool, np.bool_)):
raise TypeError("The evaluator must return a boolean viability decision.")
if result:
self._admit(trial, partner)
self._pending = None
return self.stats