Source code for qdpy.algorithms.bayesian_deep_qd

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Bayesian illumination of configuration alternatives in a deep archive.
# @see https://doi.org/10.1016/j.ast.2026.113578

"""Bayesian Deep QD with competitive or balanced configuration proposals."""

import numpy as np

from qdpy.base import registry
from .conditional_bayesian import ConditionalBayesianQD
from .deep_qd import DeepQDArchive

__all__ = ["BayesianDeepQD"]


## @brief Evaluate conditional designs that improve or populate a layer of a Deep QD archive.
[docs] @registry.register class BayesianDeepQD(ConditionalBayesianQD): """Use a feasibility-weighted Expected Improvement of the Deep Archive. The exact archive holds the best feasible design for each configuration in every occupied cell. The supplied grid shows the best across configurations. Each surrogate prediction competes with the incumbent from its own configuration when present. A candidate for a missing configuration receives a more permissive reference based on estimated unfilled cells in the previous batch's cheap pool. Predictions are assigned by posterior-mean descriptor. At most one planned proposal per configuration and cell enters a batch. The default allocates the shared budget competitively. Equal allocation guarantees that configuration attempt counts differ by at most one, including warm-up and an incomplete final batch. Both modes use the same per-layer acquisition; callbacks follow ConditionalBayesianQD. :param container: Empty parentless Grid or CVTGrid with capacity for every cell. :param budget: Budget in exact evaluation attempts. :param variables: Mapping of conditional variable specifications. :param configurations: Ordered ConditionalConfiguration sequence. :param allocation: ``competitive`` (default) or ``equal`` attempt allocation. :param kwargs: ConditionalBayesianQD proposal and surrogate settings. """ def __init__(self, container, budget, variables, *, configurations, allocation="competitive", **kwargs): if container.parents or container.capacity < len(container.solutions): raise ValueError("Bayesian Deep QD requires a parentless archive with capacity for each cell.") if allocation not in ("competitive", "equal"): raise ValueError("Choose competitive or equal allocation.") self.allocation = allocation super().__init__(container, budget, variables, configurations=configurations, **kwargs) self.deep_archive = DeepQDArchive(container, self.configurations) def __deepcopy__(self, memo): # QDAlgorithm copies share their supplied archive and its live layers. memo[id(self.deep_archive)] = self.deep_archive return super().__deepcopy__(memo)
[docs] def reinit(self): """Reset acquisition models and counters, retaining the live archive.""" super().reinit() count = len(self.configurations) self._predicted = None self._beta = (1.,) * count
@property def coverage_multipliers(self): """Return the latest deep-archive coverage multipliers in configuration order.""" return self._beta def _prepare_deep_context(self): total = len(self.container.solutions) filled = self.deep_archive.configuration_counts predicted = filled if self._predicted is None else self._predicted self._beta = tuple(1. + max(estimate - observed, 0) / total for estimate, observed in zip(predicted, filled)) self._predicted = list(predicted) qualities = [row[0] for observations in self._observations for _, row in observations] low, high = min(qualities), max(qualities) self._quality_span = high - low if not np.isfinite(self._quality_span): raise ValueError("The EIDA acquisition needs a finite observed fitness span.") self._best_observed = high return low def _plan_batch(self, size): self._prepare_deep_context() return super()._plan_batch(size) def _prepare_promotions(self, size): if getattr(self, "allocation", "competitive") == "competitive": super()._prepare_promotions(size) return count = len(self.configurations) if self.nb_suggestions < self.initial_samples * count or not any(self._observations): return plan = [(self.nb_suggestions + offset) % count if self._rng.random() >= self.exploration_probability else None for offset in range(size)] if all(branch is None for branch in plan): return low = self._prepare_deep_context() floor = low if self.quality_floor is None else self._direction * self.quality_floor branch_picks = {} for branch in dict.fromkeys(plan): if branch is None or not self._observations[branch]: continue pool = self._pool(branch, self._observations[branch]) if not pool: continue rows = sorted(self._rank_pool(branch, pool, floor), key=lambda row: row[:3], reverse=True) cells = {} for _, _, _, cell, vector in rows: cells.setdefault(cell, vector) branch_picks[branch] = iter(cells.values()) for branch in plan: choices = branch_picks.get(branch) self._promoted.append(next(choices, None) if choices is not None else None) def _next_vector(self): if getattr(self, "allocation", "competitive") == "competitive": return super()._next_vector() vector = self._promoted.popleft() if self._promoted else None if vector is None: branch = self.nb_suggestions % len(self.configurations) return self._draw(branch, reserved=self._promoted) self._modelled_proposals += 1 return vector def _rank_pool(self, branch, vectors, floor): ranked = super()._rank_pool(branch, vectors, floor) # Only count cells with a plausible feasible member. self._predicted[branch] = len({row[3] for row in ranked if row[1] >= .5}) return ranked def _acquisition_reference(self, branch, cell, floor): own = self.deep_archive.cell_elites(cell).get(branch) if own is not None: return self._direction * self.container.get_ind_fitness(own).values[0] if not self.container.solutions[cell]: return floor reference = super()._acquisition_reference(branch, cell, floor) # Use a cost origin one observed span beyond the best quality. # Multiplying positive losses relaxes the signed-quality reference. bonus = self._beta[branch] - 1. if not bonus: return reference gap = max(self._best_observed - reference, 0.) return max(floor, reference - bonus * gap - bonus * self._quality_span) def _acquisition_key(self, cell, vector): return cell, vector[0] def _offer_feasible(self, individual, cell): return self.deep_archive._offer(individual)