QDpy
Loading...
Searching...
No Matches
qdgp.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Evolve sequencing and routing trees using fixed scheduling decision probes."""
6
7from dataclasses import dataclass
8from math import isfinite, prod
9from operator import index
10
11import numpy as np
12
13from .modern import _positive_int
14
15__all__ = ["DecisionProbe", "SchedulingRules", "SchedulingElite", "QDGP"]
16
17
18
19@dataclass(frozen=True)
21 """Define candidate feature rows and a best-first permutation of candidate indices."""
22
23 candidates: tuple[tuple[float, ...], ...]
24 reference_order: tuple[int, ...]
25
26 def __post_init__(self):
27 rows = np.asarray(self.candidates, dtype=float)
28 order = tuple(index(item) for item in self.reference_order)
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)
34
35 def rank(self, rule):
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.")
40 return self.reference_order.index(int(np.argmin(priorities)))
41
42
43
44@dataclass(frozen=True)
46 """Store two trees in the text representation of the corresponding primitive sets."""
47
48 sequencing: str
49 routing: str
50
51
52
53@dataclass(frozen=True)
55 """Describe a measured elite, with one mixed-radix index per decision kind."""
56
57 rules: SchedulingRules
58 fitness: float
59 cell: tuple[int, int]
60
61
62
63class QDGP:
64 """QDGPf from Xu et al. (GECCO 2025), with caller-defined scheduling instances.
65
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.
71
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.
82 """
83
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):
87 try:
88 from deap import gp
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.")
96 # Both legacy Ephemeral and current MetaEphemeral generators are classes.
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
108 self._direction = 1 if maximize else -1
109 self._rng = np.random.default_rng(seed)
110 self._archive = {}
111 self.evaluations = 0
112
113 @property
114 def archive(self):
115 """Return a dictionary snapshot of the current elites."""
116 return dict(self._archive)
117
118 @property
119 def best(self):
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)
122
123 @property
124 def shape(self):
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)
127
128 def _pick(self, values):
129 return values[int(self._rng.integers(len(values)))]
130
131 def _tree(self, pset, max_height):
132 from deap import gp
133
134 primitives, terminals = pset.primitives[pset.ret], pset.terminals[pset.ret]
135
136 def grow(remaining):
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)]
141
142 return gp.PrimitiveTree(grow(max_height))
143
144 def _parent(self, pool):
145 sampled = [self._pick(pool) for _ in range(self._tournament)]
146 return max(sampled, key=lambda elite: self._direction * elite.fitness).rules
147
148 def _decode(self, rules):
149 from deap import gp
150
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)]
155
156 def _propose(self):
157 if len(self._archive) == 0 or self.evaluations < self._initial:
158 return [self._tree(pset, min(3, self._depth)) for pset in self._sets]
159 pool = tuple(self._archive.values())
160 trees = self._decode(self._parent(pool))
161 part = int(self._rng.integers(2))
162 tree = trees[part]
163 start = int(self._rng.integers(1, len(tree))) if len(tree) > 1 else 0
164 target = tree.searchSubtree(start)
165 if self._rng.random() < self._cross:
166 mate = self._decode(self._parent(pool))[part]
167 donor = int(self._rng.integers(1, len(mate))) if len(mate) > 1 else 0
168 replacement = mate[mate.searchSubtree(donor)]
169 else:
170 replacement = self._tree(self._sets[part], min(2, self._depth))
171 old = tree[target]
172 tree[target] = replacement
173 if tree.height > self._depth:
174 tree[tree.searchSubtree(start)] = old
175 return trees
176
177 def _compile(self, trees):
178 from deap import gp
179
180 return tuple(gp.compile(expr=tree, pset=pset) for tree, pset in zip(trees, self._sets))
181
182
183 def compile(self, rules):
184 """Return (sequencing, routing) callables using this search's primitive sets."""
185 return self._compile(self._decode(rules))
186
187 def _cell(self, compiled):
188 cells = []
189 for rule, probes in zip(compiled, self._probes):
190 cell = 0
191 for probe in probes:
192 cell = cell * len(probe.candidates) + probe.rank(rule)
193 cells.append(cell)
194 return tuple(cells)
195
196
197 def characterize(self, rules):
198 """Return the pair of mixed-radix rank coordinates."""
199 return self._cell(self.compile(rules))
200
201
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")):
207 trees = self._propose()
208 functions = self._compile(trees)
209 self.evaluations += 1
210 value = evaluate(*functions)
211 if value is None:
212 continue
213 quality = float(value)
214 if not isfinite(quality):
215 raise ValueError("Scheduling fitness must be finite.")
216 cell = self._cell(functions)
217 incumbent = self._archive.get(cell)
218 if incumbent is None or self._direction * quality > self._direction * incumbent.fitness:
219 self._archive[cell] = SchedulingElite(SchedulingRules(*map(str, trees)), quality, cell)
220 return self.best
A fixed decision and the reference ranking of its candidates.
Definition qdgp.py:20
Fixed-instance QD Genetic Programming on a sparse MAP-Elites archive.
Definition qdgp.py:63
_parent(self, pool)
Definition qdgp.py:144
_cell(self, compiled)
Definition qdgp.py:187
_pick(self, values)
Definition qdgp.py:128
_decode(self, rules)
Definition qdgp.py:148
compile(self, rules)
Rebuild the priority functions from a trusted text rule pair.
Definition qdgp.py:183
run(self, evaluate, budget)
Spend an additional number of fixed-instance evaluations.
Definition qdgp.py:202
_tree(self, pset, max_height)
Definition qdgp.py:131
characterize(self, rules)
Characterize a given rule pair on the fixed sequencing and routing probes.
Definition qdgp.py:197
_compile(self, trees)
Definition qdgp.py:177
One evaluated scheduling rule pair and its rank-based behavior.
Definition qdgp.py:54
Paired DEAP expressions for sequencing jobs and routing them to machines.
Definition qdgp.py:45