Simpy
Build realistic discrete-event simulations with Python processes and resources
✨ The solution you've been looking for
Process-based discrete-event simulation framework in Python. Use this skill when building simulations of systems with processes, queues, resources, and time-based events such as manufacturing systems, service operations, network traffic, logistics, or any system where entities interact with shared resources over time.
See It In Action
Interactive preview & real-world examples
AI Conversation Simulator
See how users interact with this skill
User Prompt
Help me build a SimPy simulation of a manufacturing line with 3 machines where parts queue between stations. I want to analyze wait times and machine utilization.
Skill Processing
Analyzing request...
Agent Response
A complete discrete-event simulation with process definitions, resource modeling, statistics collection, and performance analysis recommendations
Quick Start (3 Steps)
Get up and running in minutes
Install
claude-code skill install simpy
claude-code skill install simpyConfig
First Trigger
@simpy helpCommands
| Command | Description | Required Args |
|---|---|---|
| @simpy manufacturing-line-optimization | Model production processes to identify bottlenecks and optimize throughput | None |
| @simpy service-queue-analysis | Simulate customer service systems to determine optimal staffing levels | None |
| @simpy network-traffic-simulation | Model packet flow and bandwidth allocation in network systems | None |
Typical Use Cases
Manufacturing Line Optimization
Model production processes to identify bottlenecks and optimize throughput
Service Queue Analysis
Simulate customer service systems to determine optimal staffing levels
Network Traffic Simulation
Model packet flow and bandwidth allocation in network systems
Overview
SimPy - Discrete-Event Simulation
Overview
SimPy is a process-based discrete-event simulation framework based on standard Python. Use SimPy to model systems where entities (customers, vehicles, packets, etc.) interact with each other and compete for shared resources (servers, machines, bandwidth, etc.) over time.
Core capabilities:
- Process modeling using Python generator functions
- Shared resource management (servers, containers, stores)
- Event-driven scheduling and synchronization
- Real-time simulations synchronized with wall-clock time
- Comprehensive monitoring and data collection
When to Use This Skill
Use the SimPy skill when:
- Modeling discrete-event systems - Systems where events occur at irregular intervals
- Resource contention - Entities compete for limited resources (servers, machines, staff)
- Queue analysis - Studying waiting lines, service times, and throughput
- Process optimization - Analyzing manufacturing, logistics, or service processes
- Network simulation - Packet routing, bandwidth allocation, latency analysis
- Capacity planning - Determining optimal resource levels for desired performance
- System validation - Testing system behavior before implementation
Not suitable for:
- Continuous simulations with fixed time steps (consider SciPy ODE solvers)
- Independent processes without resource sharing
- Pure mathematical optimization (consider SciPy optimize)
Quick Start
Basic Simulation Structure
1import simpy
2
3def process(env, name):
4 """A simple process that waits and prints."""
5 print(f'{name} starting at {env.now}')
6 yield env.timeout(5)
7 print(f'{name} finishing at {env.now}')
8
9# Create environment
10env = simpy.Environment()
11
12# Start processes
13env.process(process(env, 'Process 1'))
14env.process(process(env, 'Process 2'))
15
16# Run simulation
17env.run(until=10)
Resource Usage Pattern
1import simpy
2
3def customer(env, name, resource):
4 """Customer requests resource, uses it, then releases."""
5 with resource.request() as req:
6 yield req # Wait for resource
7 print(f'{name} got resource at {env.now}')
8 yield env.timeout(3) # Use resource
9 print(f'{name} released resource at {env.now}')
10
11env = simpy.Environment()
12server = simpy.Resource(env, capacity=1)
13
14env.process(customer(env, 'Customer 1', server))
15env.process(customer(env, 'Customer 2', server))
16env.run()
Core Concepts
1. Environment
The simulation environment manages time and schedules events.
1import simpy
2
3# Standard environment (runs as fast as possible)
4env = simpy.Environment(initial_time=0)
5
6# Real-time environment (synchronized with wall-clock)
7import simpy.rt
8env_rt = simpy.rt.RealtimeEnvironment(factor=1.0)
9
10# Run simulation
11env.run(until=100) # Run until time 100
12env.run() # Run until no events remain
2. Processes
Processes are defined using Python generator functions (functions with yield statements).
1def my_process(env, param1, param2):
2 """Process that yields events to pause execution."""
3 print(f'Starting at {env.now}')
4
5 # Wait for time to pass
6 yield env.timeout(5)
7
8 print(f'Resumed at {env.now}')
9
10 # Wait for another event
11 yield env.timeout(3)
12
13 print(f'Done at {env.now}')
14 return 'result'
15
16# Start the process
17env.process(my_process(env, 'value1', 'value2'))
3. Events
Events are the fundamental mechanism for process synchronization. Processes yield events and resume when those events are triggered.
Common event types:
env.timeout(delay)- Wait for time to passresource.request()- Request a resourceenv.event()- Create a custom eventenv.process(func())- Process as an eventevent1 & event2- Wait for all events (AllOf)event1 | event2- Wait for any event (AnyOf)
Resources
SimPy provides several resource types for different scenarios. For comprehensive details, see references/resources.md.
Resource Types Summary
| Resource Type | Use Case |
|---|---|
| Resource | Limited capacity (servers, machines) |
| PriorityResource | Priority-based queuing |
| PreemptiveResource | High-priority can interrupt low-priority |
| Container | Bulk materials (fuel, water) |
| Store | Python object storage (FIFO) |
| FilterStore | Selective item retrieval |
| PriorityStore | Priority-ordered items |
Quick Reference
1import simpy
2
3env = simpy.Environment()
4
5# Basic resource (e.g., servers)
6resource = simpy.Resource(env, capacity=2)
7
8# Priority resource
9priority_resource = simpy.PriorityResource(env, capacity=1)
10
11# Container (e.g., fuel tank)
12fuel_tank = simpy.Container(env, capacity=100, init=50)
13
14# Store (e.g., warehouse)
15warehouse = simpy.Store(env, capacity=10)
Common Simulation Patterns
Pattern 1: Customer-Server Queue
1import simpy
2import random
3
4def customer(env, name, server):
5 arrival = env.now
6 with server.request() as req:
7 yield req
8 wait = env.now - arrival
9 print(f'{name} waited {wait:.2f}, served at {env.now}')
10 yield env.timeout(random.uniform(2, 4))
11
12def customer_generator(env, server):
13 i = 0
14 while True:
15 yield env.timeout(random.uniform(1, 3))
16 i += 1
17 env.process(customer(env, f'Customer {i}', server))
18
19env = simpy.Environment()
20server = simpy.Resource(env, capacity=2)
21env.process(customer_generator(env, server))
22env.run(until=20)
Pattern 2: Producer-Consumer
1import simpy
2
3def producer(env, store):
4 item_id = 0
5 while True:
6 yield env.timeout(2)
7 item = f'Item {item_id}'
8 yield store.put(item)
9 print(f'Produced {item} at {env.now}')
10 item_id += 1
11
12def consumer(env, store):
13 while True:
14 item = yield store.get()
15 print(f'Consumed {item} at {env.now}')
16 yield env.timeout(3)
17
18env = simpy.Environment()
19store = simpy.Store(env, capacity=10)
20env.process(producer(env, store))
21env.process(consumer(env, store))
22env.run(until=20)
Pattern 3: Parallel Task Execution
1import simpy
2
3def task(env, name, duration):
4 print(f'{name} starting at {env.now}')
5 yield env.timeout(duration)
6 print(f'{name} done at {env.now}')
7 return f'{name} result'
8
9def coordinator(env):
10 # Start tasks in parallel
11 task1 = env.process(task(env, 'Task 1', 5))
12 task2 = env.process(task(env, 'Task 2', 3))
13 task3 = env.process(task(env, 'Task 3', 4))
14
15 # Wait for all to complete
16 results = yield task1 & task2 & task3
17 print(f'All done at {env.now}')
18
19env = simpy.Environment()
20env.process(coordinator(env))
21env.run()
Workflow Guide
Step 1: Define the System
Identify:
- Entities: What moves through the system? (customers, parts, packets)
- Resources: What are the constraints? (servers, machines, bandwidth)
- Processes: What are the activities? (arrival, service, departure)
- Metrics: What to measure? (wait times, utilization, throughput)
Step 2: Implement Process Functions
Create generator functions for each process type:
1def entity_process(env, name, resources, parameters):
2 # Arrival logic
3 arrival_time = env.now
4
5 # Request resources
6 with resource.request() as req:
7 yield req
8
9 # Service logic
10 service_time = calculate_service_time(parameters)
11 yield env.timeout(service_time)
12
13 # Departure logic
14 collect_statistics(env.now - arrival_time)
Step 3: Set Up Monitoring
Use monitoring utilities to collect data. See references/monitoring.md for comprehensive techniques.
1from scripts.resource_monitor import ResourceMonitor
2
3# Create and monitor resource
4resource = simpy.Resource(env, capacity=2)
5monitor = ResourceMonitor(env, resource, "Server")
6
7# After simulation
8monitor.report()
Step 4: Run and Analyze
1# Run simulation
2env.run(until=simulation_time)
3
4# Generate reports
5monitor.report()
6stats.report()
7
8# Export data for further analysis
9monitor.export_csv('results.csv')
Advanced Features
Process Interaction
Processes can interact through events, process yields, and interrupts. See references/process-interaction.md for detailed patterns.
Key mechanisms:
- Event signaling: Shared events for coordination
- Process yields: Wait for other processes to complete
- Interrupts: Forcefully resume processes for preemption
Real-Time Simulations
Synchronize simulation with wall-clock time for hardware-in-the-loop or interactive applications. See references/real-time.md.
1import simpy.rt
2
3env = simpy.rt.RealtimeEnvironment(factor=1.0) # 1:1 time mapping
4# factor=0.5 means 1 sim unit = 0.5 seconds (2x faster)
Comprehensive Monitoring
Monitor processes, resources, and events. See references/monitoring.md for techniques including:
- State variable tracking
- Resource monkey-patching
- Event tracing
- Statistical collection
Scripts and Templates
basic_simulation_template.py
Complete template for building queue simulations with:
- Configurable parameters
- Statistics collection
- Customer generation
- Resource usage
- Report generation
Usage:
1from scripts.basic_simulation_template import SimulationConfig, run_simulation
2
3config = SimulationConfig()
4config.num_resources = 2
5config.sim_time = 100
6stats = run_simulation(config)
7stats.report()
resource_monitor.py
Reusable monitoring utilities:
ResourceMonitor- Track single resourceMultiResourceMonitor- Monitor multiple resourcesContainerMonitor- Track container levels- Automatic statistics calculation
- CSV export functionality
Usage:
1from scripts.resource_monitor import ResourceMonitor
2
3monitor = ResourceMonitor(env, resource, "My Resource")
4# ... run simulation ...
5monitor.report()
6monitor.export_csv('data.csv')
Reference Documentation
Detailed guides for specific topics:
references/resources.md- All resource types with examplesreferences/events.md- Event system and patternsreferences/process-interaction.md- Process synchronizationreferences/monitoring.md- Data collection techniquesreferences/real-time.md- Real-time simulation setup
Best Practices
- Generator functions: Always use
yieldin process functions - Resource context managers: Use
with resource.request() as req:for automatic cleanup - Reproducibility: Set
random.seed()for consistent results - Monitoring: Collect data throughout simulation, not just at the end
- Validation: Compare simple cases with analytical solutions
- Documentation: Comment process logic and parameter choices
- Modular design: Separate process logic, statistics, and configuration
Common Pitfalls
- Forgetting yield: Processes must yield events to pause
- Event reuse: Events can only be triggered once
- Resource leaks: Use context managers or ensure release
- Blocking operations: Avoid Python blocking calls in processes
- Time units: Stay consistent with time unit interpretation
- Deadlocks: Ensure at least one process can make progress
Example Use Cases
- Manufacturing: Machine scheduling, production lines, inventory management
- Healthcare: Emergency room simulation, patient flow, staff allocation
- Telecommunications: Network traffic, packet routing, bandwidth allocation
- Transportation: Traffic flow, logistics, vehicle routing
- Service operations: Call centers, retail checkout, appointment scheduling
- Computer systems: CPU scheduling, memory management, I/O operations
What Users Are Saying
Real feedback from the community
Environment Matrix
Dependencies
Framework Support
Context Window
Security & Privacy
Information
- Author
- davila7
- Updated
- 2026-01-30
- Category
- architecture-patterns