QDpy
Loading...
Searching...
No Matches
evolutionary_portfolios.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Evolve sets as individuals, using member quality and within-set diversity."""
7
8from dataclasses import dataclass
9from math import fsum, isfinite
10
11import numpy as np
12from scipy.spatial.distance import cdist
13
14from ._population import _attempt_budget, _nsga_order, _pareto_fronts, _tournament
15from .modern import _positive_int
16
17__all__ = ["EvolutionaryPortfolio", "EvolutionaryPortfolioResult", "evolutionary_portfolios"]
18
19
20
21@dataclass(frozen=True, slots=True)
23 """The diversity is the sum of Hamming distances over unordered member pairs."""
24
25 members: tuple[tuple[int, ...], ...]
26 member_qualities: tuple[float, ...]
27 quality: float
28 diversity: int
29
30
31
32@dataclass(frozen=True, slots=True)
34 """The evaluation budget counts calls for each member, including failures and repeats."""
35
36 portfolios: tuple[EvolutionaryPortfolio, ...]
37 member_evaluations: int
38 failed_members: int
39 portfolio_attempts: int
40 generations: int
41
42
43def _binary(bits, name, width=None):
44 bits = np.asarray(bits)
45 if bits.ndim != 1 or not bits.size or (width is not None and len(bits) != width) or not np.isin(bits, (0, 1)).all():
46 raise ValueError(f"{name} must be a nonempty binary vector of the configured length.")
47 return tuple(map(int, bits))
48
49
50def _hamming_total(descriptors):
51 ones = np.sum(descriptors, axis=0, dtype=np.int64)
52 return int(sum(int(count) * (len(descriptors) - int(count)) for count in ones))
53
54
55def _spea2_order(scores, capacity):
56 dominates = ((scores[:, None] >= scores).all(axis=2) & (scores[:, None] > scores).any(axis=2))
57 raw = dominates.T @ dominates.sum(axis=1)
58 # A common normalized scale keeps the density tie-break comparable across objectives.
59 scaled = scores / np.maximum(1., np.abs(scores).max(axis=0))
60 width = np.ptp(scaled, axis=0)
61 distances = cdist(scaled / np.where(width, width, 1.), scaled / np.where(width, width, 1.))
62 np.fill_diagonal(distances, np.inf)
63 k = min(int(np.sqrt(len(scores))) - 1, len(scores) - 1)
64 fitness = raw + 1. / (2. + np.partition(distances, k, axis=1)[:, k])
65 selected = np.flatnonzero(raw == 0).tolist()
66 if len(selected) <= capacity:
67 selected = np.argsort(fitness, kind="stable")[:capacity].tolist()
68 else:
69 while len(selected) > capacity:
70 neighborhood = np.sort(distances[np.ix_(selected, selected)], axis=1)
71 crowded = min(range(len(selected)), key=lambda i: (tuple(neighborhood[i]), -selected[i]))
72 selected.pop(crowded)
73 return selected, [(fitness[i],) for i in selected]
74
75
76
90def evolutionary_portfolios(evaluate, *, dimension, portfolio_size, budget, population_size=20,
91 quality="mean", method="nsga2", crossover_probability=.8,
92 mutation_probability=None, descriptor=None, repair=None, seed=0):
93 """Treat a concatenation of member bit strings as a single evolutionary individual.
94
95 Uniform crossover shuffles the second parent's member order before
96 exchanging bits. Mutation flips bits independently. The optional
97 descriptor changes the space where Hamming distances are computed,
98 for example from vertex indicators to cut-edge indicators.
99
100 Every member slot is evaluated. Repeated designs are allowed and
101 contribute zero pair distance to an identical descriptor. A failed
102 member excludes its portfolio from selection. Pass a repair callback
103 to enforce constraints before evaluation, or handle them in the
104 evaluator. The uniform control uses random proposals and the same
105 bounded NSGA-II survival rule.
106 """
107 dimension = _positive_int(dimension, "dimension")
108 portfolio_size = _positive_int(portfolio_size, "portfolio_size")
109 population_size = _positive_int(population_size, "population_size")
110 budget = _attempt_budget(budget)
111 if method not in ("nsga2", "spea2", "uniform") or quality not in ("mean", "worst"):
112 raise ValueError("Choose nsga2, spea2, or uniform and mean or worst portfolio quality.")
113 rate = .5 / dimension if mutation_probability is None else mutation_probability
114 if not (0. <= crossover_probability <= 1. and 0. <= rate <= 1.):
115 raise ValueError("Mutation and crossover probabilities must be in [0, 1].")
116 if not callable(evaluate) or any(callback is not None and not callable(callback) for callback in (descriptor, repair)):
117 raise TypeError("Supply a callable evaluator and optional descriptor and repair callbacks.")
118
119 rng = np.random.default_rng(seed)
120 population, keys = [], []
121 attempts = failures = generations = 0
122 descriptor_width = None
123 while (count := min(population_size, budget // portfolio_size - attempts)) > 0:
124 children = []
125 for _ in range(count):
126 if not population or method == "uniform":
127 bits = rng.integers(2, size=(portfolio_size, dimension))
128 else:
129 first = np.asarray(_tournament(population, keys, rng).members)
130 if rng.random() < crossover_probability:
131 second = np.asarray(_tournament(population, keys, rng).members)[rng.permutation(portfolio_size)]
132 first = np.where(rng.random(first.shape) < .5, first, second)
133 bits = np.bitwise_xor(first, rng.random(first.shape) < rate)
134 members, values, descriptors = [], [], []
135 attempts += 1
136 for row in bits:
137 member = tuple(map(int, row))
138 if repair is not None:
139 member = _binary(repair(member), "Repaired member", dimension)
140 result = evaluate(member)
141 if result is None:
142 failures += 1
143 continue
144 value = float(result)
145 if not isfinite(value):
146 raise ValueError("Member quality must be finite.")
147 measured = member if descriptor is None else _binary(descriptor(member), "Descriptor", descriptor_width)
148 descriptor_width = len(measured)
149 members.append(member)
150 descriptors.append(measured)
151 values.append(value)
152 if len(members) == portfolio_size:
153 score = min(values) if quality == "worst" else fsum(value / portfolio_size for value in values)
154 children.append(EvolutionaryPortfolio(tuple(members), tuple(values), score, _hamming_total(descriptors)))
155 combined = population + children
156 if combined:
157 scores = np.asarray([(row.quality, row.diversity) for row in combined])
158 survivor = _spea2_order if method == "spea2" else _nsga_order
159 selected, keys = survivor(scores, population_size)
160 population = [combined[i] for i in selected]
161 generations += 1
162 front = {}
163 if population:
164 scores = np.asarray([(row.quality, row.diversity) for row in population])
165 for i in next(_pareto_fronts(scores)):
166 row = population[i]
167 front.setdefault((row.quality, row.diversity), row)
168 return EvolutionaryPortfolioResult(tuple(front[key] for key in sorted(front, reverse=True)),
169 attempts * portfolio_size, failures, attempts, generations)
Return the final nondominated portfolios and exact search accounting.
Store one evaluated set and its measured quality and diversity objectives.