5  An Example SimPy Model

In the example we’re going to look at, we’ll model a very simple model - patients arriving at a clinic for a nurse consultation. One type of entity, one generator, one activity, one queue, one sink, one type of resource.

A SimPy model can seem quite complex at first, particularly for such a simple model as this. But the good news is the overall structure is always the same, regardless of complexity.

5.1 Import statements

First we need our import statements. The libraries you import will vary depending on your model and what you need, but these three are likely going to always be in there (the first must be!)

import simpy
import random
import pandas as pd
Tip

random gives us access to stochastic sampling from probability distributions

5.2 g class

Remember - the g Class stores our global parameter values for the model so we can easily change aspects of the model to test scenarios.

# 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_n_consult_time = 6
    number_of_nurses = 1
    sim_duration = 120
    number_of_runs = 5

5.3 Patient (entity) class

# Class representing patients coming in to the clinic.  Here, patients have
# two attributes that they carry with them - their ID, and the amount of time
# they spent queuing for the nurse.  The ID is passed in when a new patient is
# created.
class Patient:
    def __init__(self, p_id):
        self.id = p_id
        self.q_time_nurse = 0

5.4 Model class

# 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 a SimPy resource to represent a nurse, that will live in the
        # environment created above.  The number of this resource we have is
        # specified by the capacity, and we grab this value from our g class.
        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 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 time for the nurse
        # across this run of the model
        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.  Here the pathway is extremely simple - a patient
    # arrives, waits to see a nurse, and then leaves.
    # 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):
        # 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 for the nurse across patients in
        # this run of the model.
        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)

5.5 Trial class

# 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 (just the mean queuing time for the nurse here)
    # 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 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()

            self.df_trial_results.loc[run] = [my_model.mean_q_time_nurse]

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

Now we just need to run the trial and print out the results!

# 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 Nurse  Time with Nurse
Patient ID                               
1               0.000000        10.005984
2               9.530564         0.788354
3               7.997071        10.323407
4              14.600225         8.684079
5              21.661080         0.272340
6              21.363241         4.313784
7              21.270075         5.932860
8              24.034840         1.409238
9              23.985928         1.618109
10             25.421153         4.227256
11             28.725894         7.031321
12             35.405006         6.926833
13             41.376775        25.388000
14             55.693531         3.730151
15             59.196802         9.651763
16             60.767746        11.582869
17             61.994175        22.805393
Run Number 1
            Q Time Nurse  Time with Nurse
Patient ID                               
1               0.000000         8.729877
2               8.516543         4.471304
3               3.875692         3.670750
4               0.000000         0.782498
5               0.012678         0.491535
6               0.000000         0.783461
7               0.000000         0.588255
8               0.000000         2.852097
9               0.000000         2.183086
10              0.000000         4.428163
11              2.003196         0.621856
12              0.762303         1.609048
13              1.041870         1.887637
14              0.000000         3.133172
15              2.881876         7.259336
16              9.697588         7.497698
17              8.639955         2.523572
18              8.877796         0.990891
19              9.392761        14.257064
20             17.802538         6.913618
21             21.039163         3.477209
22             21.590498         9.739477
Run Number 2
            Q Time Nurse  Time with Nurse
Patient ID                               
1               0.000000         1.834262
2               0.000000         5.833186
3               0.000000         0.526344
4               0.456512        15.416482
5               9.186150         4.817408
6              10.688880         4.434043
7               0.000000         1.074554
8               0.000000         1.411072
9               0.000000         5.213737
10              0.000000         0.582687
11              0.000000         3.859013
12              3.516711         3.327609
13              4.734854        13.115957
Run Number 3
            Q Time Nurse  Time with Nurse
Patient ID                               
1               0.000000         5.719854
2               0.000000         4.500717
3               3.457072         1.480659
4               3.276519         3.604015
5               4.777624         6.813211
6               8.646425         0.366041
7               2.712706        13.743612
8              13.710850         1.809517
9              11.877919         2.730500
10             13.922982         1.892958
11             13.149556         2.591808
12              2.832675         5.656350
13              7.973737         0.486789
14              6.436274         6.356053
15             12.539856         5.365700
16              8.933750         2.706886
17              5.697609         1.119059
18              0.000000         1.669012
19              0.000000         3.486286
20              1.982601         4.329950
21              5.390025         9.617998
22             11.186354         0.929493
23              7.321821        10.497823
24             13.618125         1.156036
25             11.431256         1.469715
26              2.313958        10.400478
27              4.023364        23.476560
Run Number 4
            Q Time Nurse  Time with Nurse
Patient ID                               
1               0.000000         6.244373
2               0.000000         2.471548
3               1.502250         8.119143
4               9.249617         1.784242
5               8.259637        23.219788
6              28.044819         2.548595
7              14.640165         4.443710
8              17.517514         7.850674
9              19.804084         1.225654
10             18.196885        11.753394
11             15.675784         8.705642
12             24.358869         1.103491
13             21.178995         3.088403
14              8.241796         6.068328
15              9.086240         7.852371
16             14.346696         2.391780
17             15.594367         4.063312
18             19.543197        20.121796
Trial Results
            Mean Q Time Nurse
Run Number                   
0                   30.177889
1                    5.278839
2                    2.198701
3                    6.563447
4                   13.624495