#!/usr/bin/env python
### lemmings.py from sip015.py (and sms015

from __future__ import generators
from SimPy.Simulation import *
from random import Random,expovariate,uniform
import unittest
""" Lemmings with a gatekeeper using SiPy

    Modified 2002 Sept 15 to use SimPy with resources (91a)

"""
__version__='$Revision: 1.0 $ $Date: 2004-05-15 11:09:32+02 $'

g = Random(333555)

class Generator(Process):
    """ generates Lemmings at random """
    def __init__(self,maxNumber,MeanInterval):
        Process.__init__(self)
        self.name = "gen"
        self.Int = MeanInterval
        self.maxNumber =maxNumber 
        self.idle=0
        self.total_idle=0

    def execute(self):
        ##print "%7.4f %s starts"%(now(), self.name)
        for i in range(self.maxNumber):
            L = Lemming("Lemming "+`i`)
            activate(L,L.execute(),delay=0)
            yield hold,self,g.expovariate(1.0/self.Int)
            print "%7.4f %s "%(now(), self.name)

gateKeeper=Resource(name='Gatekeeper')

class Lemming(Process):
    """ Lemmings request a gatekeeper and hold it for an exponential time """
    def __init__(self,name):
        Process.__init__(self)
        self.name = name
        
    def execute(self):       
        print "%7.4f %s says Hello World"%(now(),self.name)
        yield request,self,gateKeeper
        print "%7.4f %s At last  "%(now(), self.name)
        yield hold,self,3.3
        yield release,self,gateKeeper
        print "%7.4f %s says Geronimo  "%(now(), self.name)

def main():
    initialize()
    g = Generator(maxNumber=10,MeanInterval=1.0)
    activate(g,g.execute(),delay=0)
    simulate(until=20.0) #run simulation 


## ---------------------------------------------------
## tests
## ----------------------------------------------
  
class makeTestCase(unittest.TestCase):
    """Testing  
    """

    def testInit(self):
        """Test initialisation of conveyer """
        initialize()
        assert 1,'Generator initialise wrong'
 
    def testGen(self):
        """Test execution of Generatorr """
        #g = Random(333555)
        c = Generator(maxNumber=10,MeanInterval=1.0)
        activate(c,c.execute(),delay=0)
        scheduler(till=30.0) #run simulation 
        print "%7.4f simulation ends"%(now(),)
        assert abs(now() - 11.4037)< 0.001, 'Generator wrong'
       
def makeTestSuite():
    suite = unittest.TestSuite()
    testInit = makeTestCase("testInit")
    testGen = makeTestCase("testGen")
    suite.addTests([testInit,testGen,]) 
    return suite

initialize()
alltests = unittest.TestSuite((makeTestSuite(),))

runner = unittest.TextTestRunner()


TEST = 0
if TEST:
    runner.run(alltests)
else: main()

