6  Adding Multiple Activities

Very often there will be more than one activity in a model.

What if instead of this model

We wanted something more like this?

If we want patients to flow from one activity to another, we just write another one after the first one in the pathway generator function. That (aside from adding in any extra resources and results capture elsewhere) is it.

Warning

Just make sure you write the next bit outside of the with statement. Otherwise you’ll drag across the resource from the previous activity too…

Of course, in some cases, you might want that - perhaps if you’re modelling a bed as a resource, for example, but then want to model using an additional resource like a nurse for some parts of the process.

6.1 Coding the model

Tip

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.

6.1.1 The g class

First, lets add some additional parameters to our g class.

class g:
    patient_inter = 5
    mean_reception_time = 2 ##NEW
    mean_n_consult_time = 6
    number_of_receptionists = 1 ##NEW
    number_of_nurses = 1
    sim_duration = 120
    number_of_runs = 5

6.1.2 The Patient class

Next we’ll add an additional attribute - think of it as an extra box on their clipboard that they need to fill in - to record how long they are queuing for the receptionist.

class Patient:
    def __init__(self, p_id):
        self.id = p_id
        self.q_time_recep = 0 ##NEW
        self.q_time_nurse = 0

6.1.3 The Model class

Now we move to our model class. Let’s start by looking at the init method - the list of things that are set up when we create an instance of our model class.

First, we have added in a new type of resource - a receptionist, pulling in the number of receptionist to create from our g class.

We’ve then added two additional fields to our results dataframe - how long each patient queues for a receptionist, and how long each patient spends with the receptionist.

Finally, we add in an attribute that we will use to store the mean average queuing time for receptionists across the whole 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
        ) ##NEW
        self.nurse = simpy.Resource(self.env, capacity=g.number_of_nurses)

        # 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] ##NEW
        self.results_df["Time with Recep"] = [0.0] ##NEW
        self.results_df["Q Time Nurse"] = [0.0]
        self.results_df["Time with Nurse"] = [0.0]
        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 ##NEW
        self.mean_q_time_nurse = 0

Our generator_patient_arrivals method remains unchanged as nothing has been tweaked about how patients turn up to the system.

Our attend_clinic method is where we make the actual change to the process the patient goes through.

Note that we have a new line with an indended section inside it.

with self.receptionist.request() as req:

Everything at one level of indentation within this now relates to the use of the receptionist resource.

 # A generator function that represents the pathway for a patient going
    # through the clinic.
    # The patient object is passed in to the generator function so we can
    # extract information from / record information to it
    def attend_clinic(self, patient):
        ##NEW - added reception activity
        start_q_recep = self.env.now

        with self.receptionist.request() as req:
            yield req

            end_q_recep = self.env.now

            patient.q_time_recep = end_q_recep - start_q_recep

            sampled_recep_act_time = random.expovariate(
                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

        # Record the time the patient started queuing for a nurse
        start_q_nurse = self.env.now

        # This code says request a nurse resource, and do all of the following
        # block of code with that nurse resource held in place (and therefore
        # not usable by another patient)
        with self.nurse.request() as req:
            # Freeze the function until the request for a nurse can be met.
            # The patient is currently queuing.
            yield req

            # When we get to this bit of code, control has been passed back to
            # the generator function, and therefore the request for a nurse has
            # been met.  We now have the nurse, and have stopped queuing, so we
            # can record the current time as the time we finished queuing.
            end_q_nurse = self.env.now

            # Calculate the time this patient was queuing for the nurse, and
            # record it in the patient's attribute for this.
            patient.q_time_nurse = end_q_nurse - start_q_nurse

            # Now we'll randomly sample the time this patient with the nurse.
            # Here, we use an Exponential distribution for simplicity, but you
            # would typically use a Log Normal distribution for a real model
            # (we'll come back to that).  As with sampling the inter-arrival
            # times, we grab the mean from the g class, and pass in 1 / mean
            # as the lambda value.
            sampled_nurse_act_time = random.expovariate(1.0 /
                                                        g.mean_n_consult_time)

            # Here we'll store the queuing time for the nurse and the sampled
            # time to spend with the nurse in the results DataFrame against the
            # ID for this patient.  In real world models, you may not want to
            # bother storing the sampled activity times - but as this is a
            # simple model, we'll do it here.
            # We use a handy property of pandas called .at, which works a bit
            # like .loc.  .at allows us to access (and therefore change) a
            # particular cell in our DataFrame by providing the row and column.
            # Here, we specify the row as the patient ID (the index), and the
            # column for the value we want to update for that patient.
            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)

            # Freeze this function in place for the activity time we sampled
            # above.  This is the patient spending time with the nurse.
            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.  We could choose to add
            # something here if we wanted to record something - e.g. a counter
            # for number of patients that left, recording something about the
            # patients that left at a particular sink etc.

