# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Self-adaptive differential evolution over descriptor-guided collaborators.
# @see https://doi.org/10.1109/TETCI.2026.3670689
"""Adapt variation between critical-path edits and guided block-wise differential evolution."""
from dataclasses import dataclass
import numpy as np
from ._population import _attempt_budget, _finite_vector
from .modern import _positive_int
from .task_search import _measurement, _offer, _validate_grid
__all__ = ["SADEQDResult", "sade_qd"]
## @brief Archive and counts for every attempted schedule measurement.
[docs]
@dataclass(frozen=True)
class SADEQDResult:
"""Report evaluations by proposal type, including guided DE followed by a critical edit."""
archive: object
evaluations: int
samples: int
critical_edits: int
guided_steps: int
admissions: int
def _guided_block(base, transport, idle, scale, block):
if block == 0:
return base + scale * (transport + idle - 2. * base)
edge = transport if block == 1 else idle
return base + scale * (base - edge)
## @brief Use measured archive progress to switch on guided differential evolution.
# @param archive Empty best-only two-descriptor grid in transport and idle order.
# @param evaluate Callable (genome) returning (quality, (transport, idle), payload).
# @param critical_edit Callable (genome, payload, block, rng) returning bounded random keys.
# @param block_sizes Positive lengths of the factory, order, and machine blocks.
# @param budget Hard number of decoded candidates.
# @param initial_samples Number of uniform proposals before archive-based edits.
# @param stall Number of unsuccessful admissions before DE can be used.
# @param edge_pool Sample collaborators from this many low-cost elites per descriptor.
# @param scale Weight of the guided DE step.
# @param guided_probability Probability of using DE after the stall threshold.
# @param seed Private variation seed.
# @return SADEQDResult with the archive and separate operator counts.
[docs]
def sade_qd(archive, evaluate, critical_edit, *, block_sizes, budget, initial_samples=16, stall=12,
edge_pool=20, scale=.5, guided_probability=.75, seed=0):
"""Search one native grid with the paper's three guided DE formulas.
A genome contains three contiguous blocks of keys in [0, 1].
Begin with random keys, then ask the caller to edit a critical
component of a measured archive member. When admissions stall,
use a random elite and donors with low transport or idle time.
The measured DE proposal supplies the next critical edit even
when it has not entered the archive. Both calls count toward budget.
"""
_validate_grid(archive)
if len(archive.features_domain) != 2 or not callable(evaluate) or not callable(critical_edit):
raise ValueError("Supply a two-axis archive and callable schedule evaluation and edits.")
sizes = tuple(_positive_int(size, "block_sizes") for size in block_sizes)
if len(sizes) != 3 or not 0 < scale <= 1 or not 0 <= guided_probability <= 1:
raise ValueError("Use three blocks, a scale in (0, 1], and a probability in [0, 1].")
budget, initial = _attempt_budget(budget), _attempt_budget(initial_samples)
stall, count = _positive_int(stall, "stall"), _positive_int(edge_pool, "edge_pool")
offsets = np.cumsum((0, *sizes))
if archive.fitness_weights is None:
archive._set_fitness_weights((-1.,))
rng = np.random.default_rng(seed)
payloads = {}
follow_up = None
samples = edits = guided = stale = 0
before = archive.nb_added
for step in range(budget):
block = int(rng.integers(3))
guided_block = None
if follow_up is not None:
source, payload, block = follow_up
follow_up = None
genome = critical_edit(source, payload, block, rng)
edits += 1
elif step < initial or not archive:
genome = rng.uniform(size=offsets[-1])
samples += 1
elif len(archive) >= 2 and stale >= stall and rng.random() < guided_probability:
source = archive[int(rng.integers(len(archive)))]
elite_pool = [elite for elite in archive if elite is not source]
donors = [sorted(elite_pool, key=lambda elite: elite.features.values[axis])[:count] for axis in (0, 1)]
transport, idle = (group[int(rng.integers(len(group)))] for group in donors)
active = slice(offsets[block], offsets[block + 1])
genome = np.asarray(source, dtype=float).copy()
genome[active] = np.clip(_guided_block(genome[active], np.asarray(transport[active]),
np.asarray(idle[active]), scale, block), 0., 1.)
guided += 1
guided_block = block
else:
parent = archive[int(rng.integers(len(archive)))]
genome = critical_edit(tuple(parent), payloads[archive.index_grid(parent)], block, rng)
edits += 1
genome = _finite_vector(genome, "Schedule keys", offsets[-1])
if not all(0 <= value <= 1 for value in genome):
raise ValueError("Every schedule key must lie in [0, 1].")
fitness, descriptors, payload = evaluate(genome)
candidate = _measurement(archive, ((fitness,), descriptors), genome)
previous = archive.nb_added
_offer(archive, candidate)
if archive.nb_added != previous:
payloads[candidate[1]] = payload
stale = 0
else:
stale += 1
if guided_block is not None:
follow_up = (genome, payload, guided_block)
return SADEQDResult(archive, budget, samples, edits, guided, archive.nb_added - before)