【问题标题】:How to run a Poisson Process simulation?如何运行泊松过程模拟?
【发布时间】:2023-03-23 10:05:01
【问题描述】:

我正在尝试模拟以泊松率(每分钟 2.5 辆)进入停车位的汽车;停车时间与参数 45 分钟呈指数关系。这是我拥有的代码,但它似乎不起作用。我收到缩进错误,但 Python shell 中没有运行:

import matplotlib.pyplot as plt
import random, math
import numpy as np
import scipy as sp
import scipy.stats as stats
import matplotlib.pyplot as plt
import SimPy.Simulation as Sim


class G:
    maxTime = 960.0 # 16 hours * 60 min
    arrivalrate = 2.5 # per min
    parkingtime = 45 # mins
    parkedcars = 0
    seedVal = 9999


class Arrival(Sim.Process):
""" Source generates cars at random
Arrivals are at a time-dependent rate
"""
    def generate(self):
       i=0
       tnow = self.sim.now()
       while (self.sim.now() < 960 ):
          arrivalrate = 2.5 + 10 * math.sin(math.pi * tnow/12.0)
          t = random.expovariate(arrivalrate)
          yield Sim.hold, self, t
          c = Car(name="Car%02d" % (i), sim=self.sim)
          timeParking = random.expovariate(1.0/45)
          self.sim.activate(c, c.visit(timeParking))
          i += ArithmeticError
        
class Car(Sim.Process):
""" Cars arrives, parks for a while, and leaves
Maintain a count of the number of parked cars as cars arrive and leave
"""
    def visit(self, timeParking=0):
        self.sim.parkedcars += 1
        self.sim.parking.observe(self.sim.parkedcars)
        yield Sim.hold, self, timeParking
        self.sim.parkedcars -= 1
        self.sim.parking.observe(self.sim.parkedcars)




class Parkingsim(Sim.Simulation):
    def run(self, aseed):
        random.seed(seed)
        Sim.initialize()
        s = Arrival(name=’Arrivals’, sim=self)
        self.parking = Sim.Monitor(name=’Parking’, ylab=’cars’,
        tlab=’time’, sim=self)
        self.activate(s, s.generate(), at=0.0)
        self.simulate(until=G.maxTime)
        parkinglot = Parkingsim()
        parkinglot.run(1234)


plt.figure(figsize=(5.5,4))
plt.plot(parkinglot.parking.tseries(),parkinglot.parking.yseries())
plt.xlabel(’Time’)
plt.ylabel(’Number of cars’)
plt.xlim(0, 24)
plt.show()

【问题讨论】:

  • 欢迎来到 Stack Overflow。您能否在问题中包含错误回溯?

标签: python simulation


【解决方案1】:

我认为您在使用 SimPy 时遇到了问题。 python 2和python 3的版本有非常明显的变化。

https://simpy.readthedocs.io/en/latest/topical_guides/porting_from_simpy2.html 对如何处理从 2 到 3 的转变进行了精彩的讨论。

另外,当使用 """ 时,你应该有三个块

class Arrival(Sim.Process):
""" Source generates cars at random
Arrivals are at a time-dependent rate
"""

应该变成

class Arrival(Sim.Process):
    """ Source generates cars at random
    Arrivals are at a time-dependent rate"""

【讨论】:

  • 您的文档字符串注释与PEP 8 和PEP 257 相矛盾:“请注意,最重要的是,结束多行文档字符串的“”应该单独一行 i>”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 2017-06-27
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多