simpy
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSimPy - Discrete-Event Simulation
SimPy - 离散事件仿真
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
SimPy是一个基于标准Python的流程式离散事件仿真框架。使用SimPy对实体(客户、车辆、数据包等)随时间相互作用并竞争共享资源(服务器、机器、带宽等)的系统进行建模。
核心能力:
- 使用Python生成器函数进行流程建模
- 共享资源管理(服务器、容器、存储)
- 事件驱动的调度与同步
- 与挂钟时间同步的实时仿真
- 全面的监控与数据收集
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)
在以下场景使用SimPy技能:
- 建模离散事件系统 - 事件以不规则间隔发生的系统
- 资源竞争 - 实体竞争有限资源(服务器、机器、员工)
- 队列分析 - 研究等待队列、服务时间和吞吐量
- 流程优化 - 分析制造、物流或服务流程
- 网络仿真 - 数据包路由、带宽分配、延迟分析
- 容量规划 - 确定实现预期性能的最优资源水平
- 系统验证 - 在实施前测试系统行为
不适用场景:
- 固定时间步长的连续仿真(考虑使用SciPy ODE求解器)
- 无资源共享的独立流程
- 纯数学优化(考虑使用SciPy optimize)
Quick Start
快速入门
Basic Simulation Structure
基础仿真结构
python
import simpy
def process(env, name):
"""A simple process that waits and prints."""
print(f'{name} starting at {env.now}')
yield env.timeout(5)
print(f'{name} finishing at {env.now}')python
import simpy
def process(env, name):
"""A simple process that waits and prints."""
print(f'{name} starting at {env.now}')
yield env.timeout(5)
print(f'{name} finishing at {env.now}')Create environment
Create environment
env = simpy.Environment()
env = simpy.Environment()
Start processes
Start processes
env.process(process(env, 'Process 1'))
env.process(process(env, 'Process 2'))
env.process(process(env, 'Process 1'))
env.process(process(env, 'Process 2'))
Run simulation
Run simulation
env.run(until=10)
undefinedenv.run(until=10)
undefinedResource Usage Pattern
资源使用模式
python
import simpy
def customer(env, name, resource):
"""Customer requests resource, uses it, then releases."""
with resource.request() as req:
yield req # Wait for resource
print(f'{name} got resource at {env.now}')
yield env.timeout(3) # Use resource
print(f'{name} released resource at {env.now}')
env = simpy.Environment()
server = simpy.Resource(env, capacity=1)
env.process(customer(env, 'Customer 1', server))
env.process(customer(env, 'Customer 2', server))
env.run()python
import simpy
def customer(env, name, resource):
"""Customer requests resource, uses it, then releases."""
with resource.request() as req:
yield req # Wait for resource
print(f'{name} got resource at {env.now}')
yield env.timeout(3) # Use resource
print(f'{name} released resource at {env.now}')
env = simpy.Environment()
server = simpy.Resource(env, capacity=1)
env.process(customer(env, 'Customer 1', server))
env.process(customer(env, 'Customer 2', server))
env.run()Core Concepts
核心概念
1. Environment
1. 环境
The simulation environment manages time and schedules events.
python
import simpy仿真环境管理时间并调度事件。
python
import simpyStandard environment (runs as fast as possible)
Standard environment (runs as fast as possible)
env = simpy.Environment(initial_time=0)
env = simpy.Environment(initial_time=0)
Real-time environment (synchronized with wall-clock)
Real-time environment (synchronized with wall-clock)
import simpy.rt
env_rt = simpy.rt.RealtimeEnvironment(factor=1.0)
import simpy.rt
env_rt = simpy.rt.RealtimeEnvironment(factor=1.0)
Run simulation
Run simulation
env.run(until=100) # Run until time 100
env.run() # Run until no events remain
undefinedenv.run(until=100) # Run until time 100
env.run() # Run until no events remain
undefined2. Processes
2. 流程
Processes are defined using Python generator functions (functions with statements).
yieldpython
def my_process(env, param1, param2):
"""Process that yields events to pause execution."""
print(f'Starting at {env.now}')
# Wait for time to pass
yield env.timeout(5)
print(f'Resumed at {env.now}')
# Wait for another event
yield env.timeout(3)
print(f'Done at {env.now}')
return 'result'流程使用Python生成器函数(带有语句的函数)定义。
yieldpython
def my_process(env, param1, param2):
"""Process that yields events to pause execution."""
print(f'Starting at {env.now}')
# Wait for time to pass
yield env.timeout(5)
print(f'Resumed at {env.now}')
# Wait for another event
yield env.timeout(3)
print(f'Done at {env.now}')
return 'result'Start the process
Start the process
env.process(my_process(env, 'value1', 'value2'))
undefinedenv.process(my_process(env, 'value1', 'value2'))
undefined3. Events
3. 事件
Events are the fundamental mechanism for process synchronization. Processes yield events and resume when those events are triggered.
Common event types:
- - Wait for time to pass
env.timeout(delay) - - Request a resource
resource.request() - - Create a custom event
env.event() - - Process as an event
env.process(func()) - - Wait for all events (AllOf)
event1 & event2 - - Wait for any event (AnyOf)
event1 | event2
事件是流程同步的基本机制。流程会让出事件,并在这些事件被触发时恢复执行。
常见事件类型:
- - 等待时间流逝
env.timeout(delay) - - 请求资源
resource.request() - - 创建自定义事件
env.event() - - 作为事件的流程
env.process(func()) - - 等待所有事件完成(AllOf)
event1 & event2 - - 等待任一事件完成(AnyOf)
event1 | event2
Resources
资源
SimPy provides several resource types for different scenarios. For comprehensive details, see .
references/resources.mdSimPy为不同场景提供了多种资源类型。有关详细信息,请参阅。
references/resources.mdResource 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 |
| 资源类型 | 适用场景 |
|---|---|
| Resource | 有限容量(服务器、机器) |
| PriorityResource | 基于优先级的排队 |
| PreemptiveResource | 高优先级可中断低优先级 |
| Container | 批量物料(燃料、水) |
| Store | Python对象存储(先进先出) |
| FilterStore | 选择性检索物品 |
| PriorityStore | 按优先级排序的物品 |
Quick Reference
快速参考
python
import simpy
env = simpy.Environment()python
import simpy
env = simpy.Environment()Basic resource (e.g., servers)
Basic resource (e.g., servers)
resource = simpy.Resource(env, capacity=2)
resource = simpy.Resource(env, capacity=2)
Priority resource
Priority resource
priority_resource = simpy.PriorityResource(env, capacity=1)
priority_resource = simpy.PriorityResource(env, capacity=1)
Container (e.g., fuel tank)
Container (e.g., fuel tank)
fuel_tank = simpy.Container(env, capacity=100, init=50)
fuel_tank = simpy.Container(env, capacity=100, init=50)
Store (e.g., warehouse)
Store (e.g., warehouse)
warehouse = simpy.Store(env, capacity=10)
undefinedwarehouse = simpy.Store(env, capacity=10)
undefinedCommon Simulation Patterns
常见仿真模式
Pattern 1: Customer-Server Queue
模式1:客户-服务器队列
python
import simpy
import random
def customer(env, name, server):
arrival = env.now
with server.request() as req:
yield req
wait = env.now - arrival
print(f'{name} waited {wait:.2f}, served at {env.now}')
yield env.timeout(random.uniform(2, 4))
def customer_generator(env, server):
i = 0
while True:
yield env.timeout(random.uniform(1, 3))
i += 1
env.process(customer(env, f'Customer {i}', server))
env = simpy.Environment()
server = simpy.Resource(env, capacity=2)
env.process(customer_generator(env, server))
env.run(until=20)python
import simpy
import random
def customer(env, name, server):
arrival = env.now
with server.request() as req:
yield req
wait = env.now - arrival
print(f'{name} waited {wait:.2f}, served at {env.now}')
yield env.timeout(random.uniform(2, 4))
def customer_generator(env, server):
i = 0
while True:
yield env.timeout(random.uniform(1, 3))
i += 1
env.process(customer(env, f'Customer {i}', server))
env = simpy.Environment()
server = simpy.Resource(env, capacity=2)
env.process(customer_generator(env, server))
env.run(until=20)Pattern 2: Producer-Consumer
模式2:生产者-消费者
python
import simpy
def producer(env, store):
item_id = 0
while True:
yield env.timeout(2)
item = f'Item {item_id}'
yield store.put(item)
print(f'Produced {item} at {env.now}')
item_id += 1
def consumer(env, store):
while True:
item = yield store.get()
print(f'Consumed {item} at {env.now}')
yield env.timeout(3)
env = simpy.Environment()
store = simpy.Store(env, capacity=10)
env.process(producer(env, store))
env.process(consumer(env, store))
env.run(until=20)python
import simpy
def producer(env, store):
item_id = 0
while True:
yield env.timeout(2)
item = f'Item {item_id}'
yield store.put(item)
print(f'Produced {item} at {env.now}')
item_id += 1
def consumer(env, store):
while True:
item = yield store.get()
print(f'Consumed {item} at {env.now}')
yield env.timeout(3)
env = simpy.Environment()
store = simpy.Store(env, capacity=10)
env.process(producer(env, store))
env.process(consumer(env, store))
env.run(until=20)Pattern 3: Parallel Task Execution
模式3:并行任务执行
python
import simpy
def task(env, name, duration):
print(f'{name} starting at {env.now}')
yield env.timeout(duration)
print(f'{name} done at {env.now}')
return f'{name} result'
def coordinator(env):
# Start tasks in parallel
task1 = env.process(task(env, 'Task 1', 5))
task2 = env.process(task(env, 'Task 2', 3))
task3 = env.process(task(env, 'Task 3', 4))
# Wait for all to complete
results = yield task1 & task2 & task3
print(f'All done at {env.now}')
env = simpy.Environment()
env.process(coordinator(env))
env.run()python
import simpy
def task(env, name, duration):
print(f'{name} starting at {env.now}')
yield env.timeout(duration)
print(f'{name} done at {env.now}')
return f'{name} result'
def coordinator(env):
# Start tasks in parallel
task1 = env.process(task(env, 'Task 1', 5))
task2 = env.process(task(env, 'Task 2', 3))
task3 = env.process(task(env, 'Task 3', 4))
# Wait for all to complete
results = yield task1 & task2 & task3
print(f'All done at {env.now}')
env = simpy.Environment()
env.process(coordinator(env))
env.run()Workflow Guide
工作流指南
Step 1: Define the System
步骤1:定义系统
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
步骤2:实现流程函数
Create generator functions for each process type:
python
def entity_process(env, name, resources, parameters):
# Arrival logic
arrival_time = env.now
# Request resources
with resource.request() as req:
yield req
# Service logic
service_time = calculate_service_time(parameters)
yield env.timeout(service_time)
# Departure logic
collect_statistics(env.now - arrival_time)为每种流程类型创建生成器函数:
python
def entity_process(env, name, resources, parameters):
# Arrival logic
arrival_time = env.now
# Request resources
with resource.request() as req:
yield req
# Service logic
service_time = calculate_service_time(parameters)
yield env.timeout(service_time)
# Departure logic
collect_statistics(env.now - arrival_time)Step 3: Set Up Monitoring
步骤3:设置监控
Use monitoring utilities to collect data. See for comprehensive techniques.
references/monitoring.mdpython
from scripts.resource_monitor import ResourceMonitor使用监控工具收集数据。有关全面技术,请参阅。
references/monitoring.mdpython
from scripts.resource_monitor import ResourceMonitorCreate and monitor resource
Create and monitor resource
resource = simpy.Resource(env, capacity=2)
monitor = ResourceMonitor(env, resource, "Server")
resource = simpy.Resource(env, capacity=2)
monitor = ResourceMonitor(env, resource, "Server")
After simulation
After simulation
monitor.report()
undefinedmonitor.report()
undefinedStep 4: Run and Analyze
步骤4:运行与分析
python
undefinedpython
undefinedRun simulation
Run simulation
env.run(until=simulation_time)
env.run(until=simulation_time)
Generate reports
Generate reports
monitor.report()
stats.report()
monitor.report()
stats.report()
Export data for further analysis
Export data for further analysis
monitor.export_csv('results.csv')
undefinedmonitor.export_csv('results.csv')
undefinedAdvanced Features
高级功能
Process Interaction
流程交互
Processes can interact through events, process yields, and interrupts. See for detailed patterns.
references/process-interaction.mdKey mechanisms:
- Event signaling: Shared events for coordination
- Process yields: Wait for other processes to complete
- Interrupts: Forcefully resume processes for preemption
流程可以通过事件、流程让出和中断进行交互。有关详细模式,请参阅。
references/process-interaction.md关键机制:
- 事件信号:用于协调的共享事件
- 流程让出:等待其他流程完成
- 中断:强制恢复流程以实现抢占
Real-Time Simulations
实时仿真
Synchronize simulation with wall-clock time for hardware-in-the-loop or interactive applications. See .
references/real-time.mdpython
import simpy.rt
env = simpy.rt.RealtimeEnvironment(factor=1.0) # 1:1 time mapping将仿真与挂钟时间同步,用于硬件在环或交互式应用。有关设置,请参阅。
references/real-time.mdpython
import simpy.rt
env = simpy.rt.RealtimeEnvironment(factor=1.0) # 1:1 time mappingfactor=0.5 means 1 sim unit = 0.5 seconds (2x faster)
factor=0.5 means 1 sim unit = 0.5 seconds (2x faster)
undefinedundefinedComprehensive Monitoring
全面监控
Monitor processes, resources, and events. See for techniques including:
references/monitoring.md- State variable tracking
- Resource monkey-patching
- Event tracing
- Statistical collection
监控流程、资源和事件。有关技术,请参阅,包括:
references/monitoring.md- 状态变量跟踪
- 资源猴子补丁
- 事件追踪
- 统计数据收集
Scripts and Templates
脚本与模板
basic_simulation_template.py
basic_simulation_template.py
Complete template for building queue simulations with:
- Configurable parameters
- Statistics collection
- Customer generation
- Resource usage
- Report generation
Usage:
python
from scripts.basic_simulation_template import SimulationConfig, run_simulation
config = SimulationConfig()
config.num_resources = 2
config.sim_time = 100
stats = run_simulation(config)
stats.report()用于构建队列仿真的完整模板,包含:
- 可配置参数
- 统计数据收集
- 客户生成
- 资源使用
- 报告生成
用法:
python
from scripts.basic_simulation_template import SimulationConfig, run_simulation
config = SimulationConfig()
config.num_resources = 2
config.sim_time = 100
stats = run_simulation(config)
stats.report()resource_monitor.py
resource_monitor.py
Reusable monitoring utilities:
- - Track single resource
ResourceMonitor - - Monitor multiple resources
MultiResourceMonitor - - Track container levels
ContainerMonitor - Automatic statistics calculation
- CSV export functionality
Usage:
python
from scripts.resource_monitor import ResourceMonitor
monitor = ResourceMonitor(env, resource, "My Resource")可复用的监控工具:
- - 跟踪单个资源
ResourceMonitor - - 监控多个资源
MultiResourceMonitor - - 跟踪容器水平
ContainerMonitor - 自动统计计算
- CSV导出功能
用法:
python
from scripts.resource_monitor import ResourceMonitor
monitor = ResourceMonitor(env, resource, "My Resource")... run simulation ...
... run simulation ...
monitor.report()
monitor.export_csv('data.csv')
undefinedmonitor.report()
monitor.export_csv('data.csv')
undefinedReference Documentation
参考文档
Detailed guides for specific topics:
- - All resource types with examples
references/resources.md - - Event system and patterns
references/events.md - - Process synchronization
references/process-interaction.md - - Data collection techniques
references/monitoring.md - - Real-time simulation setup
references/real-time.md
详细的特定主题指南:
- - 所有资源类型及示例
references/resources.md - - 事件系统与模式
references/events.md - - 流程同步
references/process-interaction.md - - 数据收集技术
references/monitoring.md - - 实时仿真设置
references/real-time.md
Best Practices
最佳实践
- Generator functions: Always use in process functions
yield - Resource context managers: Use for automatic cleanup
with resource.request() as req: - Reproducibility: Set for consistent results
random.seed() - 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
- 生成器函数:流程函数中始终使用
yield - 资源上下文管理器:使用进行自动清理
with resource.request() as req: - 可复现性:设置以获得一致结果
random.seed() - 监控:在仿真全程收集数据,而不仅仅是在结束时
- 验证:将简单案例与解析解进行比较
- 文档:注释流程逻辑和参数选择
- 模块化设计:分离流程逻辑、统计数据和配置
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
- 忘记yield:流程必须让出事件才能暂停
- 事件复用:事件只能被触发一次
- 资源泄漏:使用上下文管理器或确保释放资源
- 阻塞操作:避免在流程中使用Python阻塞调用
- 时间单位:保持时间单位解释的一致性
- 死锁:确保至少有一个流程可以推进
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
- 制造业:机器调度、生产线、库存管理
- 医疗保健:急诊室仿真、患者流动、人员配置
- 电信:网络流量、数据包路由、带宽分配
- 交通运输:交通流、物流、车辆路径规划
- 服务运营:呼叫中心、零售结账、预约调度
- 计算机系统:CPU调度、内存管理、I/O操作