这是一种方法
"""
Simple simulation of several bike rental stations
Stations are modeled with containers so bikes can be returned
to a station different from where it was rented from
programer: Michael R. Gibbs
"""
import simpy
import random
# scenario attributes
station_names = ['A','B']
rent_probs = [.9,.1]
return_probs = [.5,.5]
bikes_per_station = 5
def rent_proc(env, id, station_names, rent_probs, return_probs, station_map):
"""
Models the process of:
selecting a station
renting a bike
using a bike
returning a bike (can be different station)
"""
#select a station
name = random.choices(station_names,weights=rent_probs)
name = name[0]
station = station_map[name]
print(f'{env.now}: id:{id} has arrived at station {name} q-len:{len(station.get_queue)} and {station.level} bikes')
# get a bike
yield station.get(1)
print(f'{env.now}: id:{id} has rented bike at station {name} q-len:{len(station.get_queue)} and {station.level} bikes')
# use bike
yield env.timeout(random.triangular(1,5,3))
# return bike
name = random.choices(station_names,weights=return_probs)
name = name[0]
station = station_map[name]
yield station.put(1)
print(f'{env.now}: id:{id} has returned bike at station {name} q-len:{len(station.get_queue)} and {station.level} bikes')
def gen_arrivals(env, station_names, rent_probs, return_probs, station_map):
"""
Generates arrivales to the rental stations
"""
cnt = 0
while True:
yield env.timeout(random.expovariate(2.5))
cnt += 1
env.process(rent_proc(env,cnt,station_names,rent_probs,return_probs, station_map))
# set up
env = simpy.Environment()
# create station based on name list
cap = len(station_names) * bikes_per_station
station_map = {
name: simpy.Container(env, init=bikes_per_station, capacity=cap)
for name in station_names
}
# start generation arrivals
env.process(gen_arrivals(env, station_names, rent_probs, return_probs, station_map))
# start sim
env.run(100)