Simpy 模擬排隊系統(tǒng)

以下代碼是模擬了一個 M/M/c/k/n 系統(tǒng)
M 顧客以指數(shù)分布達到
M 服務(wù)顧客的事件服從指數(shù)分布
c 隊列人數(shù)上限
k 服務(wù)臺的數(shù)目
n 最長等待時間

項目地址:
https://github.com/eftales/PythonDemo/blob/master/%E7%A6%BB%E6%95%A3%E4%BA%8B%E4%BB%B6%E4%BB%BF%E7%9C%9F/simpyDemo.py

'''
基礎(chǔ)知識:
1. random.expovariate(miu) 生成均值為 1/miu 的指數(shù)分布的隨機數(shù) 
2. 泊松過程的強度參數(shù)的意義:如果泊松過程的強度參數(shù)為 lambda,則在單位時間上新增一次的概率為 lambda梧税,lambda 越大事件越可能發(fā)生
3. 泊松事件的事件間隔彼此獨立且服從參數(shù)為 lambda 的指數(shù)分布
4. ρ = λ/μ 
5. 平均等待時間 = ρ/(μ-λ)
6. 平均隊列長度(包含正在被服務(wù)的人) = λ/(μ-λ)
'''

'''
實現(xiàn)的細節(jié):
1. 統(tǒng)計函數(shù)沒有將仿真結(jié)束時沒有被服務(wù)完的人算入
'''

import simpy
import random
from time import time
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

## 隨機種子
randomSeed = time() # time()

## 指數(shù)分布的均值
miuService = 1  # 單位時間平均離開 1 個人
lambdaReachInterval = 0.5  # 單位時間平均來 0.5 個人

## 服務(wù)臺的數(shù)目
numService = 1

## 仿真程序運行的時間 min
Until = 100

## 系統(tǒng)容量
systemCapacity = None # None 表示無容量限制 max(10,numService)

## 最大等待時間 超過這個事件之后顧客會離開隊伍
maxWaiteTime = Until

## 初始隊列長度
initLen = 1

## 客戶類
class Customer(object):
    def __init__(self,index_,startTime_,queueLenStart_,reachInterval_):
        self.index = index_ # 第幾個來到隊列中來的
        self.startTime = startTime_ # 開始時間
        self.getServedTime = None # 開始被服務(wù)的時間
        self.endTime = None # 結(jié)束時間 
        self.queueLenStart = queueLenStart_ # 開始排隊時隊列長度
        self.queueLenEnd = None # 結(jié)束排隊時隊列長度
        self.reachInterval = reachInterval_  # 空閑了多長時間本 customer 才到達


## 顧客列表
customerList = []

## 當(dāng)前隊列長度
queueLen = 0


class System(object):
    def __init__(self, env, numService,miuService_):
        self.env = env
        self.service = simpy.Resource(env, numService)
        self.miuService =  miuService_

        
    def beingServed(self):
        # 服務(wù)事件為均值為 miuService 的指數(shù)分布
        yield self.env.timeout(random.expovariate(self.miuService))

def inoutQueue(env, moviegoer, sys):
    # 等待被服務(wù) 
    with sys.service.request() as request:  #觀眾向收銀員請求購票
        yield request  | env.timeout(maxWaiteTime)  #觀眾等待收銀員完成面的服務(wù)野来,超過最長等待事件maxCashierTime就會離開
        global customerList
        customerList[moviegoer].getServedTime = env.now
        yield env.process(sys.beingServed()) 
            
    # 完善統(tǒng)計資料
    global queueLen
    queueLen -= 1
    customerList[moviegoer].endTime = env.now
    customerList[moviegoer].queueLenEnd = queueLen


def runSys(env, numService,miuService):
    sys = System(env, numService, miuService)
    global initLen,customerList
    moviegoer = initLen
    for moviegoer in range(initLen):#初始化設(shè)置,開始的隊伍長度為 initLen
        customerList.append(Customer(moviegoer,env.now,initLen,0))
        env.process(inoutQueue(env, moviegoer, sys))
    global queueLen
    queueLen = initLen 
    while True:
        reachInterval_ = random.expovariate(lambdaReachInterval)
        yield env.timeout(reachInterval_) # 顧客到達時間滿足 lambdaReachInterval 的指數(shù)分布
        if systemCapacity == None or queueLen <= systemCapacity:  
            moviegoer += 1
            queueLen += 1
            customerList.append(Customer(moviegoer,env.now,queueLen,reachInterval_))
            env.process(inoutQueue(env, moviegoer, sys))

