Mô phỏng Sự kiện Rời rạc bằng Python
Dr Diogo Costa
Adjunct Professor, University of Saskatchewan, Canada & CEO of ImpactBLUE-Scientific

Khung mô phỏng sự kiện rời rạc dựa trên tiến trình, chạy trên Python chuẩn
Dùng các hàm bộ sinh (generator) để định nghĩa tiến trình và sự kiện (đã học trong khóa Công cụ bắt buộc)
Khả năng mở rộng:
Hàm thông thường
def mygenerator():
return 10
return trả về giá trị và kết thúc hàmChạy hàm:
10
Hàm bộ sinh (generator)
def mygenerator():
yield 20
yield 12
yield trả về giá trị và tạm dừng, giữ trạng thái bên trong.Chạy bộ sinh:
20
12
1) Tạo Environment của SimPy
env = simpy.Environment()
2) Thêm hàm bộ sinh vào Environment
env.process()
3) Chạy mô hình
env.run()
4) Cho thời gian trong mô phỏng trôi qua
env.timeout()
5) Lấy thời gian mô phỏng hiện tại
env.now
1) Import gói SimPy
import simpy
2) Tạo hàm bộ sinh chứa các tiến trình
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!")
3) Tạo môi trường SimPy
env = simpy.Environment()
4) Thêm bộ sinh vào môi trường SimPy
env.process(traffic_light(env, "Leslie St.", 15))
env.process(traffic_light(env, "Arlington Av.", 30))
5) Chạy mô hình
env.run(until=90)
Kết quả trên console:
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!
Mô phỏng Sự kiện Rời rạc bằng Python