/
schedulers.py
1248 lines (1155 loc) · 47.6 KB
/
schedulers.py
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
import copy
import random
import collections
import sys
from person import (
Patient,
Interpreter
)
from location import (
Grid,
Point,
Location
)
from schedule import (
Schedule,
Appointment
)
from utils import (
timer,
Time,
sum_lists_product
)
from person import Patient
from constants import (
TIME_FORMAT,
WALKING_RATE
)
from operator import attrgetter
class ObjectInitializer(Grid):
"""
Initializes scheduler objects
"""
def __init__(self, schedule):
"""
Initialize the ObjectInitializer class
:param schedule: A Schedule object
"""
Grid.__init__(self)
self.schedule = schedule
self.schedule_dict = {}
self.appts_dict = {}
self.appts_to_assign = copy.deepcopy([appt for appt in schedule.appts if
len(appt.interpreter) == 0])
self.language_dict = collections.defaultdict(list)
self.time_dict = collections.defaultdict(list)
self.valid_choices = collections.defaultdict(list)
self.patients = {appt.patient for appt in self.schedule.appts
if len(appt.patient) > 0}
self.languages = set()
self.jobs = {}
self.schedule_paths = []
self.best_paths = {}
self.default_appt = Appointment(0, "00:00", 0,
Patient(0, "None", [], "None"),
Point(0, 0), 0, "", "").copy()
self.interpreters = []
self.init_all_objects()
def init_job(self, interpreter, appt):
"""
Add the interpreter's initial appointment to the job list
:param interpreter: An Interpreter object
:param appt: An Appointment object
:return: None
"""
if interpreter in self.jobs:
raise ValueError('Interpreter exists in jobs.')
self.jobs[interpreter] = [appt]
def init_all_objects(self):
"""
Wrapper for the two main initialization functions
:return: None
"""
self.populate_objects()
self.populate_collections()
def populate_objects(self):
"""
Processes self.schedule and builds objects used by other methods
:return: None
"""
# Reset interpreters to initial positions
for interpreter in self.schedule.interpreters:
if interpreter not in self.interpreters:
self.interpreters.append(interpreter)
for interpreter in self.interpreters:
self.add_loc(interpreter, Point(0, 0))
self.init_job(interpreter, self.default_appt)
for patient in self.patients:
for language in patient.languages:
self.languages.add(language)
self.default_appt.patient.languages = self.languages
# Associate appts by idnum for optimization functions/objects
for appt in self.schedule.appts:
self.appts_dict[appt.idnum] = appt
def populate_collections(self):
"""
Processes self.schedule and builds collections used by other methods
:return: None
"""
self.gen_language_dict()
def gen_language_dict(self):
"""
Processes self.languages and builds a dict used by other methods
:return: None
"""
# This is a useful heuristic to reduce node size
# processed by scheduling algorithms
for language in self.languages:
appts_in_lang = [appt for appt in self.appts_to_assign
if language in appt.patient.languages]
self.language_dict[language] = appts_in_lang
class Reinitializer(ObjectInitializer):
"""
Reinitialize objects initialized by ObjectInitializer
"""
def __init__(self, schedule):
"""
Initialize the Reinitializer class
:param schedule: A Schedule object
"""
ObjectInitializer.__init__(self, schedule)
self.orig_schedule = schedule.copy()
def reset(self):
"""
Reinitialize the class
:return: None
"""
self._reset_attributes()
self._reset_data_structures()
self._reset_objects()
def _reset_attributes(self):
"""
Reinitialize class attributes
:return: None
"""
self.impact = 0
self.schedule.impact = 0
def _reset_data_structures(self):
"""
Reinitialize class data structures
:return: None
"""
self.appts_to_assign = list([appt for appt in self.schedule.appts if
len(appt.interpreter) == 0])
self.time_dict = collections.defaultdict(list)
self.valid_choices = collections.defaultdict(list)
self.jobs = {}
self.locs = {}
self.schedule_dict = {}
self.schedule_paths = []
self.best_paths = {}
def _reset_objects(self):
"""
Reinitialize class objects
:return: None
"""
for appt in self.schedule.appts:
appt.interpreter = ""
for interpreter in self.interpreters:
self.add_loc(interpreter, Point(0, 0))
self.init_job(interpreter, self.default_appt)
class JobSupervisor(Reinitializer):
"""
Keeps track of correctly assigning jobs to Interpreters
"""
def __init__(self, schedule):
"""
Initialize the JobSupervisor class
:param schedule: A Schedule object
"""
Reinitializer.__init__(self, schedule)
self._populate_appts()
def _populate_appts(self):
"""
Add interpreter jobs for each job already in self.schedule.appts
Should only be called by self.__init__
:return: None
"""
assigned_interpreters = [appt.interpreter for
appt in self.schedule.appts if
appt.interpreter]
for interpreter in self.interpreters:
if interpreter in assigned_interpreters:
appts_assigned = [appt for appt in self.schedule.appts
if appt.interpreter == interpreter]
self.group_assign(interpreter, appts_assigned)
def reset(self):
"""
Reinitialize the class
:return: None
"""
super(JobSupervisor, self).reset()
def get_job_with_id(self, job_id):
"""
Get the appointment with the id number job_id
:param job_id: An Appointment id number
:return: An Appointment object
"""
if job_id in self.appts_dict.keys():
job = self.appts_dict[job_id]
return job
def get_jobs_with_ids(self, job_ids):
"""
Get the appointments with the id numbers in ids
:param job_ids: A list of Appointment id numbers
:return: A list of Appointment objects
"""
jobs_found = []
for job_id in job_ids:
job = self.get_job_with_id(job_id)
if job:
jobs_found.append(job)
return jobs_found
def get_open_job_with_id(self, job_id):
"""
Get the unassigned appointment from self.appts_to_assign with job_id
:param job_id: The appointment's idnum
:return: An appointment object
"""
job = self.get_job_with_id(job_id)
if job in self.appts_to_assign:
return job
def get_open_jobs_with_ids(self, job_ids):
"""
Get the unassigned appointments with the id numbers in ids
:param job_ids: A list of Appointment id numbers
:return: A list of Appointment objects
"""
jobs_found = []
for job_id in job_ids:
job = self.get_open_job_with_id(job_id)
if job:
jobs_found.append(job)
return jobs_found
def get_last_job(self, interpreter):
"""
Get the last job worked by interpreter
:param interpreter: An interpreter object
:return: An Appointment object
"""
if interpreter not in self.jobs:
raise ValueError('Interpreter not in jobs.')
return self.jobs[interpreter][-1]
def get_jobs(self, interpreter):
"""
Get all jobs worked by interpreter
:param interpreter: An Interpreter object
:return: A list of Appointment objects
"""
if interpreter not in self.jobs:
raise ValueError('Interpreter not in jobs.')
return self.jobs[interpreter]
def add_job(self, interpreter, appt):
"""
Add a new job to the jobs list for interpreter
:param interpreter: An Interpreter object
:param appt: An appointment object to add
:return: None
"""
if interpreter not in self.jobs:
raise ValueError('Interpreter not in jobs.')
jobs = self.jobs[interpreter]
jobs.append(appt)
jobs.sort()
@staticmethod
def calc_arrival(appt1, appt2):
"""
Compute when staff would arrive at appt2 after finishing appt1
:param appt1: An Appointment object (time order IS important)
:param appt2: An Appointment object (time order IS important)
:return: A Time object representing when staff could begin appt2
"""
appts = [appt1, appt2]
appts.sort()
dist = int(appts[0].location.distance_from(appts[1].location))
commute_time = round(dist / WALKING_RATE, 0)
time = appts[0].finish.copy()
time.add_time(hours=0, minutes=commute_time)
time = max(time, appts[1].start.copy())
return time
def calc_impact(self):
"""
Calculate the schedule's total impact score
:return: A number representing the total impact score for self.schedule
"""
return sum([appt.priority for appt in self.schedule.appts
if len(appt.interpreter) > 0])
@staticmethod
def is_appt_in_shift(interpreter, appt):
"""
Check if appt intervals are compatible with shift start and end times
:param interpreter: An Interpreter object
:param appt: An Appointment object
:return: A Boolean indicating True if appt is compatible
"""
if appt.start >= interpreter.shift_start and \
appt.finish <= interpreter.shift_finish:
return True
return False
def can_assign(self, interpreter, new_job, last_job=None):
"""
Test if possible to assign both new_job and last_job to interpreter
:param interpreter: An Interpreter object
:param new_job: An Appointment object (order IS important)
:param last_job: An Appointment object (order IS important)
:return: A Boolean indicating that it can be assigned without overlap
"""
if last_job is None:
last_job = self.get_last_job(interpreter)
appt_is_compatible = new_job.is_compatible(last_job)
patient_is_compatible = (interpreter.is_compatible(new_job.patient) and
interpreter.is_compatible(last_job.patient))
new_job_in_shift = self.is_appt_in_shift(interpreter, new_job)
last_job_in_shift = self.is_appt_in_shift(interpreter, last_job)
if last_job == self.default_appt:
last_job_in_shift = True
shift_is_compatible = new_job_in_shift and last_job_in_shift
needs_to_assign = new_job in self.appts_to_assign
return (appt_is_compatible and
patient_is_compatible and
shift_is_compatible and
needs_to_assign)
def can_insert_job(self, interpreter, appt):
"""
Locate where to insert appointment and test for overlap with others
:param interpreter: An Interpreter object
:param appt: An Appointment object
:return: A Boolean indicating that it can be inserted without overlap
"""
try:
interpreter_jobs = self.get_jobs(interpreter)
except IndexError:
interpreter_jobs = []
if not interpreter_jobs:
return True
temp_lst = copy.deepcopy(interpreter_jobs)
temp_lst.append(appt)
temp_lst.sort()
temp_index = temp_lst.index(appt)
try:
can_assign_before = self.can_assign(interpreter, appt,
temp_lst[temp_index - 1])
except IndexError:
can_assign_before = True
try:
can_assign_after = self.can_assign(interpreter, appt,
temp_lst[temp_index + 1])
except IndexError:
can_assign_after = True
if can_assign_before and can_assign_after:
return True
return False
def assign(self, interpreter, appt):
"""
Assign the appointment to the Interpreter, adding it to his/her jobs
:param interpreter: An Interpreter object
:param appt: An Appointment object
:return: None
"""
if not self.can_assign(interpreter, appt):
raise ValueError('Interpreter cannot be assigned to:'
+ '\n' + str(appt) + ".")
try:
self.move_to(interpreter, appt.location)
except ValueError:
self.add_loc(interpreter, appt.location)
try:
self.add_job(interpreter, appt)
except ValueError:
self.init_job(interpreter, appt)
appt.interpreter = interpreter
if interpreter not in self.interpreters:
self.interpreters.append(interpreter)
self.appts_to_assign.remove(appt)
self.schedule.impact += appt.priority
def safe_assign(self, interpreter, appt):
"""
Only assign if interpreter satisfies self.can_assign criteria
:param interpreter: The Interpreter object overing appt
:param appt: The appointment to assign interpreter to
:return: None
"""
if self.can_assign(interpreter, appt):
self.assign(interpreter, appt)
def group_assign(self, interpreter, jobs):
"""
Take a list of jobs and assign interpreter to each
:param interpreter: An Interpreter object
:param jobs: A list of Appointment objects
:return: None
"""
for job in jobs:
self.assign(interpreter, job)
def group_safe_assign(self, interpreter, jobs):
"""
Take a list of jobs and assign interpreter only if able to cover job
:param interpreter: An Interpreter object
:param jobs: A list of Appointment objects
:return: None
"""
for job in jobs:
self.safe_assign(interpreter, job)
class AvailabilityController(JobSupervisor):
"""
Controls the availability of Interpreter objects using Time dicts
"""
def __init__(self, schedule):
"""
Initialize the AvailabilityController class
:param schedule: A Schedule object
"""
JobSupervisor.__init__(self, schedule)
def update_time_dict(self, time, appts):
"""
A dict of Appointments in ascending order at or after a given time
:param time: A Time object at or after which appts start
:param appts: A collection of Appointment objects at or after time
:return: None
"""
self.time_dict = collections.defaultdict(list)
for appt in appts:
if appt.start >= time:
appt_time = str(appt.start)
self.time_dict[appt_time].append(appt)
def rev_update_time_dict(self, time, appts):
"""
A dict of Appointments in descending order at or after a given time
:param time: A Time object at or before which appts start
:param appts: A collection of Appointment objects at or before time
:return: None
"""
self.time_dict = collections.defaultdict(list)
for appt in appts:
if appt.start <= time:
appt_time = str(appt.start)
self.time_dict[appt_time].append(appt)
def update_valid_choices(self, time, appts):
"""
A dict of Appointment lists indexed to interpreters that can cover them
Warning: Do not use if appointments are assigned out of sequence, or
self.get_last_job(interpreter) will not work correctly
:param time: A Time object to direct self.update_time_dict
:param appts: A list of Appointment objects
:return: None
"""
self.update_time_dict(time, appts)
self.valid_choices = collections.defaultdict(list)
for interpreter in self.interpreters:
time_when_available = self.get_last_job(interpreter).finish
for appt_time, appt_list in self.time_dict.items():
if Time(appt_time, TIME_FORMAT) >= time_when_available:
for appt in appt_list:
if self.can_assign(interpreter, appt):
self.valid_choices[interpreter].append(appt)
def rev_update_valid_choices(self, time, appts):
"""
A dict of Appointment lists indexed to interpreters that can cover them
:param time: A Time object to direct self.rev_update_time_dict
:param appts: A list of Appointment objects
:return: None
"""
self.rev_update_time_dict(time, appts)
self.valid_choices = collections.defaultdict(list)
for interpreter in self.interpreters:
time_when_available = self.get_last_job(interpreter).finish
for appt_time, appt_list in self.time_dict.items():
if Time(appt_time, TIME_FORMAT) >= time_when_available:
for appt in appt_list:
if self.can_assign(interpreter, appt):
self.valid_choices[interpreter].append(appt)
def next_valid_choice(self, interpreter, time, mode='after'):
"""
Get next appointment that interpreter can do. It also has modes.
:param interpreter: An Interpreter object
:param time: A Time object
:param mode: A string whether it should look after or before
:return: An Appointment object
"""
mode_dict = {'before': self.rev_update_valid_choices,
'after': self.update_valid_choices}
mode_dict[mode](time, self.appts_to_assign)
current_appt = self.get_last_job(interpreter)
choices = self.valid_choices[interpreter]
arrival_times = [self.calc_arrival(appt, current_appt)
for appt in choices]
if len(choices) > 0:
idx = arrival_times.index(min(arrival_times))
return choices[idx]
return None
class MonteCarlo(AvailabilityController):
"""
Generate pseudo-random schedules with variable impact scores
"""
def __init__(self, schedule):
"""
Initialize the MonteCarlo class
:param schedule: A Schedule object
"""
AvailabilityController.__init__(self, schedule)
def optimized_random_schedule(self, time, printing=False):
"""
Exhaust interpreter's availability by assigning randomly selected appts
:param time: A Time object representing indicating minimum sᵢ
:param printing: A Boolean whether to print status messages
:return: A Schedule object
"""
self.reset()
for interpreter in self.interpreters:
temp_lst = []
for language in interpreter.languages:
temp_lst += list(
[appt for appt in self.language_dict[language] if
appt in self.appts_to_assign and
appt.start >= time]
)
while temp_lst:
self.update_valid_choices(time, temp_lst)
rand_appt = random.choice(temp_lst)
is_valid_choice = self.can_insert_job(interpreter,
rand_appt)
if is_valid_choice:
self.assign(interpreter, rand_appt)
if printing:
print(str(interpreter) +
" assigned to " +
str(rand_appt.idnum) +
", priority = " +
str(rand_appt.priority))
temp_lst.remove(rand_appt)
return copy.deepcopy(self.schedule)
@timer
def monte_carlo_trials(self, time, ntrials,
max_repeated=sys.maxsize, printing=False):
"""
Assigns randomly selected appointments using Monte Carlo methods.
It ends if the same value repeats a max num of consecutive trials.
This is useful if you expect it to max out the value before ending.
:param time: A Time object indicating minimum sᵢ
:param ntrials: An integer number of Monte Carlo trials
:param max_repeated = An integer number of Monte Carlo trials
:param printing: A Boolean whether to print
:return: A Schedule Object
"""
best_schedule = None
current_max = 0
repeated = 0
for idx in range(ntrials):
self.reset()
max_impact = current_max
self.optimized_random_schedule(time, False)
current_max = max(max_impact, self.schedule.impact)
if current_max == max_impact:
repeated += 1
elif current_max > max_impact:
best_schedule = copy.deepcopy(self.schedule)
if printing:
print("New best found! trial#: " +
str(idx) + ", impact: " +
str(self.schedule.impact))
repeated = 0
if idx > 0 and idx % 10 == 0:
if printing:
print("trial #" + str(idx) +
", impact: " +
str(self.schedule.impact) +
", Running best:" + str(current_max))
if repeated >= max_repeated:
break
try:
if printing:
print("Best: " + str(best_schedule.impact))
except:
if printing:
print("No best found.")
return copy.deepcopy(best_schedule)
class Greedy(AvailabilityController):
"""
Utilizes the greedy heuristic for scheduling optimization
"""
def __init__(self, schedule):
"""
Initialize the Greedy class
:param schedule: A Schedule object
"""
AvailabilityController.__init__(self, schedule)
def select_highest_priority(self, interpreter, time, appts):
"""
Return appointment in appts with the highest priority
:param interpreter: An Interpreter object
:param time: A Time object to direct self.update_valid_choices
:param appts: A list of Appointment objects
:return: An Appointment object
"""
self.update_valid_choices(time, appts)
current_max = 0
highest_priority_appt = None
try:
interpreter_appts = self.valid_choices[interpreter]
except:
raise ValueError('Interpreter not in valid choices')
for appt in interpreter_appts:
max_value = current_max
current_max = max(max_value, appt.priority)
if current_max > max_value:
highest_priority_appt = appt
return highest_priority_appt
# @staticmethod
def process_args(self, optimal, appt_lst, interpreter):
"""
Process args used to direct the Greedy methods of this class, which
allows customization of the greedy strategy
:param optimal: A string, 'weight' or 'number', to optimize for
:param appt_lst: A list of Appointment objects
:param interpreter: An Interpreter object
:return: A tuple containing the optimal Appointment and a string
"""
optimal = optimal.lower()
if optimal == 'weight':
# Scan wᵢ in the appt_list and select the maximum,
# which is the highest priority
priority_lst = list([(appt.priority, appt)
for appt in appt_lst])
greedy_appt = max(priority_lst)[1]
greedy_str = (str(interpreter) +
" assigned to " +
str(greedy_appt.idnum) +
", priority = " +
str(greedy_appt.priority))
elif optimal == 'number':
# Scan fᵢ in the appt_lst and select the minimum,
# which is the earliest finish time
len_lst = list([(appt.finish, appt)
for appt in appt_lst])
earliest_fi = min(len_lst)[1]
greedy_appt = earliest_fi
greedy_str = (str(interpreter) +
" assigned to " +
str(greedy_appt.idnum) +
", finish = " +
str(greedy_appt.finish))
else:
raise ValueError('optimal is not a valid value.')
return greedy_appt, greedy_str
@timer
def create_classic_greedy_schedule(self, time, optimal, printing=False):
"""
Assigns appointments using a classic greedy strategy
:param time: A Time object indicating minimum sᵢ
:param optimal: A string, 'weight' or 'number', to optimize for
:param printing: A Boolean whether or not to print status messages
:return: A Schedule object
"""
self.reset()
is_valid_choice = False
for interpreter in self.interpreters:
stack = []
for language in interpreter.languages:
stack += [appt for appt in self.appts_to_assign
if language in appt.patient.languages
and appt.start >= time]
while stack:
self.update_valid_choices(time, stack)
greedy_appt, greedy_str = self.process_args(optimal,
stack,
interpreter)
if isinstance(greedy_appt, Appointment):
if self.can_insert_job(interpreter, greedy_appt):
self.assign(interpreter, greedy_appt)
if printing:
print(greedy_str)
stack.remove(greedy_appt)
else:
break
return copy.deepcopy(self.schedule)
@timer
def create_balanced_greedy_schedule(self, time, optimal, printing=False):
"""
Assigns appointments while balancing the load on each employee.
:param time: A Time object indicating minimum sᵢ
:param optimal: A string, 'weight' or 'number', to optimize for
:param printing: A Boolean whether or not to print status messages
:return: A Schedule object
"""
self.reset()
appts = {}
for interpreter in self.interpreters:
stack = []
for language in interpreter.languages:
stack += [appt for appt in self.appts_to_assign
if language in appt.patient.languages
and appt.start >= time]
appts[interpreter] = stack
while appts:
for interpreter in dict(appts):
if len(appts[interpreter]) < 1:
del appts[interpreter]
else:
appts_sublist = appts[interpreter]
self.update_valid_choices(time,
appts_sublist)
greedy_data = self.process_args(optimal, appts_sublist,
interpreter)
greedy_appt, greedy_str = greedy_data
if isinstance(greedy_appt, Appointment):
is_valid_appt = self.can_insert_job(interpreter,
greedy_appt)
else:
is_valid_appt = False
if is_valid_appt:
self.assign(interpreter, greedy_appt)
if printing:
print(greedy_str)
# Remove the assigned appointment from the other
# interpreters' appointment lists
appt_keys = set(appts.keys()) - set([interpreter])
for interp_key in appt_keys:
if greedy_appt in appts[interp_key]:
appts[interp_key].remove(greedy_appt)
else:
appts[interpreter].remove(greedy_appt)
return copy.deepcopy(self.schedule)
@timer
def group_greedy(self, interpreter_lists, optimal, balanced=False,
printing=False):
"""
Greedy heuristic on each sublist in the interpreter_lists
:param interpreter_lists:
:param optimal: A string, 'weight' or 'number', to optimize for
:param balanced: A Boolean whether to balance the load on employees
:param printing: A Boolean whether or not to print status messages
:return: A Schedule object
"""
self.reset()
current_interpreters = self.interpreters
if printing:
print(self.schedule.brief())
for interpreter_sublist in interpreter_lists:
if printing:
print("Greedy for " +
str([interpreter.name for interpreter
in interpreter_sublist]) + "...")
self.interpreters = interpreter_sublist
if balanced:
self.create_balanced_greedy_schedule(Time("00:00", TIME_FORMAT),
printing)
else:
self.create_classic_greedy_schedule(Time("00:00", TIME_FORMAT),
optimal, printing)
if printing:
print(self.schedule.brief())
if printing:
print("Impact: ", self.schedule.calc_impact())
self.interpreters = current_interpreters
sched_copy = self.schedule.copy()
return sched_copy
class BruteForce(AvailabilityController):
"""
Utilizes a brute force approach to computing as many of the
total appointments in the power set as can reasonably be
computed (given how many schedule order permutations you
want to test) and selecting the list of valid, highest weight
"""
def __init__(self, schedule):
"""
Initialize the BruteForce class
:param schedule:
"""
AvailabilityController.__init__(self, schedule)
def dfs_weighted(self, tree, start, finish, interpreter):
"""
DFS for max weight appointment list in the power set of appt lists
:param tree: An adjacency list using idnums to represent node number
:param start: The start time as a Time object
:param finish: The finish time as a Time object
:param interpreter: An Interpreter object
:return: A generator object
"""
stack = [(start, [start])]
appts_dict = self.appts_dict
if interpreter not in self.best_paths:
self.best_paths[interpreter] = (0, [])
max_weight = self.best_paths[interpreter][0]
while stack:
(vertex, path) = stack.pop()
for next in tree[vertex] - set(path):
if next == finish:
weight = sum([appts_dict[ID].priority for ID in
(path + [next]) if ID in appts_dict])
if weight > max_weight:
self.best_paths[interpreter] = (weight, path + [next])
max_weight = weight
yield path + [next]
else:
stack.append((next, path + [next]))
def dfs_weighted_by_assignment(self, tree, start, finish, interpreter):
"""
DFS for max weight appointment list in the power set of appt lists
Weights used are modified beforehand by assignment multipliers
:param tree: An adjacency list using idnums to represent node number
:param start: The start time as a Time object
:param finish: The finish time as a Time object
:param interpreter: An Interpreter object
:return: A generator object
"""
stack = [(start, [start])]
appts_dict = self.appts_dict
if interpreter not in self.best_paths:
self.best_paths[interpreter] = (0, [])
max_weight = self.best_paths[interpreter][0]
while stack:
(vertex, path) = stack.pop()
for next in tree[vertex] - set(path):
if next == finish:
appt_wts = [appts_dict[ID].priority for ID in
(path + [next]) if ID in appts_dict]
inter_wts = [interpreter.assignments[
appts_dict[ID].location.building
]
for ID in (path + [next]) if ID in appts_dict]
weight = sum_lists_product(appt_wts, inter_wts)
if weight > max_weight:
self.best_paths[interpreter] = (weight, path + [next])
max_weight = weight
yield path + [next]
else:
stack.append((next, path + [next]))
def gen_schedule_dict(self, interpreter, appts):
"""
Modify self.schedule_dict to include appts that Interpreter can cover
:param interpreter: An Interpreter object
:param appts: A list of Appointment objects
:return: None
"""
self.schedule_dict = {}
appts = copy.deepcopy(appts)
sched = Schedule(appts, [interpreter])
opt = Optimum(sched)
opt.reset()
opt_appts = opt.schedule.appts
opt.update_valid_choices(interpreter.shift_start, opt_appts)
temp_lst = [appt.idnum for appt in
opt.valid_choices[interpreter]]
temp_lst.sort()
self.schedule_dict[0] = set(temp_lst)
for appt in opt.valid_choices[interpreter]:
opt.reset()
opt.assign(interpreter, appt)
appt.interpreter = ""
opt.update_valid_choices(appt.finish, opt_appts)
temp_lst = [appt.idnum for appt in
opt.valid_choices[interpreter]]
temp_lst.sort()
self.schedule_dict[appt.idnum] = set(temp_lst)
@timer
def gen_all_paths(self, tree_function, interpreter):
"""
The DFS core function that generates all paths through tree,
it modifies self.schedule_paths or self.best_paths
:param tree_function: An adjacency list (idnum: [idnums])
:param interpreter: An Interpreter object
:return: None
"""
list_of_paths = []
appts = list(self.appts_to_assign)
appt_ids = [appt.idnum for appt in appts]
sched = Schedule(appts, [interpreter])
opt = Optimum(sched)
opt.gen_schedule_dict(interpreter, appts)
tree = dict(opt.schedule_dict)
nodes = [node for node in tree if node > 0] # skip the root
for node in nodes:
# This lets gen_all_paths iteratively explore the tree,
# visiting only nodes that are processed instead of all possible
node_idx = appt_ids.index(node)
appts_subset = appts[:node_idx + 1]
opt.gen_schedule_dict(interpreter, appts_subset)
subtree = dict(opt.schedule_dict)
# To guard against index errors, tamp down endNode
(startNode, endNode) = (min(subtree),
min(node, max(subtree)))
list_of_paths.append(
list(tree_function(subtree, startNode,
endNode, interpreter))
)
self.schedule_paths = []
for row in list_of_paths:
for appt in row:
self.schedule_paths.append(appt)
if interpreter in opt.best_paths:
self.best_paths[interpreter] = opt.best_paths[interpreter]
@timer
def group_gen_all_paths(self, tree_function, interpreters, printing=False):
"""
Iteratively run tree_function on list of Interpreter objects
:param tree_function: A function that iterates through the tree
:param interpreters: A list of Interpreter objects
:param printing: A Boolean whether to print status messages
:return: A Schedule object
"""
if printing:
print(self.schedule.brief())
for interpreter in interpreters:
if printing:
print("Finding optimal paths for " + str(interpreter) + "...")
self.gen_all_paths(tree_function, interpreter)
if interpreter in self.best_paths.keys():
jobs = [self.appts_dict[ID] for ID in
(self.best_paths[interpreter][1])
if ID in self.appts_dict]
self.group_assign(interpreter, jobs)
sched_copy = self.schedule.copy()
return sched_copy
def create_bruteforce_schedule(self, printing=False):
"""
Use dfs_weighted to generate the optimal schedule
:param printing: A Boolean whether to print status messages
:return: A Schedule object
"""
self.reset()
return self.group_gen_all_paths(self.dfs_weighted,
self.interpreters, printing)
def create_bruteforce_assignment(self, printing=False):
"""
Use dfs_weighted_by_assignment to generate the optimal schedule
:param printing: A Boolean whether to print status messages
:return: A Schedule object
"""
self.reset()
return self.group_gen_all_paths(self.dfs_weighted_by_assignment,