在 Simpy 模拟中根据需要创建尽可能多的事件

问题描述

我正在使用 Simpy 进行 python 模拟,但我有一些砖墙。模拟有一个到达过程和一个运输过程。目标是在订单到达时运送尽可能多的订单,而不是让订单等待。这段代码为我提供了一个发货多于收到的订单的流程。

class LC:
    def __init__(self,env):
        self.dispatch=simpy.Container(env,capacity=100000,init=0)
        self.costs=simpy.Container(env,init=0)
        self.shipment_count=simpy.Container(env,capacity=10000,init=0)
        self.orders=simpy.Container(env,init=0)
def shipping(env,ship):
    while True:
        #yield env.timeout(i)
        print('Shipment was sent at %d' % (env.Now))
        time,weight=get_weight_n_time() ####other function that assigns weight and time of shipment
        if weight <=35:
            cost=get_cost(weight,0)###other function that calculates costs 
        else:
            cost=get_cost(weight,1)
        yield env.timeout(time)
        print ('Shipment of %d kgs where delivered after %d days with cost of $ %d' %(weight,time,cost))
        yield ship.dispatch.put(weight)
        yield ship.orders.get(1)
        yield ship.costs.put(cost)
        yield ship.shipment_count.put(1)

def arrival (env,ship):
    while True:
        print('Order arrived at %d'%(env.Now))
        yield ship.orders.put(1)
        yield env.timeout(1)
        

def shipment_gen(env,ship):
    
        env.process(arrival(env,ship))
        num_trucks=5
        for i in range(num_trucks):
           env.process(shipping(env,ship))
           yield env.timeout(0)
        
env = simpy.Environment()
ship=LC(env)
env.process(shipment_gen(env,ship))    
env.run(until=100)

当我添加一个变量来确定天气或不根据订单数量发货时,发货过程不会发生

class LC:
    def __init__(self,init=0)
        self.order=0
def shipping(env,weight=get_weight_n_time()
        if weight <=35:
            cost=get_cost(weight,0)
        else:
            cost=get_cost(weight,ship):
    while True:
        print('Order arrived at %d'%(env.Now))
        yield ship.orders.put(1)
        yield env.timeout(1)
        ship.order+=1
        

def shipment_gen(env,ship))
        # if ship.orders.level >0:
        #     num_trucks=get_number_trucks(ship)
        # else:
        #     num_trucks=get_number_trucks(ship)
        num_trucks=5
        for i in range(num_trucks):
            if ship.order>0:
                env.process(shipping(env,ship))
                yield env.timeout(0)
                ship.order-=1
            else:
                print('-')
env = simpy.Environment()
ship=LC(env)
env.process(shipment_gen(env,ship))    
env.run(until=100)

解决方法

您不需要在类中添加额外的ship.order。容器中有订单数量的信息(ship.orders.level)。所以删除ship.order并删除shipping_gen中的循环,你的代码就可以正常执行了。通过使用多线程,Simpy实现了多进程。如果在船类中添加额外的变量,可能会导致错误。

,

你想移动你的

yield ship.orders.get(1)

排到函数的顶部,以便您的卡车在执行其他任何操作之前等待订单到达?

还有 ship_gen 在时间 0 执行 if 语句,但您的订单计数器在时间 1 之前不是 =+1 所以在时间 0 你的订单计数器仍然是 0 所以你的 if 总是会做 else