# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Diverse initial designs for bounded local optimization.
# @see https://doi.org/10.1145/3670693
"""Generate a repertoire of starts, then refine each with a user-supplied solver."""
from dataclasses import dataclass
import numpy as np
from qdpy.tools import iso_line_dd
from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int
from .task_search import _measurement, _offer, _search_bounds, _validate_grid
__all__ = ["QDIDStart", "QDIDResult", "qd_seeded_refinement"]
## @brief One local solve, including the seed and its best verified result.
[docs]
@dataclass(frozen=True, slots=True)
class QDIDStart:
"""The reported seed remains available if all refinements are worse."""
seed: tuple[float, ...]
solution: tuple[float, ...]
initial_fitness: float
fitness: float
evaluations: int
failures: int
## @brief The measured starts, refined archive, and stage budgets.
[docs]
@dataclass(frozen=True)
class QDIDResult:
"""Keep exact evaluator calls for the seed search and for local refinement."""
seeds: object
archive: object
starts: tuple[QDIDStart, ...]
search_evaluations: int
search_failures: int
refinement_evaluations: int
refinement_failures: int
class _RefinementBudgetReached(Exception):
pass
def _direction(archive):
if archive.fitness_weights is None:
return 1.
return float(np.sign(archive.fitness_weights[0]))
## @brief Illuminate initial designs before locally refining a bounded panel of them.
# @param seed_archive Empty Grid or CVTGrid of seed designs.
# @param archive Distinct final Grid or CVTGrid of measured refined designs.
# @param evaluate Callable (genome) returning ((fitness,), descriptors) or None.
# @param refine Callable (start, objective, rng) running a bounded local solve.
# @param dimension Length of the real-valued genome.
# @param search_budget Number of attempted seed search evaluations.
# @param starts Maximum number of local solves.
# @param refinement_budget_per_start Evaluator call cap for each local solve.
# @param ind_domain Shared finite bounds on the genome.
# @param initial_samples Number of uniform samples before MAP-Elites variation.
# @param seed_selection "archive" for QDID or "random" for independent restarts.
# @param propose Optional callable (archive, rng) for custom seed variation or initialization.
# @param seed Private random seed.
# @return QDIDResult with measured starts and stage costs.
[docs]
def qd_seeded_refinement(seed_archive, archive, evaluate, refine, *, dimension, search_budget, starts,
refinement_budget_per_start, ind_domain=(0., 1.), initial_samples=8,
seed_selection="archive", propose=None, seed=0):
"""Use the local solver's measured trials to choose one result per start.
The solver receives a scalar minimization objective and a measured start.
Return values from the solver are advisory. Selection uses the best
feasible measured point, including the start, so a failed or worse
trial cannot erase it. The objective raises a private stop signal before
exceeding its call cap. A rejected measurement returns positive infinity.
The random control samples seed designs independently and retains a
uniform reservoir of valid points for refinement. Both modes start up
to the configured number of solves without extra seed evaluations.
"""
_validate_grid(seed_archive)
_validate_grid(archive)
direction = _direction(archive)
if seed_archive is archive or _direction(seed_archive) != direction:
raise ValueError("Supply distinct archives with the same fitness direction.")
if (tuple(seed_archive.features_domain) != tuple(archive.features_domain)
or tuple(seed_archive.fitness_domain) != tuple(archive.fitness_domain)):
raise ValueError("The seed and output archives must use common descriptor and fitness bounds.")
if not callable(evaluate) or not callable(refine) or (propose is not None and not callable(propose)):
raise TypeError("Supply an evaluator, local solver and an optional proposer.")
if seed_selection not in ("archive", "random"):
raise ValueError("Choose archive or random seed selection.")
dimension, starts = _positive_int(dimension, "dimension"), _positive_int(starts, "starts")
search_budget, initial_samples = _attempt_budget(search_budget), _attempt_budget(initial_samples)
limit = _attempt_budget(refinement_budget_per_start)
low, high = _search_bounds(ind_domain)
for grid in (seed_archive, archive):
if grid.fitness_weights is None:
grid._set_fitness_weights((direction,))
search_rng, panel_rng, local_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
pool, valid, failures = [], 0, 0
randomized = seed_selection == "random"
def measure(target, genome):
result = evaluate(genome)
return None if result is None else _measurement(target, result, genome)
search_evaluations = 0
for iteration in range(search_budget):
if propose is not None:
raw = propose(seed_archive if not randomized else (), search_rng)
elif randomized or iteration < initial_samples or not seed_archive:
raw = search_rng.uniform(low, high, size=dimension)
else:
left, right = (seed_archive[i] for i in search_rng.integers(len(seed_archive), size=2))
raw = iso_line_dd(left, right, iso_sigma=.05 * (high - low), bounds=(low, high), rng=search_rng)
genome = _finite_vector(raw, "Seed design", dimension)
if any(not low <= value <= high for value in genome):
raise ValueError("The seed proposer returned a point outside ind_domain.")
search_evaluations += 1
measured = measure(seed_archive, genome)
if measured is None:
failures += 1
continue
_offer(seed_archive, measured)
if randomized and measured[1] is not None:
valid += 1
if len(pool) < starts:
pool.append(measured[0])
elif (slot := panel_rng.integers(valid)) < starts:
pool[slot] = measured[0]
if not randomized and seed_archive:
selected = panel_rng.choice(len(seed_archive), size=min(starts, len(seed_archive)), replace=False)
pool = [seed_archive[i] for i in selected]
def refine_seed(elite):
initial = (tuple(elite.fitness.values), tuple(elite.features))
best = _measurement(archive, initial, tuple(elite))
attempts = misses = 0
def objective(raw):
nonlocal best, attempts, misses
if attempts == limit:
raise _RefinementBudgetReached
genome = _finite_vector(raw, "Local trial", dimension)
if any(not low <= value <= high for value in genome):
return np.inf
attempts += 1
trial = measure(archive, genome)
if trial is None or trial[1] is None:
misses += 1
return np.inf
quality = direction * trial[0].fitness.values[0]
if quality > direction * best[0].fitness.values[0]:
best = trial
return -quality
if limit:
try:
refine(tuple(elite), objective, local_rng)
except _RefinementBudgetReached:
pass
_offer(archive, best)
solution = best[0]
return QDIDStart(tuple(elite), tuple(solution), elite.fitness.values[0], solution.fitness.values[0],
attempts, misses)
refined = tuple(map(refine_seed, pool))
return QDIDResult(seed_archive, archive, refined, search_evaluations, failures,
sum(row.evaluations for row in refined), sum(row.failures for row in refined))