QDpy
Loading...
Searching...
No Matches
jobshop.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Build feasible schedules for jobs assigned to factories with alternative machines."""
6
7from dataclasses import dataclass
8
9import numpy as np
10
11from ._population import _finite_vector
12
13__all__ = ["FlexibleJobShop", "ScheduledOperation", "JobShopSchedule"]
14
15
16
17@dataclass(frozen=True, slots=True)
19 """Order in the schedule is the priority decoder's dispatch order."""
20
21 index: int
22 job: int
23 operation: int
24 machine: int
25 start: float
26 finish: float
27
28
29
30@dataclass(frozen=True)
32 """Critical indices refer to the job-major operation order used by the genome."""
33
34 operations: tuple[ScheduledOperation, ...]
35 makespan: float
36 transport: float
37 idle: float
38 critical: tuple[int, ...]
39
40
41def _pick(keys, choices):
42 return choices[min(int(keys * len(choices)), len(choices) - 1)]
43
44
45
47 """Assign jobs to a factory and pick machine choices with random keys.
48
49 The order block supplies a key for each operation. Only the next
50 unscheduled operation of each job competes in priority selection.
51 Decoding appends to the selected machine and honors both job
52 precedence and travel from the previous machine. Transportation
53 delays allow concurrent travel and require no extra vehicle resource.
54
55 :param jobs: Jobs containing operations with (machine, duration) alternatives.
56 :param machine_factories: Factory label for each zero-based machine index.
57 :param travel: Optional nonnegative matrix of delays from machine to machine.
58 """
59
60 def __init__(self, jobs, machine_factories, *, travel=None):
61 from operator import index
62
63 self._factories = tuple(machine_factories)
64 self._jobs = tuple(tuple(tuple((index(m), float(d)) for m, d in op) for op in job) for job in jobs)
65 m = len(self._factories)
66 if not m or not self._jobs or any(not job for job in self._jobs):
67 raise ValueError("Provide machines and at least one operation in every job.")
68 for op in (op for job in self._jobs for op in job):
69 if (not op or len({machine for machine, _ in op}) != len(op)
70 or any(not 0 <= machine < m or not 0 < duration < np.inf for machine, duration in op)):
71 raise ValueError("Operations need distinct eligible machines and finite positive durations.")
72 self._labels = tuple(dict.fromkeys(self._factories))
73 self._eligible = tuple(tuple(f for f in self._labels
74 if all(any(self._factories[machine] == f for machine, _ in op) for op in job))
75 for job in self._jobs)
76 if any(not group for group in self._eligible):
77 raise ValueError("Each job needs one factory eligible for all its operations.")
78 self._offsets = np.cumsum((0, *map(len, self._jobs)))
79 travel = np.zeros((m, m)) if travel is None else np.asarray(travel, dtype=float)
80 if travel.shape != (m, m) or not np.all((0 <= travel) & (travel < np.inf)):
81 raise ValueError("Provide finite nonnegative travel delays for every machine pair.")
82 self._travel = travel.copy()
83
84 @property
85 def block_sizes(self):
86 """Return the lengths of the factory, order, and machine key blocks."""
87 return len(self._jobs), int(self._offsets[-1]), int(self._offsets[-1])
88
89
90 def decode(self, genome):
91 """Return a feasible schedule and critical path measured from time zero."""
92 jobs, operations, _ = self.block_sizes
93 keys = _finite_vector(genome, "Schedule keys", jobs + 2 * operations)
94 if not all(0 <= value <= 1 for value in keys):
95 raise ValueError("Every schedule key must lie in [0, 1].")
96 factories = [_pick(keys[j], eligible) for j, eligible in enumerate(self._eligible)]
97 priorities, machines = keys[jobs:jobs + operations], keys[jobs + operations:]
98 machine_tail, machine_ready = [None] * len(self._factories), [0.] * len(self._factories)
99 workload = [0.] * len(machine_tail)
100 positions, job_tail = [0] * jobs, [None] * jobs
101 active = list(range(jobs))
102 records, predecessor, transport = [], {}, 0.
103 while active:
104 job = min(active, key=lambda j: priorities[self._offsets[j] + positions[j]])
105 position = positions[job]
106 slot = int(self._offsets[job]) + position
107 options = tuple(pair for pair in self._jobs[job][position] if self._factories[pair[0]] == factories[job])
108 machine, duration = _pick(machines[slot], options)
109 previous = job_tail[job]
110 transfer = float(self._travel[previous.machine, machine]) if previous is not None else 0.
111 arrival = previous.finish + transfer if previous is not None else 0.
112 start = max(arrival, machine_ready[machine])
113 finish = start + duration
114 record = ScheduledOperation(slot, job, position, machine, start, finish)
115 transport += transfer
116 workload[machine] += duration
117 predecessor[slot] = previous if arrival > machine_ready[machine] else machine_tail[machine]
118 machine_tail[machine] = job_tail[job] = record
119 machine_ready[machine] = finish
120 records.append(record)
121 positions[job] += 1
122 if positions[job] == len(self._jobs[job]):
123 active.remove(job)
124 record = max(records, key=lambda op: op.finish)
125 makespan = record.finish
126 critical = []
127 while record is not None:
128 critical.append(record.index)
129 record = predecessor[record.index]
130 idle = sum(max(0., finish - busy) for finish, busy in zip(machine_ready, workload))
131 if not np.isfinite((makespan, transport, idle)).all():
132 raise ValueError("Schedule times overflowed. Rescale durations and travel.")
133 return JobShopSchedule(tuple(records), makespan, transport, idle, tuple(reversed(critical)))
134
135
136 def evaluate(self, genome):
137 """Minimize makespan and track transport and total idle time."""
138 schedule = self.decode(genome)
139 return schedule.makespan, (schedule.transport, schedule.idle), schedule
140
141
142 def critical_edit(self, genome, schedule, block, rng):
143 """Choose one critical operation and preserve feasibility through decoding."""
144 jobs, operations, _ = self.block_sizes
145 if block not in (0, 1, 2):
146 raise ValueError("The block must be 0, 1, or 2.")
147 slot = int(rng.choice(schedule.critical))
148 record = next(row for row in schedule.operations if row.index == slot)
149 result = list(genome)
150 if block == 0:
151 options = self._eligible[record.job]
152 column = record.job
153 current = self._factories[record.machine]
154 elif block == 2:
155 factory = self._factories[record.machine]
156 options = tuple(m for m, _ in self._jobs[record.job][record.operation] if self._factories[m] == factory)
157 column = jobs + operations + slot
158 current = record.machine
159 else:
160 options, column, current = (), jobs + slot, None
161 alternatives = [i for i, choice in enumerate(options) if choice != current]
162 if alternatives:
163 result[column] = (int(rng.choice(alternatives)) + .5) / len(options)
164 else:
165 # An unavailable factory or machine move can still change dispatch priority.
166 result[jobs + slot] = float(rng.random())
167 return tuple(result)
Decode feasible schedules with release times from precedence and travel.
Definition jobshop.py:46
decode(self, genome)
Decode keys and identify a critical path controlling makespan.
Definition jobshop.py:90
critical_edit(self, genome, schedule, block, rng)
Modify a factory assignment, order key, or eligible machine on the critical path.
Definition jobshop.py:142
evaluate(self, genome)
Adapt a decoded schedule to the SADE-QD evaluation callback.
Definition jobshop.py:136
Decoded makespan, feature measurements, and critical operations.
Definition jobshop.py:31