QDpy
Loading...
Searching...
No Matches
mix_me.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Cooperative MAP-Elites with fixed role blocks."""
6
7from collections.abc import Mapping
8from math import isfinite
9import random
10
11import numpy as np
12
13from qdpy.base import registry
14from qdpy.containers import Grid
15from qdpy.tools import iso_line_dd, mut_polynomial_bounded
16from .modern import _bounds, _FixedGeneration, _positive_int, _variation_settings
17
18__all__ = ["MixME"]
19
20
21
22@registry.register
24 """Use a flat genome and archive each evaluated team as one solution.
25
26 Once the archive has an elite, the three operators are used in turn
27 across proposals. Team crossover draws an elite team with replacement
28 for each role and copies only that team's block for the role. Polynomial
29 variation and Iso+LineDD preserve team membership during parent selection.
30 A partial batch carries its position in the operator cycle into the next
31 batch. The empty archive draws uniformly bounded genomes.
32
33 :param container: Best-only Grid or CVTGrid for team measurements.
34 :param budget: Number of attempted evaluations of whole teams.
35 :param role_sizes: Positive genome lengths in role order, or a mapping
36 from role names to lengths in insertion order.
37 :param role_bounds: One (lower, upper) interval per role, in role
38 order. Defaults to (0, 1) for every role.
39 :param batch_size: Number of proposals between archive updates.
40 :param team_crossover: Include team mixing in the operator cycle.
41 :param iso_sigma: Independent Iso+LineDD noise scale.
42 :param line_sigma: Shared Iso+LineDD direction scale within a role.
43 :param polynomial_eta: Polynomial mutation distribution index.
44 :param mutation_probability: Polynomial mutation chance per gene.
45 Defaults to the reciprocal of the total genome length.
46 """
47
48 _requires_proposed_genome = True
49
50 def __init__(self, container, budget, role_sizes, *, role_bounds=None,
51 batch_size=12, team_crossover=True, iso_sigma=0.01,
52 line_sigma=0.2, polynomial_eta=20., mutation_probability=None, **kwargs):
53 if (not isinstance(container, Grid) or container.max_items_per_bin != 1
54 or len(container.fitness_domain or ()) != 1 or container.discard_random_on_bin_overload):
55 raise ValueError("MixME requires a best-only Grid or CVTGrid with one objective.")
56 self.role_names = tuple(role_sizes) if isinstance(role_sizes, Mapping) else None
57 lengths = tuple(_positive_int(size, "role size") for size in
58 (role_sizes.values() if self.role_names is not None else role_sizes))
59 if len(lengths) < 2:
60 raise ValueError("Provide at least two team roles.")
61 boundaries = (0, *np.cumsum(lengths).tolist())
62 self._roles = tuple(slice(start, end) for start, end in zip(boundaries, boundaries[1:]))
63 if role_bounds is None:
64 role_bounds = ((0., 1.),) * len(lengths)
65 self.role_bounds = tuple(_bounds(bounds) for bounds in role_bounds)
66 if len(self.role_bounds) != len(lengths) or any(
67 not isfinite(high - low) for low, high in self.role_bounds):
68 raise ValueError("Provide one finite-width interval per role.")
69 _variation_settings(self.role_bounds[0], iso_sigma, line_sigma)
70 self.iso_sigma = iso_sigma
71 self.line_sigma = line_sigma
72 self.polynomial_eta = polynomial_eta
73 self.mutation_probability = (1. / boundaries[-1] if mutation_probability is None
74 else mutation_probability)
75 if not isfinite(polynomial_eta) or polynomial_eta <= 0 or not 0 <= self.mutation_probability <= 1:
76 raise ValueError("Provide positive finite eta and a mutation probability in [0, 1].")
77 self.team_crossover = team_crossover
78 if container.fitness_weights is not None:
79 kwargs.setdefault("optimisation_task", tuple(container.fitness_weights))
80 super().__init__(container, _positive_int(budget, "budget"),
81 dimension=boundaries[-1], batch_size=_positive_int(batch_size, "batch_size"),
82 **kwargs)
83 for elite in container:
84 self._check_candidate(elite)
85 if any(not low <= value <= high for role, (low, high) in zip(self._roles, self.role_bounds)
86 for value in elite[role]):
87 raise ValueError("A seed team is outside its role bounds.")
88
89 def reinit(self):
90 """Reset the position in the operator cycle."""
91 super().reinit()
92 self._variation_count = 0
93
94
95 def decode_team(self, genome):
96 """Return tuples of role genes, or an ordered dict for named roles."""
97 if len(genome) != self.dimension:
98 raise ValueError("The genome length must match the team layout.")
99 blocks = tuple(tuple(genome[role]) for role in self._roles)
100 return dict(zip(self.role_names, blocks)) if self.role_names is not None else blocks
101
102 def _internal_ask(self, base_ind):
103 archive = self.container
104 if not archive:
105 base_ind[:] = [value for role, bounds in zip(self._roles, self.role_bounds)
106 for value in np.random.uniform(*bounds, role.stop - role.start)]
107 return base_ind
108
109 operator = self._variation_count % (3 if self.team_crossover else 2)
110 self._variation_count += 1
111 if operator == 2:
112 base_ind[:] = [value for role in self._roles for value in random.choice(archive)[role]]
113 return base_ind
114
115 first = random.choice(archive)
116 second = random.choice(archive) if operator == 1 else None
117 for role, bounds in zip(self._roles, self.role_bounds):
118 if second is None:
119 block = mut_polynomial_bounded(list(first[role]), self.polynomial_eta,
120 *bounds, self.mutation_probability)
121 else:
122 block = iso_line_dd(first[role], second[role], bounds=bounds,
123 iso_sigma=self.iso_sigma, line_sigma=self.line_sigma)
124 base_ind[role] = block
125 return base_ind
126
127 def _commit_generation(self, evaluated):
128 return {slot for slot, team in enumerate(evaluated)
129 if team is not None and self._offer_to_grid(team, self.container.index_grid(team))}
Evolve whole teams with within-role policy variation and team crossover.
Definition mix_me.py:23
_internal_ask(self, base_ind)
Definition mix_me.py:102
decode_team(self, genome)
Copy an encoded team into ordered or named role blocks.
Definition mix_me.py:95
_commit_generation(self, evaluated)
Definition mix_me.py:127
_offer_to_grid(self, individual, cell)
Definition modern.py:228