# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Quality-diversity genetic programming for paired scheduling rules.
"""Evolve sequencing and routing trees using fixed scheduling decision probes."""
from dataclasses import dataclass
from math import isfinite, prod
from operator import index
import numpy as np
from .modern import _positive_int
__all__ = ["DecisionProbe", "SchedulingRules", "SchedulingElite", "QDGP"]
## @brief A fixed decision and the reference ranking of its candidates.
[docs]
@dataclass(frozen=True)
class DecisionProbe:
"""Define candidate feature rows and a best-first permutation of candidate indices."""
candidates: tuple[tuple[float, ...], ...]
reference_order: tuple[int, ...]
def __post_init__(self):
rows = np.asarray(self.candidates, dtype=float)
order = tuple(index(item) for item in self.reference_order)
if (rows.ndim != 2 or len(rows) < 2 or not rows.shape[1] or not np.isfinite(rows).all()
or sorted(order) != list(range(len(rows)))):
raise ValueError("Supply finite candidate feature rows and a reference permutation.")
object.__setattr__(self, "candidates", tuple(tuple(map(float, row)) for row in rows))
object.__setattr__(self, "reference_order", order)
[docs]
def rank(self, rule):
"""Return the reference rank of the lowest-priority choice, with stable ties."""
priorities = [float(rule(*candidate)) for candidate in self.candidates]
if not all(map(isfinite, priorities)):
raise ValueError("Scheduling priorities must be finite.")
return self.reference_order.index(int(np.argmin(priorities)))
## @brief Paired DEAP expressions for sequencing jobs and routing them to machines.
[docs]
@dataclass(frozen=True)
class SchedulingRules:
"""Store two trees in the text representation of the corresponding primitive sets."""
sequencing: str
routing: str
## @brief One evaluated scheduling rule pair and its rank-based behavior.
[docs]
@dataclass(frozen=True)
class SchedulingElite:
"""Describe a measured elite, with one mixed-radix index per decision kind."""
rules: SchedulingRules
fitness: float
cell: tuple[int, int]
## @brief Fixed-instance QD Genetic Programming on a sparse MAP-Elites archive.
[docs]
class QDGP:
"""QDGPf from Xu et al. (GECCO 2025), with caller-defined scheduling instances.
An evaluation receives two compiled priority functions. Lower scores
take precedence at each probe. Encode the rank of the chosen candidate
under fixed reference rules in two mixed-radix cell coordinates.
A sparse archive stores the best measured rule pair per coordinate.
Use the same training instances whenever you call run on this search.
:param sequencing: Untyped DEAP PrimitiveSet for sequencing rules.
:param routing: Untyped DEAP PrimitiveSet for routing rules.
:param sequencing_probes: Sequence of DecisionProbe instances.
:param routing_probes: Sequence of DecisionProbe instances.
:param initial_samples: Number of randomly initialized candidates.
:param max_depth: Maximum height of either tree.
:param tournament_size: Number of randomly sampled elites per parent tournament.
:param crossover_probability: Probability of using subtree crossover instead of mutation.
:param maximize: Whether the caller's fitness is higher-is-better.
:param seed: Search seed. Use fixed literal terminals for deterministic initialization.
"""
def __init__(self, sequencing, routing, *, sequencing_probes, routing_probes,
initial_samples=24, max_depth=6, tournament_size=3, crossover_probability=.75,
maximize=False, seed=0):
try:
from deap import gp
except ImportError as error:
raise ImportError("QDGP requires the QDpy 'deap' extra.") from error
self._sets = (sequencing, routing)
self._probes = (tuple(sequencing_probes), tuple(routing_probes))
for primitive_set, probes in zip(self._sets, self._probes):
if not isinstance(primitive_set, gp.PrimitiveSet) or not primitive_set.terminals[primitive_set.ret]:
raise ValueError("Use untyped DEAP primitive sets with at least one terminal.")
# Both legacy Ephemeral and current MetaEphemeral generators are classes.
if any(isinstance(terminal, type) for terminal in primitive_set.terminals[primitive_set.ret]):
raise ValueError("Use fixed literal terminals or feature arguments.")
if not probes or any(not isinstance(probe, DecisionProbe)
or len(probe.candidates[0]) != len(primitive_set.arguments) for probe in probes):
raise ValueError("Each rule needs probes that match its primitive set's feature width.")
if not 0 <= crossover_probability <= 1:
raise ValueError("crossover_probability must be in [0, 1].")
self._initial = _positive_int(initial_samples, "initial_samples")
self._depth = _positive_int(max_depth, "max_depth")
self._tournament = _positive_int(tournament_size, "tournament_size")
self._cross = crossover_probability
self._direction = 1 if maximize else -1
self._rng = np.random.default_rng(seed)
self._archive = {}
self.evaluations = 0
@property
def archive(self):
"""Return a dictionary snapshot of the current elites."""
return dict(self._archive)
@property
def best(self):
"""Return the best measured rule pair, or None for an empty archive."""
return max(self._archive.values(), key=lambda elite: self._direction * elite.fitness, default=None)
@property
def shape(self):
"""Return the number of possible mixed-radix coordinates on each axis."""
return tuple(prod(len(probe.candidates) for probe in probes) for probes in self._probes)
def _pick(self, values):
return values[int(self._rng.integers(len(values)))]
def _tree(self, pset, max_height):
from deap import gp
primitives, terminals = pset.primitives[pset.ret], pset.terminals[pset.ret]
def grow(remaining):
if remaining and primitives and self._rng.random() >= .25:
node = self._pick(primitives)
return [node, *(child for _ in range(node.arity) for child in grow(remaining - 1))]
return [self._pick(terminals)]
return gp.PrimitiveTree(grow(max_height))
def _parent(self, pool):
sampled = [self._pick(pool) for _ in range(self._tournament)]
return max(sampled, key=lambda elite: self._direction * elite.fitness).rules
def _decode(self, rules):
from deap import gp
if not isinstance(rules, SchedulingRules):
raise TypeError("rules must be a SchedulingRules pair.")
return [gp.PrimitiveTree.from_string(code, pset)
for code, pset in zip((rules.sequencing, rules.routing), self._sets)]
def _propose(self):
if len(self._archive) == 0 or self.evaluations < self._initial:
return [self._tree(pset, min(3, self._depth)) for pset in self._sets]
pool = tuple(self._archive.values())
trees = self._decode(self._parent(pool))
part = int(self._rng.integers(2))
tree = trees[part]
start = int(self._rng.integers(1, len(tree))) if len(tree) > 1 else 0
target = tree.searchSubtree(start)
if self._rng.random() < self._cross:
mate = self._decode(self._parent(pool))[part]
donor = int(self._rng.integers(1, len(mate))) if len(mate) > 1 else 0
replacement = mate[mate.searchSubtree(donor)]
else:
replacement = self._tree(self._sets[part], min(2, self._depth))
old = tree[target]
tree[target] = replacement
if tree.height > self._depth:
tree[tree.searchSubtree(start)] = old
return trees
def _compile(self, trees):
from deap import gp
return tuple(gp.compile(expr=tree, pset=pset) for tree, pset in zip(trees, self._sets))
## @brief Rebuild the priority functions from a trusted text rule pair.
[docs]
def compile(self, rules):
"""Return (sequencing, routing) callables using this search's primitive sets."""
return self._compile(self._decode(rules))
def _cell(self, compiled):
cells = []
for rule, probes in zip(compiled, self._probes):
cell = 0
for probe in probes:
cell = cell * len(probe.candidates) + probe.rank(rule)
cells.append(cell)
return tuple(cells)
## @brief Characterize a given rule pair on the fixed sequencing and routing probes.
[docs]
def characterize(self, rules):
"""Return the pair of mixed-radix rank coordinates."""
return self._cell(self.compile(rules))
## @brief Spend an additional number of fixed-instance evaluations.
[docs]
def run(self, evaluate, budget):
"""Return the best retained SchedulingElite. An evaluator may return None for a failed attempt."""
if not callable(evaluate):
raise TypeError("evaluate must be callable.")
for _ in range(_positive_int(budget, "budget")):
trees = self._propose()
functions = self._compile(trees)
self.evaluations += 1
value = evaluate(*functions)
if value is None:
continue
quality = float(value)
if not isfinite(quality):
raise ValueError("Scheduling fitness must be finite.")
cell = self._cell(functions)
incumbent = self._archive.get(cell)
if incumbent is None or self._direction * quality > self._direction * incumbent.fitness:
self._archive[cell] = SchedulingElite(SchedulingRules(*map(str, trees)), quality, cell)
return self.best