simpy

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SimPy - 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:
  1. Modeling discrete-event systems - Systems where events occur at irregular intervals
  2. Resource contention - Entities compete for limited resources (servers, machines, staff)
  3. Queue analysis - Studying waiting lines, service times, and throughput
  4. Process optimization - Analyzing manufacturing, logistics, or service processes
  5. Network simulation - Packet routing, bandwidth allocation, latency analysis
  6. Capacity planning - Determining optimal resource levels for desired performance
  7. 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技能:
  1. 建模离散事件系统 - 事件以不规则间隔发生的系统
  2. 资源竞争 - 实体竞争有限资源(服务器、机器、员工)
  3. 队列分析 - 研究等待队列、服务时间和吞吐量
  4. 流程优化 - 分析制造、物流或服务流程
  5. 网络仿真 - 数据包路由、带宽分配、延迟分析
  6. 容量规划 - 确定实现预期性能的最优资源水平
  7. 系统验证 - 在实施前测试系统行为
不适用场景:
  • 固定时间步长的连续仿真(考虑使用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)
undefined
env.run(until=10)
undefined

Resource 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 simpy

Standard 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
undefined
env.run(until=100) # Run until time 100 env.run() # Run until no events remain
undefined

2. Processes

2. 流程

Processes are defined using Python generator functions (functions with
yield
statements).
python
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生成器函数(带有
yield
语句的函数)定义。
python
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'))
undefined
env.process(my_process(env, 'value1', 'value2'))
undefined

3. Events

3. 事件

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 pass
  • resource.request()
    - Request a resource
  • env.event()
    - Create a custom event
  • env.process(func())
    - Process as an event
  • event1 & event2
    - Wait for all events (AllOf)
  • event1 | event2
    - Wait for any event (AnyOf)
事件是流程同步的基本机制。流程会让出事件,并在这些事件被触发时恢复执行。
常见事件类型:
  • env.timeout(delay)
    - 等待时间流逝
  • resource.request()
    - 请求资源
  • env.event()
    - 创建自定义事件
  • env.process(func())
    - 作为事件的流程
  • event1 & event2
    - 等待所有事件完成(AllOf)
  • event1 | event2
    - 等待任一事件完成(AnyOf)

Resources

资源

SimPy provides several resource types for different scenarios. For comprehensive details, see
references/resources.md
.
SimPy为不同场景提供了多种资源类型。有关详细信息,请参阅
references/resources.md

Resource Types Summary

资源类型摘要

Resource TypeUse Case
ResourceLimited capacity (servers, machines)
PriorityResourcePriority-based queuing
PreemptiveResourceHigh-priority can interrupt low-priority
ContainerBulk materials (fuel, water)
StorePython object storage (FIFO)
FilterStoreSelective item retrieval
PriorityStorePriority-ordered items
资源类型适用场景
Resource有限容量(服务器、机器)
PriorityResource基于优先级的排队
PreemptiveResource高优先级可中断低优先级
Container批量物料(燃料、水)
StorePython对象存储(先进先出)
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)
undefined
warehouse = simpy.Store(env, capacity=10)
undefined

Common 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
references/monitoring.md
for comprehensive techniques.
python
from scripts.resource_monitor import ResourceMonitor
使用监控工具收集数据。有关全面技术,请参阅
references/monitoring.md
python
from scripts.resource_monitor import ResourceMonitor

Create 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()
undefined
monitor.report()
undefined

Step 4: Run and Analyze

步骤4:运行与分析

python
undefined
python
undefined

Run 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')
undefined
monitor.export_csv('results.csv')
undefined

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
流程可以通过事件、流程让出和中断进行交互。有关详细模式,请参阅
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.md
.
python
import simpy.rt

env = simpy.rt.RealtimeEnvironment(factor=1.0)  # 1:1 time mapping
将仿真与挂钟时间同步,用于硬件在环或交互式应用。有关设置,请参阅
references/real-time.md
python
import simpy.rt

env = simpy.rt.RealtimeEnvironment(factor=1.0)  # 1:1 time mapping

factor=0.5 means 1 sim unit = 0.5 seconds (2x faster)

factor=0.5 means 1 sim unit = 0.5 seconds (2x faster)

undefined
undefined

Comprehensive Monitoring

全面监控

Monitor processes, resources, and events. See
references/monitoring.md
for techniques including:
  • 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:
  • ResourceMonitor
    - Track single resource
  • MultiResourceMonitor
    - Monitor multiple resources
  • ContainerMonitor
    - Track container levels
  • 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')
undefined
monitor.report() monitor.export_csv('data.csv')
undefined

Reference Documentation

参考文档

Detailed guides for specific topics:
  • references/resources.md
    - All resource types with examples
  • references/events.md
    - Event system and patterns
  • references/process-interaction.md
    - Process synchronization
  • references/monitoring.md
    - Data collection techniques
  • references/real-time.md
    - Real-time simulation setup
详细的特定主题指南:
  • references/resources.md
    - 所有资源类型及示例
  • references/events.md
    - 事件系统与模式
  • references/process-interaction.md
    - 流程同步
  • references/monitoring.md
    - 数据收集技术
  • references/real-time.md
    - 实时仿真设置

Best Practices

最佳实践

  1. Generator functions: Always use
    yield
    in process functions
  2. Resource context managers: Use
    with resource.request() as req:
    for automatic cleanup
  3. Reproducibility: Set
    random.seed()
    for consistent results
  4. Monitoring: Collect data throughout simulation, not just at the end
  5. Validation: Compare simple cases with analytical solutions
  6. Documentation: Comment process logic and parameter choices
  7. Modular design: Separate process logic, statistics, and configuration
  1. 生成器函数:流程函数中始终使用
    yield
  2. 资源上下文管理器:使用
    with resource.request() as req:
    进行自动清理
  3. 可复现性:设置
    random.seed()
    以获得一致结果
  4. 监控:在仿真全程收集数据,而不仅仅是在结束时
  5. 验证:将简单案例与解析解进行比较
  6. 文档:注释流程逻辑和参数选择
  7. 模块化设计:分离流程逻辑、统计数据和配置

Common Pitfalls

常见陷阱

  1. Forgetting yield: Processes must yield events to pause
  2. Event reuse: Events can only be triggered once
  3. Resource leaks: Use context managers or ensure release
  4. Blocking operations: Avoid Python blocking calls in processes
  5. Time units: Stay consistent with time unit interpretation
  6. Deadlocks: Ensure at least one process can make progress
  1. 忘记yield:流程必须让出事件才能暂停
  2. 事件复用:事件只能被触发一次
  3. 资源泄漏:使用上下文管理器或确保释放资源
  4. 阻塞操作:避免在流程中使用Python阻塞调用
  5. 时间单位:保持时间单位解释的一致性
  6. 死锁:确保至少有一个流程可以推进

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操作