Build a genetic algorithm for job shop scheduling. Define a custom crossover operator like Order Crossover OX1 that preserves relative task order to avoid invalid schedules. Implement elitism to keep the top 1% of solutions unchanged.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This thought finalizes the representation of job shop schedules as permutations of unique (job, operation) pairs and lays out a clear plan to implement Order Crossover (OX1), elitism, decoding for makespan evaluation, selection, mutation, and a small test instance in Python for demonstration.
Below is a self-contained Python implementation of a simple genetic algorithm (GA) for a job shop scheduling problem using an operation-based encoding. Each gene in a chromosome represents a specific operation (job index, operation index). A custom Order Crossover (OX1) preserves relative order of tasks to avoid invalid sequences. Elitism is included to keep the top 1% of the population unchanged in each generation.
python
import random
import math
from typing import List, Tuple, Any
# ------------------------------------------------------------
# Example Job Shop instance
# jobs[job_id] = list of operations [(machine_id, duration), ...] in required order
# ------------------------------------------------------------
jobs = [
[(0, 3), (1, 2), (2, 2)], # Job 0
[(0, 2), (2, 1), (1, 4)], # Job 1
[(1, 3), (2, 3), (0, 1)], # Job 2
]
# ------------------------------------------------------------
# Build a list of unique operation IDs (job_id, op_index)
# ------------------------------------------------------------
def all_operations(jobs: List[List[Tuple[int, int]]]) -> List[Tuple[int, int]]:
ops = []
for j, ops_list in enumerate(jobs):
for op_idx in range(len(ops_list)):
ops.append((j, op_idx))
return ops
# ------------------------------------------------------------
# Schedule decoding: compute makespan from a chromosome
# chromosome is a list of (job_id, op_index), each operation is unique
# ------------------------------------------------------------
def compute_makespan(chromosome: List[Tuple[int, int]], jobs: List[List[Tuple[int, int]]]) -> int:
# track completion time for each job
job_completion = [0] * len(jobs)
# track when each machine becomes free
# find max machine id
max_machine = max(m for job in jobs for (m, _) in job)
machine_available = [0] * (max_machine + 1)
for (j, op_idx) in chromosome:
machine, duration = jobs[j][op_idx]
# operation can start after the job's previous operation finishes
earliest_start_job = job_completion[j]
# operation can also only start when the machine is free
earliest_start_machine = machine_available[machine]
start_time = max(earliest_start_job, earliest_start_machine)
end_time = start_time + duration
# update completions
job_completion[j] = end_time
machine_available[machine] = end_time
# makespan is maximum completion across all jobs
return max(job_completion)
# ------------------------------------------------------------
# Genetic Algorithm components
# ------------------------------------------------------------
def order_crossover_ox1(parent1: List[Any], parent2: List[Any]) -> List[Any]:
"""
Custom Order Crossover (OX1) for permutations.
This preserves the relative order of operations and ensures no duplicates.
"""
size = len(parent1)
child = [None] * size
# pick two cut points
c1, c2 = sorted(random.sample(range(size), 2))
# copy slice from parent1 to child
child[c1:c2] = parent1[c1:c2]
# fill remaining positions with genes from parent2 in order
pos_child = 0
for gene in parent2:
if gene in child:
continue
# find the next empty slot in child
while child[pos_child] is not None:
pos_child += 1
child[pos_child] = gene
return child
def mutate_swap(chromosome: List[Any], mutation_rate: float = 0.1) -> List[Any]:
"""
Swap mutation: with small probability swap two genes.
"""
child = list(chromosome)
if random.random() < mutation_rate:
i, j = random.sample(range(len(child)), 2)
child[i], child[j] = child[j], child[i]
return child
def tournament_selection(population: List[List[Any]], fitnesses: List[float], k: int = 3) -> List[Any]:
"""
Select one individual using tournament selection.
"""
selected_idx = random.sample(range(len(population)), k)
# better is higher fitness (i.e., lower makespan => higher fitness)
best = max(selected_idx, key=lambda idx: fitnesses[idx])
return population[best]
def evaluate_population(population: List[List[Any]], jobs: List[List[Tuple[int,int]]]) -> List[int]:
"""
Returns the makespan of each individual.
"""
return [compute_makespan(ind, jobs) for ind in population]
# ------------------------------------------------------------
# Genetic Algorithm
# ------------------------------------------------------------
def genetic_algorithm_job_shop(
jobs: List[List[Tuple[int,int]]],
pop_size: int = 100,
generations: int = 200,
crossover_rate: float = 0.9,
mutation_rate: float = 0.1,
elitism_rate: float = 0.01
):
# build operations list (unique)
ops = all_operations(jobs)
# initialize population: random permutations of operations
population = [random.sample(ops, len(ops)) for _ in range(pop_size)]
for gen in range(generations):
# evaluate
makespans = evaluate_population(population, jobs)
# fitness: inverse of makespan (larger is better)
fitnesses = [1.0 / m for m in makespans]
# elitism: keep top 1%
elite_count = max(1, math.floor(pop_size * elitism_rate))
# sort population by fitness descending
sorted_indices = sorted(range(pop_size), key=lambda i: fitnesses[i], reverse=True)
elites = [population[i] for i in sorted_indices[:elite_count]]
# produce offspring
new_population = []
while len(new_population) < pop_size - elite_count:
# selection
p1 = tournament_selection(population, fitnesses)
p2 = tournament_selection(population, fitnesses)
# crossover
if random.random() < crossover_rate:
child = order_crossover_ox1(p1, p2)
else:
child = list(p1)
# mutation
child = mutate_swap(child, mutation_rate)
new_population.append(child)
# add elites unchanged
new_population.extend(elites)
population = new_population
# track best
best_mk = min(makespans)
if gen % 10 == 0 or gen == generations - 1:
print(f"Generation {gen}: best makespan = {best_mk}")
# final
makespans = evaluate_population(population, jobs)
best_idx = min(range(len(population)), key=lambda i: makespans[i])
best_solution = population[best_idx]
return best_solution, makespans[best_idx]
# ------------------------------------------------------------
# Example usage
# ------------------------------------------------------------
if __name__ == "__main__":
random.seed(42)
best_seq, best_makespan = genetic_algorithm_job_shop(
jobs=jobs,
pop_size=200,
generations=200,
crossover_rate=0.9,
mutation_rate=0.1,
elitism_rate=0.01
)
print("\nBest solution sequence (job, op_idx):")
print(best_seq)
print(f"Best makespan: {best_makespan}")
Notes
Encoding
Each gene is a unique operation (job_id, op_idx). A chromosome is a permutation of all operations across all jobs. A legal schedule is derived by processing operations in the order they appear in the chromosome, respecting machine availability and job precedence.
Order Crossover (OX1)
The order_crossover_ox1 function preserves relative ordering of operations (genes) from both parents. Two cut points are selected, the middle slice from parent1 is copied to the child, and the remainder is filled with the genes of parent2 in order, skipping duplicates. Because each operation is unique in this encoding, the result is always a valid permutation of all operations.
Elitism
Top 1% of individuals by fitness are copied unchanged into the next generation. The code uses elitism_rate=0.01 and ensures at least one elite is kept.
Fitness & Selection
Fitness is the inverse of the makespan (1.0 / makespan). Tournament selection is used to pick parents.
Mutation
Swap mutation randomly swaps two genes in a chromosome with probability mutation_rate.
You can adjust pop_size, generations, crossover/mutation rates, and the problem instance as needed for larger job shop cases.