# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Random-key decoding and critical-path edits for flexible job shops.
"""Build feasible schedules for jobs assigned to factories with alternative machines."""
from dataclasses import dataclass
import numpy as np
from ._population import _finite_vector
__all__ = ["FlexibleJobShop", "ScheduledOperation", "JobShopSchedule"]
## @brief One scheduled operation. Times refer to the same shop clock.
[docs]
@dataclass(frozen=True, slots=True)
class ScheduledOperation:
"""Order in the schedule is the priority decoder's dispatch order."""
index: int
job: int
operation: int
machine: int
start: float
finish: float
## @brief Decoded makespan, feature measurements, and critical operations.
[docs]
@dataclass(frozen=True)
class JobShopSchedule:
"""Critical indices refer to the job-major operation order used by the genome."""
operations: tuple[ScheduledOperation, ...]
makespan: float
transport: float
idle: float
critical: tuple[int, ...]
def _pick(keys, choices):
return choices[min(int(keys * len(choices)), len(choices) - 1)]
## @brief Decode feasible schedules with release times from precedence and travel.
[docs]
class FlexibleJobShop:
"""Assign jobs to a factory and pick machine choices with random keys.
The order block supplies a key for each operation. Only the next
unscheduled operation of each job competes in priority selection.
Decoding appends to the selected machine and honors both job
precedence and travel from the previous machine. Transportation
delays allow concurrent travel and require no extra vehicle resource.
:param jobs: Jobs containing operations with (machine, duration) alternatives.
:param machine_factories: Factory label for each zero-based machine index.
:param travel: Optional nonnegative matrix of delays from machine to machine.
"""
def __init__(self, jobs, machine_factories, *, travel=None):
from operator import index
self._factories = tuple(machine_factories)
self._jobs = tuple(tuple(tuple((index(m), float(d)) for m, d in op) for op in job) for job in jobs)
m = len(self._factories)
if not m or not self._jobs or any(not job for job in self._jobs):
raise ValueError("Provide machines and at least one operation in every job.")
for op in (op for job in self._jobs for op in job):
if (not op or len({machine for machine, _ in op}) != len(op)
or any(not 0 <= machine < m or not 0 < duration < np.inf for machine, duration in op)):
raise ValueError("Operations need distinct eligible machines and finite positive durations.")
self._labels = tuple(dict.fromkeys(self._factories))
self._eligible = tuple(tuple(f for f in self._labels
if all(any(self._factories[machine] == f for machine, _ in op) for op in job))
for job in self._jobs)
if any(not group for group in self._eligible):
raise ValueError("Each job needs one factory eligible for all its operations.")
self._offsets = np.cumsum((0, *map(len, self._jobs)))
travel = np.zeros((m, m)) if travel is None else np.asarray(travel, dtype=float)
if travel.shape != (m, m) or not np.all((0 <= travel) & (travel < np.inf)):
raise ValueError("Provide finite nonnegative travel delays for every machine pair.")
self._travel = travel.copy()
@property
def block_sizes(self):
"""Return the lengths of the factory, order, and machine key blocks."""
return len(self._jobs), int(self._offsets[-1]), int(self._offsets[-1])
## @brief Decode keys and identify a critical path controlling makespan.
[docs]
def decode(self, genome):
"""Return a feasible schedule and critical path measured from time zero."""
jobs, operations, _ = self.block_sizes
keys = _finite_vector(genome, "Schedule keys", jobs + 2 * operations)
if not all(0 <= value <= 1 for value in keys):
raise ValueError("Every schedule key must lie in [0, 1].")
factories = [_pick(keys[j], eligible) for j, eligible in enumerate(self._eligible)]
priorities, machines = keys[jobs:jobs + operations], keys[jobs + operations:]
machine_tail, machine_ready = [None] * len(self._factories), [0.] * len(self._factories)
workload = [0.] * len(machine_tail)
positions, job_tail = [0] * jobs, [None] * jobs
active = list(range(jobs))
records, predecessor, transport = [], {}, 0.
while active:
job = min(active, key=lambda j: priorities[self._offsets[j] + positions[j]])
position = positions[job]
slot = int(self._offsets[job]) + position
options = tuple(pair for pair in self._jobs[job][position] if self._factories[pair[0]] == factories[job])
machine, duration = _pick(machines[slot], options)
previous = job_tail[job]
transfer = float(self._travel[previous.machine, machine]) if previous is not None else 0.
arrival = previous.finish + transfer if previous is not None else 0.
start = max(arrival, machine_ready[machine])
finish = start + duration
record = ScheduledOperation(slot, job, position, machine, start, finish)
transport += transfer
workload[machine] += duration
predecessor[slot] = previous if arrival > machine_ready[machine] else machine_tail[machine]
machine_tail[machine] = job_tail[job] = record
machine_ready[machine] = finish
records.append(record)
positions[job] += 1
if positions[job] == len(self._jobs[job]):
active.remove(job)
record = max(records, key=lambda op: op.finish)
makespan = record.finish
critical = []
while record is not None:
critical.append(record.index)
record = predecessor[record.index]
idle = sum(max(0., finish - busy) for finish, busy in zip(machine_ready, workload))
if not np.isfinite((makespan, transport, idle)).all():
raise ValueError("Schedule times overflowed. Rescale durations and travel.")
return JobShopSchedule(tuple(records), makespan, transport, idle, tuple(reversed(critical)))
## @brief Adapt a decoded schedule to the SADE-QD evaluation callback.
[docs]
def evaluate(self, genome):
"""Minimize makespan and track transport and total idle time."""
schedule = self.decode(genome)
return schedule.makespan, (schedule.transport, schedule.idle), schedule
## @brief Modify a factory assignment, order key, or eligible machine on the critical path.
[docs]
def critical_edit(self, genome, schedule, block, rng):
"""Choose one critical operation and preserve feasibility through decoding."""
jobs, operations, _ = self.block_sizes
if block not in (0, 1, 2):
raise ValueError("The block must be 0, 1, or 2.")
slot = int(rng.choice(schedule.critical))
record = next(row for row in schedule.operations if row.index == slot)
result = list(genome)
if block == 0:
options = self._eligible[record.job]
column = record.job
current = self._factories[record.machine]
elif block == 2:
factory = self._factories[record.machine]
options = tuple(m for m, _ in self._jobs[record.job][record.operation] if self._factories[m] == factory)
column = jobs + operations + slot
current = record.machine
else:
options, column, current = (), jobs + slot, None
alternatives = [i for i, choice in enumerate(options) if choice != current]
if alternatives:
result[column] = (int(rng.choice(alternatives)) + .5) / len(options)
else:
# An unavailable factory or machine move can still change dispatch priority.
result[jobs + slot] = float(rng.random())
return tuple(result)