Source code for qdpy.algorithms.conditional_bayesian

# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Bayesian illumination with separate models for each conditional design space.
# @see https://doi.org/10.1007/s11081-025-10041-w

"""Promote promising designs across conditional subspaces under an exact-call budget."""

from collections import deque
from functools import partial

import numpy as np
from scipy.special import ndtr

from qdpy.base import registry
from .bayesian import _expected_improvement
from .constrained import HiGeME, RealVariable, _constraint_violation, _mutate_gene, _sample_gene
from .mixed_bayesian import _MixedGaussianProcess, _gower_covariance
from .modern import _positive_int

__all__ = ["ConditionalBayesianQD"]


class _BranchModel:
    """Fit objective, descriptor and residual GPs using only active genes."""

    def __init__(self, search, branch):
        self.active = search._active[branch]
        self.continuous = np.asarray([isinstance(search.variables[i], RealVariable) for i in self.active], dtype=bool)
        lower = [search._bounds[i][0] for i in self.active if isinstance(search.variables[i], RealVariable)]
        upper = [search._bounds[i][1] for i in self.active if isinstance(search.variables[i], RealVariable)]
        self.origin = np.asarray(lower)
        self.span = np.asarray([hi - lo or 1. for lo, hi in zip(lower, upper)])
        covariance = partial(_gower_covariance, continuous=self.continuous,
                             length_scale=search.real_length_scale, correlation=search.discrete_correlation)
        genomes, responses = zip(*search._observations[branch])
        self.gp = _MixedGaussianProcess(self._encode(genomes), np.asarray(responses), covariance)

    def _encode(self, genomes):
        points = np.asarray([[genome[i + 1] for i in self.active] for genome in genomes], dtype=float)
        real = self.continuous
        points[:, real] = (points[:, real] - self.origin) / self.span
        return points

    def predict(self, genomes):
        return self.gp.predict(self._encode(genomes))


def _probability_feasible(mean, sigma):
    with np.errstate(over="ignore"):
        z = np.divide(-mean, sigma, out=np.zeros_like(mean), where=sigma > 0)
    return np.prod(np.where(sigma > 0, ndtr(z), mean <= 0.), axis=-1)


