import random
from dataclasses import dataclass
from typing import List, Dict, Tuple, Optional
# -------------------------
# Problem definition
# -------------------------
@dataclass
class Task:
id: int
duration: int
machine: int # which machine/resource this task needs
predecessors: List[int]
# -------------------------
# Schedule decoding
# -------------------------
def decode_schedule(
chromosome: List[int],
tasks: List[Task],
n_machines: int
) -> Tuple[int, Dict[int, int], Dict[int, int]]:
"""
Given a permutation of task IDs, build a feasible schedule by
scheduling each task as early as possible respecting:
- Predecessors
- Machine capacity (one task at a time per machine)
Returns:
makespan, start_times, finish_times
"""
task_by_id = {t.id: t for t in tasks}
machine_available_at = [0] * n_machines # time when each machine becomes free
start_times: Dict[int, int] = {}
finish_times: Dict[int, int] = {}
for tid in chromosome:
t = task_by_id[tid]
# Finish time of all predecessors
pred_finish = 0
for p in t.predecessors:
pred_finish = max(pred_finish, finish_times[p])
# Machine availability
m = t.machine
earliest_start = max(pred_finish, machine_available_at[m])
start_times[tid] = earliest_start
finish_time = earliest_start + t.duration
finish_times[tid] = finish_time
# Update machine availability
machine_available_at[m] = finish_time
makespan = max(finish_times.values())
return makespan, start_times, finish_times
def fitness_function(
chromosome: List[int],
tasks: List[Task],
n_machines: int,
deadlines: Optional[Dict[int, int]] = None,
late_penalty_per_time: float = 10.0
) -> float:
"""
Compute fitness = makespan + penalties (lower is better).
"""
makespan, _, finish_times = decode_schedule(chromosome, tasks, n_machines)
penalty = 0.0
if deadlines is not None:
for tid, ddl in deadlines.items():
ft = finish_times[tid]
if ft > ddl:
penalty += late_penalty_per_time * (ft - ddl)
return makespan + penalty
# -------------------------
# Genetic operators
# -------------------------
def init_population(pop_size: int, task_ids: List[int]) -> List[List[int]]:
population = []
for _ in range(pop_size):
chrom = task_ids[:]
random.shuffle(chrom)
population.append(chrom)
return population
def tournament_selection(
population: List[List[int]],
fitnesses: List[float],
tournament_size: int = 3
) -> List[int]:
"""
Select one individual using tournament selection.
"""
selected_idx = random.randrange(len(population))
best_idx = selected_idx
best_fit = fitnesses[selected_idx]
for _ in range(tournament_size - 1):
selected_idx = random.randrange(len(population))
if fitnesses[selected_idx] < best_fit: # lower fitness is better
best_idx = selected_idx
best_fit = fitnesses[selected_idx]
return population[best_idx][:] # return a copy
def ordered_crossover(parent1: List[int], parent2: List[int]) -> Tuple[List[int], List[int]]:
"""
Ordered Crossover (OX) for permutations.
"""
size = len(parent1)
a, b = sorted(random.sample(range(size), 2))
def ox(p1, p2):
child = [None] * size
# copy slice from p1
child[a:b+1] = p1[a:b+1]
# fill remaining from p2 in order
fill_positions = [i for i in range(size) if child[i] is None]
p2_items = [g for g in p2 if g not in child]
for pos, gene in zip(fill_positions, p2_items):
child[pos] = gene
return child
return ox(parent1, parent2), ox(parent2, parent1)
def swap_mutation(chromosome: List[int], mutation_rate: float) -> None:
"""
Swap two genes with given probability.
"""
if random.random() < mutation_rate:
i, j = random.sample(range(len(chromosome)), 2)
chromosome[i], chromosome[j] = chromosome[j], chromosome[i]
# -------------------------
# Main GA loop
# -------------------------
def genetic_algorithm(
tasks: List[Task],
n_machines: int,
pop_size: int = 50,
generations: int = 200,
crossover_rate: float = 0.9,
mutation_rate: float = 0.1,
tournament_size: int = 3,
deadlines: Optional[Dict[int, int]] = None,
late_penalty_per_time: float = 10.0,
elitism: bool = True
):
task_ids = [t.id for t in tasks]
population = init_population(pop_size, task_ids)
best_chrom = None
best_fit = float('inf')
best_schedule = None
for gen in range(generations):
# Evaluate fitness of population
fitnesses = [
fitness_function(
chrom, tasks, n_machines, deadlines=deadlines,
late_penalty_per_time=late_penalty_per_time
)
for chrom in population
]
# Track global best
for i, fit in enumerate(fitnesses):
if fit < best_fit:
best_fit = fit
best_chrom = population[i][:]
ms, st, ft = decode_schedule(best_chrom, tasks, n_machines)
best_schedule = (ms, st, ft)
# Print some progress (optional)
# print(f"Gen {gen}, best fitness: {best_fit:.2f}")
# Create new population
new_population = []
# Elitism: carry the best individual to the next generation
if elitism and best_chrom is not None:
new_population.append(best_chrom[:])
while len(new_population) < pop_size:
# Selection
parent1 = tournament_selection(population, fitnesses, tournament_size)
parent2 = tournament_selection(population, fitnesses, tournament_size)
# Crossover
if random.random() < crossover_rate:
child1, child2 = ordered_crossover(parent1, parent2)
else:
child1, child2 = parent1[:], parent2[:]
# Mutation
swap_mutation(child1, mutation_rate)
swap_mutation(child2, mutation_rate)
new_population.append(child1)
if len(new_population) < pop_size:
new_population.append(child2)
population = new_population
return best_chrom, best_fit, best_schedule
# -------------------------
# Example usage
# -------------------------
if __name__ == "__main__":
# Example: 6 tasks, 2 machines, simple precedence
tasks = [
Task(id=0, duration=3, machine=0, predecessors=[]),
Task(id=1, duration=2, machine=0, predecessors=[0]),
Task(id=2, duration=4, machine=1, predecessors=[]),
Task(id=3, duration=2, machine=1, predecessors=[2]),
Task(id=4, duration=3, machine=0, predecessors=[1, 3]),
Task(id=5, duration=1, machine=1, predecessors=[3]),
]
n_machines = 2
# Optional deadlines (task_id -> latest allowed finish time)
deadlines = {
4: 12, # task 4 should ideally finish by time 12
5: 10, # task 5 should ideally finish by time 10
}
best_chrom, best_fit, (makespan, start_times, finish_times) = genetic_algorithm(
tasks,
n_machines,
pop_size=50,
generations=200,
crossover_rate=0.9,
mutation_rate=0.1,
tournament_size=3,
deadlines=deadlines,
late_penalty_per_time=5.0,
elitism=True,
)
print("Best chromosome (task order):", best_chrom)
print(f"Best fitness: {best_fit:.2f}")
print(f"Makespan: {makespan}")
print("Start times:", start_times)
print("Finish times:", finish_times)