QDpy
Loading...
Searching...
No Matches
qdgp_schedule.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Evolve and audit expression-tree scheduling rules on small job shops."""
6
7import argparse
8from heapq import heapify, heappop, heappush
9import json
10from operator import add, mul, sub
11
12import numpy as np
13from deap import gp
14
15from qdpy.algorithms import DecisionProbe, QDGP
16
17
18def instance(rng):
19 """Generate arrivals, due dates, and two machine options for each operation."""
20 arrivals = rng.integers(0, 9, 8)
21 due = arrivals + rng.integers(8, 22, len(arrivals))
22 durations = rng.integers(1, 10, (len(arrivals), 2, 2))
23 return arrivals, due, durations
24
25
26def evaluate_jobs(problem, sequencing, routing):
27 """Return total tardiness plus a small makespan cost."""
28 arrivals, due, durations = problem
29 operations, machines = durations.shape[1:]
30 events = [(int(time), job, 0) for job, time in enumerate(arrivals)]
31 heapify(events)
32 available = [0] * machines
33 queues = [[] for _ in range(machines)]
34 completed = np.zeros(len(arrivals), dtype=int)
35 while events:
36 clock = events[0][0]
37 while events and events[0][0] == clock:
38 _, job, operation = heappop(events)
39 if operation == operations:
40 completed[job] = clock
41 continue
42 times = durations[job, operation]
43 loads = [max(0, available[m] - clock) + sum(entry[3] for entry in queue)
44 for m, queue in enumerate(queues)]
45 selected = min(range(machines), key=lambda machine: routing(
46 float(times[machine]), float(loads[machine]), float(due[job] - clock)))
47 queues[selected].append((job, operation, clock, int(times[selected])))
48 for machine, queue in enumerate(queues):
49 if queue and available[machine] <= clock:
50 slot = min(range(len(queue)), key=lambda i: sequencing(
51 float(queue[i][3]), float(clock - queue[i][2]), float(due[queue[i][0]] - clock)))
52 job, operation, _, duration = queue.pop(slot)
53 available[machine] = clock + duration
54 heappush(events, (clock + duration, job, operation + 1))
55 return float(np.maximum(0, completed - due).sum() + .1 * completed.max())
56
57
58def make_search(seed, one_cell=False):
59 """Use finite primitives and rank probes independent of the scoring instances."""
60 primitives = gp.PrimitiveSet("priority", 3)
61 primitives.renameArguments(ARG0="duration", ARG1="waiting", ARG2="slack")
62 for operation in (add, sub, mul, min, max):
63 primitives.addPrimitive(operation, 2)
64 primitives.addTerminal(1.)
65 rng = np.random.default_rng(381)
66 probes = []
67 for _ in range(6):
68 candidates = rng.integers(0, 12, (3, 3))
69 if one_cell:
70 candidates[:] = candidates[0]
71 order = np.argsort(candidates[:, 0] + candidates[:, 1], kind="stable")
72 probes.append(DecisionProbe(candidates, tuple(order)))
73 return QDGP(primitives, primitives, sequencing_probes=probes[:3], routing_probes=probes[3:],
74 max_depth=4, initial_samples=16, seed=seed)
75
76
77def run(method, seed, budget):
78 """Train on the same cases and audit the training winner on unseen cases."""
79 rng = np.random.default_rng(677)
80 training = [instance(rng) for _ in range(5)]
81 held_out = [instance(rng) for _ in range(8)]
82 search = make_search(seed, one_cell=method == "single-niche")
83 best = search.run(lambda seq, route: np.mean([evaluate_jobs(case, seq, route) for case in training]), budget)
84 seq, route = search.compile(best.rules)
85 scores = [evaluate_jobs(case, seq, route) for case in held_out]
86 return dict(method=method, seed=seed, attempts=search.evaluations,
87 training_cases=budget * len(training), audit_cases=len(held_out),
88 occupied=len(search.archive), training_cost=best.fitness, held_out_cost=float(np.mean(scores)))
89
90
91if __name__ == "__main__":
92 parser = argparse.ArgumentParser(description=__doc__)
93 parser.add_argument("--budget", type=int, default=144)
94 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33])
95 args = parser.parse_args()
96 for seed in args.seeds:
97 for method in ("qdgp", "single-niche"):
98 print(json.dumps(run(method, seed, args.budget), sort_keys=True, allow_nan=False))