## @brief Reuse HiGeME's conditional schema with competitive Bayesian infill.
[docs] @registry.register class ConditionalBayesianQD(HiGeME): """Fit per-configuration surrogates and promote exact evaluations into a shared grid. Each cheap pool uses a mix of uniform designs and perturbations of prior measurements from that configuration. Assign each predicted design to its posterior-mean descriptor cell. Rank proposals by feasibility-weighted expected improvement over the measured cell incumbent. Select at most one predicted winner per cell per batch before filling unused slots. Only measured feasible designs are offered to the reporting grid. :param container: Empty best-only Grid or CVTGrid with one objective. :param budget: Total exact evaluation attempts. :param variables: Ordered mapping from variable names to HiGeME gene specifications. :param configurations: Allowed ConditionalConfiguration objects. :param initial_samples: Space-filling draws per configuration before fitting. :param surrogate_budget: Candidate prediction attempts per fitted configuration and batch. :param quality_floor: Optional raw fitness reference for empty cells. By default use the worst signed fitness measured so far. :param exploration_probability: Chance of a fresh random draw after warm-up. :param real_length_scale: Gaussian length scale on normalized real genes. :param discrete_correlation: Kernel factor for mismatched discrete genes. :param batch_size: Total exact proposals per acquisition update. :param seed: Private random seed. :param optimisation_task: Single objective direction or weight. Defaults to the supplied archive's direction when set. """ def __init__(self, container, budget, variables, *, configurations, initial_samples=4, surrogate_budget=96, quality_floor=None, exploration_probability=.1, real_length_scale=.25, discrete_correlation=.25, batch_size=1, seed=0, optimisation_task=None): if not (0 <= exploration_probability <= 1 and 0 < real_length_scale < np.inf and 0 <= discrete_correlation < 1): raise ValueError("Use finite GP settings and an exploration probability in [0, 1].") if quality_floor is not None and not np.isfinite(quality_floor): raise ValueError("quality_floor must be finite.") self.initial_samples = _positive_int(initial_samples, "initial_samples") self.surrogate_budget = _positive_int(surrogate_budget, "surrogate_budget") self.quality_floor = quality_floor self.exploration_probability = exploration_probability self.real_length_scale, self.discrete_correlation = real_length_scale, discrete_correlation if optimisation_task is None: optimisation_task = "minimisation" if container.fitness_weights is None else container.fitness_weights super().__init__(container, budget, variables, configurations=configurations, seed=seed, batch_size=batch_size, optimisation_task=optimisation_task) self._direction = float(np.sign(self._fitness_weights[0])) if not np.isfinite(self._fitness_weights[0]) or not self._direction: raise ValueError("Use a finite nonzero fitness weight.") active = {i for branch in self._active for i in branch} if any(not isinstance(self.variables[i], RealVariable) and max(map(abs, self._bounds[i])) > 2**53 for i in active): raise ValueError("Active discrete genes must be exactly representable in float64.") self._mutable_by_branch = tuple(tuple(i for i in indices if self._bounds[i][0] < self._bounds[i][1]) for indices in self._active) def reinit(self): """Reset models, proposal streams, and conditional evaluation counts.""" super().reinit() self._observations = [[] for _ in self.configurations] self._counts = [0] * len(self.configurations) self._seen, self._promoted = set(), deque() self._surrogate_evaluations = self._model_fits = self._modelled_proposals = 0 @property def configuration_attempts(self): """Return exact proposals in configuration order, including failed evaluations.""" return tuple(self._counts) @property def configuration_observations(self): """Return counts of finite observations used by each configuration model.""" return tuple(map(len, self._observations)) @property def surrogate_evaluations(self): """Return the number of distinct cheap predictions across all batches.""" return self._surrogate_evaluations @property def model_fits(self): """Return the number of per-configuration model refits.""" return self._model_fits @property def modelled_proposals(self): """Return exact proposals chosen by the surrogate.""" return self._modelled_proposals def _random(self, branch): genome = [lo for lo, _ in self._bounds] for i in self._active[branch]: genome[i] = _sample_gene(self.variables[i], self._bounds[i], self._rng) return (branch, *genome) def _draw(self, branch, reserved=()): for _ in range(64): vector = self._random(branch) if vector not in self._seen and vector not in reserved: break return vector def _pool(self, branch, observations): """Draw cheap trials from between and around prior exact designs.""" mutable = self._mutable_by_branch[branch] if not mutable: return () pool = {} for _ in range(self.surrogate_budget): if self._rng.random() < .5: genome = list(self._rng.choice(observations)[0]) i = self._rng.choice(mutable) genome[i + 1] = _mutate_gene(genome[i + 1], self.variables[i], self._bounds[i], .15, self._rng) vector = tuple(genome) else: vector = self._random(branch) if vector not in self._seen: pool[vector] = None return tuple(pool) def _rank_pool(self, branch, vectors, floor): model = _BranchModel(self, branch) self._model_fits += 1 means, deviations = model.predict(vectors) self._surrogate_evaluations += len(vectors) grid = self.container width = len(grid.features_domain) probability = _probability_feasible(means[:, width + 1:], deviations[:, width + 1:]) rows = [] for i, vector in enumerate(vectors): features = tuple(means[i, 1:width + 1]) if not np.isfinite(features).all() or not grid.in_bounds(features, grid.features_domain): continue cell = grid.index_grid(features) threshold = self._acquisition_reference(branch, cell, floor) rows.append((i, threshold, cell, vector)) if not rows: return () indices, thresholds, _, _ = zip(*rows) indices = list(indices) with np.errstate(over="ignore", divide="ignore", invalid="ignore"): improvement = _expected_improvement(means[indices, 0], deviations[indices, 0], np.asarray(thresholds)) scores = probability[indices] * improvement return [(float(score), float(probability[i]), float(deviations[i, 0]), cell, vector) for (i, _, cell, vector), score in zip(rows, scores) if np.isfinite(score)] def _acquisition_reference(self, branch, cell, floor): occupants = self.container.solutions[cell] return self._direction * self.container.get_ind_fitness(occupants[0]).values[0] if occupants else floor def _acquisition_key(self, cell, vector): return cell def _plan_batch(self, size): floor = (self._direction * self.quality_floor if self.quality_floor is not None else min(row[0] for observations in self._observations for _, row in observations)) ranked = [] for branch, observations in enumerate(self._observations): if observations: pool = self._pool(branch, observations) if pool: ranked.extend(self._rank_pool(branch, pool, floor)) ranked.sort(key=lambda row: row[:3], reverse=True) selected = {} for _, _, _, cell, vector in ranked: selected.setdefault(self._acquisition_key(cell, vector), vector) if len(selected) == size: break return selected.values() def _start_fixed_batch(self, size): super()._start_fixed_batch(size) self._promoted.clear() self._prepare_promotions(size) def _prepare_promotions(self, size): """Queue model-based proposals for the next fixed batch.""" if self.nb_suggestions >= self.initial_samples * len(self.configurations) and any(self._observations): picks = size - sum(self._rng.random() < self.exploration_probability for _ in range(size)) if picks: self._promoted.extend(self._plan_batch(picks)) def _next_vector(self): count = len(self.configurations) if self._promoted: vector = self._promoted.popleft() self._modelled_proposals += 1 else: branch = (self.nb_suggestions % count if self.nb_suggestions < self.initial_samples * count else self._rng.randrange(count)) vector = self._draw(branch) return vector def _internal_ask(self, base_ind): vector = self._next_vector() self._counts[vector[0]] += 1 self._seen.add(vector) base_ind[:] = vector return base_ind def _check_candidate(self, individual): self.decode(individual) self._check_measurements(individual) if len(self.container.get_ind_features(individual)) != len(self.container.features_domain): raise ValueError("Provide one measured descriptor per grid axis.") _constraint_violation(individual, self.configurations[individual[0]].constraints) def _offer_feasible(self, individual, cell): return self._offer_to_grid(individual, cell) def _commit_generation(self, evaluated): grid, admitted = self.container, set() for slot, individual in enumerate(evaluated): if individual is None: continue branch = individual[0] fitness = grid.get_ind_fitness(individual).values features = tuple(grid.get_ind_features(individual)) residuals = tuple(float(individual.scores[name]) for name in self.configurations[branch].constraints) response = (self._direction * float(fitness[0]), *features, *residuals) self._observations[branch].append((tuple(individual), response)) if (all(value <= 0. for value in residuals) and grid.in_bounds(fitness, grid.fitness_domain) and grid.in_bounds(features, grid.features_domain) and self._offer_feasible(individual, grid.index_grid(features))): admitted.add(slot) return admitted