Running a Discrete-Event Simulation in Python Using SimPy
In this post, I demonstrate how to successfully run a simple discrete-event queueing simulation in Python using the SimPy framework. This example models customers arriving at a movie theater and waiting for service.
Background
SimPy is a process-based discrete-event simulation framework used in research areas such as traffic modeling, communication networks, healthcare systems, and V2X latency analysis.
Initial Challenge
While running the simulation, I encountered the following error:
statistics.StatisticsError: mean requires at least one data point
This happened because multiple simulation environments were created. In SimPy, all processes must run in the same environment. Once corrected, the simulation executed successfully.
Corrected and Working Code
import simpy
import random
import statistics
wait_times = []
class Theater:
def __init__(self, env, num_cashiers):
self.env = env
self.cashier = simpy.Resource(env, num_cashiers)
def purchase_ticket(self, customer):
service_time = random.uniform(1, 3)
yield self.env.timeout(service_time)
def customer(env, name, theater):
arrival_time = env.now
with theater.cashier.request() as request:
yield request
wait = env.now - arrival_time
wait_times.append(wait)
print(f"{name} waited {wait:.2f} minutes")
yield env.process(theater.purchase_ticket(name))
def run_theater_simulation(env, num_cashiers=2, num_customers=10, arrival_rate=1):
theater = Theater(env, num_cashiers)
for i in range(num_customers):
env.process(customer(env, f"Customer {i+1}", theater))
yield env.timeout(random.expovariate(1.0 / arrival_rate))
random.seed(42)
env = simpy.Environment()
env.process(run_theater_simulation(env))
env.run()
average_wait = statistics.mean(wait_times)
print("\n--- Simulation Results ---")
print(f"Average wait time: {average_wait:.2f} minutes")
print(f"Max wait time: {max(wait_times):.2f} minutes")
Simulation Output
The screenshot below shows the successful execution of the simulation, including individual waiting times and summary statistics.
Figure 1: Terminal output showing successful execution of the SimPy-based discrete-event theater queue simulation.
Key Lesson Learned
In SimPy, all processes must share a single simulation environment. Creating multiple environments prevents scheduled events from executing.
Conclusion
This example demonstrates a correct and reproducible implementation of a discrete-event simulation using SimPy. The same modeling approach can be extended to research problems such as NR-V2X latency modeling, pedestrian delay analysis, and network queueing systems.
Comments
Post a Comment