QDpy
Loading...
Searching...
No Matches
bayesian_deep_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Bayesian Deep QD with competitive or balanced configuration proposals."""
7
8import numpy as np
9
10from qdpy.base import registry
11from .conditional_bayesian import ConditionalBayesianQD
12from .deep_qd import DeepQDArchive
13
14__all__ = ["BayesianDeepQD"]
15
16
17
18@registry.register
20 """Use a feasibility-weighted Expected Improvement of the Deep Archive.
21
22 The exact archive holds the best feasible design for each configuration
23 in every occupied cell. The supplied grid shows the best across
24 configurations. Each surrogate prediction competes with the
25 incumbent from its own configuration when present. A candidate for a
26 missing configuration receives a more permissive reference based on
27 estimated unfilled cells in the previous batch's cheap pool.
28
29 Predictions are assigned by posterior-mean descriptor. At most one
30 planned proposal per configuration and cell enters a batch. The
31 default allocates the shared budget competitively. Equal allocation
32 guarantees that configuration attempt counts differ by at most one,
33 including warm-up and an incomplete final batch. Both modes use the
34 same per-layer acquisition; callbacks follow ConditionalBayesianQD.
35
36 :param container: Empty parentless Grid or CVTGrid with capacity for every cell.
37 :param budget: Budget in exact evaluation attempts.
38 :param variables: Mapping of conditional variable specifications.
39 :param configurations: Ordered ConditionalConfiguration sequence.
40 :param allocation: ``competitive`` (default) or ``equal`` attempt allocation.
41 :param kwargs: ConditionalBayesianQD proposal and surrogate settings.
42 """
43
44 def __init__(self, container, budget, variables, *, configurations, allocation="competitive", **kwargs):
45 if container.parents or container.capacity < len(container.solutions):
46 raise ValueError("Bayesian Deep QD requires a parentless archive with capacity for each cell.")
47 if allocation not in ("competitive", "equal"):
48 raise ValueError("Choose competitive or equal allocation.")
49 self.allocation = allocation
50 super().__init__(container, budget, variables, configurations=configurations, **kwargs)
51 self.deep_archive = DeepQDArchive(container, self.configurations)
52
53 def __deepcopy__(self, memo):
54 # QDAlgorithm copies share their supplied archive and its live layers.
55 memo[id(self.deep_archive)] = self.deep_archive
56 return super().__deepcopy__(memo)
57
58 def reinit(self):
59 """Reset acquisition models and counters, retaining the live archive."""
60 super().reinit()
61 count = len(self.configurations)
62 self._predicted = None
63 self._beta = (1.,) * count
64
65 @property
67 """Return the latest deep-archive coverage multipliers in configuration order."""
68 return self._beta
69
70 def _prepare_deep_context(self):
71 total = len(self.container.solutions)
72 filled = self.deep_archive.configuration_counts
73 predicted = filled if self._predicted is None else self._predicted
74 self._beta = tuple(1. + max(estimate - observed, 0) / total for estimate, observed in zip(predicted, filled))
75 self._predicted = list(predicted)
76 qualities = [row[0] for observations in self._observations for _, row in observations]
77 low, high = min(qualities), max(qualities)
78 self._quality_span = high - low
79 if not np.isfinite(self._quality_span):
80 raise ValueError("The EIDA acquisition needs a finite observed fitness span.")
81 self._best_observed = high
82 return low
83
84 def _plan_batch(self, size):
86 return super()._plan_batch(size)
87
88 def _prepare_promotions(self, size):
89 if getattr(self, "allocation", "competitive") == "competitive":
90 super()._prepare_promotions(size)
91 return
92 count = len(self.configurations)
93 if self.nb_suggestions < self.initial_samples * count or not any(self._observations):
94 return
95 plan = [(self.nb_suggestions + offset) % count if self._rng.random() >= self.exploration_probability
96 else None for offset in range(size)]
97 if all(branch is None for branch in plan):
98 return
99 low = self._prepare_deep_context()
100 floor = low if self.quality_floor is None else self._direction * self.quality_floor
101 branch_picks = {}
102 for branch in dict.fromkeys(plan):
103 if branch is None or not self._observations[branch]:
104 continue
105 pool = self._pool(branch, self._observations[branch])
106 if not pool:
107 continue
108 rows = sorted(self._rank_pool(branch, pool, floor), key=lambda row: row[:3], reverse=True)
109 cells = {}
110 for _, _, _, cell, vector in rows:
111 cells.setdefault(cell, vector)
112 branch_picks[branch] = iter(cells.values())
113 for branch in plan:
114 choices = branch_picks.get(branch)
115 self._promoted.append(next(choices, None) if choices is not None else None)
116
117 def _next_vector(self):
118 if getattr(self, "allocation", "competitive") == "competitive":
119 return super()._next_vector()
120 vector = self._promoted.popleft() if self._promoted else None
121 if vector is None:
122 branch = self.nb_suggestions % len(self.configurations)
123 return self._draw(branch, reserved=self._promoted)
124 self._modelled_proposals += 1
125 return vector
126
127 def _rank_pool(self, branch, vectors, floor):
128 ranked = super()._rank_pool(branch, vectors, floor)
129 # Only count cells with a plausible feasible member.
130 self._predicted[branch] = len({row[3] for row in ranked if row[1] >= .5})
131 return ranked
132
133 def _acquisition_reference(self, branch, cell, floor):
134 own = self.deep_archive.cell_elites(cell).get(branch)
135 if own is not None:
136 return self._direction * self.container.get_ind_fitness(own).values[0]
137 if not self.container.solutions[cell]:
138 return floor
139 reference = super()._acquisition_reference(branch, cell, floor)
140 # Use a cost origin one observed span beyond the best quality.
141 # Multiplying positive losses relaxes the signed-quality reference.
142 bonus = self._beta[branch] - 1.
143 if not bonus:
144 return reference
145 gap = max(self._best_observed - reference, 0.)
146 return max(floor, reference - bonus * gap - bonus * self._quality_span)
147
148 def _acquisition_key(self, cell, vector):
149 return cell, vector[0]
150
151 def _offer_feasible(self, individual, cell):
152 return self.deep_archive._offer(individual)
Evaluate conditional designs that improve or populate a layer of a Deep QD archive.
Reuse HiGeME's conditional schema with competitive Bayesian infill.
Read the configuration alternatives held by a DeepQD search.
Definition deep_qd.py:23