The user wants me to implement a Python program to simulate queueing systems.
1. Understand the Goal:
The request is quite broad ("simulate queueing systems"). Queueing theory involves customers arriving, waiting in a queue, being served by servers, and departing.
Common parameters in queueing theory (Kendall's Notation: A/S/c):
A: Arrival process (e.g., Poisson/Markovian - M, Deterministic - D, General - G).
S: Service time distribution (e.g., Exponential - M, Deterministic - D, General - G).
c: Number of servers.
I should implement a flexible simulation engine that can handle at least the M/M/1 case (Markovian arrivals, Markovian service times, 1 server) and ideally M/M/c.
2. Core Concepts:
Events: Something happening at a specific time.
Arrival: A customer enters the system.
Departure: A customer finishes service and leaves.
Loop until the simulation end time (or max events):
a. Pull the next event from an event list (Priority Queue).
b. Advance clock to event time.
c. Process the event:
* If Arrival:
* Schedule the next arrival.
* If server is free: Start service (schedule departure).
* If server is busy: Add to queue.
* If Departure:
* Free the server.
* If queue is not empty: Pull next customer, start service (schedule departure).
3. Python Implementation Strategy:
I need a Customer class (optional, but good for tracking ID).
I need an Event class to hold time, type, and customer.
I need a EventQueue (using heapq is the standard Python way for priority queues).
Arrival Generation: Next arrival time = current time + exponential random variable (rate λ).
Service Generation: Service time = exponential random variable (rate μ).
6. Adding Complexity (M/M/c):
Instead of a boolean server_busy, I need a counter servers_available.
When a customer arrives:
If servers_available > 0: decrement servers_available, schedule departure.
Else: enqueue.
When a customer departs:
Increment servers_available.
If queue is not empty: dequeue customer, schedule departure.
7. Output/Metrics:
What do users want to see?
Average wait time.
Average service time.
Average queue length.
Server utilization.
8. Drafting the Code (Mental or Scratchpad):
python
import simpy # Wait, external libraries are tricky. Better to use standard libraries unless requested otherwise. I will use standard library (random, heapq).
Let's stick to standard library heapq.
9. Finalizing the Implementation Plan:
Step 1: Define constants/types for Events (Arrival, Departure).
Need to store wait times and system times in lists.
Step 5: Main execution block to run the sim and print results.
10. Self-Correction/Refinement:
Issue: Infinite loop if rates are bad.
Fix: Add a max simulation time parameter.
Visuals: A console log is fine, but maybe a simple ASCII chart or just clear formatted text is better.
Generators: Use random.expovariate for exponential distribution (Poisson process).
11. Writing the specific Python code:
Class Customer: To track arrival time.
Class Event: Time, Type, Customer.
Class Simulation:
__init__: Lambda (arrival rate), Mu (service rate), duration.
schedule_event: pushes to heap.
run: while time < duration and heap not empty.
Let's write the code.
Randomness:random.expovariate(lambd) returns a value based on rate lambd.
Server Logic:
self.servers (int): free servers.
self.queue (list): waiting customers.
12. Adding "What if" scenarios?
The prompt asks to "simulate queueing systems". Plural. I should probably structure it so the user can easily change parameters or even the distribution logic, but a clean M/M/c implementation is the most standard answer. I will provide a class-based approach for reusability.
13. Analysis:
I will compute:
ρ (Utilization) = λ/(c×μ)
Avg Wait Time.
Avg System Time (Wait + Service).
14. Final Polish:
Add comments explaining the "Discrete Event Simulation" technique. Ensure PEP 8 formatting.
Let's construct the final response.
Explanation of the approach (DES).
The Code (Event, Customer, Simulation classes).
Example usage (M/M/1 vs M/M/2).
Interpretation of results.
This looks solid. I will write the solution now.
To simulate a queueing system effectively, the standard approach is to use Discrete Event Simulation (DES). In this model, the system state changes only at specific points in time (events), such as a customer arriving or a service completing.
Below is a robust, object-oriented implementation using Python's standard library. It supports:
Generic Queueing Systems: Configurable arrival rates, service rates, and number of servers (e.g., M/M/1, M/M/c).
Priority Queue: Using heapq to manage events chronologically.
Statistics: Tracking wait times, server utilization, and queue lengths.
The Python Implementation
python
How the Code Works
The Event Class: This is the heart of the simulation. We use Python's heapq module. By defining the Event class with time as the first attribute and setting order=True (via dataclass), the heap automatically sorts events so the next upcoming event is always popped first.
The Logic Flow:
Arrival: When a customer arrives, we immediately schedule the next customer's arrival (creating a continuous stream of traffic). We then check if a server is idle. If yes, they start service; if no, they enter a FIFO list (self.customer_queue).
Service Start: We record the time service starts. The difference between service_start_time and arrival_time is the Wait Time. We then generate a random service duration and schedule a Departure event.
Departure: When a customer leaves, we free up the server. We immediately check the queue. If people are waiting, we pull the first one out and start their service immediately.
Randomness: We use random.expovariate(rate). This models the "Markovian" (M) property in M/M/1 queues, meaning arrivals are Poisson distributed and service times are exponentially distributed.
Interpreting the Output
When you run this code, you will see something like this:
text
Starting Simulation...
--- Simulation Results ---
Total Customers Served: 30012
Average Wait Time: 0.1234 units
Average Service Time: 0.2000 units
Average Time in System: 0.3234 units
Server Utilization: 60.02%
Arrival Rate (lambda): 3.0012 cust/unit
Avg Customers in System: 0.9708 (Little's Law Estimate)
Server Utilization: This should be close to λ/(c×μ). In the example above, 3/5=0.6 or 60%.
Average Wait Time: In an M/M/1 queue, theoretical wait time is . For , this is . The simulation result will converge to this as increases.
How to Extend
M/M/c (Multiple Servers): Change num_servers in the constructor to 2, 3, etc. The logic handles this automatically via the available_servers counter.
Different Distributions: Change _generate_service or _generate_interarrival to use normal distributions (random.gauss) or constant times to simulate deterministic systems (D).
import heapq
import random
import statistics
from dataclasses import dataclass, field
from typing import List, Optional
# ==========================================
# 1. Define Core Structures
# ==========================================
@dataclass(order=True)
class Event:
"""
Represents a simulation event.
Sorted by time so the scheduler processes them in chronological order.
"""
time: float
event_type: str = field(compare=False)
customer_id: int = field(compare=False)
class Customer:
"""
Represents a customer in the system.
"""
def __init__(self, cid, arrival_time):
self.cid = cid
self.arrival_time = arrival_time
self.service_start_time = None
self.service_end_time = None
class SimulationStats:
"""
Collects and calculates simulation metrics.
"""
def __init__(self):
self.wait_times = []
self.service_times = []
self.system_times = []
self.queue_length_over_time = []
self.server_busy_time = 0
def report(self, total_sim_time, num_servers):
avg_wait = statistics.mean(self.wait_times) if self.wait_times else 0
avg_service = statistics.mean(self.service_times) if self.service_times else 0
avg_system = statistics.mean(self.system_times) if self.system_times else 0
utilization = self.server_busy_time / (total_sim_time * num_servers) if total_sim_time > 0 else 0
print("\n--- Simulation Results ---")
print(f"Total Customers Served: {len(self.wait_times)}")
print(f"Average Wait Time: {avg_wait:.4f} units")
print(f"Average Service Time: {avg_service:.4f} units")
print(f"Average Time in System: {avg_system:.4f} units")
print(f"Server Utilization: {utilization:.2%}")
# Little's Law check (L = lambda * W)
# lambda = customers / time
arrival_rate = len(self.wait_times) / total_sim_time
print(f"Arrival Rate (lambda): {arrival_rate:.4f} cust/unit")
print(f"Avg Customers in System: {arrival_rate * avg_system:.4f} (Little's Law Estimate)")
# ==========================================
# 2. The Simulation Engine
# ==========================================
class QueueingSystem:
def __init__(self,
arrival_rate: float, # Lambda (e.g., customers per minute)
service_rate: float, # Mu (e.g., customers served per minute)
num_servers: int = 1,
simulation_time: float = 1000):
self.arrival_rate = arrival_rate
self.service_rate = service_rate
self.num_servers = num_servers
self.max_sim_time = simulation_time
# State Variables
self.clock = 0.0
self.event_queue = [] # Priority Queue (Heap)
self.customers_in_system = 0
self.customer_queue = [] # FIFO Queue for waiting customers
self.available_servers = num_servers
self.customer_counter = 0
# Statistics Helper
self.stats = SimulationStats()
# Tracking customers currently being processed to update stats later
self.active_customers = {}
def _schedule_event(self, delay: float, event_type: str, customer_id: int):
"""Pushes a new event onto the heap."""
event_time = self.clock + delay
heapq.heappush(self.event_queue, Event(event_time, event_type, customer_id))
def _generate_interarrival(self):
"""Exponential distribution for time between arrivals."""
return random.expovariate(self.arrival_rate)
def _generate_service(self):
"""Exponential distribution for service duration."""
return random.expovariate(self.service_rate)
def run(self):
"""Main simulation loop."""
print("Starting Simulation...")
# Kickstart: Schedule the first arrival
first_arrival = self._generate_interarrival()
self._schedule_event(first_arrival, "ARRIVAL", 0)
while self.event_queue:
# 1. Pop next event
event = heapq.heappop(self.event_queue)
# Update Clock
self.clock = event.time
# Stop condition
if self.clock > self.max_sim_time:
break
# 2. Process Event
if event.event_type == "ARRIVAL":
self._handle_arrival(event)
elif event.event_type == "DEPARTURE":
self._handle_departure(event)
self.stats.report(self.clock, self.num_servers)
def _handle_arrival(self, event: Event):
"""Logic for when a customer enters the system."""
self.customer_counter += 1
cust = Customer(self.customer_counter, self.clock)
self.active_customers[cust.cid] = cust
# Schedule the NEXT arrival (Poisson process memoryless property)
next_arrival_delay = self._generate_interarrival()
self._schedule_event(next_arrival_delay, "ARRIVAL", 0) # Customer ID for future arrival not needed yet
# Logic: Is a server free?
if self.available_servers > 0:
# Go directly to service
self._start_service(cust)
else:
# Join the queue
self.customer_queue.append(cust)
def _start_service(self, cust: Customer):
"""Logic to begin serving a customer."""
self.available_servers -= 1
cust.service_start_time = self.clock
# Calculate wait time for this customer
wait = cust.service_start_time - cust.arrival_time
self.stats.wait_times.append(wait)
# Determine service duration and schedule departure
service_duration = self._generate_service()
self.stats.service_times.append(service_duration)
self.stats.server_busy_time += service_duration
self._schedule_event(service_duration, "DEPARTURE", cust.cid)
def _handle_departure(self, event: Event):
"""Logic for when a customer leaves."""
cust = self.active_customers.pop(event.customer_id)
# Record total time in system
system_time = self.clock - cust.arrival_time
self.stats.system_times.append(system_time)
# Free up the server
self.available_servers += 1
# Check if anyone is in the queue
if self.customer_queue:
next_cust = self.customer_queue.pop(0) # FIFO
self._start_service(next_cust)
# ==========================================
# 3. Execution
# ==========================================
if __name__ == "__main__":
# Configuration: M/M/1 Queue
# Arrival Rate (lambda) = 3 customers per unit time
# Service Rate (mu) = 5 customers per unit time
# Utilization (rho) = lambda / mu = 0.6 (System should be stable)
sim = QueueingSystem(
arrival_rate=3.0,
service_rate=5.0,
num_servers=1,
simulation_time=10000 # Run for a long time to average out variance
)
sim.run()