SimPy 包简介

Python 中的离散事件模拟

Dr Diogo Costa

Adjunct Professor, University of Saskatchewan, Canada & CEO of ImpactBLUE-Scientific

什么是 SimPy?

SimPy 包徽标:用于 Python 的离散事件仿真

  • 基于标准 Python 的离散事件仿真框架(以进程为基础)

  • 使用生成器函数定义进程和事件(在工具箱先修课中介绍)

  • 可扩展性:

    • 模型可包含多个生成器
    • 每个生成器可含有多个进程
    • 进程可串行或并行运行
Python 中的离散事件模拟

普通函数 vs. 生成器函数

普通函数

def mygenerator():
    return 10
  • return 返回一个值并终止函数执行

执行函数:

10

生成器函数

def mygenerator():
    yield 20
    yield 12
  • yield 返回一个值并暂停执行,同时保留内部状态

执行生成器:

20
12
Python 中的离散事件模拟

SimPy 关键方法汇总

1) 创建 SimPy 环境

env = simpy.Environment()

2) 将生成器函数加入 SimPy 环境

env.process()

3) 运行模型

env.run()

4) 在仿真中让时间流逝

env.timeout()

5) 获取当前仿真时间

env.now
Python 中的离散事件模拟

红绿灯:构建 SimPy 模型

1) 导入 SimPy

import simpy

2) 创建包含进程的生成器函数

def traffic_light(env, name, timestep):
     while True:
        yield env.timeout(timestep)
        print(f"Time {env.now:02d} sec | Traffic light at {name} | Red light!")
        yield env.timeout(timestep)
        print(f"Time {env.now:02d} sec | Traffic light at {name} | Yellow Light!")
        yield env.timeout(timestep)
        print(f"Time {env.now:02d} sec | Traffic light at {name} | Green Light!")
Python 中的离散事件模拟

红绿灯:构建 SimPy 模型

3) 创建 SimPy 仿真环境

env = simpy.Environment()

4) 将生成器加入 SimPy 环境

env.process(traffic_light(env, "Leslie St.", 15))
env.process(traffic_light(env, "Arlington Av.", 30))

5) 运行模型

env.run(until=90)
Python 中的离散事件模拟

红绿灯:模型输出

控制台输出:

Time 15 sec  |  Traffic light at Leslie St.     |  Red light!
Time 30 sec  |  Traffic light at Arlington Av.  |  Red light!
Time 30 sec  |  Traffic light at Leslie St.     |  Yellow Light!
Time 45 sec  |  Traffic light at Leslie St.     |  Green Light!
Time 60 sec  |  Traffic light at Arlington Av.  |  Yellow Light!
Time 60 sec  |  Traffic light at Leslie St.     |  Red light!
Time 75 sec  |  Traffic light at Leslie St.     |  Yellow Light!
Python 中的离散事件模拟

让我们来练习!

Python 中的离散事件模拟

Preparing Video For Download...