21 """Define candidate feature rows and a best-first permutation of candidate indices."""
23 candidates: tuple[tuple[float, ...], ...]
24 reference_order: tuple[int, ...]
26 def __post_init__(self):
27 rows = np.asarray(self.
candidates, dtype=float)
29 if (rows.ndim != 2
or len(rows) < 2
or not rows.shape[1]
or not np.isfinite(rows).all()
30 or sorted(order) != list(range(len(rows)))):
31 raise ValueError(
"Supply finite candidate feature rows and a reference permutation.")
32 object.__setattr__(self,
"candidates", tuple(tuple(map(float, row))
for row
in rows))
33 object.__setattr__(self,
"reference_order", order)
36 """Return the reference rank of the lowest-priority choice, with stable ties."""
37 priorities = [float(rule(*candidate))
for candidate
in self.
candidates]
38 if not all(map(isfinite, priorities)):
39 raise ValueError(
"Scheduling priorities must be finite.")
64 """QDGPf from Xu et al. (GECCO 2025), with caller-defined scheduling instances.
66 An evaluation receives two compiled priority functions. Lower scores
67 take precedence at each probe. Encode the rank of the chosen candidate
68 under fixed reference rules in two mixed-radix cell coordinates.
69 A sparse archive stores the best measured rule pair per coordinate.
70 Use the same training instances whenever you call run on this search.
72 :param sequencing: Untyped DEAP PrimitiveSet for sequencing rules.
73 :param routing: Untyped DEAP PrimitiveSet for routing rules.
74 :param sequencing_probes: Sequence of DecisionProbe instances.
75 :param routing_probes: Sequence of DecisionProbe instances.
76 :param initial_samples: Number of randomly initialized candidates.
77 :param max_depth: Maximum height of either tree.
78 :param tournament_size: Number of randomly sampled elites per parent tournament.
79 :param crossover_probability: Probability of using subtree crossover instead of mutation.
80 :param maximize: Whether the caller's fitness is higher-is-better.
81 :param seed: Search seed. Use fixed literal terminals for deterministic initialization.
84 def __init__(self, sequencing, routing, *, sequencing_probes, routing_probes,
85 initial_samples=24, max_depth=6, tournament_size=3, crossover_probability=.75,
86 maximize=False, seed=0):
89 except ImportError
as error:
90 raise ImportError(
"QDGP requires the QDpy 'deap' extra.")
from error
91 self.
_sets = (sequencing, routing)
92 self.
_probes = (tuple(sequencing_probes), tuple(routing_probes))
93 for primitive_set, probes
in zip(self.
_sets, self.
_probes):
94 if not isinstance(primitive_set, gp.PrimitiveSet)
or not primitive_set.terminals[primitive_set.ret]:
95 raise ValueError(
"Use untyped DEAP primitive sets with at least one terminal.")
97 if any(isinstance(terminal, type)
for terminal
in primitive_set.terminals[primitive_set.ret]):
98 raise ValueError(
"Use fixed literal terminals or feature arguments.")
99 if not probes
or any(
not isinstance(probe, DecisionProbe)
100 or len(probe.candidates[0]) != len(primitive_set.arguments)
for probe
in probes):
101 raise ValueError(
"Each rule needs probes that match its primitive set's feature width.")
102 if not 0 <= crossover_probability <= 1:
103 raise ValueError(
"crossover_probability must be in [0, 1].")
104 self.
_initial = _positive_int(initial_samples,
"initial_samples")
105 self.
_depth = _positive_int(max_depth,
"max_depth")
106 self.
_tournament = _positive_int(tournament_size,
"tournament_size")
107 self.
_cross = crossover_probability
109 self.
_rng = np.random.default_rng(seed)
115 """Return a dictionary snapshot of the current elites."""
120 """Return the best measured rule pair, or None for an empty archive."""
121 return max(self.
_archive.values(), key=
lambda elite: self.
_direction * elite.fitness, default=
None)
125 """Return the number of possible mixed-radix coordinates on each axis."""
126 return tuple(prod(len(probe.candidates)
for probe
in probes)
for probes
in self.
_probes)
128 def _pick(self, values):
129 return values[int(self.
_rng.integers(len(values)))]
131 def _tree(self, pset, max_height):
134 primitives, terminals = pset.primitives[pset.ret], pset.terminals[pset.ret]
137 if remaining
and primitives
and self.
_rng.random() >= .25:
138 node = self.
_pick(primitives)
139 return [node, *(child
for _
in range(node.arity)
for child
in grow(remaining - 1))]
140 return [self.
_pick(terminals)]
142 return gp.PrimitiveTree(grow(max_height))
144 def _parent(self, pool):
146 return max(sampled, key=
lambda elite: self.
_direction * elite.fitness).rules
148 def _decode(self, rules):
151 if not isinstance(rules, SchedulingRules):
152 raise TypeError(
"rules must be a SchedulingRules pair.")
153 return [gp.PrimitiveTree.from_string(code, pset)
154 for code, pset
in zip((rules.sequencing, rules.routing), self.
_sets)]
159 pool = tuple(self.
_archive.values())
161 part = int(self.
_rng.integers(2))
163 start = int(self.
_rng.integers(1, len(tree)))
if len(tree) > 1
else 0
164 target = tree.searchSubtree(start)
167 donor = int(self.
_rng.integers(1, len(mate)))
if len(mate) > 1
else 0
168 replacement = mate[mate.searchSubtree(donor)]
172 tree[target] = replacement
173 if tree.height > self.
_depth:
174 tree[tree.searchSubtree(start)] = old
177 def _compile(self, trees):
180 return tuple(gp.compile(expr=tree, pset=pset)
for tree, pset
in zip(trees, self.
_sets))
184 """Return (sequencing, routing) callables using this search's primitive sets."""
187 def _cell(self, compiled):
189 for rule, probes
in zip(compiled, self.
_probes):
192 cell = cell * len(probe.candidates) + probe.rank(rule)
198 """Return the pair of mixed-radix rank coordinates."""
202 def run(self, evaluate, budget):
203 """Return the best retained SchedulingElite. An evaluator may return None for a failed attempt."""
204 if not callable(evaluate):
205 raise TypeError(
"evaluate must be callable.")
206 for _
in range(_positive_int(budget,
"budget")):
210 value = evaluate(*functions)
213 quality = float(value)
214 if not isfinite(quality):
215 raise ValueError(
"Scheduling fitness must be finite.")
216 cell = self.
_cell(functions)