QDpy
Loading...
Searching...
No Matches
sade_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Adapt variation between critical-path edits and guided block-wise differential evolution."""
7
8from dataclasses import dataclass
9
10import numpy as np
11
12from ._population import _attempt_budget, _finite_vector
13from .modern import _positive_int
14from .task_search import _measurement, _offer, _validate_grid
15
16__all__ = ["SADEQDResult", "sade_qd"]
17
18
19
20@dataclass(frozen=True)
22 """Report evaluations by proposal type, including guided DE followed by a critical edit."""
23
24 archive: object
25 evaluations: int
26 samples: int
27 critical_edits: int
28 guided_steps: int
29 admissions: int
30
31
32def _guided_block(base, transport, idle, scale, block):
33 if block == 0:
34 return base + scale * (transport + idle - 2. * base)
35 edge = transport if block == 1 else idle
36 return base + scale * (base - edge)
37
38
39
52def sade_qd(archive, evaluate, critical_edit, *, block_sizes, budget, initial_samples=16, stall=12,
53 edge_pool=20, scale=.5, guided_probability=.75, seed=0):
54 """Search one native grid with the paper's three guided DE formulas.
55
56 A genome contains three contiguous blocks of keys in [0, 1].
57 Begin with random keys, then ask the caller to edit a critical
58 component of a measured archive member. When admissions stall,
59 use a random elite and donors with low transport or idle time.
60 The measured DE proposal supplies the next critical edit even
61 when it has not entered the archive. Both calls count toward budget.
62 """
63 _validate_grid(archive)
64 if len(archive.features_domain) != 2 or not callable(evaluate) or not callable(critical_edit):
65 raise ValueError("Supply a two-axis archive and callable schedule evaluation and edits.")
66 sizes = tuple(_positive_int(size, "block_sizes") for size in block_sizes)
67 if len(sizes) != 3 or not 0 < scale <= 1 or not 0 <= guided_probability <= 1:
68 raise ValueError("Use three blocks, a scale in (0, 1], and a probability in [0, 1].")
69 budget, initial = _attempt_budget(budget), _attempt_budget(initial_samples)
70 stall, count = _positive_int(stall, "stall"), _positive_int(edge_pool, "edge_pool")
71 offsets = np.cumsum((0, *sizes))
72 if archive.fitness_weights is None:
73 archive._set_fitness_weights((-1.,))
74 rng = np.random.default_rng(seed)
75 payloads = {}
76 follow_up = None
77 samples = edits = guided = stale = 0
78 before = archive.nb_added
79
80 for step in range(budget):
81 block = int(rng.integers(3))
82 guided_block = None
83 if follow_up is not None:
84 source, payload, block = follow_up
85 follow_up = None
86 genome = critical_edit(source, payload, block, rng)
87 edits += 1
88 elif step < initial or not archive:
89 genome = rng.uniform(size=offsets[-1])
90 samples += 1
91 elif len(archive) >= 2 and stale >= stall and rng.random() < guided_probability:
92 source = archive[int(rng.integers(len(archive)))]
93 elite_pool = [elite for elite in archive if elite is not source]
94 donors = [sorted(elite_pool, key=lambda elite: elite.features.values[axis])[:count] for axis in (0, 1)]
95 transport, idle = (group[int(rng.integers(len(group)))] for group in donors)
96 active = slice(offsets[block], offsets[block + 1])
97 genome = np.asarray(source, dtype=float).copy()
98 genome[active] = np.clip(_guided_block(genome[active], np.asarray(transport[active]),
99 np.asarray(idle[active]), scale, block), 0., 1.)
100 guided += 1
101 guided_block = block
102 else:
103 parent = archive[int(rng.integers(len(archive)))]
104 genome = critical_edit(tuple(parent), payloads[archive.index_grid(parent)], block, rng)
105 edits += 1
106 genome = _finite_vector(genome, "Schedule keys", offsets[-1])
107 if not all(0 <= value <= 1 for value in genome):
108 raise ValueError("Every schedule key must lie in [0, 1].")
109 fitness, descriptors, payload = evaluate(genome)
110 candidate = _measurement(archive, ((fitness,), descriptors), genome)
111 previous = archive.nb_added
112 _offer(archive, candidate)
113 if archive.nb_added != previous:
114 payloads[candidate[1]] = payload
115 stale = 0
116 else:
117 stale += 1
118 if guided_block is not None:
119 follow_up = (genome, payload, guided_block)
120 return SADEQDResult(archive, budget, samples, edits, guided, archive.nb_added - before)
Archive and counts for every attempted schedule measurement.
Definition sade_qd.py:21