I'm currently focused on the fundamental building blocks of this scheduling problem. Each task will need attributes such as processing time, deadline, resource requirements, and dependencies. I'm also considering the types of constraints we'll need to enforce, like resource availability, precedence, and deadlines. I am figuring out how to represent these tasks and constraints in a format that a genetic algorithm can work with.
Refining the Encoding
I'm now fully immersed in the genetic algorithm implementation. The permutation encoding is the clear frontrunner for schedule representation. Decoding this permutation into an actual timetable feels more manageable now that I'm considering resource availability and precedence. The fitness function is shaping up as a weighted combination of hard constraint violations (which will be heavily penalized) and soft constraint optimization (makespan, idle time, and load balance).
Implementing the Algorithm
I've been working on the details of the genetic algorithm, solidifying the selection, crossover, and mutation operators. Tournament selection for parent selection and order-preserving crossover such as Ordered Crossover (OX1) are what I'm leaning toward. For mutation, I am considering swap mutation. I've also decided to use a custom implementation for educational purposes rather than a library.
Constructing The Scheduler
I'm deep into the coding now, starting with essential data structures, such as a simple Task class. The decoder, the heart of schedule creation, is proving trickier than anticipated. Right now, I'm focusing on managing resource contention. GA operators like tournament selection and Ordered Crossover are set. I'm choosing a simpler crossover for better readability for now. Next, I need to flesh out the breeding approach to generate new schedules.
Revising Constraint Strategy
I've been thinking about precedence constraints. Instead of direct precedence enforcement in the decoder, I'll focus on resource constraints and minimizing makespan to keep the code concise. Although this simplifies it, I will still describe how to add precedence constraints conceptually. For mutation, I will only use the swap operator.
Structuring the Solution
The decoder design has been improved, and I am finalizing the algorithm's explanation, which will include an introduction, explanation of GA concepts, and Python code. The code will be well-commented and clean, and will be accompanied by a visualization. Finally, I will address future extensions to handle more difficult constraints.
Generating Visuals and Final Touches
I'm now putting the finishing touches on the project. I've integrated a Gantt chart using Matplotlib to visually represent the schedules. I've also focused on clear variable naming and code readability for ease of understanding. I've re-examined the code, and ensured the Ordered Crossover generates valid children, avoiding duplicate tasks, which I realized was a critical requirement. The output now includes a clear and concise visual schedule.
This is a classic optimization problem. To solve this with a Genetic Algorithm (GA), we need to define how to represent a schedule as DNA, how to measure its quality, and how to handle the constraints.
The Strategy
The Problem: We have a set of Tasks and a set of Resources (e.g., CPU cores, workers).
The Constraints:
Resource Constraint: A resource can only handle one task at a time.
Constraint Handling: We will handle this inside the "Decoder" (Fitness function). The GA assumes a task can start as soon as its resource is free.
The Objective: Minimize the Makespan (the total time required to finish all tasks).
The Encoding (Chromosome)
We will use Permutation Encoding.
A chromosome is a simple list of all Task IDs (e.g., [Task A, Task C, Task B]).
The order represents the priority. The decoder reads the list from left to right and schedules the task on its assigned resource as early as possible.
Python Implementation
You will need matplotlib for the visualization if you run the plotting code.
python
How this Code Works
1. The Chromosome
We treat the schedule as a list: [Task 3, Task 1, Task 5...].
While simple, this effectively represents a Priority Queue. In scheduling, the "constraint" is usually that resources are blocked. By listing tasks in order, we tell the algorithm: "Attempt to schedule Task 3 first, then Task 1."
2. The Fitness Function (calculate_makespan)
This is the "Decoder". It simulates the schedule creation:
It creates a dictionary resource_end_times.
It walks through the chromosome task by task.
If Task 3 needs Resource 2, it looks at when Resource 2 is free (current_end_time).
It adds the duration to update the resource's free time.
Fitness Score: The maximum time found among all resources (the time the factory shuts down).
3. Crossover (Crucial Step)
Standard crossover (cutting a list in half and swapping) does not work for scheduling.
Example: Parent A has [1, 2, 3], Parent B has [3, 2, 1].
Bad Crossover: First half of A [1] + Second half of B [2, 1] = Child [1, 2, 1].
Issue: Task 1 is duplicated, Task 3 is missing.
Solution: We use Ordered Crossover. It copies a chunk from Parent A, and fills the empty spots using the relative order found in Parent B. This ensures every task appears exactly once.
Adding More Constraints?
If you need to make this more complex (e.g., Task B cannot start until Task A finishes), you modify only the Fitness Function (Decoder):
Add a finish_time tracker for every individual Task ID.
When calculating the start time for a task:
python
# Resource constraint
resource_avail_time = resource_end_times[task.resource_id]
# Precedence constraint (e.g., task.depends_on = [PrecedingTaskID])
dependency_avail_time = max([task_finish_times[dep_id] for dep_id in task.depends_on])
# Actual start is the later of the two
actual_start_time = max(resource_avail_time, dependency_avail_time)
If the schedule breaks a hard constraint (impossible to schedule), apply a massive penalty score (e.g., +10000 to fitness) so the GA kills that individual off.
import random
import numpy as np
import matplotlib.pyplot as plt
# --- 1. Define the Problem ---
class Task:
def __init__(self, id, duration, resource_id):
self.id = id
self.duration = duration
self.resource_id = resource_id
def __repr__(self):
return f"T{self.id}(R{self.resource_id}, {self.duration}h)"
# Define a set of tasks
# ID, Duration, Resource ID
TASKS = [
Task(1, 4, 1), Task(2, 2, 1), Task(3, 5, 2),
Task(4, 2, 3), Task(5, 6, 1), Task(6, 3, 2),
Task(7, 4, 3), Task(8, 7, 1), Task(9, 2, 2),
Task(10, 3, 3), Task(11, 4, 1), Task(12, 2, 2)
]
# --- 2. Helper Functions ---
def plot_schedule(individual):
"""Visualizes the schedule as a Gantt Chart"""
resource_timelines = {} # Stores (start, duration) for each resource
resource_free_time = {} # Tracks when each resource becomes free
for task in individual:
r_id = task.resource_id
# Calculate start time: It's current free time of the resource
start_time = resource_free_time.get(r_id, 0)
if r_id not in resource_timelines:
resource_timelines[r_id] = []
resource_timelines[r_id].append((start_time, task.duration, task.id))
resource_free_time[r_id] = start_time + task.duration
# Plotting
fig, ax = plt.subplots(figsize=(10, 6))
colors = plt.cm.tab20.colors
y_labels = []
y_ticks = []
for i, (r_id, tasks) in enumerate(sorted(resource_timelines.items())):
y_ticks.append(i * 10)
y_labels.append(f"Resource {r_id}")
for (start, duration, t_id) in tasks:
ax.broken_barh([(start, duration)], (i * 10 - 4, 8),
facecolors=colors[t_id % len(colors)], edgecolor='black')
ax.text(start + duration/2, i * 10, f"T{t_id}",
ha='center', va='center', color='white', fontweight='bold')
ax.set_yticks(y_ticks)
ax.set_yticklabels(y_labels)
ax.set_xlabel("Time")
ax.set_title("Optimized Schedule (Gantt Chart)")
ax.grid(True, axis='x', linestyle='--', alpha=0.6)
plt.show()
# --- 3. Genetic Algorithm Components ---
def create_individual():
"""Creates a random permutation of tasks"""
individual = TASKS[:]
random.shuffle(individual)
return individual
def calculate_makespan(individual):
"""
Calculates the total time to complete all tasks (fitness).
Lower is better.
"""
resource_end_times = {}
for task in individual:
r_id = task.resource_id
# Start time is when the resource finishes its previous task
current_end_time = resource_end_times.get(r_id, 0)
new_end_time = current_end_time + task.duration
resource_end_times[r_id] = new_end_time
# Makespan is the time when the LAST resource finishes
max_time = max(resource_end_times.values()) if resource_end_times else 0
return max_time
def selection(population, k=3):
"""Tournament Selection: Pick k random, return the best."""
tournament = random.sample(population, k)
best = min(tournament, key=calculate_makespan)
return best
def crossover(parent1, parent2):
"""
Ordered Crossover (OX).
Preserves the order of tasks to ensure valid permutations.
"""
size = len(parent1)
start, end = sorted(random.sample(range(size), 2))
# Initialize child with None
child = [None] * size
# Copy a slice from parent 1
child[start:end] = parent1[start:end]
# Fill the rest with tasks from parent 2 (in order, skipping existing)
current_p2_index = 0
for i in range(size):
if child[i] is None:
while parent2[current_p2_index] in child:
current_p2_index += 1
child[i] = parent2[current_p2_index]
return child
def mutate(individual, mutation_rate=0.1):
"""Swap Mutation: Swaps two tasks in the priority list."""
if random.random() < mutation_rate:
idx1, idx2 = random.sample(range(len(individual)), 2)
individual[idx1], individual[idx2] = individual[idx2], individual[idx1]
return individual
# --- 4. Main GA Loop ---
def run_genetic_algorithm(pop_size=50, generations=100, mutation_rate=0.2):
# 1. Initialization
population = [create_individual() for _ in range(pop_size)]
best_overall = None
best_makespan = float('inf')
for gen in range(generations):
# 2. Evaluation
population_sorted = sorted(population, key=calculate_makespan)
current_best = population_sorted[0]
current_best_score = calculate_makespan(current_best)
if current_best_score < best_makespan:
best_makespan = current_best_score
best_overall = current_best[:] # Copy
# Elitism: Keep the absolute best from this generation
new_population = [current_best]
# 3. Breeding
while len(new_population) < pop_size:
parent1 = selection(population)
parent2 = selection(population)
child = crossover(parent1, parent2)
child = mutate(child, mutation_rate)
new_population.append(child)
population = new_population
if gen % 10 == 0:
print(f"Generation {gen}: Best Makespan = {best_makespan}")
return best_overall, best_makespan
# --- Run and Visualize ---
if __name__ == "__main__":
best_schedule, makespan = run_genetic_algorithm(pop_size=100, generations=50)
print("\n--- Optimization Complete ---")
print(f"Minimum Makespan Found: {makespan} hours")
print("Best Task Order:", [f"T{t.id}" for t in best_schedule])
# Visualize
plot_schedule(best_schedule)