def plotSimRes(customerList):
    #! 初始設(shè)置
    # 用于正常顯示中文標(biāo)簽
    plt.rcParams['font.sans-serif']=['SimHei']
    # 用來正常顯示負號
    plt.rcParams['axes.unicode_minus']=False


    def plotTime_Service(customerList):
        plt.figure(figsize=(14,7)) # 新建一個畫布
        plt.xlabel('時間/min')
        plt.ylabel('用戶序列')
        servedUser = 0
        for customer in customerList:
            y = [customer.index]*2

            # 等待時間 
            if customer.endTime == None:
                customer.endTime = Until
                color = 'r'
            else:
                color = 'b'
                servedUser += 1
            x = [customer.startTime,customer.endTime]
            plt.plot(x,y,color=color)

            # 被服務(wù)的時間
            if customer.getServedTime != None and customer.endTime != Until:
                color = 'g'
                x = [customer.getServedTime,customer.endTime]
                plt.plot(x,y,color=color)

        plt.title("時間-隊列-服務(wù)圖 服務(wù)的用戶數(shù):%d" % servedUser)

    def plotQueueLen_time(customerList):
        plt.figure(figsize=(14,7)) # 新建一個畫布
        plt.xlabel('時間/min')
        plt.ylabel('隊列長度/人')
        

        queueLenList = []

        for customer in customerList:
            queueLenList.append([customer.startTime,customer.queueLenStart])
            queueLenList.append([customer.endTime,customer.queueLenEnd])
        queueLenList.sort()

        preTime = 0
        preLen = 0
        integralQueueLen = 0
        maxLen = 0
        global Until
        timeInCount = Until
        for each in queueLenList:
            if each[1] != None:
                x = [each[0]] * 2
                y = [0,each[1]]
                plt.plot(x,y,color='b')
                plt.plot(each[0],each[1],'bo')
            else:
                timeInCount = preTime
                break # 沒有把仿真結(jié)束時未被服務(wù)完的人算進來
            integralQueueLen += (each[0] - preTime) * preLen
            preTime = each[0]
            preLen = each[1]
            maxLen = max(maxLen,each[1])
        
        averageQueueLen = integralQueueLen / timeInCount
        plt.title("時間-隊列長度圖 平均隊列長度:%f" % averageQueueLen)
        
        
    def plotWaiteTime_time(customerList):
        plt.figure(figsize=(14,7)) # 新建一個畫布
        plt.xlabel('時間/min')
        plt.ylabel('等待時間/min')
        

        queueLenList = []
        peopleInCount = 0
        for customer in customerList:
            if customer.getServedTime != None:
                peopleInCount += 1
                queueLenList.append([customer.startTime,customer.getServedTime - customer.startTime])
        queueLenList.sort()
        
        integralWaiteTime = 0
        maxWaiteTime = 0
        for each in queueLenList:
            x = [each[0]] * 2
            y = [0,each[1]]
            integralWaiteTime += each[1]
            maxWaiteTime = max(maxWaiteTime,each[1])
            plt.plot(x,y,color='b')
            plt.plot(each[0],each[1],'bo')

        averageWaiteTime = integralWaiteTime / peopleInCount
        
        plt.title("時間-等待時間圖 平均等待時間:%f" % averageWaiteTime)

    def plotWaiteTime_time_QueueLen(customerList):
        fig = plt.figure(figsize=(14,7)) # 新建一個畫布
        ax = fig.gca(projection='3d')
        plt.xlabel('時間/min')
        plt.ylabel('隊列長度/人')
        ax.set_zlabel('等待時間/min')
        plt.title("時間-隊列長度-等待時間圖")

        queueLenList = [] # 格式:時間 隊列長度 等待時間

        global Until
        for customer in customerList:
            if customer.getServedTime != None: # 沒有把仿真結(jié)束時未被服務(wù)完的人算進來
                queueLenList.append([customer.startTime,customer.queueLenStart,customer.getServedTime-customer.startTime])
        queueLenList.sort(key=lambda x:x[0])

        for each in queueLenList:
            if each[1] != None:
                x = [each[0]]*2
                y = [each[1]]*2
                z = [0,each[2]]
                ax.plot(x,y,z,color='b')
                ax.scatter(x[1],y[1],z[1],c='b')

    plotTime_Service(customerList)
    plotQueueLen_time(customerList)
    plotWaiteTime_time(customerList)
    # plotWaiteTime_time_QueueLen(customerList)
    plt.show()



def main():
    random.seed(randomSeed)
    #運行模擬場景
    env = simpy.Environment()
    env.process(runSys(env, numService,miuService))
    env.run(until=Until) 
    
    #查看統(tǒng)計結(jié)果
    plotSimRes(customerList)

main()


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末扁位,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌萎胰,老刑警劉巖纲熏,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件妆丘,死亡現(xiàn)場離奇詭異,居然都是意外死亡局劲,警方通過查閱死者的電腦和手機勺拣,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鱼填,“玉大人药有,你說我怎么就攤上這事。” “怎么了愤惰?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵苇经,是天一觀的道長。 經(jīng)常有香客問我宦言,道長扇单,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任奠旺,我火速辦了婚禮令花,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘凉倚。我一直安慰自己兼都,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布稽寒。 她就那樣靜靜地躺著扮碧,像睡著了一般。 火紅的嫁衣襯著肌膚如雪杏糙。 梳的紋絲不亂的頭發(fā)上慎王,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天,我揣著相機與錄音宏侍,去河邊找鬼赖淤。 笑死,一個胖子當(dāng)著我的面吹牛谅河,可吹牛的內(nèi)容都是我干的咱旱。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼绷耍,長吁一口氣:“原來是場噩夢啊……” “哼吐限!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起褂始,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤诸典,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后崎苗,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體狐粱,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年胆数,在試婚紗的時候發(fā)現(xiàn)自己被綠了肌蜻。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡幅慌,死狀恐怖宋欺,靈堂內(nèi)的尸體忽然破棺而出轰豆,到底是詐尸還是另有隱情胰伍,我是刑警寧澤齿诞,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站骂租,受9級特大地震影響祷杈,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜渗饮,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一但汞、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧互站,春花似錦私蕾、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至翠胰,卻和暖如春容贝,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背之景。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工斤富, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人锻狗。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓满力,卻偏偏與公主長得像,于是被迫代替她去往敵國和親轻纪。 傳聞我的和親對象是個殘疾皇子脚囊,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容