-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoctor_scheduling.R
1575 lines (1280 loc) · 57 KB
/
doctor_scheduling.R
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
# TODO: Description
# require(Hmisc) # Seems this is no longer required
require(xlsx) # This is pathetic, but the only way we can output formatted (and editable, so no LaTeX) data seems to be xlsx
### static variables
# TODO: once this is a package, see to it that these can not be overwritten
N_shifts <- c("N", "N1", "N2")
holiday_shifts <- c("U", "ZA", "NG")
day_shifts <- c("5", "6", "7", "7.5", "8", "8.5", "9", "10")
day_shifts_absent <- c("FB5", "FB6", "FB7", "FB8")
day_requests <- c(day_shifts, day_shifts_absent, "<5", "<6", "<7", "<8", "<9", "<10")
valid_shifts <- c(N_shifts, holiday_shifts, day_shifts, day_shifts_absent, "X", "FT", "-")
valid_requests <- c("!N", "!N1", "!N2", N_shifts, holiday_shifts, day_requests, "X", "FT", "-")
friday_weight <- 0.95
saturday_weight <- 1.1
sunday_weight <- 0.95
if(file.exists("../holidays.list"))
{
holidays <- as.Date(as.character(read.csv("../holidays.list", header = FALSE)$V1))
} else
{
warning("No 'holidays.list' file found. This file should contain dates of holiday in the format YYYY-MM-DD, separated by newlines, specifying holidays (Gesetzliche Feiertage). Proceeding without any holidays")
}
# TODO: input validation
read.doctors <- function(file = "doctors.xlsx")
{
doctors <- read.xlsx("doctors.xlsx", sheetIndex=1, row.names = TRUE)
doctors$split_shifts <- doctors$split_shifts == "yes"
doctors$friday_sunday <- doctors$friday_sunday == "yes"
doctors$fill_all_days <- doctors$fill_all_days == "yes"
# doctors$number_of_shifts_factor <- rep(1)
# if(all(c("less", "more") %in% doctors$number_of_shifts))
# {
# n.less <- sum(doctors$number_of_shifts == "less")
# n.more <- sum(doctors$number_of_shifts == "more")
# deviation <- 0.25
# if(n.less < n.more)
# {
# doctors$number_of_shifts_factor[doctors$number_of_shifts == "less"] <- 1 - deviation
# doctors$number_of_shifts_factor[doctors$number_of_shifts == "more"] <- 1 + deviation * n.less / n.more
# } else
# {
# doctors$number_of_shifts_factor[doctors$number_of_shifts == "more"] <- 1 + deviation
# doctors$number_of_shifts_factor[doctors$number_of_shifts == "less"] <- 1 - deviation * n.more / n.less
# }
# }
doctors$hours_min <- rep(NA)
doctors$hours_max <- rep(NA)
doctors$hours <- rep(0)
doctors$weekhours <- rep(NA)
doctors$shifts_target <- rep(NA)
doctors$weekends_target <- rep(NA)
doctors$shifts <- rep(0)
doctors$days <- rep(0)
doctors$nights <- rep(0)
doctors$weekends <- rep(0)
# doctors$conflicts_won <- rep(0)
# doctors$conflicts_lost <- rep(0)
doctors$requests_granted <- rep(0)
doctors$requests_denied <- rep(0)
doctors$soft_requests_granted <- rep(0)
doctors$soft_requests_denied <- rep(0)
# doctors$fridays <- rep(0)
# doctors$saturdays <- rep(0)
# doctors$sundays <- rep(0)
# doctors$fridays_relative <- rep(0)
# doctors$saturdays_relative <- rep(0)
# doctors$sundays_relative <- rep(0)
doctors$shifts_carryover <- doctors$shifts_carryover - sum(doctors$shifts_carryover) / length(doctors$shifts_carryover)
doctors$weekends_carryover <- doctors$weekends_carryover - sum(doctors$weekends_carryover) / length(doctors$weekends_carryover)
return(doctors)
}
# XLSX version
# this is a bit tedious, but we can have formatted spreadsheets
write.template <- function(start_date, end_date, doctors = read.doctors("doctors.csv"))
{
# if(file.exists("input.xlsx"))
# {
# return(warning("File 'input.xlsx' already exists, cowardly refusing to overwrite"))
# }
dates <- seq(from=start_date, to=end_date, by=1)
requests <- matrix(rep(""), nrow(doctors), length(dates), dimnames = list(rownames(doctors), format(dates, format="%d")))
wards_min_presence <- matrix(rep(""), length(unique(doctors$ward)), length(dates), dimnames = list(unique(doctors$ward), format(dates, format="%d")))
wb <- createWorkbook()
for(i in c("requests", "wards_min_presence"))
{
# here begins the xlsx stuff
sheetname <- paste0("sheet.", i)
assign(sheetname, createSheet(wb, sheetName=i))
addDataFrame(as.data.frame(get(i)), get(sheetname))
rows <- getRows(get(sheetname))
cells <- getCells(rows)
# YYYY-MM in topleft cell
setCellValue(cells[["1.1"]], format(dates[1], format="%Y-%m"))
cellstyle.table <- CellStyle(wb) + Border(color="black", position = c("TOP", "LEFT", "BOTTOM", "RIGHT"))
for(day in seq_along(dates))
{
for(row in 1:nrow(get(i)))
{
setCellStyle(cells[[paste(row + 1, day + 1, sep = ".")]], cellstyle.table)
}
}
# Colored background for weekends
cellstyle.holiday <- cellstyle.table + Fill(foregroundColor="#add8e6")
for(day in seq_along(dates))
{
if(!is.workday(dates[day]))
{
for(row in 1:nrow(get(i)))
{
setCellStyle(cells[[paste(row + 1, day + 1, sep = ".")]], cellstyle.holiday)
}
}
}
# Resize Columns
setColumnWidth(get(sheetname), 1, 13.5)
for(column in 2:(length(dates)+1))
{
setColumnWidth(get(sheetname), column, 4.5)
}
setRowHeight(rows, multiplier = 1)
}
explanation <- c("!N", "Kein Nachtdienst (auch kein N1 oder N2)",
"!N1", "Kein N1 (auch kein N, aber N2 möglich)",
"!N2", "Kein N2 (auch kein N, aber N1 möglich)",
"U,ZA,NG", "Urlaub/Zeitausgleich/Nachtdienstgutstunden",
"-", "Freier Tag mit 0h",
"5,6,7,8", "Normaler 5/6/7/8h-Tag",
"<5,<6,<7,<8", "5/6/7/8h oder weniger (also auch X, FT, oder -)",
"FB5,FB6,FB7,FB8", "Fortbildung 5/6/7/8h (Arbeitszeit ohne Stationspräsenz)",
"!N?", "Kein N gewünscht (aber möglich)",
"!N1?", "wie oben",
"!N2?", "wie oben",
"N?", "Nachtdienst gewünscht (aber nicht garantiert da es die Planung stark einschränkt)",
"*?", "'?' kann für alle obigen Dienstformen verwendet werden, z.B. '7?'",
"N", "Nachtdienst fix geplant - nur für Weihnachten o.Ä. vorgesehen")
explanation <- matrix(explanation, ncol=2, byrow=TRUE)
for(row in (nrow(doctors)+3):(nrow(doctors)+nrow(explanation)+2))
{
addMergedRegion(sheet.requests, row, row, 2, 16)
}
addDataFrame(explanation, sheet.requests, row.names = FALSE, col.names = FALSE, startRow = nrow(doctors) + 3)
saveWorkbook(wb, "input.xlsx")
}
# this is a bit tedious, but we can have formatted spreadsheets
write.schedule <- function(doctors = NA, schedule = NA, wards = NA, opt_parms = NA, warnings = NA)
{
dates <- as.Date(colnames(schedule))
colnames(schedule) <- format(dates, format="%d")
# here begins the xlsx stuff
wb <- createWorkbook()
sheet.schedule <- createSheet(wb, sheetName="schedule")
addDataFrame(as.data.frame(schedule), sheet.schedule)
addDataFrame(as.data.frame(rbind(wards$presence - wards$min_presence, colSums(wards$presence - wards$min_presence))), sheet.schedule, col.names = FALSE, startRow = nrow(doctors) + 3)
rows <- getRows(sheet.schedule)
cells <- getCells(rows)
# YYYY-MM in topleft cell
setCellValue(cells[["1.1"]], format(dates[1], format="%Y-%m"))
cellstyle.table <- CellStyle(wb) + Border(color="black", position = c("TOP", "LEFT", "BOTTOM", "RIGHT"))
for(day in seq_along(dates))
{
for(row in seq_along(rownames(doctors)))
{
setCellStyle(cells[[paste(row + 1, day + 1, sep = ".")]], cellstyle.table)
}
}
# Colored background for weekends
cellstyle.holiday <- cellstyle.table + Fill(foregroundColor="#add8e6")
for(day in seq_along(dates))
{
if(!is.workday(dates[day]))
{
for(row in seq_along(rownames(doctors)))
{
setCellStyle(cells[[paste(row + 1, day + 1, sep = ".")]], cellstyle.holiday)
}
}
}
# Colored background for specific shifts
cellstyle.holiday <- cellstyle.table + Fill(foregroundColor="#add8e6")
cellstyle.N <- cellstyle.table + Fill(foregroundColor="#00cc00")
cellstyle.N1 <- cellstyle.table + Fill(foregroundColor="#cccc00")
cellstyle.N2 <- cellstyle.table + Fill(foregroundColor="#00cccc")
cellstyle.absent <- cellstyle.table + Fill(foregroundColor="#c2c2c2")
for(day in seq_along(dates))
{
for(row in seq_along(rownames(doctors)))
{
value <- getCellValue(cells[[paste(row + 1, day + 1, sep = ".")]])
if(value %in% c("X", "FT", "-", holiday_shifts))
{
setCellStyle(cells[[paste(row + 1, day + 1, sep = ".")]], cellstyle.holiday)
} else if(value == "N")
{
setCellStyle(cells[[paste(row + 1, day + 1, sep = ".")]], cellstyle.N)
} else if(value == "N1")
{
setCellStyle(cells[[paste(row + 1, day + 1, sep = ".")]], cellstyle.N1)
} else if(value == "N2")
{
setCellStyle(cells[[paste(row + 1, day + 1, sep = ".")]], cellstyle.N2)
} else if(value %in% day_shifts_absent)
{
setCellStyle(cells[[paste(row + 1, day + 1, sep = ".")]], cellstyle.absent)
}
}
}
# Colored background for day presence
max_colored_value <- 3
for(day in seq_along(dates))
{
if(is.workday(dates[day]))
{
for(row in 1:(nrow(wards$presence)))
{
value <- getCellValue(cells[[paste(row + nrow(doctors) + 2, day + 1, sep = ".")]])
if(value > 0)
{
redblue <- round(max(0, 1 - value / max_colored_value) * 255)
color <- paste0("#", paste(as.hexmode(c(redblue,255,redblue)), collapse=''))
cellstyle.colorscale <- CellStyle(wb) + Fill(foregroundColor = color)
setCellStyle(cells[[paste(row + nrow(doctors) + 2, day + 1, sep = ".")]], cellstyle.colorscale)
} else
if(value < 0)
{
greenblue <- round(max(0, 1 + value / max_colored_value) * 255)
color <- paste0("#", paste(as.hexmode(c(255,greenblue,greenblue)), collapse=''))
cellstyle.colorscale <- CellStyle(wb) + Fill(foregroundColor = color)
setCellStyle(cells[[paste(row + nrow(doctors) + 2, day + 1, sep = ".")]], cellstyle.colorscale)
}
}
} else
{
for(row in 1:(nrow(wards$presence)))
{
setCellValue(cells[[paste(row + nrow(doctors) + 2, day + 1, sep = ".")]], "")
}
}
}
# the following is only for a line to separate the sum
# for some reason, getCellStyle doesn't work, which would have made this easier
cellstyle.neutral <- CellStyle(wb) + Border(color="black", position = "TOP")
for(day in seq_along(dates))
{
if(is.workday(dates[day]))
{
value <- getCellValue(cells[[paste(nrow(doctors) + nrow(wards$presence) + 3, day + 1, sep = ".")]])
if(value == 0)
{
setCellStyle(cells[[paste(nrow(doctors) + nrow(wards$presence) + 3, day + 1, sep = ".")]], cellstyle.neutral)
} else
if(value > 0)
{
redblue <- round(max(0, 1 - value / max_colored_value) * 255)
color <- paste0("#", paste(as.hexmode(c(redblue,255,redblue)), collapse=''))
cellstyle.colorscale <- CellStyle(wb) + Fill(foregroundColor = color) + Border(color="black", position = "TOP")
setCellStyle(cells[[paste(nrow(doctors) + nrow(wards$presence) + 3, day + 1, sep = ".")]], cellstyle.colorscale)
} else
if(value < 0)
{
greenblue <- round(max(0, 1 + value / max_colored_value) * 255)
color <- paste0("#", paste(as.hexmode(c(255,greenblue,greenblue)), collapse=''))
cellstyle.colorscale <- CellStyle(wb) + Fill(foregroundColor = color) + Border(color="black", position = "TOP")
setCellStyle(cells[[paste(nrow(doctors) + nrow(wards$presence) + 3, day + 1, sep = ".")]], cellstyle.colorscale)
}
} else
{
setCellValue(cells[[paste(nrow(doctors) + nrow(wards$presence) + 3, day + 1, sep = ".")]], "")
}
}
# Resize Columns
setColumnWidth(sheet.schedule, 1, 13.5)
for(column in 2:(length(dates)+1))
{
setColumnWidth(sheet.schedule, column, 4.5)
}
setRowHeight(rows, multiplier = 1)
sheet.doctors.stats <- createSheet(wb, sheetName="doctors.stats")
addDataFrame(as.data.frame(doctors), sheet.doctors.stats)
# for(column in 1:(ncol(doctors)+1))
# {
# autoSizeColumn(sheet.doctors.stats, column)
# }
sheet.opt_parms <- createSheet(wb, sheetName="opt_parms")
addDataFrame(as.data.frame(opt_parms), sheet.opt_parms)
# for(column in 1:(length(opt_parms)+1))
# {
# autoSizeColumn(sheet.opt_parms, column)
# }
sheet.warnings <- createSheet(wb, sheetName="warnings")
addDataFrame(as.data.frame(warnings), sheet.warnings)
autoSizeColumn(sheet.warnings, 2)
filename <- "schedule.xlsx"
i <- 1
while(file.exists(filename))
{
filename <- paste0("schedule", i, ".xlsx")
i <- i + 1
}
message("Writing to '", filename, "'")
saveWorkbook(wb, filename)
}
# TODO: input validation
# TODO: not very elegant, but this requires doctors as input to select relevant part of the xlsx file (and not comments etc)
read.input <- function(file = "input.xlsx", doctors = read.doctors("doctors.csv"))
{
#colClasses="character" doesn't seem to work, it is coerced to factor
raw <- read.xlsx(file, sheetName="requests", rowIndex=0:nrow(doctors) + 1, colClasses="character")
raw <- as.matrix(raw)
raw[is.na(raw)] <- ""
# TODO: i don't know why there are some whitespaces here, they were not in the input
raw <- sub(" *", "", raw)
# i have no idea why colnames are prefixed with "X" when reading xlsx
colnames(raw) <- sub("^X", "", colnames(raw))
# i also don't know why "-" is converted to "." when reading xlsx
date.ym <- sub("\\.", "-", colnames(raw)[1])
requests <- raw[,-1]
dimnames(requests) <- list(raw[,1], paste(date.ym, colnames(raw)[-1], sep = "-"))
# change U or ZA on holidays to -
requests[,!is.workday(colnames(requests))][requests[,!is.workday(colnames(requests))] %in% c("U", "ZA")] <- "-"
valid_input <- c(valid_requests, paste(valid_requests, "?", sep=""), "")
if(!all(requests %in% valid_input))
{
errors <- character(0)
for(doctor in rownames(requests))
{
for(day in seq_along(colnames(requests)))
{
if(!requests[doctor,day] %in% valid_input)
errors <- c(errors, paste("Doctor ", doctor, ", day ", day, ": unrecognized input '", requests[doctor,day], "'\n", sep=""))
}
}
errors <- c(errors, "Valid input is: ", paste(valid_input, collapse=", "))
stop(errors)
}
#colClasses="character" doesn't seem to work, it is coerced to factor
raw <- read.xlsx(file, sheetName="wards_min_presence", rowIndex=0:length(unique(doctors$ward)) + 1, colClasses="character")
raw <- as.matrix(raw)
raw[is.na(raw)] <- ""
# i have no idea why colnames are prefixed with "X" when reading xlsx
colnames(raw) <- sub("^X", "", colnames(raw))
# i also don't know why "-" is converted to "." when reading xlsx
date.ym <- sub("\\.", "-", colnames(raw)[1])
wards_min_presence <- raw[,-1]
dimnames(wards_min_presence) <- list(raw[,1], paste(date.ym, colnames(raw)[-1], sep = "-"))
mode(wards_min_presence) <- "numeric"
wards_min_presence[is.na(wards_min_presence)] <- 0
names <- rownames(wards_min_presence)
dates <- colnames(wards_min_presence)
empty_matrix <- matrix(rep(0), length(names), length(dates), dimnames = list(names, as.character(dates)))
wards <- list(min_presence = wards_min_presence,
presence = empty_matrix,
hours = empty_matrix)
return(list(requests = requests, wards = wards))
}
# Strip "soft" requests (matching the pattern "?.*")
# hardmode: TRUE, FALSE, or numeric in between 0 and 1:
# if FALSE, grant all soft requests, if TRUE, deny all soft requests, if in between, randomly grant proportion of soft requests
strip.requests <- function(requests, hardmode = FALSE)
{
if(hardmode == FALSE)
{
requests <- sub("\\?", "", requests)
} else
{
if (hardmode == TRUE)
{
requests <- sub(".*\\?.*", "", requests)
} else
{
prob <- 1 - hardmode
requests.soft <- grep("\\?", requests)
requests.grant <- as.logical(rbinom(length(requests.soft), size = 1, prob = prob))
requests[requests.soft][requests.grant] <- sub("\\?", "", requests[requests.soft][requests.grant])
requests[requests.soft][!requests.grant] <- sub(".*\\?.*", "", requests[requests.soft][!requests.grant])
}
# weed out nonsensical requests
days <- seq_along(colnames(requests))
days <- days[-length(days)]
for(doctor in rownames(requests)[rowSums(requests == "N") > 1])
{
for(day in days[requests[doctor,days] == "N"])
{
if(requests[doctor,day + 1] == "N")
requests[doctor,day + sample(0:1, 1)] <- ""
}
}
}
return(requests)
}
is.holiday <- function(dates)
{
x <- as.Date(dates) %in% holidays
return(x)
}
is.sunday <- function(dates)
{
x <- format(as.Date(dates), format = "%w") == "0"
return(x)
}
is.saturday <- function(dates)
{
x <- format(as.Date(dates), format = "%w") == "6"
return(x)
}
is.friday <- function(dates)
{
x <- format(as.Date(dates), format = "%w") == "5"
return(x)
}
is.workday <- function(dates)
{
x <- !is.holiday(dates) & !is.sunday(dates) & !is.saturday(dates)
return(x)
}
is.fridaylike <- function(dates)
{
next_days <- as.Date(dates) + 1
x <- is.workday(dates) & !is.workday(next_days)
return(x)
}
is.saturdaylike <- function(dates)
{
next_days <- as.Date(dates) + 1
x <- !is.workday(dates) & !is.workday(next_days)
return(x)
}
is.sundaylike <- function(dates)
{
next_days <- as.Date(dates) + 1
x <- !is.workday(dates) & is.workday(next_days)
return(x)
}
# x: shift(s), also works for matrix of shifts
# Output: Work Hours
as.hours <- function(x, count_holidays = TRUE)
{
if(length(x) > 1)
{
if(is.matrix(x))
{
hours <- matrix(rep(0), nrow = nrow(x), ncol = ncol(x), dimnames = dimnames(x))
} else
{
hours <- numeric(length(x))
}
for(i in seq_along(x))
hours[i] <- as.hours(x[i], count_holidays = count_holidays)
return(hours)
}
if(length(x) == 0)
return(0)
if(x == "N")
return(16)
if(x == "N1")
return(12.5)
# TODO: the following two aren't entirely correct, fixing this will require differentiating X after N vs X after N2
if(x == "N2")
return(3.5)
if(x == "X")
return(9)
if(x %in% day_shifts)
return(as.numeric(x))
if(x %in% day_shifts_absent)
return(as.numeric(sub("FB", "", x)))
if(x %in% day_requests)
return(as.numeric(sub("<", "", x)))
if(count_holidays && x %in% holiday_shifts)
return(8)
return(0)
}
# x: shift(s), also works for matrix of shifts
# Output: Work Hours
as.day_hours <- function(x)
{
if(length(x) > 1)
{
if(is.matrix(x))
{
hours <- matrix(rep(0), nrow = nrow(x), ncol = ncol(x), dimnames = dimnames(x))
} else
{
hours <- numeric(length(x))
}
for(i in seq_along(x))
hours[i] <- as.day_hours(x[i])
return(hours)
}
if(length(x) == 0)
return(0)
if(x %in% c("N", "N1"))
return(5)
if(x %in% day_shifts)
return(as.numeric(x))
if(x %in% day_shifts_absent)
return(0)
if(x %in% day_requests)
return(as.numeric(sub("<", "", x)))
return(0)
}
# TODO: this function should be overhauled together with shift variables at the top - it's easy to miss something
check.requests.granted <- function(requests, schedule)
{
if(length(requests) > 1)
{
if(is.matrix(requests))
{
granted <- matrix(rep(NA), nrow = nrow(requests), ncol = ncol(requests), dimnames = dimnames(requests))
} else
{
granted <- logical(length(requests))
}
for(i in seq_along(requests))
granted[i] <- check.requests.granted(requests = requests[i], schedule = schedule[i])
return(granted)
}
if(requests == "!N")
return(!schedule %in% c("N", "N1", "N2"))
if(requests == "!N1")
return(!schedule %in% c("N", "N1"))
if(requests == "!N2")
return(!schedule %in% c("N", "N2"))
if(requests == "-")
return(schedule %in% c("-", "FT", ""))
# TODO: we need a variable for "<n" requests
if(requests %in% day_requests && !requests %in% c(day_shifts, day_shifts_absent))
{
if(schedule %in% day_shifts)
return(as.numeric(sub("<", "", requests)) >= as.numeric(schedule))
if(schedule %in% c("X", "FT", "-"))
return(TRUE)
return(FALSE)
}
if(requests != "")
return(requests == schedule)
return(NA)
}
# TODO: this looks overly complicated for such an easy task
count.requests.granted <- function(requests, schedule)
{
hard_requests <- strip.requests(requests, hardmode = TRUE)
all_requests <- strip.requests(requests, hardmode = FALSE)
soft_requests <- all_requests
soft_requests[hard_requests != ""] <- ""
hard_requests_granted <- check.requests.granted(requests = hard_requests, schedule = schedule)
soft_requests_granted <- check.requests.granted(requests = soft_requests, schedule = schedule)
n.hard_requests <- rowSums(!is.na(hard_requests_granted))
n.soft_requests <- rowSums(!is.na(soft_requests_granted))
hard_requests_granted[is.na(hard_requests_granted)] <- rep(FALSE)
soft_requests_granted[is.na(soft_requests_granted)] <- rep(FALSE)
n.hard_requests_granted <- rowSums(hard_requests_granted)
n.soft_requests_granted <- rowSums(soft_requests_granted)
n.hard_requests_denied <- n.hard_requests - n.hard_requests_granted
n.soft_requests_denied <- n.soft_requests - n.soft_requests_granted
return(list(requests_granted = n.hard_requests_granted,
requests_denied = n.hard_requests_denied,
soft_requests_granted = n.soft_requests_granted,
soft_requests_denied = n.soft_requests_denied))
}
# find doctor with the fewest hours or night shifts
pick.doctor <- function(doctors, sort_by, jitter = FALSE)
{
# TODO: Description
if(nrow(doctors) == 1)
return(rownames(doctors)[1])
out <- matrix(numeric(), nrow(doctors), 2, dimnames = list(rownames(doctors), c("sort_value", "enough")))
if(sort_by == "hours")
{
out[,"sort_value"] <- doctors$hours / doctors$hours_min
out[,"enough"] <- doctors$hours >= doctors$hours_min
} else if(sort_by == "shifts")
{
out[,"sort_value"] <- doctors$shifts / doctors$shifts_target
out[,"enough"] <- doctors$shifts >= doctors$shifts_target
} else if(sort_by %in% c("days", "nights"))
{
out[,"sort_value"] <- doctors[,sort_by] / doctors$shifts_target
out[,"enough"] <- doctors$shifts >= doctors$shifts_target
} else if(sort_by == "weekends")
{
out[,"sort_value"] <- doctors$weekends / doctors$weekends_target
out[,"enough"] <- doctors$weekends >= doctors$weekends_target
}
if(jitter && length(out[,"sort_value"]) > 1)
out[,"sort_value"] <- out[,"sort_value"] * (1 - jitter) + runif(length(out[,"sort_value"]), min = min(out[,"sort_value"]), max = max(out[,"sort_value"])) * jitter
# reshuffle
out <- out[sample(rownames(out)),]
# sort by sort_by
out <- out[sort(out[,"sort_value"], index.return = TRUE)$ix,]
# those with enough still come last
out <- out[sort(out[,"enough"], index.return = TRUE)$ix,]
# return first doctor
return(rownames(out)[1])
}
# TODO: useful warnings
create.schedule <- function(doctors = read.doctors(), requests = read.requests(), wards = read.wards(), hardmode = FALSE, jitter = FALSE)
{
warnings <- NULL
opt_parms <- list(n.unresolved = 0, n.requests_denied = 0, n.soft_requests = 0, n.soft_requests_granted = 0, range.shifts = NA, range.weekends = NA, range.nights = NA, n.splittable = NA, n.split = NA, day_presence_missing = NA, day_presence_missing.squared = NA)
days <- seq_along(colnames(requests))
dates <- as.Date(colnames(requests))
# Do all calendar lookups here for performance reasons
is_holiday <- is.holiday(dates)
is_sunday <- is.sunday(dates)
is_saturday <- is.saturday(dates)
is_friday <- is.friday(dates)
is_workday <- !is_holiday & !is_sunday & !is_saturday
is_sundaylike <- is.sundaylike(dates)
is_saturdaylike <- is.saturdaylike(dates)
is_fridaylike <- is.fridaylike(dates)
is_splitday <- is_workday & !is_fridaylike
schedule <- matrix(rep(""), nrow(doctors), length(days), dimnames = list(rownames(doctors), as.character(dates)))
requests.orig <- requests
requests <- strip.requests(requests, hardmode = hardmode)
# Calculate various hours
doctors$hours_min <- sum(is_workday) * 8 * doctors$weekhours_min / 40
doctors$hours_max <- sum(is_workday) * 8 * doctors$weekhours_max / 40
hours_min_work <- doctors$hours_min - rowSums(requests == "U" | requests == "ZA" | requests == "NG") * 8
doctors$shifts_target <- (hours_min_work - rowSums(requests == "FB8") * 8) * doctors$number_of_shifts_factor
doctors$shifts_target <- doctors$shifts_target * length(days) / sum(doctors$shifts_target)
doctors$shifts_target <- doctors$shifts_target - doctors$shifts_carryover
doctors$shifts_carryover <- rep(0)
doctors$weekends_target <- (hours_min_work - rowSums(requests == "FB8") * 8) * doctors$number_of_shifts_factor
doctors$weekends_target <- doctors$weekends_target * (sum(is_fridaylike) * friday_weight + sum(is_saturdaylike) * saturday_weight + sum(is_sundaylike) * sunday_weight) / sum(doctors$weekends_target)
doctors$weekends_target <- doctors$weekends_target - doctors$weekends_carryover
doctors$weekends_carryover <- rep(0)
### preliminary - just enter days off ###########################################################
for(day in days)
{
schedule[,day][requests[,day] %in% c(holiday_shifts, "FT", "-")] <- requests[,day][requests[,day] %in% c(holiday_shifts, "FT", "-")]
}
# doctors$hours <- rowSums(as.hours(schedule, count_holidays = TRUE))
### preliminary - enter X on first day ##########################################################
for(doctor in rownames(requests)[requests[,1] == "X"])
{
schedule[doctor,1] <- "X"
if(requests[doctor,2] == "")
requests[doctor,2] <- "!N1"
# doctors[doctor,"hours"] <- doctors[doctor,"hours"] + 9
# Request surrounding weekends free
if(is_friday[7])
{
if((7) %in% days && requests[doctor, 7] == "" && doctors[doctor, "keep_weekends_apart"] > 4)
requests[doctor, 7] <- "!N"
if((8) %in% days && requests[doctor, 8] == "" && doctors[doctor, "keep_weekends_apart"] > 2)
requests[doctor, 8] <- "!N"
if((9) %in% days && requests[doctor, 9] == "" && doctors[doctor, "keep_weekends_apart"] > 5)
requests[doctor, 9] <- "!N"
}
if(is_saturday[7])
{
if((6) %in% days && requests[doctor, 6] == "" && doctors[doctor, "keep_weekends_apart"] > 1)
requests[doctor, 6] <- "!N"
if((7) %in% days && requests[doctor, 7] == "" && doctors[doctor, "keep_weekends_apart"] > 0)
requests[doctor, 7] <- "!N"
if((8) %in% days && requests[doctor, 8] == "" && doctors[doctor, "keep_weekends_apart"] > 2)
requests[doctor, 8] <- "!N"
}
if(is_sunday[7])
{
if((5) %in% days && requests[doctor, 5] == "" && doctors[doctor, "keep_weekends_apart"] > 3)
requests[doctor, 5] <- "!N"
if((6) %in% days && requests[doctor, 6] == "" && doctors[doctor, "keep_weekends_apart"] > 1)
requests[doctor, 6] <- "!N"
if((7) %in% days && requests[doctor, 7] == "" && doctors[doctor, "keep_weekends_apart"] > 4)
requests[doctor, 7] <- "!N"
}
}
### preliminary - no night shifts before these requests
for (day in days)
{
prev_day <- day - 1
if (prev_day %in% days)
requests[,prev_day][requests[,prev_day] == "" & requests[,day] %in% c(day_shifts, day_shifts_absent, holiday_shifts, "FT", "-")] <- "!N2"
}
### iteration 1 - night shifts ##################################################################
days.shuffled <- sample(days)
n.available <- rep(0, length(days))
for (day in days)
{
n.available[day] <- sum(schedule[,day] != "X" & requests[,day] %in% c("", "N"))
}
days.sorted <- days.shuffled[sort(n.available[days.shuffled], index.return = TRUE)$ix]
dofirst <- colSums(requests == "N" | requests == "N1" | requests == "N2")[days.sorted] > 0
days.ordered <- c(days.sorted[dofirst],
days.sorted[!dofirst & is_sundaylike[days.sorted]],
days.sorted[!dofirst & is_saturdaylike[days.sorted]],
days.sorted[!dofirst & is_fridaylike[days.sorted]],
days.sorted[!dofirst & is_workday[days.sorted] & !is_fridaylike[days.sorted]])
for(day in days.ordered)
{
# # No more jitter for the last few days
# if(which(day == days.ordered) > 24)
# jitter <- FALSE
prev_day <- day - 1
next_day <- day + 1
p_prev_day <- day - 2
n_next_day <- day + 2
date <- dates[day]
p_prev_date <- date - 2
n_next_date <- date + 2
message(date, ": ", appendLF = FALSE)
### find someone for either N1 or N
doctor <- NULL
doctors.available <- NULL
split <- NULL
N_requested <- sum(requests[,day] == "N") > 0
N1_requested <- sum(requests[,day] == "N1") > 0
N2_reqested <- sum(requests[,day] == "N2") > 0
# TODO: resulting day presence can still be -1 if doctor from the same ward gets X *after* this
provisional_day_presence_allowing <- rep(TRUE, nrow(doctors))
if(is_splitday[day] && !N_requested)
{
provisional_day_presence <- schedule[,day] != "X" & !requests[,day] %in% c("FT", "-", day_shifts_absent, holiday_shifts)
for (ward in levels(doctors$ward))
{
provisional_day_presence_allowing[doctors$ward == ward] <- sum(provisional_day_presence[doctors$ward == ward]) > wards$min_presence[ward,day]
}
# also forbid if resulting total presence would be < -1
# TODO: this should not be a general rule
provisional_day_presence_allowing <- provisional_day_presence_allowing & sum(!requests[,day] %in% c("FT", "-", day_shifts_absent, holiday_shifts)) > sum(wards$min_presence[,day])
}
if(!any(provisional_day_presence_allowing))
warnings <- c(warnings, warning(date, ": No split possible based on provisional day presence"))
provisional_next_day_presence_allowing <- rep(TRUE, nrow(doctors))
if(next_day %in% days && is_workday[next_day] && !N_requested)
{
provisional_next_day_presence <- schedule[,next_day] != "N2" & !requests[,next_day] %in% c("N2", "FT", "-", day_shifts_absent, holiday_shifts)
for (ward in levels(doctors$ward))
{
provisional_next_day_presence_allowing[doctors$ward == ward] <- sum(provisional_next_day_presence[doctors$ward == ward]) > wards$min_presence[ward,next_day] - 1
}
}
if(!any(provisional_next_day_presence_allowing))
warnings <- c(warnings, warning(date, ": ignoring provisional next day presence in choosing doctor for N"))
doctors.available.for.N <- schedule[,day] != "X" & requests[,day] == ""
if(any(provisional_next_day_presence_allowing & doctors.available.for.N))
doctors.available.for.N <- doctors.available.for.N & provisional_next_day_presence_allowing
doctors.available.for.N <- doctors.available.for.N | requests[,day] == "N"
doctors.available.for.N1 <- schedule[,day] != "X" & requests[,day] == "" & doctors[,"split_shifts"]
doctors.available.for.N1 <- doctors.available.for.N1 | requests[,day] == "N1"
doctors.available.for.N2 <- schedule[,day] != "X" & requests[,day] == "" & doctors[,"split_shifts"]
doctors.available.for.N2 <- doctors.available.for.N2 & provisional_day_presence_allowing
if(any(provisional_next_day_presence_allowing & doctors.available.for.N2))
doctors.available.for.N2 <- doctors.available.for.N2 & provisional_next_day_presence_allowing
doctors.available.for.N2 <- doctors.available.for.N2 | requests[,day] == "N2"
split_possible <- is_splitday[day] &&
any(doctors.available.for.N1) &&
any(doctors.available.for.N2) &&
sum(doctors.available.for.N1 | doctors.available.for.N2) >= 2 ||
N1_requested && N2_reqested
sort_by <- "days"
if(!is_workday[day] || is_fridaylike[day])
sort_by <- "weekends"
if(N_requested || N1_requested && split_possible)
{
doctors.available <- schedule[,day] != "X" & requests[,day] %in% c("N", "N1")
if(sum(doctors.available) == 0)
{
message("skipping day")
warnings <- c(warnings, warning(date, ": No doctor found for N or N1"))
opt_parms$n.unresolved <- opt_parms$n.unresolved + 1
next
}
doctor <- pick.doctor(doctors[doctors.available,], sort_by = sort_by, jitter = jitter)
split <- ifelse(requests[doctor, day] == "N1", TRUE, FALSE)
} else
{
if(split_possible && N2_reqested)
{
doctors.available <- doctors.available.for.N1
} else if(split_possible)
{
doctors.available <- doctors.available.for.N | doctors.available.for.N1
} else
{
doctors.available <- doctors.available.for.N
}
if(sum(doctors.available) == 0)
{
message("skipping day")
warnings <- c(warnings, warning(date, ": No doctor found for N or N1"))
opt_parms$n.unresolved <- opt_parms$n.unresolved + 1
next
}
doctor <- pick.doctor(doctors[doctors.available,], sort_by = sort_by, jitter = jitter)
split <- doctors[doctor,"split_shifts"] && split_possible
# in case the only doctor available for n2 is chosen for n1 -> do not split after all
if(split && !any(doctors.available.for.N2[rownames(doctors) != doctor]))
split <- FALSE
}
message(doctor, " will do ", appendLF = FALSE)
if(split)
{
### assign N1
message("N1, ", appendLF = FALSE)
schedule[doctor,day] <- "N1"
doctors[doctor,"shifts"] <- doctors[doctor,"shifts"] + 0.5
doctors[doctor,"days"] <- doctors[doctor,"days"] + 1
# doctors[doctor,"hours"] <- doctors[doctor,"hours"] + 12.5
if(is_fridaylike[day])
doctors[doctor,"weekends"] <- doctors[doctor,"weekends"] + friday_weight / 2
if(is_saturdaylike[day])
doctors[doctor,"weekends"] <- doctors[doctor,"weekends"] + saturday_weight / 2
if(is_sundaylike[day])