# Class to store global parameter values. We don't create an instance of this
# class - we just refer to the class blueprint itself to access the numbers
# inside.
class g:
= 5
patient_inter = 2
mean_reception_time = 6
mean_n_consult_time = 20 ##NEW
mean_d_consult_time = 1
number_of_receptionists = 1
number_of_nurses = 2 ##NEW
number_of_doctors = 0.6 ##NEW
prob_seeing_doctor = 120
sim_duration = 5 number_of_runs
7 Adding Branching Paths
“Most real world systems aren’t linear!” we hear you say. “Some people go over here, some go over there.”
You want branching paths? Coming right up!
So this time, instead of this model
Or this model
We will create something more like this:
To model a branching path, we can use our good old Python friend Conditional Logic.
Often, the branches in a DES are based on probabilities that represent the proportion of patients (or whatever your entity is) that travel along a certain route. For example, the data might show that 60% of patients see a doctor after seeing a nurse.
To model this, we can randomly sample from a uniform distribution between 0 and 1, and compare the value to this probability. If we pick a value below the probability, then we say that the patient follows this route. Why does this work? Well…
60% of values between 0 and 1 are below 0.6.
Therefore, if there’s an equal chance of any value being picked (as is the case in a uniform distribution) then there’s a 60% probability of picking one below 0.6.
We can use this to emulate the probability of following a path.
Not all branching paths will be probability-based.
It may be that some paths are followed depending on:
- The time of day.
- The type of patient.
- How long a patient spends in an activity.
- etc.
In these cases, you’d still use conditional logic, but just alter the condition you’re checking.
For the time of day, you’d want to check the current simulation time in the run.
For the type of patient, you may have stored this in an attribute of the patient.
7.1 Coding the model
Throughout the code, anything new that’s been added will be followed by the comment ##NEW
- so look out for that in the following code chunks.
7.1.1 g class
We need to add a few additional parameters to our g class.
7.1.2 Patient class
We want to add an additional attribute to record the time patients spend with the doctor if they see one.
# Class representing patients coming in to the clinic.
class Patient:
def __init__(self, p_id):
self.id = p_id
self.q_time_recep = 0
self.q_time_nurse = 0
self.q_time_doctor = 0 ##NEW
7.1.3 Model class
7.1.3.1 the init method
In the init method, we add a few additional atrributes to store additional outputs from the model.
# Class representing our model of the clinic.
class Model:
# Constructor to set up the model for a run. We pass in a run number when
# we create a new model.
def __init__(self, run_number):
# Create a SimPy environment in which everything will live
self.env = simpy.Environment()
# Create a patient counter (which we'll use as a patient ID)
self.patient_counter = 0
# Create our resources
self.receptionist = simpy.Resource(
self.env, capacity=g.number_of_receptionists
)self.nurse = simpy.Resource(self.env, capacity=g.number_of_nurses)
self.doctor = simpy.Resource(
self.env, capacity=g.number_of_doctors) ##NEW
# Store the passed in run number
self.run_number = run_number
# Create a new Pandas DataFrame that will store some results against
# the patient ID (which we'll use as the index).
self.results_df = pd.DataFrame()
self.results_df["Patient ID"] = [1]
self.results_df["Q Time Recep"] = [0.0]
self.results_df["Time with Recep"] = [0.0]
self.results_df["Q Time Nurse"] = [0.0]
self.results_df["Time with Nurse"] = [0.0]
self.results_df["Q Time Doctor"] = [0.0] ##NEW
self.results_df["Time with Doctor"] = [0.0] ##NEW
self.results_df.set_index("Patient ID", inplace=True)
# Create an attribute to store the mean queuing times across this run of
# the model
self.mean_q_time_recep = 0
self.mean_q_time_nurse = 0
self.mean_q_time_doctor = 0 ##NEW
7.1.3.2 The generator_patient_arrivals method
This method is unchanged.
7.1.3.3 The attend_clinic method
Here, we need to add in a chance of patients seeing the doctor on their journey.
def attend_clinic(self, patient):
= self.env.now
start_q_recep
with self.receptionist.request() as req:
yield req
= self.env.now
end_q_recep
= end_q_recep - start_q_recep
patient.q_time_recep
= random.expovariate(
sampled_recep_act_time 1.0 / g.mean_reception_time
)
self.results_df.at[patient.id, "Q Time Recep"] = (
patient.q_time_recep
)self.results_df.at[patient.id, "Time with Recep"] = (
sampled_recep_act_time
)
yield self.env.timeout(sampled_recep_act_time)
# Here's where the patient finishes with the receptionist, and starts
# queuing for the nurse
= self.env.now
start_q_nurse
with self.nurse.request() as req:
yield req
= self.env.now
end_q_nurse
= end_q_nurse - start_q_nurse
patient.q_time_nurse
= random.expovariate(1.0 /
sampled_nurse_act_time
g.mean_n_consult_time)
self.results_df.at[patient.id, "Q Time Nurse"] = (
patient.q_time_nurse)self.results_df.at[patient.id, "Time with Nurse"] = (
sampled_nurse_act_time)
yield self.env.timeout(sampled_nurse_act_time)
# When the time above elapses, the generator function will return
# here. As there's nothing more that we've written, the function
# will simply end. This is a sink.
##NEW
##
## -----------------------------------------------------------
## This is where our new code for seeing the doctor is
## We use conditional logic to determine whether the patient goes
## on to see the doctor or not
## ------------------------------------------------------------
#
# We sample from the uniform distribution between 0 and 1. If the value
# is less than the probability of seeing a doctor (stored in g Class)
# then we say the patient sees a doctor.
#
# If not, this block of code won't be run and the patient will just
# leave the system (we could add in an else if we wanted a branching
# path to another activity instead)
if random.uniform(0,1) < g.prob_seeing_doctor:
= self.env.now
start_q_doctor
with self.doctor.request() as req:
yield req
= self.env.now
end_q_doctor
= end_q_doctor - start_q_doctor
patient.q_time_doctor
= random.expovariate(
sampled_doctor_act_time 1.0 / g.mean_d_consult_time
)
self.results_df.at[patient.id, "Q Time Doctor"] = (
patient.q_time_doctor
)self.results_df.at[patient.id, "Time with Doctor"] = (
sampled_doctor_act_time
)
yield self.env.timeout(sampled_doctor_act_time)
Let’s try and understand a bit more about how we trigger the conditional logic.
Let’s look at the output of the line random.uniform(0,1)
0,1) random.uniform(
0.6394267984578837
What about if we run it multiple times?
for i in range(10):
print(random.uniform(0,1))
0.025010755222666936
0.27502931836911926
0.22321073814882275
0.7364712141640124
0.6766994874229113
0.8921795677048454
0.08693883262941615
0.4219218196852704
0.029797219438070344
0.21863797480360336
So how does this relate to our code?
In our g class, we set a probability threshold for patients being seen. Let’s pull that out:
print(g.prob_seeing_doctor)
0.6
The code in the Model class tests whether the number generated by the random number generator is below the threshold we’ve set of seeing the doctor. If it is, the indented code where we actually see the doctor will be run for that patient. If it is not, that bit is bypassed - which in this case means they’ve reached the end of their journey and leave the system (a sink).
for i in range(10):
= random.uniform(0,1)
random_number = random_number < g.prob_seeing_doctor
is_below_threshold
if is_below_threshold:
print(f"Random number {random_number:.2f} is LOWER than threshold ({g.prob_seeing_doctor}). " +
"Doctor code is triggered.")
else:
print(f"Random number {random_number:.2f} is HIGHER than threshold ({g.prob_seeing_doctor}). " +
"Doctor code is **not** triggered.")
Random number 0.51 is LOWER than threshold (0.6). Doctor code is triggered.
Random number 0.03 is LOWER than threshold (0.6). Doctor code is triggered.
Random number 0.20 is LOWER than threshold (0.6). Doctor code is triggered.
Random number 0.65 is HIGHER than threshold (0.6). Doctor code is **not** triggered.
Random number 0.54 is LOWER than threshold (0.6). Doctor code is triggered.
Random number 0.22 is LOWER than threshold (0.6). Doctor code is triggered.
Random number 0.59 is LOWER than threshold (0.6). Doctor code is triggered.
Random number 0.81 is HIGHER than threshold (0.6). Doctor code is **not** triggered.
Random number 0.01 is LOWER than threshold (0.6). Doctor code is triggered.
Random number 0.81 is HIGHER than threshold (0.6). Doctor code is **not** triggered.
If we run this code a hundred thousand times and plot the results, we can start to see the pattern emerging despite the random element of the number generator.
import plotly.express as px
import pandas as pd
import numpy as np
= [random.uniform(0,1) for i in range(100000)]
random_vals
= pd.DataFrame({"value" :random_vals})
random_vals_df
'threshold'] = np.where(random_vals_df["value"]<0.6, 'below', 'above')
random_vals_df[
= px.histogram(random_vals_df, color="threshold")
fig
=dict(
fig.update_traces(xbins=0.0,
start=1.0,
end=0.1
size
),=1,marker_line_color="black")
marker_line_width
fig.show()