#!/usr/bin/env python
""" bank12: Multiple runs of the bank with a Monitor""" 
from SimPy.Simulation  import * 
from random import expovariate,seed

class Source(Process):
    """ Source generates customers randomly"""

    def generate(self,number,interval):       
        for i in range(number):
            c = Customer(name = "Customer%02d"%(i,))
            activate(c,c.visit(timeInBank=12.0))
            t = expovariate(1.0/interval)
            yield hold,self,t

def NoInSystem(R):
    """ The number of customers in the resource R
    in waitQ and active Q"""
    return (len(R.waitQ)+len(R.activeQ))

class Customer(Process):
    """ Customer arrives, is served and leaves """
        
    def visit(self,timeInBank=0):       
        arrive=now()
        Qlength = [NoInSystem(counter[i]) for i in range(Nc)]
        for i in range(Nc):
            if Qlength[i] ==0 or Qlength[i]==min(Qlength): join =i ; break
        yield request,self,counter[join]
        wait=now()-arrive
        waitMonitor.observe(wait)                                
        tib = expovariate(1.0/timeInBank)
        yield hold,self,tib
        yield release,self,counter[join]
 
def model(theseed=393939):
    global Nc,counter,waitMonitor                     
    seed(theseed)
    Nc = 2
    counter = [Resource(name="Clerk0"),Resource(name="Clerk1")]

    waitMonitor = Monitor()                                     

    initialize()
    source = Source('Source')
    activate(source,source.generate(50,10.0),0.0)               
    simulate(until=2000.0)
    return (waitMonitor.count(),waitMonitor.mean())        


# now carry out a number of replications
theseed = [393939,31555999,777999555,319999771]         
for i in range(4):
    result = model(theseed[i])
    print "Average wait for %4d completions was %6.2f"% result  

