QDpy
Loading...
Searching...
No Matches
optimal_mixing.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Recombine categorical archive members in linked groups of variables."""
7
8from dataclasses import dataclass
9from operator import index
10
11import numpy as np
12from scipy.cluster.hierarchy import linkage
13from scipy.special import entr
14
15from .modern import _positive_int
16from .task_search import _measurement, _offer, _validate_grid
17
18__all__ = ["learn_categorical_linkage", "GOMMAPElites", "GOMSearchStats"]
19
20
21
22def learn_categorical_linkage(genomes):
23 """Cluster variables by normalized empirical mutual information.
24
25 Return singleton groups and all non-root merges, in tree construction
26 order. Use at least two encoded genomes. Invariant columns have zero
27 similarity to other columns. Ties follow SciPy's deterministic linkage.
28 """
29 points = np.asarray(genomes)
30 if points.ndim != 2 or len(points) < 2 or not points.shape[1] or points.dtype.kind not in "biu":
31 raise ValueError("Supply two or more equal-length categorical integer rows.")
32 count, width = points.shape
33 groups = [(column,) for column in range(width)]
34 if width == 1:
35 return tuple(groups)
36 entropy = [entr(np.unique(column, return_counts=True)[1] / count).sum() for column in points.T]
37 distances = []
38 for first in range(width - 1):
39 for second in range(first + 1, width):
40 scale = entropy[first] + entropy[second]
41 if not scale:
42 distances.append(1.)
43 continue
44 joint = np.unique(points[:, [first, second]], axis=0, return_counts=True)[1] / count
45 mutual = scale - entr(joint).sum()
46 distances.append(float(np.clip(1. - 2 * mutual / scale, 0., 1.)))
47 for first, second, _, _ in linkage(distances, method="average")[:-1]:
48 groups.append(tuple(sorted((*groups[int(first)], *groups[int(second)]))))
49 return tuple(groups)
50
51
52
53@dataclass(frozen=True)
55 """Every measured intermediate proposal contributes to evaluations."""
56
57 evaluations: int
58 random_evaluations: int
59 block_evaluations: int
60 accepted_blocks: int
61 linkage_fits: int
62 archive_updates: int
63 out_of_domain: int
64
65
66
68 """Search a product of integer categories using measured block recombination.
69
70 Groups are inferred from archived genomes. Each mix chooses donors
71 from a snapshot so admissions during the mix do not change its gene
72 pool. Offer every measured intermediate to the archive. Continue
73 mixing from a trial if it preserves or improves the parent's scalar
74 fitness, using the archive's comparison direction.
75
76 :param archive: Empty parentless scalar best-only Grid or CVTGrid.
77 :param nvec: Number of categories for each variable, starting at zero.
78 :param initial_samples: Minimum number of initial proposals before mixing.
79 :param random_injection: Probability of a random instead of a mixing proposal.
80 :param linkage_period: Minimum number of measurements between linkage fits.
81 :param learn_linkage: Learn groups or use only singleton groups for a control.
82 :param seed: Private seed for sampling and selecting genomes.
83 """
84
85 def __init__(self, archive, nvec, *, initial_samples=16, random_injection=.05,
86 linkage_period=32, learn_linkage=True, seed=0):
87 _validate_grid(archive)
88 nvec = tuple(_positive_int(size, "category count") for size in nvec)
89 if not nvec or max(nvec) > np.iinfo(np.int64).max:
90 raise ValueError("Use at least one categorical variable with an int64 category count.")
91 if not 0. <= random_injection <= 1. or type(learn_linkage) is not bool:
92 raise ValueError("Use a probability for random_injection and a bool for learn_linkage.")
93 self.archive, self.nvec, self.seed = archive, nvec, seed
94 self.initial_samples = _positive_int(initial_samples, "initial_samples")
95 self.linkage_period = _positive_int(linkage_period, "linkage_period")
96 self.random_injection, self.learn_linkage = random_injection, learn_linkage
97
98 def _seed_genome(self, values):
99 point = tuple(map(index, values))
100 if len(point) != len(self.nvec) or not all(0 <= value < n for value, n in zip(point, self.nvec)):
101 raise ValueError("Seed genomes must use valid categories in every position.")
102 return point
103
104
109 def run(self, evaluate, budget, *, seed_genomes=()):
110 """Fill the supplied empty archive and return its search costs."""
111 if self.archive or not callable(evaluate):
112 raise ValueError("Use an empty archive and a callable evaluator.")
113 budget = _positive_int(budget, "budget")
114 rng = np.random.default_rng(self.seed)
115 archive = self.archive
116 weights = archive.fitness_weights
117 direction = -1. if weights is None or weights[0] < 0. else 1.
118 seeds, sentinel = iter(seed_genomes), object()
119 singles = tuple((column,) for column in range(len(self.nvec)))
120 groups = singles
121 calls = random_calls = block_calls = accepted = fits = outside = 0
122 start_updates = archive.nb_added
123 last_fit = -self.linkage_period
124
125 def measure(genome):
126 nonlocal calls, outside
127 calls += 1
128 fitness, features = evaluate(genome)
129 result = _measurement(archive, ((fitness,), features), genome)
130 outside += result[1] is None
131 _offer(archive, result)
132 return direction * result[0].fitness.values[0]
133
134 def random_point():
135 return tuple(map(int, rng.integers(self.nvec)))
136
137 while calls < budget:
138 supplied = next(seeds, sentinel)
139 if supplied is not sentinel or calls < self.initial_samples or len(archive) < 2 or (
140 rng.random() < self.random_injection):
141 genome = random_point() if supplied is sentinel else self._seed_genome(supplied)
142 measure(genome)
143 random_calls += 1
144 continue
145
146 members = tuple(archive)
147 donors = np.asarray([tuple(member) for member in members], dtype=np.int64)
148 if self.learn_linkage and calls - last_fit >= self.linkage_period:
149 groups = learn_categorical_linkage(donors)
150 fits += 1
151 last_fit = calls
152 parent = int(rng.integers(len(members)))
153 incumbent = donors[parent]
154 quality = direction * archive.get_ind_fitness(members[parent]).values[0]
155 before = calls
156 for group_id in rng.permutation(len(groups)):
157 columns = list(groups[int(group_id)])
158 choices = np.flatnonzero(np.any(donors[:, columns] != incumbent[columns], axis=1))
159 if not len(choices):
160 continue
161 child = incumbent.copy()
162 child[columns] = donors[int(rng.choice(choices)), columns]
163 score = measure(tuple(map(int, child)))
164 block_calls += 1
165 if score >= quality:
166 accepted += 1
167 incumbent, quality = child, score
168 if calls == budget:
169 break
170 if calls == before:
171 measure(random_point())
172 random_calls += 1
173
174 return GOMSearchStats(calls, random_calls, block_calls, accepted, fits, archive.nb_added - start_updates,
175 outside)
Adapt gene-pool optimal mixing to categorical best-only archives.
run(self, evaluate, budget, *, seed_genomes=())
Run a new search with exactly budget objective calls.
Count random measurements, block probes, and updates to the measured archive.