QDpy
Loading...
Searching...
No Matches
cmoea.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Combinatorial multiobjective evolution over bounded subtask populations."""
7
8from dataclasses import dataclass
9from itertools import combinations
10from operator import index
11from types import MappingProxyType
12
13import numpy as np
14from scipy.spatial.distance import cdist
15
16from .evolvability_es import _pareto_utilities
17from .modern import _positive_int
18
19__all__ = ["CMOEA", "CMOEARecord", "CMOEAStats"]
20
21
22def _choose_subsets(count, cap, rng):
23 if count <= cap.bit_length() and (1 << count) - 1 <= cap:
24 return tuple(subset for size in range(1, count + 1) for subset in combinations(range(count), size))
25 full = tuple(range(count))
26 subsets = dict.fromkeys((*((idx,) for idx in full), full))
27 if cap < len(subsets):
28 raise ValueError("max_bins must cover all singleton subtasks and the full combination.")
29 while len(subsets) < cap:
30 subset = tuple(np.flatnonzero(rng.integers(0, 2, count)).tolist())
31 if subset:
32 subsets.setdefault(subset, None)
33 return tuple(subsets)
34
35
36
37@dataclass(frozen=True)
39 """Store one measurement that can participate in multiple populations."""
40
41 genome: tuple
42 task_scores: tuple[float, ...]
43 descriptor: tuple[float, ...]
44
45
46
47@dataclass(frozen=True)
49 """Count each candidate once even when it competes in every bin."""
50
51 evaluations: int
52 failures: int
53 generations: int
54
55
56
57class CMOEA:
58 """Combine task fitness and within-bin behavioral diversity.
59
60 Every evaluated offspring competes in each bin using its original
61 vector of task scores. Survival uses NSGA-II front ranks and
62 crowding for the aggregate task score and mean behavioral distance.
63 Parent sampling is uniform over occupied bins and then their members.
64
65 :param task_count: Number of task scores returned per evaluation.
66 :param sample: Callable (rng) returning an initial genome iterable.
67 :param mutate: Callable (genome, rng) returning an offspring genome.
68 Treat genome elements as immutable.
69 :param bin_capacity: Maximum number of survivors in each task subset.
70 :param batch_size: New candidate evaluations before the next competition.
71 :param max_bins: Cap on automatically generated subsets, defaulting
72 to max(64, 2 * task_count). Large families retain all singletons,
73 the full task, and a seeded selection of other subsets.
74 :param subsets: Optional explicit collection of task index subsets.
75 Include the full task subset. This overrides automatic bin selection.
76 :param aggregate: "mean" or "product" for fitness within each subset.
77 :param seed: Seed for selection, variation, and evaluator seeds.
78 """
79
80 def __init__(self, task_count, *, sample, mutate, bin_capacity=8, batch_size=16,
81 max_bins=None, subsets=None, aggregate="mean", seed=0):
82 self.task_count = _positive_int(task_count, "task_count")
83 self._capacity = _positive_int(bin_capacity, "bin_capacity")
84 self._batch_size = _positive_int(batch_size, "batch_size")
85 if not callable(sample) or not callable(mutate):
86 raise TypeError("sample and mutate must be callable.")
87 if aggregate not in ("mean", "product"):
88 raise ValueError("Choose 'mean' or 'product' task-score aggregation.")
89 self._aggregate = aggregate
90 self._sample, self._mutate = sample, mutate
91 geometry, self._selection, self._variation, self._evaluation = map(
92 np.random.default_rng, np.random.SeedSequence(seed).spawn(4))
93 self._full = tuple(range(self.task_count))
94 if subsets is None:
95 cap = max(64, 2 * self.task_count) if max_bins is None else _positive_int(max_bins, "max_bins")
96 subsets = _choose_subsets(self.task_count, cap, geometry)
97 else:
98 subsets = tuple(tuple(sorted(index(task) for task in subset)) for subset in subsets)
99 if (self._full not in subsets or len(set(subsets)) != len(subsets)
100 or any(not subset or len(set(subset)) != len(subset)
101 or subset[0] < 0 or subset[-1] >= self.task_count for subset in subsets)):
102 raise ValueError("Use distinct nonempty task subsets in range, including the full subset.")
103 self._bins = dict.fromkeys(subsets, ())
104 self._evaluations = self._failures = self._generations = 0
105 self._descriptor_size = None
106
107
108 @property
109 def bins(self):
110 """Return a read-only live view of each subset and its survivors."""
111 return MappingProxyType(self._bins)
112
113
114 @property
115 def best(self):
116 """Return the best measured candidate in the full subset, or None."""
117 return max(self._bins[self._full], key=lambda row: self._fitness(np.asarray(row.task_scores)), default=None)
118
119 @property
120 def stats(self):
121 """Return cumulative attempts, failures, and generations."""
122 return CMOEAStats(self._evaluations, self._failures, self._generations)
123
124 def _fitness(self, scores):
125 if self._aggregate == "mean":
126 return scores.mean(axis=-1)
127 # Log scores have the same ordering as products and avoid underflow.
128 with np.errstate(divide="ignore"):
129 return np.log(scores).sum(axis=-1)
130
131 def _measure(self, evaluate, genome):
132 self._evaluations += 1
133 result = evaluate(genome, int(self._evaluation.integers(2**32)))
134 if result is None:
135 self._failures += 1
136 return None
137 scores, descriptor = (np.asarray(row, dtype=float) for row in result)
138 if scores.shape != (self.task_count,) or not np.all((scores >= 0.) & (scores <= 1.)):
139 raise ValueError("Return one normalized task score in [0, 1] per task.")
140 if descriptor.ndim != 1 or not len(descriptor) or not np.isfinite(descriptor).all():
141 raise ValueError("Return a nonempty finite behavioral descriptor.")
142 if self._descriptor_size is None:
143 self._descriptor_size = len(descriptor)
144 elif len(descriptor) != self._descriptor_size:
145 raise ValueError("Descriptor dimensions must remain fixed throughout the search.")
146 return CMOEARecord(genome, tuple(scores), tuple(descriptor))
147
148 def _survive(self, candidates, subset):
149 if len(candidates) <= self._capacity:
150 return candidates
151 scores = np.asarray([row.task_scores for row in candidates])[:, subset]
152 quality = self._fitness(scores)
153 if self._aggregate == "product":
154 # A common product scaling preserves crowding distances while
155 # retaining precision when every absolute product is tiny.
156 best = quality.max()
157 quality = np.exp(quality - best) if np.isfinite(best) else np.zeros_like(quality)
158 descriptors = np.asarray([row.descriptor for row in candidates])
159 descriptors /= np.abs(descriptors).max() or 1.
160 diversity = cdist(descriptors, descriptors).sum(axis=1) / (len(candidates) - 1)
161 utilities = _pareto_utilities(quality, diversity)
162 survivors = np.argsort(-utilities, kind="stable")[:self._capacity]
163 return tuple(candidates[int(slot)] for slot in survivors)
164
165
169 def run(self, evaluate, budget):
170 """Use all requested attempts, including a shorter final generation."""
171 budget = index(budget)
172 if budget < 0:
173 raise ValueError("budget must be nonnegative.")
174 for start in range(0, budget, self._batch_size):
175 parents = [members for members in self._bins.values() if members]
176 measured = []
177 for _ in range(min(budget - start, self._batch_size)):
178 if parents:
179 source = parents[int(self._selection.integers(len(parents)))]
180 parent = source[int(self._selection.integers(len(source)))]
181 genome = tuple(self._mutate(parent.genome, self._variation))
182 else:
183 genome = tuple(self._sample(self._variation))
184 record = self._measure(evaluate, genome)
185 if record is not None:
186 measured.append(record)
187 if measured:
188 children = tuple(measured)
189 for subset, members in self._bins.items():
190 self._bins[subset] = self._survive(members + children, subset)
191 self._generations += 1
192 return self.stats
One evaluated genotype with every task score and its diversity descriptor.
Definition cmoea.py:38
Cumulative evaluator attempts, failed evaluations, and committed generations.
Definition cmoea.py:48
Preserve solutions to task combinations via local nondominated survival.
Definition cmoea.py:57
_survive(self, candidates, subset)
Definition cmoea.py:148
bins(self)
Return immutable populations indexed by sorted tuples of task indices.
Definition cmoea.py:109
run(self, evaluate, budget)
Spend additional evaluator attempts and commit surviving task populations.
Definition cmoea.py:169
_measure(self, evaluate, genome)
Definition cmoea.py:131
_fitness(self, scores)
Definition cmoea.py:124
best(self)
Return the highest-scoring survivor for all subtasks.
Definition cmoea.py:115