6.1.4 The trial class

The trial class is unchanged.

6.2 Evaluating the outputs

Below is the full code for our updated model. Look out for the lines that end with #NEW to find the bits we’ve added.

import simpy
import random
import pandas as pd

# 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:
    patient_inter = 5
    mean_reception_time = 2 ##NEW
    mean_n_consult_time = 6
    number_of_receptionists = 1 ##NEW
    number_of_nurses = 1
    sim_duration = 120
    number_of_runs = 2

# Class representing patients coming in to the clinic.
class Patient:
    def __init__(self, p_id):
        self.id = p_id
        self.q_time_recep = 0 ##NEW
        self.q_time_nurse = 0

# 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
        ) ##NEW
        self.nurse = simpy.Resource(self.env, capacity=g.number_of_nurses)

        # 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] ##NEW
        self.results_df["Time with Recep"] = [0.0] ##NEW
        self.results_df["Q Time Nurse"] = [0.0]
        self.results_df["Time with Nurse"] = [0.0]
        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 ##NEW
        self.mean_q_time_nurse = 0

    # A generator function that represents the DES generator for patient
    # arrivals
    def generator_patient_arrivals(self):
        # We use an infinite loop here to keep doing this indefinitely whilst
        # the simulation runs
        while True:
            # Increment the patient counter by 1 (this means our first patient
            # will have an ID of 1)
            self.patient_counter += 1

            # Create a new patient - an instance of the Patient Class we
            # defined above.  Remember, we pass in the ID when creating a
            # patient - so here we pass the patient counter to use as the ID.
            p = Patient(self.patient_counter)

            # Tell SimPy to start up the attend_clinic generator function with
            # this patient (the generator function that will model the
            # patient's journey through the system)
            self.env.process(self.attend_clinic(p))

            # Randomly sample the time to the next patient arriving.  Here, we
            # sample from an exponential distribution (common for inter-arrival
            # times), and pass in a lambda value of 1 / mean.  The mean
            # inter-arrival time is stored in the g class.
            sampled_inter = random.expovariate(1.0 / g.patient_inter)

            # Freeze this instance of this function in place until the
            # inter-arrival time we sampled above has elapsed.  Note - time in
            # SimPy progresses in "Time Units", which can represent anything
            # you like (just make sure you're consistent within the model)
            yield self.env.timeout(sampled_inter)

    # A generator function that represents the pathway for a patient going
    # through the clinic.
    # The patient object is passed in to the generator function so we can
    # extract information from / record information to it
    def attend_clinic(self, patient):
        ##NEW - added reception activity
        start_q_recep = self.env.now

        with self.receptionist.request() as req:
            yield req

            end_q_recep = self.env.now

            patient.q_time_recep = end_q_recep - start_q_recep

            sampled_recep_act_time = random.expovariate(
                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

        # Record the time the patient started queuing for a nurse
        start_q_nurse = self.env.now

        # This code says request a nurse resource, and do all of the following
        # block of code with that nurse resource held in place (and therefore
        # not usable by another patient)
        with self.nurse.request() as req:
            # Freeze the function until the request for a nurse can be met.
            # The patient is currently queuing.
            yield req

            # When we get to this bit of code, control has been passed back to
            # the generator function, and therefore the request for a nurse has
            # been met.  We now have the nurse, and have stopped queuing, so we
            # can record the current time as the time we finished queuing.
            end_q_nurse = self.env.now

            # Calculate the time this patient was queuing for the nurse, and
            # record it in the patient's attribute for this.
            patient.q_time_nurse = end_q_nurse - start_q_nurse

            # Now we'll randomly sample the time this patient with the nurse.
            # Here, we use an Exponential distribution for simplicity, but you
            # would typically use a Log Normal distribution for a real model
            # (we'll come back to that).  As with sampling the inter-arrival
            # times, we grab the mean from the g class, and pass in 1 / mean
            # as the lambda value.
            sampled_nurse_act_time = random.expovariate(1.0 /
                                                        g.mean_n_consult_time)

            # Here we'll store the queuing time for the nurse and the sampled
            # time to spend with the nurse in the results DataFrame against the
            # ID for this patient.  In real world models, you may not want to
            # bother storing the sampled activity times - but as this is a
            # simple model, we'll do it here.
            # We use a handy property of pandas called .at, which works a bit
            # like .loc.  .at allows us to access (and therefore change) a
            # particular cell in our DataFrame by providing the row and column.
            # Here, we specify the row as the patient ID (the index), and the
            # column for the value we want to update for that patient.
            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)

            # Freeze this function in place for the activity time we sampled
            # above.  This is the patient spending time with the nurse.
            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.  We could choose to add
            # something here if we wanted to record something - e.g. a counter
            # for number of patients that left, recording something about the
            # patients that left at a particular sink etc.

    # This method calculates results over a single run.  Here we just calculate
    # a mean, but in real world models you'd probably want to calculate more.
    def calculate_run_results(self):
        # Take the mean of the queuing times across patients in this run of the
        # model.
        self.mean_q_time_recep = self.results_df["Q Time Recep"].mean() ##NEW
        self.mean_q_time_nurse = self.results_df["Q Time Nurse"].mean()

    # The run method starts up the DES entity generators, runs the simulation,
    # and in turns calls anything we need to generate results for the run
    def run(self):
        # Start up our DES entity generators that create new patients.  We've
        # only got one in this model, but we'd need to do this for each one if
        # we had multiple generators.
        self.env.process(self.generator_patient_arrivals())

        # Run the model for the duration specified in g class
        self.env.run(until=g.sim_duration)

        # Now the simulation run has finished, call the method that calculates
        # run results
        self.calculate_run_results()

        # Print the run number with the patient-level results from this run of
        # the model
        print (f"Run Number {self.run_number}")
        print (self.results_df)

