# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Agent Mixing MAP-Elites for bounded numeric cooperative teams.
"""Cooperative MAP-Elites with fixed role blocks."""
from collections.abc import Mapping
from math import isfinite
import random
import numpy as np
from qdpy.base import registry
from qdpy.containers import Grid
from qdpy.tools import iso_line_dd, mut_polynomial_bounded
from .modern import _bounds, _FixedGeneration, _positive_int, _variation_settings
__all__ = ["MixME"]
## @brief Evolve whole teams with within-role policy variation and team crossover.
[docs]
@registry.register
class MixME(_FixedGeneration):
"""Use a flat genome and archive each evaluated team as one solution.
Once the archive has an elite, the three operators are used in turn
across proposals. Team crossover draws an elite team with replacement
for each role and copies only that team's block for the role. Polynomial
variation and Iso+LineDD preserve team membership during parent selection.
A partial batch carries its position in the operator cycle into the next
batch. The empty archive draws uniformly bounded genomes.
:param container: Best-only Grid or CVTGrid for team measurements.
:param budget: Number of attempted evaluations of whole teams.
:param role_sizes: Positive genome lengths in role order, or a mapping
from role names to lengths in insertion order.
:param role_bounds: One (lower, upper) interval per role, in role
order. Defaults to (0, 1) for every role.
:param batch_size: Number of proposals between archive updates.
:param team_crossover: Include team mixing in the operator cycle.
:param iso_sigma: Independent Iso+LineDD noise scale.
:param line_sigma: Shared Iso+LineDD direction scale within a role.
:param polynomial_eta: Polynomial mutation distribution index.
:param mutation_probability: Polynomial mutation chance per gene.
Defaults to the reciprocal of the total genome length.
"""
_requires_proposed_genome = True
def __init__(self, container, budget, role_sizes, *, role_bounds=None,
batch_size=12, team_crossover=True, iso_sigma=0.01,
line_sigma=0.2, polynomial_eta=20., mutation_probability=None, **kwargs):
if (not isinstance(container, Grid) or container.max_items_per_bin != 1
or len(container.fitness_domain or ()) != 1 or container.discard_random_on_bin_overload):
raise ValueError("MixME requires a best-only Grid or CVTGrid with one objective.")
self.role_names = tuple(role_sizes) if isinstance(role_sizes, Mapping) else None
lengths = tuple(_positive_int(size, "role size") for size in
(role_sizes.values() if self.role_names is not None else role_sizes))
if len(lengths) < 2:
raise ValueError("Provide at least two team roles.")
boundaries = (0, *np.cumsum(lengths).tolist())
self._roles = tuple(slice(start, end) for start, end in zip(boundaries, boundaries[1:]))
if role_bounds is None:
role_bounds = ((0., 1.),) * len(lengths)
self.role_bounds = tuple(_bounds(bounds) for bounds in role_bounds)
if len(self.role_bounds) != len(lengths) or any(
not isfinite(high - low) for low, high in self.role_bounds):
raise ValueError("Provide one finite-width interval per role.")
_variation_settings(self.role_bounds[0], iso_sigma, line_sigma)
self.iso_sigma = iso_sigma
self.line_sigma = line_sigma
self.polynomial_eta = polynomial_eta
self.mutation_probability = (1. / boundaries[-1] if mutation_probability is None
else mutation_probability)
if not isfinite(polynomial_eta) or polynomial_eta <= 0 or not 0 <= self.mutation_probability <= 1:
raise ValueError("Provide positive finite eta and a mutation probability in [0, 1].")
self.team_crossover = team_crossover
if container.fitness_weights is not None:
kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
super().__init__(container, _positive_int(budget, "budget"),
dimension=boundaries[-1], batch_size=_positive_int(batch_size, "batch_size"),
**kwargs)
for elite in container:
self._check_candidate(elite)
if any(not low <= value <= high for role, (low, high) in zip(self._roles, self.role_bounds)
for value in elite[role]):
raise ValueError("A seed team is outside its role bounds.")
def reinit(self):
"""Reset the position in the operator cycle."""
super().reinit()
self._variation_count = 0
## @brief Copy an encoded team into ordered or named role blocks.
[docs]
def decode_team(self, genome):
"""Return tuples of role genes, or an ordered dict for named roles."""
if len(genome) != self.dimension:
raise ValueError("The genome length must match the team layout.")
blocks = tuple(tuple(genome[role]) for role in self._roles)
return dict(zip(self.role_names, blocks)) if self.role_names is not None else blocks
def _internal_ask(self, base_ind):
archive = self.container
if not archive:
base_ind[:] = [value for role, bounds in zip(self._roles, self.role_bounds)
for value in np.random.uniform(*bounds, role.stop - role.start)]
return base_ind
operator = self._variation_count % (3 if self.team_crossover else 2)
self._variation_count += 1
if operator == 2:
base_ind[:] = [value for role in self._roles for value in random.choice(archive)[role]]
return base_ind
first = random.choice(archive)
second = random.choice(archive) if operator == 1 else None
for role, bounds in zip(self._roles, self.role_bounds):
if second is None:
block = mut_polynomial_bounded(list(first[role]), self.polynomial_eta,
*bounds, self.mutation_probability)
else:
block = iso_line_dd(first[role], second[role], bounds=bounds,
iso_sigma=self.iso_sigma, line_sigma=self.line_sigma)
base_ind[role] = block
return base_ind
def _commit_generation(self, evaluated):
return {slot for slot, team in enumerate(evaluated)
if team is not None and self._offer_to_grid(team, self.container.index_grid(team))}