18
Introduction Classes Opeartions and functions Examples References SimPy: Simulation in Python Roberto Solar Gallardo December 6, 2012

Simpy

Embed Size (px)

DESCRIPTION

Manual Simulation in Python

Citation preview

  • Introduction Classes Opeartions and functions Examples References

    SimPy: Simulation in Python

    Roberto Solar Gallardo

    December 6, 2012

  • Introduction Classes Opeartions and functions Examples References

    What is SimPy?

    object-oriented process-based discrete-event simulation languagebased on standard Python

    Features

    use of pythons generators

    declare a function that behaves like an iteratora generator is resumable and can branch control elsewheresemi-coroutines

    coroutines - functions that alternate execution with each other

    the exit/re-entry points are marked by pythons yield keywords

  • Introduction Classes Opeartions and functions Examples References

    Simpy programming

    The scheduler

    a list of future events is maintained automatically

    the scheduler is started by the SimPy command simulate

    Elements of discrete-event models

    Active elements: entities (Process)

    Passive elements: resources (Resource, Level and Store)

    General Structure of a SimPy program

    define one or more SimPy classes and objects

    call the function initialize

    create and activate at least one of the active entities

    start the simulation by calling simulate

    report results

  • Introduction Classes Opeartions and functions Examples References

    How it works

    Simulation. t - Simpys clock

    Simulation. timestamps (heap) - event list (t,priority,instance)

    1 class Cliente(Process):

    2 def visitar(self,tiempoDeServicio):

    3 print now(),self.name, ": He llegado"

    4 yield hold,self,tiempoDeServicio

    5 print now(),self.name, ": Ya me voy"

    6

    7 initialize()

    8 c=Cliente(name="Roberto")

    9 activate(c,c.visitar(tiempoDeServicio=1.0),at=1.0)

    10 simulate(until=10.0)

    Analysis

    line 7: t=0 and timestamps=[]

    line 9: put c into timestamps (1.0,indefined,c)

    line 4: put self into timestamps (now()+timehold,indefined,self)

  • Introduction Classes Opeartions and functions Examples References

    Processes

    Features

    model an entity with activities

    i.e. instances of some class that inherits from SimPys Processclass

    each entity has a standard method - Process execution method

    Process execution method (PEM)

    specifies entities actions in detail

    each PEM runs in parallel with (and may interact with) thePEMs of other entities

  • Introduction Classes Opeartions and functions Examples References

    Resource facilities

    simulates something to be queued for

    Resources

    model a service point with one or more identical service units

    Levels

    model a container of homogenous material which can be discrete(boxes, bricks, etc) or continuous (fluid)

    Stores

    model a list of individual objects

  • Introduction Classes Opeartions and functions Examples References

    Monitors

    collects simulation data for analysis, statistics, etc

    Monitors

    used to compile summary statistics such as waiting times andqueue lengths

    simple averages and variances

    time-weighted averages

    histograms

    Tallys

    is an alternative to Monitor that does essentially the same job butuses less storage space at some cost of speed and flexibility

  • Introduction Classes Opeartions and functions Examples References

    Operations and functions (1)

    Process interaction statements

    activate(pi , pi .pem()[, at = t|delay = period ]) - make aprocess instance (pi ) active

    reactivate(pi [, at = now()|delay = 0][, prior = false]) - makea process intance (pi ) active (previously-passivated)

    cancel(pi ) - cancels all the events associated with a processintance (pi )

    interrupt(pi ) - interrupt pi s current activity

    Simulation control statements

    initialize() - set simulated time to zero

    simulate(until=T ) - execute scheduled activities till T

    stopSimulation() - force immediate end of simulation

  • Introduction Classes Opeartions and functions Examples References

    Operations and functions (2)

    Scheduling statements

    yield hold,self,T - reactivate self after T

    yield passivate,self - make self passive

    yield request,self,resource - request use of resource

    yield release,self,resource - give up use of resource

    yield put,self,level,N - level is increased N units

    yield get,self,level,N - level is decreased N units

  • Introduction Classes Opeartions and functions Examples References

    Cliente simple

    from SimPy.Simulation import *

    class Cliente(Process):

    def visitar(self,tiempoDeServicio):

    print now(),self.name, ": He llegado"

    yield hold,self,tiempoDeServicio

    print now(),self.name, ": Ya me voy"

    initialize()

    c=Cliente(name="Roberto")

    activate(c,c.visitar(tiempoDeServicio=1.0),at=1.0)

    simulate(until=10.0)

    Output1.0 Roberto : He llegado

    2.0 Roberto : Ya me voy

  • Introduction Classes Opeartions and functions Examples References

    Cliente simple, llegada aleatoria

    from SimPy.Simulation import *

    from random import gammavariate, seed

    class Cliente(Process):

    def visitar(self,tiempoDeServicio):

    print now(),self.name,": He llegado"

    yield hold,self,tiempoDeServicio

    print now(),self.name,": Ya me voy"

    seed()

    initialize()

    c=Cliente(name="Roberto");

    inicio=gammavariate(4,1);

    activate(c,c.visitar(tiempoDeServicio=1.0),at=inicio)

    simulate(until=10.0);

    Output7.92130825474 Roberto : He llegado

    8.92130825474 Roberto : Ya me voy

  • Introduction Classes Opeartions and functions Examples References

    Varios clientes

    from SimPy.Simulation import *

    class Cliente(Process):

    def visitar(self,tiempoDeServicio):

    print now(),self.name, ": He llegado"

    yield hold,self,tiempoDeServicio

    print now(),self.name, ": Ya me voy"

    initialize()

    c1=Cliente(name="Roberto")

    c2=Cliente(name="Alonso")

    c3=Cliente(name="Veronica")

    activate(c1,c1.visitar(tiempoDeServicio=3.0),at=1.0)

    activate(c2,c2.visitar(tiempoDeServicio=2.4),at=3.0)

    activate(c3,c3.visitar(tiempoDeServicio=1.5),at=5.0)

    simulate(until=100.0)

    Output1.0 Roberto : He llegado

    3.0 Alonso : He llegado

    4.0 Roberto : Ya me voy

    5.0 Veronica : He llegado

    5.4 Alonso : Ya me voy

    6.5 Veronica : Ya me voy

  • Introduction Classes Opeartions and functions Examples References

    Muchos clientes

    from SimPy.Simulation import *

    class Generador(Process):

    def generar(self,totalDeClientes,tasaDeLlegada):

    for i in range(totalDeClientes):

    c=Cliente(name="Cli-%02d"%(i))

    activate(c,c.visitar(tiempoDeServicio=3.5))

    yield hold,self,tasaDeLlegada

    class Cliente(Process):

    def visitar(self,tiempoDeServicio):

    print "%2.1f %s: He llegado"%(now(),self.name)

    yield hold,self,tiempoDeServicio

    print "%2.1f %s: Ya me voy"%(now(),self.name)

    initialize()

    g=Generador();

    activate(g,g.generar(totalDeClientes=5,tasaDeLlegada=2.5))

    simulate(until=100.0)

    Output0.0 Cli-00: He llegado

    2.5 Cli-01: He llegado

    3.5 Cli-00: Ya me voy

    5.0 Cli-02: He llegado

    6.0 Cli-01: Ya me voy

    7.5 Cli-03: He llegado

    8.5 Cli-02: Ya me voy

    10.0 Cli-04: He llegado

    11.0 Cli-03: Ya me voy

    13.5 Cli-04: Ya me voy

  • Introduction Classes Opeartions and functions Examples References

    Muchos clientes, un recurso

    from SimPy.Simulation import *

    from random import expovariate,seed

    class Generador(Process):

    def generar(self,totalDeClientes,tasaDeLlegada,recurso):

    for i in range(totalDeClientes):

    c=Cliente(name="Cli-%02d"%(i))

    activate(c,c.visitar(tiempoDeServicio=2.7,recurso=recurso))

    t=expovariate(1.0/tasaDeLlegada);

    yield hold,self,t

    class Cliente(Process):

    def visitar(self,tiempoDeServicio=0,recurso=None):

    llegada=now()

    print "%2.1f %s: He llegado"%(now(),self.name)

    yield request,self,recurso

    tiempoDeEspera=now()-llegada;

    print "%2.1f %s: Tiempo de espera %2.1f"%(now(),self.name,tiempoDeEspera)

    yield hold,self,tiempoDeServicio

    yield release,self,recurso

    print "%2.1f %s: Ya me voy"%(now(),self.name)

    recurso=Resource(name="Contador",unitName="Cajero");

    seed()

    initialize()

    g=Generador();

    activate(g,g.generar(totalDeClientes=3,tasaDeLlegada=3.0,recurso=recurso),at=0.0)

    simulate(until=100.0)

    Output0.0 Cli-00: He llegado

    0.0 Cli-00: T. Espera 0.0

    2.3 Cli-01: He llegado

    2.7 Cli-00: Ya me voy

    2.7 Cli-01: T. Espera 0.4

    3.1 Cli-02: He llegado

    5.4 Cli-01: Ya me voy

    5.4 Cli-02: T. Espera 2.3

    8.1 Cli-02: Ya me voy

  • Introduction Classes Opeartions and functions Examples References

    El banco

    from SimPy.Simulation import *

    from random import expovariate, seed

    MEDIA_TIEMPO_DE_SERVICIO=5.0

    MEDIA_TIEMPO_DE_LLEGADA=2.5

    class Generador(Process):

    def generar(self,totalDeClientes,recurso):

    for i in range(totalDeClientes):

    c=Cliente(name="Cliente-"+str(i));

    activate(c,c.visitar(recurso=recurso));

    tiempoDeLlegada=expovariate(1.0/MEDIA_TIEMPO_DE_LLEGADA);

    yield hold,self,tiempoDeLlegada

    class Cliente(Process):

    def visitar(self,recurso):

    llegada=now()

    yield request,self,recurso

    tiempoDeEspera=now()-llegada

    monitor.observe(tiempoDeEspera);

    tiempoDeServicio=expovariate(1.0/MEDIA_TIEMPO_DE_SERVICIO)

    yield hold,self,tiempoDeServicio

    yield release,self,recurso

    seed()

    initialize()

    monitor=Monitor();

    banco=Resource(name="Banco",unitName="Cajero",capacity=2)

    generador=Generador(name="Generador")

    activate(generador,generador.generar(totalDeClientes=1000,recurso=banco))

    simulate(until=2000)

    resultado=monitor.count(),monitor.mean()

    print "El tiempo promedio de espera de %d atenciones fue %f"%resultado

  • Introduction Classes Opeartions and functions Examples References

    SimPlot

  • Introduction Classes Opeartions and functions Examples References

    1 http://sourceforge.net/projects/simpy/

    2 http://simpy.sourceforge.net/SimPyDocs/_static/

    TheBank.pdf

    3 http://msor.victoria.ac.nz/twiki/pub/Courses/

    OPRE354_2012T2/MoreReferences/LecturesOnSimPy.pdf

    4 http://python-ray.googlecode.com/hg-history/

    66da0654aaced5c4d2a8d26f2a17707d63c97174/doc/

    PyIterGen.pdf

  • Introduction Classes Opeartions and functions Examples References

    THE END

    IntroductionClassesOpeartions and functionsExamples