-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmodel_classes.py
2416 lines (1919 loc) · 81 KB
/
model_classes.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
#!/usr/bin/env python
# coding: utf-8
'''
FirstTreatment: A health clinic based in the US.
This example is based on exercise 13 from Nelson (2013) page 170.
Nelson. B.L. (2013). Foundations and methods of stochastic simulation.
Patients arrive to the health clinic between 6am and 12am following a
non-stationary poisson process. After 12am arriving patients are diverted
elsewhere and remaining WIP is completed.
On arrival, all patients quickly sign-in and are triaged.
The health clinic expects two types of patient arrivals:
**Trauma arrivals:**
patients with severe illness and trauma that must first be stablised in a
trauma room. These patients then undergo treatment in a cubicle before being
discharged.
**Non-trauma arrivals**
patients with minor illness and no trauma go through registration and
examination activities. A proportion of non-trauma patients require treatment
in a cubicle before being dicharged.
In this model treatment of trauma and non-trauma patients is modelled seperately
'''
import itertools
import numpy as np
import pandas as pd
import simpy
from distribution_classes import (
Exponential, Normal, Uniform, Bernoulli, Lognormal)
# Constants and defaults for modelling **as-is**
# Distribution parameters
# sign-in/triage parameters
DEFAULT_TRIAGE_MEAN = 6.0
# registration parameters
DEFAULT_REG_MEAN = 8.0
DEFAULT_REG_VAR = 2.0
# examination parameters
DEFAULT_EXAM_MEAN = 16.0
DEFAULT_EXAM_VAR = 3.0
# trauma/stabilisation
DEFAULT_TRAUMA_MEAN = 90.0
# Trauma treatment
DEFAULT_TRAUMA_TREAT_MEAN = 30.0
DEFAULT_TRAUMA_TREAT_VAR = 4.0
# Non trauma treatment
DEFAULT_NON_TRAUMA_TREAT_MEAN = 13.3
DEFAULT_NON_TRAUMA_TREAT_VAR = 2.0
# prob patient requires treatment given trauma
DEFAULT_NON_TRAUMA_TREAT_P = 0.60
# proportion of patients triaged as trauma
DEFAULT_PROB_TRAUMA = 0.12
# Time dependent arrival rates data
# The data for arrival rates varies between clinic opening at 6am and closure at
# 12am.
NSPP_PATH = 'resources/ed_arrivals.csv'
OVERRIDE_ARRIVAL_RATE = False
MANUAL_ARRIVAL_RATE_VALUE = 1
# Resource counts
DEFAULT_N_TRIAGE = 1
DEFAULT_N_REG = 1
DEFAULT_N_EXAM = 3
DEFAULT_N_TRAUMA = 2
# Non-trauma cubicles
DEFAULT_N_CUBICLES_1 = 1
# trauma pathway cubicles
DEFAULT_N_CUBICLES_2 = 1
# Simulation model run settings
# default random number SET
N_STREAMS = 20
# default results collection period
DEFAULT_RESULTS_COLLECTION_PERIOD = 60 * 19
# number of replications.
DEFAULT_N_REPS = 5
# Show the a trace of simulated events
# not recommended when running multiple replications
TRACE = False
# list of metrics useful for external apps
RESULT_FIELDS = ['00_arrivals',
'01a_triage_wait',
'01b_triage_util',
'02a_registration_wait',
'02b_registration_util',
'03a_examination_wait',
'03b_examination_util',
'04a_treatment_wait(non_trauma)',
'04b_treatment_util(non_trauma)',
'05_total_time(non-trauma)',
'06a_trauma_wait',
'06b_trauma_util',
'07a_treatment_wait(trauma)',
'07b_treatment_util(trauma)',
'08_total_time(trauma)',
'09_throughput']
# list of metrics useful for external apps
RESULT_LABELS = {'00_arrivals': 'Arrivals',
'01a_triage_wait': 'Triage Wait (mins)',
'01b_triage_util': 'Triage Utilisation',
'02a_registration_wait': 'Registration Waiting Time (mins)',
'02b_registration_util': 'Registration Utilisation',
'03a_examination_wait': 'Examination Waiting Time (mins)',
'03b_examination_util': 'Examination Utilisation',
'04a_treatment_wait(non_trauma)': 'Non-trauma cubicle waiting time (mins)',
'04b_treatment_util(non_trauma)': 'Non-trauma cubicle utilisation',
'05_total_time(non-trauma)': 'Total time (non-trauma)',
'06a_trauma_wait': 'Trauma stabilisation waiting time (mins)',
'06b_trauma_util': 'Trauma stabilisation utilisation',
'07a_treatment_wait(trauma)': 'Trauma cubicle waiting time (mins)',
'07b_treatment_util(trauma)': 'Trauma cubicle utilisation',
'08_total_time(trauma)': 'Total time (trauma)',
'09_throughput': 'throughput'}
# Utility functions
def trace(msg):
'''
Utility function for printing a trace as the
simulation model executes.
Set the TRACE constant to False, to turn tracing off.
Params:
-------
msg: str
string to print to screen.
'''
if TRACE:
print(msg)
class CustomResource(simpy.Resource):
def __init__(self, env, capacity, id_attribute=None):
super().__init__(env, capacity)
self.id_attribute = id_attribute
def request(self, *args, **kwargs):
# Add logic to handle the ID attribute when a request is made
# For example, you can assign an ID to the requester
# self.id_attribute = assign_id_logic()
return super().request(*args, **kwargs)
def release(self, *args, **kwargs):
# Add logic to handle the ID attribute when a release is made
# For example, you can reset the ID attribute
# reset_id_logic(self.id_attribute)
return super().release(*args, **kwargs)
# def patch_resource(resource, pre=None, post=None):
# """
# Part of the required code for event-based auditing of resources (so records each time
# utilisation of a resource changes in some way, as opposed to recording after
# defined time intervals)
# Patch *resource* so that it calls the callable *pre* before each
# put/get/request/release operation and the callable *post* after each
# operation. The only argument to these functions is the resource
# instance.
# From
# https://simpy.readthedocs.io/en/4.0.1/topical_guides/monitoring.html?highlight=monitor#resource-usage
# Used for event-based monitoring (as opposed to interval-based monitoring)
# """
# def get_wrapper(func):
# # Generate a wrapper for put/get/request/release
# @wraps(func)
# def wrapper(*args, **kwargs):
# # This is the actual wrapper
# # Call "pre" callback
# if pre:
# pre(resource)
# # Perform actual operation
# ret = func(*args, **kwargs)
# # Call "post" callback
# if post:
# post(resource)
# return ret
# return wrapper
# # Replace the original operations with our wrapper
# for name in ['put', 'get', 'request', 'release']:
# if hasattr(resource, name):
# setattr(resource, name, get_wrapper(getattr(resource, name)))
# ## Model parameterisation
class Scenario:
'''
Container class for scenario parameters/arguments
Passed to a model and its process classes
'''
def __init__(self,
random_number_set=1,
n_triage=DEFAULT_N_TRIAGE,
n_reg=DEFAULT_N_REG,
n_exam=DEFAULT_N_EXAM,
n_trauma=DEFAULT_N_TRAUMA,
n_cubicles_1=DEFAULT_N_CUBICLES_1,
n_cubicles_2=DEFAULT_N_CUBICLES_2,
triage_mean=DEFAULT_TRIAGE_MEAN,
reg_mean=DEFAULT_REG_MEAN,
reg_var=DEFAULT_REG_VAR,
exam_mean=DEFAULT_EXAM_MEAN,
exam_var=DEFAULT_EXAM_VAR,
trauma_mean=DEFAULT_TRAUMA_MEAN,
trauma_treat_mean=DEFAULT_TRAUMA_TREAT_MEAN,
trauma_treat_var=DEFAULT_TRAUMA_TREAT_VAR,
non_trauma_treat_mean=DEFAULT_NON_TRAUMA_TREAT_MEAN,
non_trauma_treat_var=DEFAULT_NON_TRAUMA_TREAT_VAR,
non_trauma_treat_p=DEFAULT_NON_TRAUMA_TREAT_P,
prob_trauma=DEFAULT_PROB_TRAUMA,
arrival_df=NSPP_PATH,
override_arrival_rate=OVERRIDE_ARRIVAL_RATE,
manual_arrival_rate=MANUAL_ARRIVAL_RATE_VALUE,
model="full"
):
'''
Create a scenario to parameterise the simulation model
Parameters:
-----------
random_number_set: int, optional (default=DEFAULT_RNG_SET)
Set to control the initial seeds of each stream of pseudo
random numbers used in the model.
n_triage: int
The number of triage cubicles
n_reg: int
The number of registration clerks
n_exam: int
The number of examination rooms
n_trauma: int
The number of trauma bays for stablisation
n_cubicles_1: int
The number of non-trauma treatment cubicles
n_cubicles_2: int
The number of trauma treatment cubicles
triage_mean: float
Mean duration of the triage distribution (Exponential)
reg_mean: float
Mean duration of the registration distribution (Lognormal)
reg_var: float
Variance of the registration distribution (Lognormal)
exam_mean: float
Mean of the examination distribution (Normal)
exam_var: float
Variance of the examination distribution (Normal)
trauma_mean: float
Mean of the trauma stabilisation distribution (Exponential)
trauma_treat_mean: float
Mean of the trauma cubicle treatment distribution (Lognormal)
trauma_treat_var: float
Variance of the trauma cubicle treatment distribution (Lognormal)
non_trauma_treat_mean: float
Mean of the non trauma treatment distribution
non_trauma_treat_var: float
Variance of the non trauma treatment distribution
non_trauma_treat_p: float
Probability non trauma patient requires treatment
prob_trauma: float
probability that a new arrival is a trauma patient.
model: string
What model to run. Default is full.
Options are "full", "simplest", "simple_with_branch"
'''
# sampling
self.random_number_set = random_number_set
# store parameters for sampling
self.triage_mean = triage_mean
self.reg_mean = reg_mean
self.reg_var = reg_var
self.exam_mean = exam_mean
self.exam_var = exam_var
self.trauma_mean = trauma_mean
self.trauma_treat_mean = trauma_treat_mean
self.trauma_treat_var = trauma_treat_var
self.non_trauma_treat_mean = non_trauma_treat_mean
self.non_trauma_treat_var = non_trauma_treat_var
self.non_trauma_treat_p = non_trauma_treat_p
self.prob_trauma = prob_trauma
self.manual_arrival_rate = manual_arrival_rate
self.arrival_df = arrival_df
self.override_arrival_rate = override_arrival_rate
self.model = model
self.init_sampling()
# count of each type of resource
self.init_resource_counts(n_triage, n_reg, n_exam, n_trauma,
n_cubicles_1, n_cubicles_2)
def set_random_no_set(self, random_number_set):
'''
Controls the random sampling
Parameters:
----------
random_number_set: int
Used to control the set of psuedo random numbers
used by the distributions in the simulation.
'''
self.random_number_set = random_number_set
self.init_sampling()
def init_resource_counts(self, n_triage, n_reg, n_exam, n_trauma,
n_cubicles_1, n_cubicles_2):
'''
Init the counts of resources to default values...
'''
self.n_triage = n_triage
self.n_reg = n_reg
self.n_exam = n_exam
self.n_trauma = n_trauma
# non-trauma (1), trauma (2) treatment cubicles
self.n_cubicles_1 = n_cubicles_1
self.n_cubicles_2 = n_cubicles_2
def init_sampling(self):
'''
Create the distributions used by the model and initialise
the random seeds of each.
'''
# create random number streams
rng_streams = np.random.default_rng(self.random_number_set)
self.seeds = rng_streams.integers(0, 999999999, size=N_STREAMS)
# create distributions
# Triage duration
self.triage_dist = Exponential(self.triage_mean,
random_seed=self.seeds[0])
# Registration duration (non-trauma only)
self.reg_dist = Lognormal(self.reg_mean,
np.sqrt(self.reg_var),
random_seed=self.seeds[1])
# Evaluation (non-trauma only)
self.exam_dist = Normal(self.exam_mean,
np.sqrt(self.exam_var),
random_seed=self.seeds[2])
# Trauma/stablisation duration (trauma only)
self.trauma_dist = Exponential(self.trauma_mean,
random_seed=self.seeds[3])
# Non-trauma treatment
self.nt_treat_dist = Lognormal(self.non_trauma_treat_mean,
np.sqrt(self.non_trauma_treat_var),
random_seed=self.seeds[4])
# treatment of trauma patients
self.treat_dist = Lognormal(self.trauma_treat_mean,
np.sqrt(self.non_trauma_treat_var),
random_seed=self.seeds[5])
# probability of non-trauma patient requiring treatment
self.nt_p_treat_dist = Bernoulli(self.non_trauma_treat_p,
random_seed=self.seeds[6])
# probability of non-trauma versus trauma patient
self.p_trauma_dist = Bernoulli(self.prob_trauma,
random_seed=self.seeds[7])
# init sampling for non-stationary poisson process
self.init_nspp()
def init_nspp(self):
# read arrival profile
self.arrivals = pd.read_csv(NSPP_PATH) # pylint: disable=attribute-defined-outside-init
self.arrivals['mean_iat'] = 60 / self.arrivals['arrival_rate']
# maximum arrival rate (smallest time between arrivals)
self.lambda_max = self.arrivals['arrival_rate'].max() # pylint: disable=attribute-defined-outside-init
# thinning exponential
if self.override_arrival_rate is True:
self.arrival_dist = Exponential(self.manual_arrival_rate, # pylint: disable=attribute-defined-outside-init
random_seed=self.seeds[8])
else:
self.arrival_dist = Exponential(60.0 / self.lambda_max, # pylint: disable=attribute-defined-outside-init
random_seed=self.seeds[8])
# thinning uniform rng
self.thinning_rng = Uniform(low=0.0, high=1.0, # pylint: disable=attribute-defined-outside-init
random_seed=self.seeds[9])
# ## Patient Pathways Process Logic
class TraumaPathway:
'''
Encapsulates the process a patient with severe injuries or illness.
These patients are signed into the ED and triaged as having severe injuries
or illness.
Patients are stabilised in resus (trauma) and then sent to Treatment.
Following treatment they are discharged.
'''
def __init__(self, identifier, env, args, full_event_log):
'''
Constructor method
Params:
-----
identifier: int
a numeric identifier for the patient.
env: simpy.Environment
the simulation environment
args: Scenario
Container class for the simulation parameters
'''
self.identifier = identifier
self.env = env
self.args = args
self.full_event_log = full_event_log
# metrics
self.arrival = -np.inf
self.wait_triage = -np.inf
self.wait_trauma = -np.inf
self.wait_treat = -np.inf
self.total_time = -np.inf
self.triage_duration = -np.inf
self.trauma_duration = -np.inf
self.treat_duration = -np.inf
def execute(self):
'''
simulates the major treatment process for a patient
1. request and wait for sign-in/triage
2. trauma
3. treatment
'''
# record the time of arrival and entered the triage queue
self.arrival = self.env.now
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Trauma',
'event_type': 'queue',
'event': 'triage_wait_begins',
'time': self.env.now}
)
###################################################
# request sign-in/triage
triage_resource = yield self.args.triage.get()
# record the waiting time for triage
self.wait_triage = self.env.now - self.arrival
trace(f'patient {self.identifier} triaged to trauma '
f'{self.env.now:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Trauma',
'event_type': 'resource_use',
'event': 'triage_begins',
'time': self.env.now,
'resource_id': triage_resource.id_attribute
}
)
# sample triage duration.
self.triage_duration = self.args.triage_dist.sample()
yield self.env.timeout(self.triage_duration)
trace(f'triage {self.identifier} complete {self.env.now:.3f}; '
f'waiting time was {self.wait_triage:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Trauma',
'event_type': 'resource_use_end',
'event': 'triage_complete',
'time': self.env.now,
'resource_id': triage_resource.id_attribute}
)
# Resource is no longer in use, so put it back in the store
self.args.triage.put(triage_resource)
###################################################
# record the time that entered the trauma queue
start_wait = self.env.now
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Trauma',
'event_type': 'queue',
'event': 'TRAUMA_stabilisation_wait_begins',
'time': self.env.now}
)
###################################################
# request trauma room
trauma_resource = yield self.args.trauma.get()
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Trauma',
'event_type': 'resource_use',
'event': 'TRAUMA_stabilisation_begins',
'time': self.env.now,
'resource_id': trauma_resource.id_attribute
}
)
# record the waiting time for trauma
self.wait_trauma = self.env.now - start_wait
# sample stablisation duration.
self.trauma_duration = self.args.trauma_dist.sample()
yield self.env.timeout(self.trauma_duration)
trace(f'stabilisation of patient {self.identifier} at '
f'{self.env.now:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Trauma',
'event_type': 'resource_use_end',
'event': 'TRAUMA_stabilisation_complete',
'time': self.env.now,
'resource_id': trauma_resource.id_attribute
}
)
# Resource is no longer in use, so put it back in the store
self.args.trauma.put(trauma_resource)
#######################################################
# record the time that entered the treatment queue
start_wait = self.env.now
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Trauma',
'event_type': 'queue',
'event': 'TRAUMA_treatment_wait_begins',
'time': self.env.now}
)
########################################################
# request treatment cubicle
trauma_treatment_resource = yield self.args.cubicle_2.get()
# record the waiting time for trauma
self.wait_treat = self.env.now - start_wait
trace(f'treatment of patient {self.identifier} at '
f'{self.env.now:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Trauma',
'event_type': 'resource_use',
'event': 'TRAUMA_treatment_begins',
'time': self.env.now,
'resource_id': trauma_treatment_resource.id_attribute
}
)
# sample treatment duration.
self.treat_duration = self.args.trauma_dist.sample()
yield self.env.timeout(self.treat_duration)
trace(f'patient {self.identifier} treatment complete {self.env.now:.3f}; '
f'waiting time was {self.wait_treat:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Trauma',
'event_type': 'resource_use_end',
'event': 'TRAUMA_treatment_complete',
'time': self.env.now,
'resource_id': trauma_treatment_resource.id_attribute}
)
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Shared',
'event': 'depart',
'event_type': 'arrival_departure',
'time': self.env.now}
)
# Resource is no longer in use, so put it back in the store
self.args.cubicle_2.put(trauma_treatment_resource)
#########################################################
# total time in system
self.total_time = self.env.now - self.arrival
class NonTraumaPathway(object):
'''
Encapsulates the process a patient with minor injuries and illness.
These patients are signed into the ED and triaged as having minor
complaints and streamed to registration and then examination.
Post examination 40% are discharged while 60% proceed to treatment.
Following treatment they are discharged.
'''
def __init__(self, identifier, env, args, full_event_log):
'''
Constructor method
Params:
-----
identifier: int
a numeric identifier for the patient.
env: simpy.Environment
the simulation environment
args: Scenario
Container class for the simulation parameters
'''
self.identifier = identifier
self.env = env
self.args = args
self.full_event_log = full_event_log
# triage resource
self.triage = args.triage
# metrics
self.arrival = -np.inf
self.wait_triage = -np.inf
self.wait_reg = -np.inf
self.wait_exam = -np.inf
self.wait_treat = -np.inf
self.total_time = -np.inf
self.triage_duration = -np.inf
self.reg_duration = -np.inf
self.exam_duration = -np.inf
self.treat_duration = -np.inf
def execute(self):
'''
simulates the non-trauma/minor treatment process for a patient
1. request and wait for sign-in/triage
2. patient registration
3. examination
4.1 40% discharged
4.2 60% treatment then discharge
'''
# record the time of arrival and entered the triage queue
self.arrival = self.env.now
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event_type': 'queue',
'event': 'triage_wait_begins',
'time': self.env.now}
)
###################################################
# request sign-in/triage
triage_resource = yield self.args.triage.get()
# record the waiting time for triage
self.wait_triage = self.env.now - self.arrival
trace(f'patient {self.identifier} triaged to minors '
f'{self.env.now:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event_type': 'resource_use',
'event': 'triage_begins',
'time': self.env.now,
'resource_id': triage_resource.id_attribute
}
)
# sample triage duration.
self.triage_duration = self.args.triage_dist.sample()
yield self.env.timeout(self.triage_duration)
trace(f'triage {self.identifier} complete {self.env.now:.3f}; '
f'waiting time was {self.wait_triage:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event_type': 'resource_use_end',
'event': 'triage_complete',
'time': self.env.now,
'resource_id': triage_resource.id_attribute}
)
# Resource is no longer in use, so put it back in the store
self.args.triage.put(triage_resource)
#########################################################
# record the time that entered the registration queue
start_wait = self.env.now
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event_type': 'queue',
'event': 'MINORS_registration_wait_begins',
'time': self.env.now}
)
#########################################################
# request registration clerk
registration_resource = yield self.args.registration.get()
# record the waiting time for registration
self.wait_reg = self.env.now - start_wait
trace(f'registration of patient {self.identifier} at '
f'{self.env.now:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event_type': 'resource_use',
'event': 'MINORS_registration_begins',
'time': self.env.now,
'resource_id': registration_resource.id_attribute
}
)
# sample registration duration.
self.reg_duration = self.args.reg_dist.sample()
yield self.env.timeout(self.reg_duration)
trace(f'patient {self.identifier} registered at'
f'{self.env.now:.3f}; '
f'waiting time was {self.wait_reg:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event': 'MINORS_registration_complete',
'event_type': 'resource_use_end',
'time': self.env.now,
'resource_id': registration_resource.id_attribute}
)
# Resource is no longer in use, so put it back in the store
self.args.registration.put(registration_resource)
########################################################
# record the time that entered the evaluation queue
start_wait = self.env.now
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event': 'MINORS_examination_wait_begins',
'event_type': 'queue',
'time': self.env.now}
)
#########################################################
# request examination resource
examination_resource = yield self.args.exam.get()
# record the waiting time for examination to begin
self.wait_exam = self.env.now - start_wait
trace(f'examination of patient {self.identifier} begins '
f'{self.env.now:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event': 'MINORS_examination_begins',
'event_type': 'resource_use',
'time': self.env.now,
'resource_id': examination_resource.id_attribute
}
)
# sample examination duration.
self.exam_duration = self.args.exam_dist.sample()
yield self.env.timeout(self.exam_duration)
trace(f'patient {self.identifier} examination complete '
f'at {self.env.now:.3f};'
f'waiting time was {self.wait_exam:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event': 'MINORS_examination_complete',
'event_type': 'resource_use_end',
'time': self.env.now,
'resource_id': examination_resource.id_attribute}
)
# Resource is no longer in use, so put it back in
self.args.exam.put(examination_resource)
############################################################################
# sample if patient requires treatment?
self.require_treat = self.args.nt_p_treat_dist.sample() #pylint: disable=attribute-defined-outside-init
if self.require_treat:
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event': 'requires_treatment',
'event_type': 'attribute_assigned',
'time': self.env.now}
)
# record the time that entered the treatment queue
start_wait = self.env.now
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event': 'MINORS_treatment_wait_begins',
'event_type': 'queue',
'time': self.env.now}
)
###################################################
# request treatment cubicle
non_trauma_treatment_resource = yield self.args.cubicle_1.get()
# record the waiting time for treatment
self.wait_treat = self.env.now - start_wait
trace(f'treatment of patient {self.identifier} begins '
f'{self.env.now:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event': 'MINORS_treatment_begins',
'event_type': 'resource_use',
'time': self.env.now,
'resource_id': non_trauma_treatment_resource.id_attribute
}
)
# sample treatment duration.
self.treat_duration = self.args.nt_treat_dist.sample()
yield self.env.timeout(self.treat_duration)
trace(f'patient {self.identifier} treatment complete '
f'at {self.env.now:.3f};'
f'waiting time was {self.wait_treat:.3f}')
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Non-Trauma',
'event': 'MINORS_treatment_ends',
'event_type': 'resource_use_end',
'time': self.env.now,
'resource_id': non_trauma_treatment_resource.id_attribute}
)
# Resource is no longer in use, so put it back in the store
self.args.cubicle_1.put(non_trauma_treatment_resource)
##########################################################################
# Return to what happens to all patients, regardless of whether they were sampled as needing treatment
self.full_event_log.append(
{'patient': self.identifier,
'pathway': 'Shared',
'event': 'depart',
'event_type': 'arrival_departure',
'time': self.env.now}
)
# total time in system
self.total_time = self.env.now - self.arrival
class TreatmentCentreModel:
'''
The treatment centre model
Patients arrive at random to a treatment centre, are triaged
and then processed in either a trauma or non-trauma pathway.
The main class that a user interacts with to run the model is
`TreatmentCentreModel`. This implements a `.run()` method, contains a simple
algorithm for the non-stationary poission process for patients arrivals and
inits instances of `TraumaPathway` or `NonTraumaPathway` depending on the
arrival type.
'''
def __init__(self, args):
self.env = simpy.Environment()
self.args = args
self.init_resources()
self.patients = []
self.trauma_patients = []
self.non_trauma_patients = []
self.rc_period = None
self.results = None
self.full_event_log = []
self.utilisation_audit = []
def init_resources(self):
'''
Init the number of resources
and store in the arguments container object
Resource list:
1. Sign-in/triage bays
2. registration clerks
3. examination bays
4. trauma bays
5. non-trauma cubicles (1)
6. trauma cubicles (2)
'''
# sign/in triage
# self.args.triage = CustomResource(self.env,
# capacity=self.args.n_triage)
self.args.triage = simpy.Store(self.env)
for i in range(self.args.n_triage):
self.args.triage.put(
CustomResource(
self.env,
capacity=1,
id_attribute = i+1)
)
# registration
# self.args.registration = CustomResource(self.env,
# capacity=self.args.n_reg)
self.args.registration = simpy.Store(self.env)
for i in range(self.args.n_reg):
self.args.registration.put(
CustomResource(
self.env,
capacity=1,
id_attribute = i+1)
)
# examination