# Class representing a Trial for our simulation - a batch of simulation runs.
class Trial:
    # The constructor sets up a pandas dataframe that will store the key
    # results from each run against run number, with run number as the index.
    def  __init__(self):
        self.df_trial_results = pd.DataFrame()
        self.df_trial_results["Run Number"] = [0]
        self.df_trial_results["Mean Q Time Recep"] = [0.0] ##NEW
        self.df_trial_results["Mean Q Time Nurse"] = [0.0]
        self.df_trial_results.set_index("Run Number", inplace=True)

    # Method to print out the results from the trial.  In real world models,
    # you'd likely save them as well as (or instead of) printing them
    def print_trial_results(self):
        print ("Trial Results")
        print (self.df_trial_results)

    # Method to run a trial
    def run_trial(self):
        # Run the simulation for the number of runs specified in g class.
        # For each run, we create a new instance of the Model class and call its
        # run method, which sets everything else in motion.  Once the run has
        # completed, we grab out the stored run results (just mean queuing time
        # here) and store it against the run number in the trial results
        # dataframe.
        for run in range(g.number_of_runs):
            my_model = Model(run)
            my_model.run()

            ##NEW (added receptionist queuing mean as first item to list)
            self.df_trial_results.loc[run] = [my_model.mean_q_time_recep,
                                              my_model.mean_q_time_nurse]

        # Once the trial (ie all runs) has completed, print the final results
        self.print_trial_results()

