QDpy
Loading...
Searching...
No Matches
cardinality.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Find good subsets across several cardinality budgets in one run."""
7
8from collections.abc import Mapping
9from dataclasses import dataclass
10from math import isfinite
11from operator import index
12
13import numpy as np
14
15from qdpy.containers import Grid
16from qdpy.phenotype import Features, Fitness, Individual
17from .modern import _positive_int
18
19__all__ = ["CardinalityMAPElites", "CardinalitySearchStats", "BooleanConjunction",
20 "ConjunctionMAPElites", "ConjunctionSearchStats"]
21
22
23def _cardinality_grid(max_items, fitness_domain, fitness_weight):
24 return Grid(shape=(max_items + 1,), features_domain=((-.5, max_items + .5),),
25 fitness_domain=(tuple(fitness_domain),), fitness_weights=(fitness_weight,))
26
27
28def _cardinality_options(dimension, max_items, mutation_probability, fitness_weight):
29 dimension = _positive_int(dimension, "dimension")
30 limit = dimension if max_items is None else index(max_items)
31 probability = 1. / dimension if mutation_probability is None else mutation_probability
32 if not 0 <= limit <= dimension or not 0 < probability <= 1 or not isfinite(fitness_weight) or not fitness_weight:
33 raise ValueError("Use max_items in [0, dimension], a positive flip rate, and a signed fitness weight.")
34 return dimension, limit, probability
35
36
37
38@dataclass(frozen=True)
40 """Rejected over-budget proposals spend proposal slots only."""
41
42 proposals: int
43 evaluations: int
44 over_limit: int
45 archive_updates: int
46
47
48
50 """Search bit vectors indexed by the number of selected coordinates.
51
52 The first measurement is the empty subset. Subsequent proposals flip
53 each bit independently with probability 1 / dimension by default.
54 The evaluator receives a tuple containing the indices of selected
55 items. Inspect the bit-vector elites through archive or use
56 best_at_most() to choose an option for one cardinality budget.
57
58 :param dimension: Number of items available for selection.
59 :param max_items: Largest allowed cardinality. Defaults to dimension.
60 :param mutation_probability: Optional independent per-bit flip probability.
61 :param fitness_domain: Closed interval of admissible raw objective values.
62 :param fitness_weight: Nonzero finite sign and magnitude of the objective.
63 :param seed: Private proposal seed.
64 """
65
66 def __init__(self, dimension, *, max_items=None, mutation_probability=None,
67 fitness_domain=(-np.inf, np.inf), fitness_weight=1., seed=0):
68 self.dimension, self.max_items, self.mutation_probability = _cardinality_options(
69 dimension, max_items, mutation_probability, fitness_weight)
70 self.archive = _cardinality_grid(self.max_items, fitness_domain, fitness_weight)
71 self._weight = fitness_weight
72 self._rng = np.random.default_rng(seed)
73
74
75 @staticmethod
76 def subset(individual):
77 """Translate the binary genome to its sorted tuple of indices."""
78 return tuple(i for i, bit in enumerate(individual) if bit)
79
80
81 def best_at_most(self, max_items):
82 """Return an archived Individual, or None when no measured option fits."""
83 limit = index(max_items)
84 if not 0 <= limit <= self.max_items:
85 raise ValueError("The requested limit must be in the configured cardinality range.")
86 return max((ind for ind in self.archive if ind.features.values[0] <= limit),
87 key=lambda ind: self._weight * ind.fitness.values[0], default=None)
88
89
94 def run(self, evaluate, budget, *, proposal_limit=None):
95 """Continue search and keep exact-cardinality elites in native grid cells."""
96 budget = _positive_int(budget, "budget")
97 limit = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
98 if not callable(evaluate):
99 raise TypeError("evaluate must be callable.")
100 proposals = evaluations = rejected = updates = 0
101 while proposals < limit and evaluations < budget:
102 proposals += 1
103 if not len(self.archive):
104 bits = np.zeros(self.dimension, dtype=bool)
105 else:
106 parent = self.archive[self._rng.integers(len(self.archive))]
107 bits = np.logical_xor(parent, self._rng.random(self.dimension) < self.mutation_probability)
108 subset = tuple(map(int, np.flatnonzero(bits)))
109 if len(subset) > self.max_items:
110 rejected += 1
111 continue
112 fitness = (float(evaluate(subset)),)
113 evaluations += 1
114 if not isfinite(fitness[0]):
115 raise ValueError("The objective must be finite.")
116 if self.archive.in_bounds(fitness, self.archive.fitness_domain):
117 elite = Individual(bits.astype(int).tolist(), fitness=Fitness(fitness, weights=(self._weight,)),
118 features=Features((len(subset),)))
119 updates += self.archive.add(elite) is not None
120 return CardinalitySearchStats(proposals, evaluations, rejected, updates)
121
122
123
124@dataclass(frozen=True)
126 """Match a subset containing every required index and no excluded index."""
127
128 required: frozenset[int] = frozenset()
129 excluded: frozenset[int] = frozenset()
130
131 def __post_init__(self):
132 required = frozenset(map(index, self.required))
133 excluded = frozenset(map(index, self.excluded))
134 if required & excluded or any(i < 0 for i in required | excluded):
135 raise ValueError("Rule indices must be nonnegative and the two sets must be disjoint.")
136 object.__setattr__(self, "required", required)
137 object.__setattr__(self, "excluded", excluded)
138
139
140 def matches(self, subset):
141 """Return whether all required indices and no excluded indices are selected."""
142 selected = set(subset)
143 return self.required <= selected and self.excluded.isdisjoint(selected)
144
145
146
147@dataclass(frozen=True)
149 """Count measured subsets, rejected proposals, and updates across rule archives."""
150
151 proposals: int
152 evaluations: int
153 over_limit: int
154 unmatched: int
155 archive_updates: int
156
157
158
161 """Optimize overlapping subset problems with one objective evaluation per proposal.
162
163 Give each rule a named cardinality archive. Try the required
164 subset for every rule that still has an empty archive. Later
165 choose parents uniformly across occupied rule/cardinality cells. Use
166 independent bit flips and optional uniform crossover. A proposed
167 subset matching several rules may improve all their archives.
168
169 :param dimension: Number of available items.
170 :param rules: Mapping from nonempty names to BooleanConjunction objects.
171 :param max_items: Largest admissible subset size shared by the rules.
172 :param mutation_probability: Independent bit flip rate.
173 :param crossover_probability: Probability of choosing two parents and
174 mixing their bits before mutation.
175 :param fitness_domain: Closed interval of admissible raw objective values.
176 :param fitness_weight: Signed objective weight. Positive maximizes.
177 :param seed: Private variation seed.
178 """
179
180 def __init__(self, dimension, rules, *, max_items=None, mutation_probability=None,
181 crossover_probability=0., fitness_domain=(-np.inf, np.inf), fitness_weight=1., seed=0):
182 if not isinstance(rules, Mapping) or not rules or any(
183 not isinstance(name, str) or not name or not isinstance(rule, BooleanConjunction)
184 for name, rule in rules.items()):
185 raise ValueError("Provide named BooleanConjunction rules.")
186 self.dimension, self.max_items, self.mutation_probability = _cardinality_options(
187 dimension, max_items, mutation_probability, fitness_weight)
188 if not 0. <= crossover_probability <= 1.:
189 raise ValueError("crossover_probability must lie in [0, 1].")
190 if any(len(rule.required) > self.max_items
191 or any(i >= self.dimension for i in rule.required | rule.excluded) for rule in rules.values()):
192 raise ValueError("Every rule must be feasible within the item and cardinality bounds.")
193 self._rules = dict(rules)
194 self.crossover_probability, self._weight = crossover_probability, fitness_weight
195 self._rng = np.random.default_rng(seed)
196 self._seeded = set()
197 fitness_domain = tuple(fitness_domain)
198 self.archives = {name: _cardinality_grid(self.max_items, fitness_domain, fitness_weight)
199 for name in self._rules}
200
201 def _propose(self):
202 for name, rule in self._rules.items():
203 if name not in self._seeded and not self.archives[name]:
204 self._seeded.add(name)
205 bits = np.zeros(self.dimension, dtype=bool)
206 bits[list(rule.required)] = True
207 return bits
208 parents = [entry for archive in self.archives.values() for entry in archive]
209 if not parents:
210 rules = tuple(self._rules.values())
211 rule = rules[self._rng.integers(len(rules))]
212 available = sorted(set(range(self.dimension)) - rule.required - rule.excluded)
213 count = self._rng.integers(min(len(available), self.max_items - len(rule.required)) + 1)
214 indices = self._rng.choice(available, size=count, replace=False).astype(int)
215 bits = np.zeros(self.dimension, dtype=bool)
216 bits[list(rule.required)] = bits[indices] = True
217 return bits
218 first = parents[int(self._rng.integers(len(parents)))]
219 if self.crossover_probability and self._rng.random() < self.crossover_probability:
220 second = parents[int(self._rng.integers(len(parents)))]
221 first = np.where(self._rng.random(self.dimension) < .5, first, second)
222 return np.logical_xor(first, self._rng.random(self.dimension) < self.mutation_probability)
223
224
225 def run(self, evaluate, budget, *, proposal_limit=None):
226 """Call evaluate(subset) with sorted selected indices and return per-call counts."""
227 if not callable(evaluate):
228 raise TypeError("evaluate must be callable.")
229 budget = _positive_int(budget, "budget")
230 limit = 10 * budget if proposal_limit is None else _positive_int(proposal_limit, "proposal_limit")
231 proposals = calls = over_limit = unmatched = updates = 0
232 while proposals < limit and calls < budget:
233 proposals += 1
234 bits = self._propose()
235 subset = tuple(map(int, np.flatnonzero(bits)))
236 if len(subset) > self.max_items:
237 over_limit += 1
238 continue
239 selected = set(subset)
240 matches = [self.archives[name] for name, rule in self._rules.items()
241 if rule.required <= selected and rule.excluded.isdisjoint(selected)]
242 if not matches:
243 unmatched += 1
244 continue
245 fitness = (float(evaluate(subset)),)
246 calls += 1
247 if not isfinite(fitness[0]):
248 raise ValueError("The objective must be finite.")
249 if matches[0].in_bounds(fitness, matches[0].fitness_domain):
250 genome = bits.astype(int).tolist()
251 for archive in matches:
252 elite = Individual(genome, fitness=Fitness(fitness, weights=(self._weight,)),
253 features=Features((len(subset),)))
254 updates += archive.add(elite) is not None
255 return ConjunctionSearchStats(proposals, calls, over_limit, unmatched, updates)
Require all named binary literals in a subset-selection problem.
matches(self, subset)
Test a subset against all literals.
Use independent bit flips and keep the best solution for each subset size.
best_at_most(self, max_items)
Return the highest-quality measured elite within a cardinality limit.
run(self, evaluate, budget, *, proposal_limit=None)
Spend an objective budget and a separate proposal cap.
subset(individual)
Return selected item indices from one archived bit vector.
Candidate and objective counts for one subset-search run.
Route one measured binary subset into each matching cardinality archive.
run(self, evaluate, budget, *, proposal_limit=None)
Spend an additional objective budget and a separate proposal cap.
Costs of a shared subset-search run.
:param obj: Slice indicating on which objectives the domination is tested.
Definition phenotype.py:405