年中無休の会社向けシフト自動作成ツールを遺伝的アルゴリズムで実装します。
import random
import numpy as np
from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import List, Dict, Tuple
import copy
@dataclass
class Employee:
"""従業員クラス"""
id: int
name: str
max_hours_per_week: int = 40
min_hours_per_week: int = 20
unavailable_days: List[int] = None # 0=月曜日, 6=日曜日
preferred_shifts: List[str] = None # ['morning', 'afternoon', 'night']
def __post_init__(self):
if self.unavailable_days is None:
self.unavailable_days = []
if self.preferred_shifts is None:
self.preferred_shifts = ['morning', 'afternoon', 'night']
class ShiftScheduler:
"""遺伝的アルゴリズムによるシフトスケジューラー"""
def __init__(self, employees: List[Employee], weeks: int = 4):
self.employees = employees
self.weeks = weeks
self.days_per_week = 7
self.shifts_per_day = 3 # morning, afternoon, night
self.shift_names = ['morning', 'afternoon', 'night']
self.shift_hours = {'morning': 8, 'afternoon': 8, 'night': 8}
self.min_staff_per_shift = 2
self.max_staff_per_shift = 4
# 遺伝的アルゴリズムのパラメータ
self.population_size = 100
self.generations = 500
self.mutation_rate = 0.1
self.crossover_rate = 0.8
self.elite_size = 10
def create_individual(self) -> np.ndarray:
"""個体(シフト表)を生成"""
# shape: (weeks, days_per_week, shifts_per_day, len(employees))
# 値: 0=勤務なし, 1=勤務あり
individual = np.zeros((self.weeks, self.days_per_week, self.shifts_per_day, len(self.employees)), dtype=int)
for week in range(self.weeks):
for day in range(self.days_per_week):
for shift in range(self.shifts_per_day):
# 各シフトに最低限の人数を配置
available_employees = []
for emp_idx, emp in enumerate(self.employees):
if day not in emp.unavailable_days:
if self.shift_names[shift] in emp.preferred_shifts:
available_employees.append(emp_idx)
if len(available_employees) >= self.min_staff_per_shift:
selected = random.sample(available_employees,
min(self.max_staff_per_shift, len(available_employees)))
for emp_idx in selected:
individual[week, day, shift, emp_idx] = 1
return individual
def calculate_fitness(self, individual: np.ndarray) -> float:
"""適応度を計算"""
fitness = 0
penalty = 0
# 1. 各シフトの人数制約
for week in range(self.weeks):
for day in range(self.days_per_week):
for shift in range(self.shifts_per_day):
staff_count = np.sum(individual[week, day, shift, :])
if staff_count < self.min_staff_per_shift:
penalty += (self.min_staff_per_shift - staff_count) * 100
elif staff_count > self.max_staff_per_shift:
penalty += (staff_count - self.max_staff_per_shift) * 50
else:
fitness += 10 # 適切な人数の場合はボーナス
# 2. 従業員の労働時間制約
for emp_idx, emp in enumerate(self.employees):
for week in range(self.weeks):
weekly_hours = 0
for day in range(self.days_per_week):
for shift in range(self.shifts_per_day):
if individual[week, day, shift, emp_idx] == 1:
weekly_hours += self.shift_hours[self.shift_names[shift]]
if weekly_hours < emp.min_hours_per_week:
penalty += (emp.min_hours_per_week - weekly_hours) * 5
elif weekly_hours > emp.max_hours_per_week:
penalty += (weekly_hours - emp.max_hours_per_week) * 10
else:
fitness += 5
# 3. 従業員の利用不可日制約
for emp_idx, emp in enumerate(self.employees):
for week in range(self.weeks):
for day in emp.unavailable_days:
for shift in range(self.shifts_per_day):
if individual[week, day, shift, emp_idx] == 1:
penalty += 200 # 重いペナルティ
# 4. 連続勤務制約(3日連続勤務を避ける)
for emp_idx in range(len(self.employees)):
for week in range(self.weeks):
for day in range(self.days_per_week - 2):
consecutive_days = 0
for d in range(day, day + 3):
if np.any(individual[week, d, :, emp_idx]):
consecutive_days += 1
if consecutive_days == 3:
penalty += 30
# 5. 希望シフト制約
for emp_idx, emp in enumerate(self.employees):
for week in range(self.weeks):
for day in range(self.days_per_week):
for shift in range(self.shifts_per_day):
if individual[week, day, shift, emp_idx] == 1:
if self.shift_names[shift] in emp.preferred_shifts:
fitness += 2
else:
penalty += 5
return max(0, fitness - penalty)
def crossover(self, parent1: np.ndarray, parent2: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""交叉操作"""
child1 = parent1.copy()
child2 = parent2.copy()
if random.random() < self.crossover_rate:
# 週単位で交叉
crossover_week = random.randint(0, self.weeks - 1)
child1[crossover_week:] = parent2[crossover_week:]
child2[crossover_week:] = parent1[crossover_week:]
return child1, child2
def mutate(self, individual: np.ndarray) -> np.ndarray:
"""突然変異操作"""
mutated = individual.copy()
if random.random() < self.mutation_rate:
# ランダムな位置で勤務状態を変更
week = random.randint(0, self.weeks - 1)
day = random.randint(0, self.days_per_week - 1)
shift = random.randint(0, self.shifts_per_day - 1)
emp_idx = random.randint(0, len(self.employees) - 1)
# 制約をチェックして変更
emp = self.employees[emp_idx]
if day not in emp.unavailable_days:
mutated[week, day, shift, emp_idx] = 1 - mutated[week, day, shift, emp_idx]
return mutated
def select_parents(self, population: List[np.ndarray], fitness_scores: List[float]) -> List[np.ndarray]:
"""親選択(トーナメント選択)"""
parents = []
tournament_size = 3
for _ in range(len(population)):
tournament_indices = random.sample(range(len(population)), tournament_size)
tournament_fitness = [fitness_scores[i] for i in tournament_indices]
winner_idx = tournament_indices[tournament_fitness.index(max(tournament_fitness))]
parents.append(population[winner_idx].copy())
return parents
def evolve(self) -> np.ndarray:
"""遺伝的アルゴリズムの実行"""
# 初期集団の生成
population = [self.create_individual() for _ in range(self.population_size)]
best_fitness_history = []
for generation in range(self.generations):
# 適応度計算
fitness_scores = [self.calculate_fitness(individual) for individual in population]
# 最良個体の記録
best_fitness = max(fitness_scores)
best_fitness_history.append(best_fitness)
if generation % 50 == 0:
print(f"Generation {generation}: Best fitness = {best_fitness}")
# エリート選択
elite_indices = sorted(range(len(fitness_scores)),
key=lambda i: fitness_scores[i], reverse=True)[:self.elite_size]
elite_population = [population[i].copy() for i in elite_indices]
# 親選択
parents = self.select_parents(population, fitness_scores)
# 新世代の生成
new_population = elite_population.copy()
while len(new_population) < self.population_size:
parent1, parent2 = random.sample(parents, 2)
child1, child2 = self.crossover(parent1, parent2)
child1 = self.mutate(child1)
child2 = self.mutate(child2)
new_population.extend([child1, child2])
population = new_population[:self.population_size]
# 最終的な最良個体を返す
final_fitness_scores = [self.calculate_fitness(individual) for individual in population]
best_individual_idx = final_fitness_scores.index(max(final_fitness_scores))
return population[best_individual_idx]
def print_schedule(self, schedule: np.ndarray):
"""シフト表を見やすく出力"""
days = ['月', '火', '水', '木', '金', '土', '日']
shifts = ['朝', '昼', '夜']
for week in range(self.weeks):
print(f"\n=== 第{week + 1}週 ===")
for day in range(self.days_per_week):
print(f"\n{days[day]}曜日:")
for shift in range(self.shifts_per_day):
working_employees = []
for emp_idx in range(len(self.employees)):
if schedule[week, day, shift, emp_idx] == 1:
working_employees.append(self.employees[emp_idx].name)
print(f" {shifts[shift]}勤: {', '.join(working_employees) if working_employees else '未配置'}")
# 使用例
def main():
# 従業員データの作成
employees = [
Employee(1, "田中", max_hours_per_week=40, min_hours_per_week=32,
unavailable_days=[6], preferred_shifts=['morning', 'afternoon']),
Employee(2, "佐藤", max_hours_per_week=35, min_hours_per_week=25,
unavailable_days=[0, 1], preferred_shifts=['afternoon', 'night']),
Employee(3, "鈴木", max_hours_per_week=40, min_hours_per_week=30,
unavailable_days=[], preferred_shifts=['morning', 'night']),
Employee(4, "高橋", max_hours_per_week=30, min_hours_per_week=20,
unavailable_days=[5, 6], preferred_shifts=['morning']),
Employee(5, "伊藤", max_hours_per_week=40, min_hours_per_week=35,
unavailable_days=[2], preferred_shifts=['night']),
Employee(6, "渡辺", max_hours_per_week=25, min_hours_per_week=15,
unavailable_days=[3, 4], preferred_shifts=['afternoon']),
]
# シフトスケジューラーの作成と実行
scheduler = ShiftScheduler(employees, weeks=2)
print("シフト最適化を開始します...")
best_schedule = scheduler.evolve()
print(f"\n最終適応度: {scheduler.calculate_fitness(best_schedule)}")
scheduler.print_schedule(best_schedule)
# 各従業員の週間労働時間を表示
print("\n=== 従業員別週間労働時間 ===")
for week in range(scheduler.weeks):
print(f"\n第{week + 1}週:")
for emp_idx, emp in enumerate(employees):
weekly_hours = 0
for day in range(scheduler.days_per_week):
for shift in range(scheduler.shifts_per_day):
if best_schedule[week, day, shift, emp_idx] == 1:
weekly_hours += scheduler.shift_hours[scheduler.shift_names[shift]]
print(f" {emp.name}: {weekly_hours}時間")
if __name__ == "__main__":
main()
このシフト自動作成ツールの主な特徴:
制約条件の考慮
- 各シフトの最低・最大人数制約
- 従業員の週間労働時間制約
- 従業員の利用不可日制約
- 連続勤務制限
- 希望シフト制約
遺伝的アルゴリズムの実装
- 適応度関数による制約違反のペナルティ化
- トーナメント選択による親選択
- 週単位での交叉操作
- ランダムな突然変異
- エリート保存戦略
カスタマイズ可能な要素
- 従業員数と属性
- シフト時間と種類
- 最適化期間(週数)
- 遺伝的アルゴリズムのパラメータ
このツールを使用することで、複雑な制約条件を満たしながら効率的なシフト表を自動生成できます。