Let’s run the updated code and see the outputs.

We can see we now get results for the time queueing for and the time spent with the receptionist and the nurse, displayed separately, and that these times are different from each other.

# Create an instance of the Trial class
my_trial = Trial()

# Call the run_trial method of our Trial object
my_trial.run_trial()
Run Number 0
            Q Time Recep  Time with Recep  Q Time Nurse  Time with Nurse
Patient ID                                                              
1               0.000000         0.566215      0.000000         3.601756
2               0.000000         0.728729      0.000000        10.245132
3               0.000000         1.174713      6.376356        11.644353
4               0.000000         5.617086      0.000000         8.039960
5               4.916341         0.060805      7.979155         4.164491
6               0.000000         0.870245      8.748850         0.138744
7               0.000000         0.975266      3.047252         0.119339
8               0.000000         2.326724      0.000000        13.039536
9               0.000000         1.385875      5.697993         0.281789
10              0.000000         4.039215      0.000000         5.714754
11              0.000000         1.088867      0.000000         9.525967
12              0.670755         1.020018      8.505949         3.535348
13              0.000000         1.464975      9.675615        12.002914
14              0.000000         0.788349     18.880364        15.420444
15              0.000000         2.610406     30.449569         1.046262
16              0.000000         2.786090           NaN              NaN
17              2.763762         0.057179           NaN              NaN
18              1.116236         0.836522           NaN              NaN
19              0.683744         4.952128           NaN              NaN
20              0.000000         1.961155           NaN              NaN
21              0.000000         7.213416           NaN              NaN
22              2.439698         5.304018           NaN              NaN
23              7.610385         0.572516           NaN              NaN
24              6.768555         3.102570           NaN              NaN
25              0.000000         1.621816           NaN              NaN
26              0.388384         2.571572           NaN              NaN
Run Number 1
            Q Time Recep  Time with Recep  Q Time Nurse  Time with Nurse
Patient ID                                                              
1               0.000000         1.856480      0.000000         4.856756
2               0.000000         2.127980      0.000000         8.388685
3               1.735568         2.290164      6.098521         5.593031
4               0.000000         3.515557      4.651919         1.502754
5               0.000000         1.265051      0.353803         8.877776
6               0.000000         8.789276      0.000000         1.170822
7               1.887744         2.171365      0.000000         2.470859
8               1.844610         1.037615      1.433244         5.784135
9               0.000000         4.296139      0.130623         4.499255
10              0.000000         2.919038      0.000000         0.896243
11              0.000000         0.879323      0.000000        14.571468
12              0.000000         1.576374      7.538812         1.269203
13              0.000000         1.379286      5.670070         1.457669
14              0.000000         1.764274      4.588624         6.275053
15              0.000000         1.036360      9.477104         7.062744
16              0.949757         0.022823     16.517025        10.247619
17              0.000000         7.243177     12.739880         2.960812
18              0.788702         0.949320     14.751372         2.039260
19              0.111882         0.092316     16.698316         7.791478
20              0.000000         4.347507     15.747008        12.125677
21              4.261170         0.298233     27.574452         5.495525
22              1.920015         0.703359           NaN              NaN
23              0.000000         5.484407           NaN              NaN
24              3.063835         2.342609           NaN              NaN
25              0.000000         1.781071           NaN              NaN
26              0.109746         1.732130           NaN              NaN
27              1.447465         3.860286           NaN              NaN
Trial Results
            Mean Q Time Recep  Mean Q Time Nurse
Run Number                                      
0                    1.052225           6.624073
1                    0.671129           6.855751