I'm starting with a fundamental understanding: the goal is a Python program simulating queueing systems. My focus now is on breaking down the broad concept. I'm visualizing customers arriving, waiting, getting served, and departing. The core elements of the simulation are crystalizing; I am mapping the required processes.
Defining Simulation Components
I've moved from the conceptual and am now pinning down specific simulation components. I'm leaning heavily towards discrete event simulation with SimPy. Modeling the events – arrivals, service starts, and departures – is next. I am also determining the best way to handle the simulation's event loop, and how SimPy's resources can be leveraged to represent servers.
Mapping the Simulation Logic
I'm now detailing the core simulation logic. It's clear that the simulation needs a customer generator, the customer behavior itself (requesting service, waiting, leaving), and a means to track key metrics. I am making a strong shift toward designing an M/M/c model using the SimPy library. The next step will be to define the parameters.
Designing the M/M/c Model
I'm now diving deep into the simulation's structure, focusing on the M/M/c queueing model and SimPy. The parameters are next; I am identifying the essential variables. Random seeds, the number of servers, and arrival/service rates are all starting to solidify. I'm focusing on defining the components and their interactions, primarily: a customer generator, the customer behavior itself, and a monitoring system. The goal now is to establish the simulation's fundamental building blocks for building the foundation.
Developing the Code's Structure
I'm now prioritizing the code's organization and the user's experience. I'll include a SimPy-based solution and a pure Python version, as suggested. I am planning on adding a "customer" process and "generator" process, then integrating all the pieces. I'm focusing on providing clear explanations and outputs, including metrics. Then the alternative implementation.
Planning the Dual-Approach
I'm now consolidating the plan. I will build the SimPy implementation first; it's the core focus. Then, the pure Python version will follow, as it will be useful for instructional purposes. The Pure Python version will be based on an event list. I'm focusing on the SimPy code details; this includes variable naming and using the appropriate random distributions.
Evaluating Final Program Details
I'm now fully immersed in the coding minutiae for both the SimPy and pure Python versions. I am confirming variable names for clarity and ensuring the use of random.expovariate is both correct and clearly explained within the context of Poisson arrivals and Exponential service times. Then, I am focusing on generating the example output for the prompt.
Here are two ways to implement a queueing system simulation in Python.
The Industrial Approach (using simpy): Best for complex, real-world scenarios.
The Educational Approach (Pure Python): Best for understanding the logic behind Discrete Event Simulation (DES) without external libraries.
Approach 1: Using simpy (Recommended)
SimPy is the standard library for discrete-event simulation in Python. It handles the "clock," resources (servers), and callbacks automatically.
Prerequisites:
bash
pip install simpy
The Code (M/M/c Queue):
This simulates a bank with multiple tellers (Servers). Customers arrive randomly (Poisson process) and service times are exponential.
python
import simpy
import random
import statistics
# --- CONFIGURATION ---
RANDOM_SEED = 42
NUM_SERVERS = 2 # Number of tellers/servers (c)
ARRIVAL_RATE = 1.0 # Customers arriving per minute (lambda)
SERVICE_RATE = 0.5 # Customers served per minute (mu)
SIM_TIME = 100 # Simulation time in minutes
class QueueSystem:
def __init__(self, env, num_servers, service_rate):
self.env = env
self.server = simpy.Resource(env, capacity=num_servers)
self.service_rate = service_rate
self.wait_times = []
def serve_customer(self, customer_id):
"""The service process (spending time at the counter)"""
# Generate random service time based on exponential distribution
# random.expovariate(rate) generates time intervals with mean 1/rate
service_duration = random.expovariate(self.service_rate)
yield self.env.timeout(service_duration)
def customer_process(env, name, system):
"""Tracks the lifecycle of a single customer"""
arrival_time = env.now
print(f"{name} arrived at {arrival_time:.2f}")
# Request a server
with system.server.request() as request:
yield request # Wait here until a server is free
# Calculate wait time
wait = env.now - arrival_time
system.wait_times.append(wait)
print(f"{name} starting service at {env.now:.2f} (Waited: {wait:.2f})")
yield env.process(system.serve_customer(name))
print(f"{name} left at {env.now:.2f}")
def arrival_generator(env, system, arrival_rate):
"""Generates new customers randomly over time"""
customer_id = 0
while True:
yield env.timeout(random.expovariate(arrival_rate))
customer_id += 1
env.process(customer_process(env, f"Customer {customer_id}", system))
# --- MAIN EXECUTION ---
def run_simulation():
random.seed(RANDOM_SEED)
# Create environment and system
env = simpy.Environment()
system = QueueSystem(env, NUM_SERVERS, SERVICE_RATE)
# Start the arrival generator
env.process(arrival_generator(env, system, ARRIVAL_RATE))
# Run
print(f"--- Simulation Started (Servers: {NUM_SERVERS}) ---")
env.run(until=SIM_TIME)
print("--- Simulation Ended ---")
# Statistics
if system.wait_times:
avg_wait = statistics.mean(system.wait_times)
print(f"\nTotal Customers: {len(system.wait_times)}")
print(f"Average Wait Time: {avg_wait:.2f} mins")
else:
print("No customers finished.")
if __name__ == "__main__":
run_simulation()
Approach 2: Pure Python (From Scratch)
If you cannot use external libraries, you must build a simple Discrete Event Simulator. This involves a "Future Event List" (FEL)—a priority queue sorted by time.
This acts as an M/M/1 Queue (Single Server).
python
Explanation of Key Concepts
Distributions (random.expovariate):
Real-life arrivals usually follow a Poisson process, which means the time between arrivals is Exponentially distributed.
random.expovariate(rate) returns a floating point number representing appropriate time intervals.
The "Clock":
Queue simulations are Discrete Event Simulations (DES).
We do not loop through every second (e.g., time.sleep(1)). Instead, the simulation "jumps" precisely from one event to the next.
If an arrival happens at T=2.5 and the next service finishes at T=10.0, the program jumps the variable now from 2.5 directly to 10.0.
Queue Discipline:
These examples use FIFO (First-In-First-Out).
If you used the Pure Python version, you could change self.queue.pop(0) to self.queue.pop() to simulate a LIFO (stack) system.
import random
import heapq # Priority queue implementation
# --- CONFIGURATION ---
RANDOM_SEED = 42
ARRIVAL_RATE = 3.0 # lambda
SERVICE_RATE = 4.0 # mu
MAX_TIME = 10 # Simulation units
class Simulator:
def __init__(self):
self.clock = 0.0
self.events = [] # Priority queue [(time, type, id), ...]
self.queue = [] # Customers waiting
self.server_busy = False
self.total_wait_time = 0.0
self.customers_served = 0
self.customer_counter = 0
def schedule_event(self, time_delta, event_type, customer_id=None):
execution_time = self.clock + time_delta
heapq.heappush(self.events, (execution_time, event_type, customer_id))
def run(self):
random.seed(RANDOM_SEED)
# Schedule first arrival
self.schedule_event(random.expovariate(ARRIVAL_RATE), 'ARRIVAL')
while self.events:
# Get next event
time, event_type, customer_id = heapq.heappop(self.events)
if time > MAX_TIME:
break
# Advance clock
self.clock = time
if event_type == 'ARRIVAL':
self.handle_arrival()
elif event_type == 'DEPARTURE':
self.handle_departure()
self.print_stats()
def handle_arrival(self):
self.customer_counter += 1
customer_id = self.customer_counter
# Schedule NEXT arrival immediately (Bootstrap method)
next_interarrival = random.expovariate(ARRIVAL_RATE)
self.schedule_event(next_interarrival, 'ARRIVAL')
if self.server_busy:
# Add to queue (store arrival time)
self.queue.append((customer_id, self.clock))
print(f"{self.clock:.2f}: Customer {customer_id} queued. Queue len: {len(self.queue)}")
else:
# Start service immediately
self.server_busy = True
service_time = random.expovariate(SERVICE_RATE)
self.schedule_event(service_time, 'DEPARTURE', customer_id)
print(f"{self.clock:.2f}: Customer {customer_id} started service immediately.")
def handle_departure(self):
self.customers_served += 1
print(f"{self.clock:.2f}: One customer finished service.")
if self.queue:
# Serve next person in line
next_cust_id, arrival_time = self.queue.pop(0)
wait_time = self.clock - arrival_time
self.total_wait_time += wait_time
service_time = random.expovariate(SERVICE_RATE)
self.schedule_event(service_time, 'DEPARTURE', next_cust_id)
print(f"{self.clock:.2f}: Customer {next_cust_id} started service (Waited {wait_time:.2f}).")
else:
self.server_busy = False
print(f"{self.clock:.2f}: Server is now IDLE.")
def print_stats(self):
print("\n--- Results ---")
print(f"Total Simulation Time: {self.clock:.2f}")
print(f"Customers Served: {self.customers_served}")
if self.customers_served > 0:
print(f"Avg Wait Time (Queue only): {self.total_wait_time / self.customers_served:.4f}")
if __name__ == "__main__":
sim = Simulator()
sim.run()