24 return Grid(shape=(max_items + 1,), features_domain=((-.5, max_items + .5),),
25 fitness_domain=(tuple(fitness_domain),), fitness_weights=(fitness_weight,))
28def _cardinality_options(dimension, max_items, mutation_probability, fitness_weight):
50 """Search bit vectors indexed by the number of selected coordinates.
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.
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.
66 def __init__(self, dimension, *, max_items=None, mutation_probability=None,
67 fitness_domain=(-np.inf, np.inf), fitness_weight=1., seed=0):
69 dimension, max_items, mutation_probability, fitness_weight)
70 self.
archive = _cardinality_grid(self.
max_items, fitness_domain, fitness_weight)
72 self.
_rng = np.random.default_rng(seed)
77 """Translate the binary genome to its sorted tuple of indices."""
78 return tuple(i
for i, bit
in enumerate(individual)
if bit)
82 """Return an archived Individual, or None when no measured option fits."""
83 limit = index(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)
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:
104 bits = np.zeros(self.
dimension, dtype=bool)
108 subset = tuple(map(int, np.flatnonzero(bits)))
112 fitness = (float(evaluate(subset)),)
114 if not isfinite(fitness[0]):
115 raise ValueError(
"The objective must be finite.")
119 updates += self.
archive.add(elite)
is not None
161 """Optimize overlapping subset problems with one objective evaluation per proposal.
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.
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.
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.")
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.")
195 self.
_rng = np.random.default_rng(seed)
197 fitness_domain = tuple(fitness_domain)
198 self.
archives = {name: _cardinality_grid(self.
max_items, fitness_domain, fitness_weight)
202 for name, rule
in self.
_rules.items():
205 bits = np.zeros(self.
dimension, dtype=bool)
206 bits[list(rule.required)] =
True
208 parents = [entry
for archive
in self.
archives.values()
for entry
in archive]
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
218 first = parents[int(self.
_rng.integers(len(parents)))]
220 second = parents[int(self.
_rng.integers(len(parents)))]
221 first = np.where(self.
_rng.random(self.
dimension) < .5, first, second)
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:
235 subset = tuple(map(int, np.flatnonzero(bits)))
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)]
245 fitness = (float(evaluate(subset)),)
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:
254 updates += archive.add(elite)
is not None