-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimplified_genetic_algorithm.py
More file actions
2004 lines (1617 loc) · 83.1 KB
/
simplified_genetic_algorithm.py
File metadata and controls
2004 lines (1617 loc) · 83.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Simplified Genetic Algorithm for Timetable Generation
This module implements a genetic algorithm to generate optimal timetables
for educational institutions. It handles multiple branches, teachers, courses,
and rooms while ensuring each professor has the required number of classes
for each course they teach.
Author: Timetable Generator Team
Version: 1.1
"""
import cProfile
# Importing all the libraries we need for our program
import random # for generating random numbers
import timeit
import copy # for making deep copies of objects
import time # to measure how long our algorithm takes
import heapq # this helps us with priority queues
from db_operations import fetch_data_from_db, insert_timetable_into_db, get_course_classes
import sqlite3 # for database operations
from tabulate import tabulate # makes our tables look nice when printed
from collections import defaultdict, Counter # special dictionaries that are helpful
# TODO: Learn about more efficient data structures for scheduling problems
# Constants for our timetable
DAYS = 5 # Monday to Friday
SLOTS_PER_DAY = 9 # 9 time slots per day
LUNCH_SLOT = 4 # Lunch break (5th slot)
POPULATION_SIZE = 30 # Population size for genetic algorithm
ELITE_SIZE = 6 # Top schedules to keep unchanged
TOURNAMENT_SIZE = 4 # Number of schedules to compete in tournament selection
MUTATION_RATE = 0.25 # Probability of mutation
CROSSOVER_RATE = 0.8 # Probability of crossover
MAX_CLASSES_PER_SLOT = 3 # Maximum number of classes in a single time slot
# Preferred time slots - morning slots (0-3) are preferred for core subjects
# This encourages important classes to be scheduled in the morning
PREFERRED_MORNING_SLOTS = [0, 1, 2, 3] # First 4 slots of the day
# List of core courses that should preferably be scheduled in the morning
# These are typically more demanding subjects that benefit from morning scheduling
CORE_COURSES = ["CSE101", "ECE101", "ME101", "CE101", "EEE101"]
# Class to store class data
class ClassSlot:
def __init__(self, course_code, course_name, teacher, room, branch, day, slot):
# Store all the information about a class
self.course_code = course_code
self.course_name = course_name
self.teacher = teacher
self.room = room
self.branch = branch
self.day = day
self.slot = slot
# print(f"Created new class: {course_code} with {teacher}")
def __str__(self):
# This helps us print the class in a readable format
return f"{self.course_code}: {self.teacher} in {self.room} ({self.branch})"
def copy(self):
return ClassSlot(
self.course_code,
self.course_name,
self.teacher,
self.room,
self.branch,
self.day,
self.slot
)
def copy_schedule(schedule):
if isinstance(schedule, dict):
return {
key: [cls.copy() for cls in class_list]
for key, class_list in schedule.items()
}
elif isinstance(schedule, list):
return [cls.copy() for cls in schedule]
else:
raise TypeError("Unsupported schedule format")
def create_empty_schedule():
"""Create an empty schedule with None values."""
# This creates a 2D array filled with None values
# First we make DAYS number of rows
empty_schedule = []
for i in range(DAYS):
# Then for each day, we add SLOTS_PER_DAY number of None values
day_slots = []
for j in range(SLOTS_PER_DAY):
day_slots.append(None)
empty_schedule.append(day_slots)
# return [[None for _ in range(SLOTS_PER_DAY)] for _ in range(DAYS)]
return empty_schedule
def check_room_conflicts(schedule):
"""Check for room conflicts in the schedule.
This function identifies instances where the same room is assigned to multiple
classes at the same time. It's optimized for performance using sets and
handles all possible schedule data formats.
Args:
schedule: The timetable schedule to check
Returns:
A list of conflicts (day, slot, room) or an empty list if no conflicts
"""
# Handle None schedule case
if schedule is None:
return []
conflicts = []
# Pre-allocate a 2D array to track room usage across all days and slots
# This is more efficient than creating new sets in each iteration
room_usage = [[set() for _ in range(SLOTS_PER_DAY)] for _ in range(DAYS)]
# First pass: collect all room usage
for day in range(DAYS):
for slot in range(SLOTS_PER_DAY):
# Skip lunch slot
if slot == LUNCH_SLOT:
continue
# Skip empty slots
if schedule[day][slot] is None:
continue
# Handle multiple classes in the same slot
classes = schedule[day][slot] if isinstance(schedule[day][slot], list) else [schedule[day][slot]]
for class_data in classes:
if class_data is None:
continue
# Extract room information, handling both object and tuple formats
room = class_data.room if hasattr(class_data, 'room') else class_data[3]
# Check for conflict and add to room usage
if room in room_usage[day][slot]:
conflicts.append((day, slot, room))
room_usage[day][slot].add(room)
return conflicts
def get_course_class_requirements():
"""Get the number of classes required for each course.
Returns a dictionary mapping course_code to the number of classes required.
"""
try:
# Get num course class from the database
course_classes = get_course_classes()
# Create a dictionary
class_requirements = {}
# Loop through each course and store its requirements
for course_code, num_classes, _, _ in course_classes:
num_classes_int = int(num_classes)
# Store the requirement in our dictionary
class_requirements[course_code] = num_classes_int
# Print out the requirement for debugging
# print(f"Course {course_code} requires {num_classes} classes")
return class_requirements
except Exception as e:
# If there's an error, print it and use a default value
print(f"Error getting course classes: {e}")
# If there's an error, use a default of 1 class per course
return defaultdict(lambda: 1)
def fix_overassigned_classes(schedule):
"""Fix a schedule by removing extra classes for teachers who have more than required.
Optimized using a heap (priority queue) to efficiently process the most overassigned classes first.
"""
fixed_schedule = copy_schedule(schedule)
class_requirements = get_course_class_requirements()
teacher_count = count_course_teacher_classes(fixed_schedule)
# Use a heap (priority queue) to efficiently track the most overassigned classes
overassigned_heap = []
for (course_code, teacher), count in teacher_count.items():
required = class_requirements.get(course_code, 1)
if count > required:
# Negative extra for max-heap behavior (Python's heapq is a min-heap)
extra = count - required
heapq.heappush(overassigned_heap, (-extra, course_code, teacher, count, required))
if not overassigned_heap:
return fixed_schedule
# Process overassigned classes in order of most overassigned first
while overassigned_heap:
neg_extra, course_code, teacher, count, required = heapq.heappop(overassigned_heap)
extra = -neg_extra # Convert back to positive
# Find all slots with this course and teacher
course_slots = []
for day in range(DAYS):
for slot in range(SLOTS_PER_DAY):
if slot == LUNCH_SLOT or fixed_schedule[day][slot] is None:
continue
if isinstance(fixed_schedule[day][slot], list):
for i, class_data in enumerate(fixed_schedule[day][slot]):
if (class_data is not None and
class_data.course_code == course_code and
class_data.teacher == teacher):
course_slots.append((day, slot, i, class_data))
elif (fixed_schedule[day][slot].course_code == course_code and
fixed_schedule[day][slot].teacher == teacher):
course_slots.append((day, slot, None, fixed_schedule[day][slot]))
# Shuffle to randomize which classes we remove
random.shuffle(course_slots)
# Remove the extra classes
removed = 0
for day, slot, idx, _ in course_slots:
if removed >= extra:
break
if idx is None:
# Single class in this slot
fixed_schedule[day][slot] = None
else:
# Multiple classes in this slot
fixed_schedule[day][slot].pop(idx)
if not fixed_schedule[day][slot]:
fixed_schedule[day][slot] = None
elif len(fixed_schedule[day][slot]) == 1:
fixed_schedule[day][slot] = fixed_schedule[day][slot][0]
removed += 1
return fixed_schedule
start_time = timeit.default_timer()
def fix_class_assignments(schedule, courses, teachers, rooms):
"""Fix a schedule by removing extra classes and adding missing classes."""
# First, fix over-assigned classes
fixed_schedule = fix_overassigned_classes(schedule)
class_requirements = get_course_class_requirements()
course_teacher_counts = count_course_teacher_classes(fixed_schedule)
# Use a heap to efficiently track the most underassigned classes
underassigned_heap = []
# Find teacher-course combinations with too few classes
for (course_code, teacher), count in course_teacher_counts.items():
required = class_requirements.get(course_code, 1)
if count < required:
# Negative missing for max-heap behavior (Python's heapq is a min-heap)
missing = required - count
heapq.heappush(underassigned_heap, (-missing, course_code, teacher, count, required))
# Also check for course-teacher combinations that should exist but don't
try:
with sqlite3.connect("timetable.db") as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT c.course_code, c.course_name, b.branch_name, t.teacher_name
FROM branch_teacher_courses btc
JOIN branches b ON btc.branch_id = b.branch_id
JOIN teachers t ON btc.teacher_id = t.teacher_id
JOIN courses c ON btc.course_code = c.course_code
""")
for course_code, course_name, branch, teacher in cursor.fetchall():
if course_code in class_requirements:
required = class_requirements[course_code]
actual = course_teacher_counts.get((course_code, teacher), 0)
if actual < required:
# Check if this combination is already in the heap
key = (course_code, teacher)
if not any(item[1:3] == key for item in underassigned_heap):
missing = required - actual
heapq.heappush(underassigned_heap, (-missing, course_code, teacher, actual, required))
except sqlite3.Error:
pass
if not underassigned_heap:
return fixed_schedule
# Track which slots are used for each teacher, room, and branch
teacher_slots = defaultdict(set) # teacher -> set of (day, slot)
room_slots = defaultdict(set) # room -> set of (day, slot)
branch_slots = defaultdict(set) # branch -> set of (day, slot)
# Fill these tracking structures based on the current schedule
for day in range(DAYS):
for slot in range(SLOTS_PER_DAY):
if slot == LUNCH_SLOT or fixed_schedule[day][slot] is None:
continue
classes = fixed_schedule[day][slot] if isinstance(fixed_schedule[day][slot], list) else [fixed_schedule[day][slot]]
for class_data in classes:
if class_data is None:
continue
if hasattr(class_data, 'teacher'):
teacher = class_data.teacher
room = class_data.room
branch = class_data.branch
else:
teacher = class_data[2]
room = class_data[3]
branch = class_data[4]
teacher_slots[teacher].add((day, slot))
room_slots[room].add((day, slot))
branch_slots[branch].add((day, slot))
# Process underassigned classes in order of most underassigned first
while underassigned_heap:
neg_missing, course_code, teacher, actual, required = heapq.heappop(underassigned_heap)
missing = -neg_missing # Convert back to positive
# Find the course details
course_details = None
for c in courses:
if c[0] == course_code:
course_details = c
break
if not course_details:
continue
_, branch, course_name = course_details
# Try to add the missing classes
for _ in range(missing):
# Try multiple slots to find one that works
success = False
for attempt in range(30):
day = random.randint(0, DAYS-1)
slot = random.randint(0, SLOTS_PER_DAY-1)
if slot == LUNCH_SLOT:
continue
# Skip if teacher or branch already has a class in this slot
if (day, slot) in teacher_slots[teacher] or (day, slot) in branch_slots[branch]:
continue
# Check if slot is available
if fixed_schedule[day][slot] is not None:
if isinstance(fixed_schedule[day][slot], list) and len(fixed_schedule[day][slot]) >= MAX_CLASSES_PER_SLOT:
continue # Slot is full
# Find available rooms not already used in this slot
available_rooms = [r for r in rooms if (day, slot) not in room_slots[r]]
if not available_rooms:
continue
# Pick a room and create a class slot
room = random.choice(available_rooms)
class_slot = ClassSlot(course_code, course_name, teacher, room, branch, day, slot)
# Add to schedule
if fixed_schedule[day][slot] is None:
fixed_schedule[day][slot] = class_slot
elif isinstance(fixed_schedule[day][slot], list):
if len(fixed_schedule[day][slot]) < MAX_CLASSES_PER_SLOT:
fixed_schedule[day][slot].append(class_slot)
else:
continue # Slot is full
else:
# Convert single class to list
fixed_schedule[day][slot] = [fixed_schedule[day][slot], class_slot]
# Update tracking
teacher_slots[teacher].add((day, slot))
room_slots[room].add((day, slot))
branch_slots[branch].add((day, slot))
success = True
break # Successfully added a class
if not success:
# If we couldn't add this class after trying all slots, move on
break
return fixed_schedule
print(timeit.default_timer() - start_time)
def get_valid_assignment(schedule, courses, teachers, rooms, day, slot, branch, course_teacher_counts=None, class_requirements=None, specific_course=None, specific_teacher=None):
"""Get a valid course, teacher, and room assignment for a given slot.
Returns a ClassSlot object or None if no valid assignment is possible
"""
# Skip lunch slot
if slot == LUNCH_SLOT:
return None
# Check if the slot already has the maximum number of classes
if schedule[day][slot] is not None:
if isinstance(schedule[day][slot], list) and len(schedule[day][slot]) >= MAX_CLASSES_PER_SLOT:
return None
# Get all entities already in this slot
slot_courses = set()
slot_teachers = set()
slot_rooms = set()
slot_branches = set()
if schedule[day][slot] is not None:
classes = schedule[day][slot] if isinstance(schedule[day][slot], list) else [schedule[day][slot]]
for class_data in classes:
if class_data is None:
continue
if hasattr(class_data, 'course_code'):
slot_courses.add(class_data.course_code)
slot_teachers.add(class_data.teacher)
slot_rooms.add(class_data.room)
slot_branches.add(class_data.branch)
else:
slot_courses.add(class_data[0])
slot_teachers.add(class_data[2])
slot_rooms.add(class_data[3])
slot_branches.add(class_data[4])
# If branch is already in this slot, we can't add another course from the same branch
if branch in slot_branches:
return None
# Filter courses for this branch
if specific_course:
# If a specific course is requested, only consider that course
branch_courses = [c for c in courses if c[1] == branch and c[0] == specific_course]
else:
branch_courses = [c for c in courses if c[1] == branch and c[0] not in slot_courses]
if not branch_courses:
return None
# If we have course-teacher counts and class requirements, prioritize courses that need more classes
if course_teacher_counts and class_requirements and not specific_course:
# Sort courses by how many more classes they need
branch_courses.sort(key=lambda c: class_requirements.get(c[0], 1) -
sum(count for (course, _), count in course_teacher_counts.items() if course == c[0]),
reverse=True)
else:
# Shuffle for randomness
random.shuffle(branch_courses)
# Try each course
for course in branch_courses:
course_code, branch_name, course_name = course
# Find teachers who can teach this course and are not already in this slot
if specific_teacher:
# If a specific teacher is requested, only consider that teacher
available_teachers = [specific_teacher] if specific_teacher not in slot_teachers else []
# Verify this teacher can teach this course
teacher_can_teach = False
for teacher_data in teachers:
teacher_name, teacher_course_code, teacher_branch = teacher_data
if teacher_name == specific_teacher and teacher_course_code == course_code and teacher_branch == branch_name:
teacher_can_teach = True
break
if not teacher_can_teach:
available_teachers = []
else:
available_teachers = []
for teacher_data in teachers:
teacher_name, teacher_course_code, teacher_branch = teacher_data
if teacher_branch == branch_name and teacher_course_code == course_code and teacher_name not in slot_teachers:
available_teachers.append(teacher_name)
if not available_teachers:
continue
# If we have course-teacher counts and class requirements, prioritize teachers who need more classes
if course_teacher_counts and class_requirements and not specific_teacher:
# Sort teachers by how many more classes they need to teach for this course
available_teachers.sort(key=lambda t: class_requirements.get(course_code, 1) -
course_teacher_counts.get((course_code, t), 0),
reverse=True)
else:
# Shuffle for randomness
random.shuffle(available_teachers)
# Try each teacher
for teacher in available_teachers:
# Find available rooms not already in this slot
available_rooms = [r for r in rooms if r not in slot_rooms]
if not available_rooms:
continue
# Select a random room
room = random.choice(available_rooms)
# Create a class slot
return ClassSlot(course_code, course_name, teacher, room, branch_name, day, slot)
return None
def create_random_schedule(courses, teachers, rooms):
"""Create a timetable with constraint-based scheduling to ensure professors have correct class counts."""
schedule = create_empty_schedule()
# Get all branches
branches = set()
for _, branch, _ in courses:
branches.add(branch)
# Get course class requirements
class_requirements = get_course_class_requirements()
# Track which slots are used for each teacher, room, and branch
teacher_slots = defaultdict(set) # teacher -> set of (day, slot)
room_slots = defaultdict(set) # room -> set of (day, slot)
branch_slots = defaultdict(set) # branch -> set of (day, slot)
# Track how many classes have been assigned for each course-teacher pair
course_counts = defaultdict(int) # course_code -> count
course_teacher_counts = defaultdict(int) # (course_code, teacher) -> count
# Create a list of all course-teacher combinations that need to be scheduled
combinations = []
# First, gather all valid course-teacher combinations from the database
with sqlite3.connect("timetable.db") as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT c.course_code, c.course_name, b.branch_name, t.teacher_name
FROM branch_teacher_courses btc
JOIN branches b ON btc.branch_id = b.branch_id
JOIN teachers t ON btc.teacher_id = t.teacher_id
JOIN courses c ON btc.course_code = c.course_code
""")
db_mappings = cursor.fetchall()
# Add all valid combinations to our list
for course_code, course_name, branch, teacher in db_mappings:
if course_code in class_requirements:
required = class_requirements[course_code]
combinations.append((course_code, course_name, branch, teacher, required))
# If we couldn't get combinations from the database, create them from the courses and teachers
if not combinations:
print("Warning: No course-teacher mappings found in database. Creating from available data.")
for course_code, required in class_requirements.items():
# Find all courses with this code
course_options = [c for c in courses if c[0] == course_code]
if not course_options:
continue
# For each branch that offers this course
for course in course_options:
branch = course[1]
course_name = course[2]
# Find teachers who can teach this course in this branch
course_teachers = []
for teacher_data in teachers:
teacher_name, teacher_course, teacher_branch = teacher_data
if teacher_course == course_code and teacher_branch == branch:
course_teachers.append(teacher_name)
if not course_teachers:
continue
# Add all valid combinations to our list
for teacher in course_teachers:
combinations.append((course_code, course_name, branch, teacher, required))
# Shuffle combinations for diversity
random.shuffle(combinations)
print(f"Scheduling {len(combinations)} course-teacher combinations...")
# First pass: Schedule exactly one class for each course-teacher combination
for course_code, course_name, branch, teacher, required in combinations:
# Skip if this teacher already has enough classes for this course
if course_teacher_counts[(course_code, teacher)] >= required:
continue
# Find the best days and slots for this class
day_slot_scores = []
for day in range(DAYS):
for slot in range(SLOTS_PER_DAY):
if slot == LUNCH_SLOT:
continue
# Skip if teacher or branch already has a class in this slot
if (day, slot) in teacher_slots[teacher] or (day, slot) in branch_slots[branch]:
continue
# Check if slot is available
if schedule[day][slot] is not None:
if isinstance(schedule[day][slot], list) and len(schedule[day][slot]) >= MAX_CLASSES_PER_SLOT:
continue # Slot is full
# Find available rooms not already used in this slot
available_rooms = []
for room in rooms:
if (day, slot) not in room_slots[room]:
available_rooms.append(room)
if not available_rooms:
continue
# Calculate a score for this day/slot based on:
# 1. How many classes are already scheduled at this time
# 2. How many classes the teacher already has on this day
# Count classes in this slot
slot_count = 0
if schedule[day][slot] is not None:
slot_count = 1 if not isinstance(schedule[day][slot], list) else len(schedule[day][slot])
# Count teacher's classes on this day
teacher_day_count = sum(1 for d, s in teacher_slots[teacher] if d == day)
# Calculate score (lower is better)
score = slot_count * 3 + teacher_day_count * 2
# Add a small random factor for diversity
score += random.random()
# Add to our list of possibilities
day_slot_scores.append((day, slot, score, available_rooms))
# Sort by score (ascending)
day_slot_scores.sort(key=lambda x: x[2])
# Try to schedule a class
for day, slot, _, available_rooms in day_slot_scores:
# Pick a room
room = random.choice(available_rooms)
# Create a class slot
class_slot = ClassSlot(course_code, course_name, teacher, room, branch, day, slot)
# Add to schedule
if schedule[day][slot] is None:
schedule[day][slot] = class_slot
elif isinstance(schedule[day][slot], list):
if len(schedule[day][slot]) < MAX_CLASSES_PER_SLOT:
schedule[day][slot].append(class_slot)
else:
continue # Slot is full
else:
# Convert single class to list
schedule[day][slot] = [schedule[day][slot], class_slot]
# Update tracking
teacher_slots[teacher].add((day, slot))
room_slots[room].add((day, slot))
branch_slots[branch].add((day, slot))
course_counts[course_code] += 1
course_teacher_counts[(course_code, teacher)] += 1
# Successfully scheduled a class
break
# Verify all course-teacher combinations have the required number of classes
missing_combinations = []
for course_code, course_name, branch, teacher, required in combinations:
actual = course_teacher_counts[(course_code, teacher)]
if actual < required:
missing_combinations.append((course_code, course_name, branch, teacher, required, actual))
# Second pass: Try to fix any missing classes
if missing_combinations:
print(f"Fixing {len(missing_combinations)} missing course-teacher combinations...")
for course_code, course_name, branch, teacher, required, actual in missing_combinations:
# Calculate how many more classes we need
needed = required - actual
# Try to schedule the needed classes
for _ in range(needed):
# Try multiple slots to find one that works
for attempt in range(30): # Try up to 30 different slots
day = random.randint(0, DAYS-1)
slot = random.randint(0, SLOTS_PER_DAY-1)
if slot == LUNCH_SLOT:
continue
# Skip if teacher already has a class in this slot
if (day, slot) in teacher_slots[teacher]:
continue
# Skip if branch already has a class in this slot
if (day, slot) in branch_slots[branch]:
continue
# Check if slot is available
if schedule[day][slot] is not None:
if isinstance(schedule[day][slot], list) and len(schedule[day][slot]) >= MAX_CLASSES_PER_SLOT:
continue # Slot is full
# Find available rooms not already used in this slot
available_rooms = []
for room in rooms:
if (day, slot) not in room_slots[room]:
available_rooms.append(room)
if not available_rooms:
continue
# Pick a room
room = random.choice(available_rooms)
# Create a class slot
class_slot = ClassSlot(course_code, course_name, teacher, room, branch, day, slot)
# Add to schedule
if schedule[day][slot] is None:
schedule[day][slot] = class_slot
elif isinstance(schedule[day][slot], list):
if len(schedule[day][slot]) < MAX_CLASSES_PER_SLOT:
schedule[day][slot].append(class_slot)
else:
continue # Slot is full
else:
# Convert single class to list
schedule[day][slot] = [schedule[day][slot], class_slot]
# Update tracking
teacher_slots[teacher].add((day, slot))
room_slots[room].add((day, slot))
branch_slots[branch].add((day, slot))
course_counts[course_code] += 1
course_teacher_counts[(course_code, teacher)] += 1
# Successfully scheduled a) > 0 class
break
# Final verification
all_correct = True
for course_code, course_name, branch, teacher, required in combinations:
actual = course_teacher_counts[(course_code, teacher)]
if actual != required:
all_correct = False
print(f"Warning: {teacher} teaching {course_code} has {actual} classes instead of {required}")
if all_correct:
print("All course-teacher combinations have the correct number of classes!")
return schedule
def tournament_selection(population):
"""Select a schedule using tournament selection.
Tournament selection works by randomly selecting a small group of schedules
and then picking the best one from that group.
"""
# First, let's remove any None values from the population
valid_population = []
for p in population:
if p is not None:
valid_population.append(p)
# Check if we have enough valid schedules for a tournament
if len(valid_population) < TOURNAMENT_SIZE:
# Not enough schedules for a tournament
if len(valid_population) > 0:
# If we have at least one valid schedule, return a random one
random_index = random.randint(0, len(valid_population) - 1)
return valid_population[random_index]
else:
# If we have no valid schedules, return None
return None # This will be handled by the crossover function
# Create a tournament by randomly selecting TOURNAMENT_SIZE schedules
tournament = random.sample(valid_population, TOURNAMENT_SIZE)
# Find the schedule with the highest fitness in the tournament
best_schedule = tournament[0] # Start with the first schedule
best_fitness_value = fitness(best_schedule)
# Loop through the rest of the schedules to find the best one
for i in range(1, len(tournament)):
current_fitness = fitness(tournament[i])
if current_fitness > best_fitness_value:
best_schedule = tournament[i]
best_fitness_value = current_fitness
# print(f"DEBUG: Selected schedule with fitness {best_fitness_value}") # Helped track selection
# Return the best schedule from the tournament
return best_schedule
def crossover(p1, p2, courses, teachers, rooms):
"""Create a child schedule by intelligently combining two parent schedules."""
if p1 is None or p2 is None:
return create_random_schedule(courses, teachers, rooms)
child = create_empty_schedule()
# Track current course-teacher assignment counts
course_teacher_counts = defaultdict(int)
class_requirements = get_course_class_requirements()
for day in range(DAYS):
for slot in range(SLOTS_PER_DAY):
if slot == LUNCH_SLOT:
continue
slot1 = p1[day][slot]
slot2 = p2[day][slot]
# Decide which parent's slot is better
def score_slot(slot_data):
if slot_data is None:
return 0
if not isinstance(slot_data, list):
slot_data = [slot_data]
score = 0
for cls in slot_data:
key = (cls.course_code, cls.teacher)
required = class_requirements.get(cls.course_code, 1)
current = course_teacher_counts[key]
if current < required:
score += 1 # Favor classes that are still under-assigned
return score
score1 = score_slot(slot1)
score2 = score_slot(slot2)
# Choose the slot with the better score
selected_slot = slot1 if score1 > score2 else slot2
if selected_slot is not None:
selected_copy = copy_schedule(selected_slot)
child[day][slot] = selected_copy
# Update counts
if not isinstance(selected_copy, list):
selected_copy = [selected_copy]
for cls in selected_copy:
course_teacher_counts[(cls.course_code, cls.teacher)] += 1
# Final fix to ensure the child is valid
return fix_class_assignments(child, courses, teachers, rooms)
import random
def mutate(schedule, courses, teachers, rooms):
"""Mutate a schedule by changing some assignments, prioritizing fixing course requirements."""
branches = set(branch for _, branch, _ in courses)
class_requirements = get_course_class_requirements()
course_counts = count_course_classes(schedule)
# Identify problem courses where the actual count of classes differs from the required count
problem_courses = []
for course_code, required in class_requirements.items():
actual = course_counts.get(course_code, 0)
if actual != required:
problem_courses.append((course_code, actual, required, abs(actual - required)))
# Determine mutation type based on the presence of problem courses
if problem_courses and random.random() < 0.7:
mutation_type = "targeted"
else:
mutation_type = random.choice(["single", "single", "swap", "multi"])
# Handle different mutation types
if mutation_type == "single":
day, slot = random.randint(0, DAYS - 1), random.randint(0, SLOTS_PER_DAY - 1)
# Skip lunch slot
if slot == LUNCH_SLOT:
return
# Randomly select a branch for mutation
branch = random.choice(list(branches))
# Skip if the selected slot is already empty
if schedule[day][slot] is None:
return
if isinstance(schedule[day][slot], list):
schedule[day][slot] = [c for c in schedule[day][slot] if c is not None and c.branch != branch]
if not schedule[day][slot]:
schedule[day][slot] = None
elif len(schedule[day][slot]) == 1:
schedule[day][slot] = schedule[day][slot][0]
elif schedule[day][slot].branch == branch:
schedule[day][slot] = None
class_slot = get_valid_assignment(schedule, courses, teachers, rooms, day, slot, branch)
if class_slot:
if schedule[day][slot] is None:
schedule[day][slot] = class_slot
elif isinstance(schedule[day][slot], list):
schedule[day][slot].append(class_slot)
else:
schedule[day][slot] = [schedule[day][slot], class_slot]
elif mutation_type == "swap":
day1, slot1 = random.randint(0, DAYS - 1), random.randint(0, SLOTS_PER_DAY - 1)
day2, slot2 = random.randint(0, DAYS - 1), random.randint(0, SLOTS_PER_DAY - 1)
# Skip lunch slot
if slot1 == LUNCH_SLOT or slot2 == LUNCH_SLOT:
return
# Skip empty slots
if schedule[day1][slot1] is None or schedule[day2][slot2] is None:
return
# Handle swapping classes
if isinstance(schedule[day1][slot1], list) and isinstance(schedule[day2][slot2], list):
if len(schedule[day1][slot1]) > 0 and len(schedule[day2][slot2]) > 0:
idx1 = random.randint(0, len(schedule[day1][slot1]) - 1)
idx2 = random.randint(0, len(schedule[day2][slot2]) - 1)
# Swap the classes
schedule[day1][slot1][idx1], schedule[day2][slot2][idx2] = schedule[day2][slot2][idx2], \
schedule[day1][slot1][idx1]
# Update class day and slot info
schedule[day1][slot1][idx1].day, schedule[day1][slot1][idx1].slot = day1, slot1
schedule[day2][slot2][idx2].day, schedule[day2][slot2][idx2].slot = day2, slot2
elif isinstance(schedule[day1][slot1], list) and not isinstance(schedule[day2][slot2], list):
if len(schedule[day1][slot1]) > 0:
idx = random.randint(0, len(schedule[day1][slot1]) - 1)
schedule[day1][slot1][idx], schedule[day2][slot2] = schedule[day2][slot2], schedule[day1][slot1][idx]
# Update class day and slot info
schedule[day1][slot1][idx].day, schedule[day1][slot1][idx].slot = day1, slot1
schedule[day2][slot2].day, schedule[day2][slot2].slot = day2, slot2
elif not isinstance(schedule[day1][slot1], list) and isinstance(schedule[day2][slot2], list):
if len(schedule[day2][slot2]) > 0:
idx = random.randint(0, len(schedule[day2][slot2]) - 1)
schedule[day1][slot1], schedule[day2][slot2][idx] = schedule[day2][slot2][idx], schedule[day1][slot1]
# Update class day and slot info
schedule[day1][slot1].day, schedule[day1][slot1].slot = day1, slot1
schedule[day2][slot2][idx].day, schedule[day2][slot2][idx].slot = day2, slot2
else:
# Swap the classes
schedule[day1][slot1], schedule[day2][slot2] = schedule[day2][slot2], schedule[day1][slot1]
# Update class day and slot info
schedule[day1][slot1].day, schedule[day1][slot1].slot = day1, slot1
schedule[day2][slot2].day, schedule[day2][slot2].slot = day2, slot2
elif mutation_type == "targeted":
if not problem_courses:
return # No problems to fix
problem_courses.sort(key=lambda x: x[3], reverse=True)
course_teacher_counts = count_course_teacher_classes(schedule)
teacher_course_problems = []
for (course, teacher), count in course_teacher_counts.items():
required = class_requirements.get(course, 1)
if count != required:
teacher_course_problems.append((course, teacher, count, required, abs(count - required)))
teacher_course_problems.sort(key=lambda x: x[4], reverse=True)
if teacher_course_problems:
course_code, teacher_name, actual, required, diff = teacher_course_problems[0]
course_details = next((c for c in courses if c[0] == course_code), None)
if not course_details:
return # Course not found
_, branch, course_name = course_details
else:
course_code, actual, required, diff = problem_courses[0]
course_details = next((c for c in courses if c[0] == course_code), None)
if not course_details:
return # Course not found
_, branch, course_name = course_details
teacher_name = None # No specific teacher to target
if actual < required:
classes_to_add = required - actual
for _ in range(classes_to_add):
for attempt in range(20):
day, slot = random.randint(0, DAYS - 1), random.randint(0, SLOTS_PER_DAY - 1)
# Skip lunch slot
if slot == LUNCH_SLOT:
continue
# Check if slot is available
if schedule[day][slot] is not None:
if isinstance(schedule[day][slot], list) and len(schedule[day][slot]) >= MAX_CLASSES_PER_SLOT:
continue # Slot is full
# Get a valid assignment
class_slot = get_valid_assignment(
schedule, courses, teachers, rooms, day, slot, branch,