def add_an_individual(self, health_status): """Adds a newborn individual to the simulation.""" self.total_newborns += 1 ind = self.Individual(self, ind_id= self.nr_individuals + self.total_newborns, health_status = health_status) self.__dict__['total_' + health_status + 's'] += 1 self.observe_vars() activate(ind, ind.live(), at=0.0)
def run(self, forward=True): """ used in DejaVu/scenarioInterface/animationGUI.py animClip.makeAndRunMAA """ if len(self.maas)==0: #print "no actors" return initialize() redraw = self.redrawActor actors = self.actors afterAnimation = self.afterAnimation start = self.firstPosition end = self.lastPosition if redraw: redraw.object.stopAutoRedraw() proc = RedrawActorProcess(redraw) activate(proc, proc.execute(), at=start, prior=True) #print 'activated redraw', for actor in actors: if actor == redraw:continue proc = ActorProcess(actor) activate(proc, proc.execute(), at=start, prior=True) simulate(until=end) #self.currentFrame = self.endFrame if forward: #self.currentFrame = self.endFrame self.currentFrame = end else: self.currentFrame = start # call callback after animation completes for f in afterAnimation: f() #self.afterAnimation_cb() if redraw: redraw.object.startAutoRedraw()
def run(self, forward=True): """ used in DejaVu/scenarioInterface/animationGUI.py animClip.makeAndRunMAA """ if len(self.maas) == 0: #print "no actors" return initialize() redraw = self.redrawActor actors = self.actors afterAnimation = self.afterAnimation start = self.firstPosition end = self.lastPosition if redraw: redraw.object.stopAutoRedraw() proc = RedrawActorProcess(redraw) activate(proc, proc.execute(), at=start, prior=True) #print 'activated redraw', for actor in actors: if actor == redraw: continue proc = ActorProcess(actor) activate(proc, proc.execute(), at=start, prior=True) simulate(until=end) #self.currentFrame = self.endFrame if forward: #self.currentFrame = self.endFrame self.currentFrame = end else: self.currentFrame = start # call callback after animation completes for f in afterAnimation: f() #self.afterAnimation_cb() if redraw: redraw.object.startAutoRedraw()
def generate(self): i = 0 while True: yield hold, self, 2 c = Car('%d' % i) activate(c, c.lifecycle()) i += 1
def initialize(self): Machine.initialize(self) # initiate the Broker responsible to control the request/release # initialize the operator pool if any if (self.operatorPool!="None"): self.operatorPool.initialize() self.broker = Broker(self) activate(self.broker,self.broker.run()) for operator in self.operatorPool.operators: operator.coreObjectIds.append(self.id) operator.coreObjects.append(self) # the time that the machine started/ended its wait for the operator self.timeWaitForOperatorStarted=0 self.timeWaitForOperatorEnded=0 self.totalTimeWaitingForOperator=0 # the time that the machine started/ended its wait for the operator self.timeWaitForLoadOperatorStarted=0 self.timeWaitForLoadOperatorEnded=0 self.totalTimeWaitingForLoadOperator=0 # the time that the operator started/ended loading the machine self.timeLoadStarted=0 self.timeLoadEnded=0 self.totalLoadTime=0 # the time that the operator started/ended setting-up the machine self.timeSetupStarted=0 self.timeSetupEnded=0 self.totalSetupTime=0 # Current entity load/setup/loadOperatorwait/operatorWait related times self.operatorWaitTimeCurrentEntity=0 # holds the time that the machine was waiting for the operator self.loadOperatorWaitTimeCurrentEntity = 0 # holds the time that the machine waits for operator to load the it self.loadTimeCurrentEntity = 0 # holds the time to load the current entity self.setupTimeCurrentEntity = 0 # holds the time to setup the machine before processing the current entity
def execute(self): checks = 0 measures = [] sample_period = 6 last_scaling_activity = -1e6 old_arrivals = 0 while True: # # update cpu utilization across all servers # busy = len(Server.busy) both = busy + len(Server.idle) Watcher.cpu_utilization.observe(100.0 * float(BUSY_FACTOR * busy) / float(BUSY_FACTOR * busy + len(Server.idle)) if both else 0.0) # # do autoscaling checks every 60 seconds # checks += 1 if checks % 10 == 0: # # compute the cpu utilization metric over the desired period # samples = self.period / sample_period utilization = sum(Watcher.cpu_utilization.yseries()[-samples:]) / samples measures.append(utilization) if len(measures) >= (self.breach_duration // self.period): if len(measures) > (self.breach_duration // self.period): measures.pop(0) if now() - last_scaling_activity > self.cooldown: new_server_target = both if all([x > self.upper_threshold for x in measures]): new_server_target = both + self.upper_breach_scale_increment new_server_target = min(new_server_target, self.max_size) elif all([x < self.lower_threshold for x in measures]): new_server_target = both + self.lower_breach_scale_increment new_server_target = max(new_server_target, self.min_size) if new_server_target < both: # scale down for _ in range(both - new_server_target): Server.terminate() last_scaling_activity = now() elif new_server_target > both: # scale up for _ in range(new_server_target - both): s = Server(self.max_wait, self.instance_type, self.latency) activate(s, s.execute()) last_scaling_activity = now() # # unrelated: also keep track of arrival rate # Watcher.arrivals_mon.observe(Job.arrivals - old_arrivals) old_arrivals = Job.arrivals yield hold, self, sample_period
def monitor_events(*args, **kwargs): """Monitor event(s) to keep them up to date. :param args: All arguments are SimEvents to wait on. :param kwargs: All keywords are passed to `activate()` Process that monitors events in `args`. :return: Monitoring Process. """ proc = Process(name="monitor events") activate(proc, _monitor_events(proc, *args), **kwargs) return proc
def generate(self, segment, interval, percent_empty=0.30): while True: p = PRT(interval, segment, 0.) segment.members.append(p) self.prts.append(p) p.occupied = random() > percent_empty activate(p, p.execute(), 0.0) yield hold, self, uniform(0.5, 1.5) for prt in self.prts: if prt.distance > 200: self.cancel(prt) prt.delete()
def run(self, forward=True): """ used in DejaVu/scenarioInterface/animationPanels.py AnimationPanel.runMAA """ if len(self.actors) == 0: #print "no actors" return initialize() redraw = self.redrawActor start = 0 #end = self.endFrame self.maxFrame = 0 maxFrame = self.getLastFrameWithChange() if maxFrame is not None: self.maxFrame = maxFrame.pos end = self.maxFrame gui = self.gui if gui: if not (gui.startFrame == 0 and gui.stopFrame == 1): start = gui.startFrame end = gui.stopFrame self.maxFrame = end + start self.moveForward = forward if redraw: redraw.object.stopAutoRedraw() proc = RedrawActorProcess(redraw) activate(proc, proc.execute(), at=start, prior=True) #print 'activated redraw', for actor in self.actors: if actor.name != "redraw": proc = ActorProcess(actor) activate(proc, proc.execute(), at=start, prior=True) #print 'activated ', actor.name, action #print 'simulate', self.endFrame simulate(until=end) #self.currentFrame = self.endFrame if forward: #self.currentFrame = self.endFrame self.currentFrame = end else: self.currentFrame = start # call callback after animation completes for f in self.afterAnimation: f() #self.afterAnimation_cb() if self.redrawActor: vi = self.redrawActor.object vi.startAutoRedraw()
def run(self, forward=True): """ used in DejaVu/scenarioInterface/animationPanels.py AnimationPanel.runMAA """ if len(self.actors)==0: #print "no actors" return initialize() redraw = self.redrawActor start = 0 #end = self.endFrame self.maxFrame = 0 maxFrame = self.getLastFrameWithChange() if maxFrame is not None: self.maxFrame = maxFrame.pos end = self.maxFrame gui = self.gui if gui: if not (gui.startFrame == 0 and gui.stopFrame == 1): start = gui.startFrame end = gui.stopFrame self.maxFrame = end + start self.moveForward = forward if redraw: redraw.object.stopAutoRedraw() proc = RedrawActorProcess(redraw) activate(proc, proc.execute(), at=start, prior=True) #print 'activated redraw', for actor in self.actors: if actor.name != "redraw": proc = ActorProcess(actor) activate(proc, proc.execute(), at=start, prior=True) #print 'activated ', actor.name, action #print 'simulate', self.endFrame simulate(until=end) #self.currentFrame = self.endFrame if forward: #self.currentFrame = self.endFrame self.currentFrame = end else: self.currentFrame = start # call callback after animation completes for f in self.afterAnimation: f() #self.afterAnimation_cb() if self.redrawActor: vi = self.redrawActor.object vi.startAutoRedraw()
def testAlarm(): wfa1 = WaitForAlarm() activate(wfa1, wfa1.onetime(10)) wfa2 = WaitForAlarm() activate(wfa2, wfa2.periodic(5, until=50), at=15) wfa3 = WaitForAlarm() activate(wfa3, wfa3.periodic(5, drift=('norm', 0, {'sigma':0.1})), at=60)
def initialize(self): MachineJobShop.initialize(self) self.type="MachineManagedJob" #create an empty Operator Pool. This will be updated by canAcceptAndIsRequested id = self.id+'_OP' name=self.objName+'_operatorPool' self.operatorPool=OperatorPool(id, name, operatorsList=[]) self.operatorPool.initialize() self.operatorPool.operators=[] #create a Broker self.broker = Broker(self) activate(self.broker,self.broker.run()) #create a Router from Globals import G if len(G.RoutersList)==0: self.router=Router() activate(self.router,self.router.run()) G.RoutersList.append(self.router) # otherwise set the already existing router as the machines Router else: self.router=G.RoutersList[0] # holds the Entity that is to be obtained and will be updated by canAcceptAndIsRequested self.entityToGet=None
def run(self): #these are just for the first Entity activate(self.conveyerMover,self.conveyerMover.run()) yield waituntil, self, self.canAcceptAndIsRequested #wait until the Queue can accept an entity #and one predecessor requests it self.getEntity() #get the entity self.timeLastMoveHappened=now() while 1: #calculate the time to reach end. If this is greater than 0 (we did not already have an entity at the end) #set it as the timeToWait of the conveyerMover and raise call=true so that it will be triggered self.timeToReachEnd=0 if(len(self.position)>0 and (not self.length-self.position[0]<0.000001)): self.timeToReachEnd=((self.length-self.position[0])/float(self.speed))/60 if self.timeToReachEnd>0: self.conveyerMover.timeToWait=self.timeToReachEnd self.call=True #wait until the conveyer is in state to receive or dispose one entity yield waituntil, self, self.canAcceptAndIsRequestedORwaitToDispose #wait for an important event in order to move the items if self.canAcceptAndIsRequested(): self.getEntity() if self.waitToDispose: pass
def setPeriodic(cls, interval, name=None, at=0, until=infinite, drift=('fixed', 0)): tm = Alarm(interval, name, until, drift) activate(tm, tm.loop(), at=at) return tm.event
def __init__(self, epidemic_params): """The constructor of the class. Full params' list: - nr_individuals: number of individuals in the population - initial_infects: number of infects at the start of the simulation - initial_immunes: number of immunes at the start of the simulation - infect_prob: probability of getting infected after a contact with an infect - contact_rate: rate of the contact between individuals - recover_rate: rate of recover from infection - immune_after_recovery: if true, individuals becomes immunes after recovery - immunization_vanish_rate: if not zero, immunization is temporary with given rate - death_rate: rate of death caused by epidemic - newborn_can_be_infect: if true, newborn can be infect - newborn_can_be_immune: if true, newborn can be immune - newborn_prob: probability that a new individual born after a contact - natural_death_prob: probability of death not caused by epidemic - run_time: time duration of the simulation - debug: show more info about the running simulation - process_debug: show more info about SimPy processes during the simulation - progress: show a progress indicator during the simulation - stats: show some stats at the end of the simulation - plot: show a plot representing the evolution of the population at the end of the simulation """ # setting up the epidemic's parameters with metaprogramming for param in epidemic_params: self.__dict__[param] = epidemic_params.get(param) # setting the uninitialized parameters to their default values self.check_and_set_default_value(['initial_immunes', 'recover_rate', 'death_rate', 'immunization_vanish_rate', 'newborn_prob', 'natural_death_prob'], ['immune_after_recovery', 'newborn_can_be_immune', 'newborn_can_be_infect', 'debug', 'process_debug', 'progress', 'stats', 'plot']) # setting the random number generator using the python standard one self.rng = random.Random() # checking some features of the model from parameters passed to the constructor self.model_has_immunization = self.model_has_immunization() self.model_immunization_is_permanent = self.model_immunization_is_permanent() self.model_has_recovering = self.model_has_recovering() self.model_has_death = self.model_has_death() self.model_has_vital_dynamics = self.model_has_vital_dynamics() self.model_newborns_always_susceptibles = self.model_newborns_always_susceptibles() self.model_has_new_susceptibles = self.model_has_new_susceptibles() self.model_has_new_infects = self.model_has_new_infects() # initialize the population counters self.total_infects = self.initial_infects self.total_immunes = self.initial_immunes self.total_susceptibles = self.nr_individuals - self.initial_infects - self.initial_immunes self.total_newborns = 0 self.total_natural_deaths = 0 self.total_deaths = 0 # setting up the monitors for watching interesting variables self.m_suscettibili = Monitor(name="Suscettibili", ylab="suscettibili") self.m_suscettibili.append([0, self.total_susceptibles]) self.m_infetti = Monitor(name="Infetti", ylab='infetti') self.m_infetti.append([0, self.initial_infects]) if self.model_has_immunization: self.m_immuni = Monitor(name="Immuni", ylab='immuni') self.m_immuni.append([0, self.initial_immunes]) # setting up the array of all the individuals partecipating to the simulation self.all_individuals = [] # initialize the simulation environment (time, events, ...) initialize() for i in range(self.nr_individuals): # add individuals to the simulation with the specified health_status if i >= (self.nr_individuals - self.initial_infects): ind = self.Individual(self, ind_id=i, health_status='infect') elif i >= (self.nr_individuals - self.initial_infects - self.initial_immunes): ind = self.Individual(self, ind_id=i, health_status='immune') else: ind = self.Individual(self, ind_id=i) # activate it with function live() activate(ind, ind.live(), at=0.0) self.start_time = time.time() if self.process_debug: self.show_processes_status() # start the simulation simulate(until=self.run_time) self.stop_time = time.time() if self.process_debug: self.show_processes_status() # show final stats if required by params if self.stats: self.show_stats() # show plot if required by params if self.plot: self.show_plot()
def setOnetime(cls, delay, name=None, at=0, drift=('fixed', 0)): tm = Alarm(delay, name, drift=drift) activate(tm, tm.onetime()) return tm.event
def activateObjects(): for j in range(len(G.ObjList)): try: activate(G.ObjList[j], G.ObjList[j].run()) except AttributeError: pass
def start(self): activate(self, self._execute())
# # use a seed if set, otherwise use some OS source as the seed # if options.seed: random.seed(options.seed) else: random.seed() initialize() # # start up initial servers # for _ in range(options.capacity): s = Server(options.max_wait, options.instance_type, options.latency) activate(s, s.execute()) e = Sources('Sources') activate(e, e.execute(options.rate, file, options.latency, options.si_period, options.si_amplitude, options.si_phase, options.si_offset, options.profile, options.rate)) w = Watcher(options.max_wait, options.instance_type, options.latency, options.as_period, options.as_breach_duration, options.as_min_size, options.as_max_size,
from SimPy.Simulation import (Process, Resource, activate, initialize, hold, now, release, request, simulate) class Car(Process): def __init__(self, name, cc): Process.__init__(self, name=name) self.cc = cc def go(self): print('%s %s %s' % (now(), self.name, 'Starting')) yield request, self, gasstation print('%s %s %s' % (now(), self.name, 'Got a pump')) yield hold, self, 100.0 yield release, self, gasstation print('%s %s %s' % (now(), self.name, 'Leaving')) gasstation = Resource(capacity=2, name='gasStation', unitName='pump') initialize() c1 = Car('Car1', 2000) c2 = Car('Car2', 1600) c3 = Car('Car3', 3000) c4 = Car('Car4', 1600) activate(c1, c1.go(), at=4.0) # activate at time 4.0 activate(c2, c2.go()) # activate at time 0.0 activate(c3, c3.go(), at=3.0) # activate at time 3.0 activate(c4, c4.go(), at=3.0) # activate at time 2.0 simulate(until=300) print('Current time is %s' % now())
def start(self): self.start_time = now() self.node.job_agents.add(self) self.listen_process = ListenProcess(self) activate(self.listen_process, self.listen_process.listen())
from SimPy.Simulation import Process, activate, hold, initialize, now, simulate class Car(Process): def __init__(self, name, cc): Process.__init__(self, name=name) self.cc = cc def go(self): print('%s %s %s' % (now(), self.name, 'Starting')) yield hold, self, 100.0 print('%s %s %s' % (now(), self.name, 'Arrived')) initialize() c1 = Car('Car1', 2000) # a new car activate(c1, c1.go(), at=6.0) # activate at time 6.0 c2 = Car('Car2', 1600) # another new car activate(c2, c2.go()) # activate at time 0 simulate(until=200) print('Current time is %s' % now()) # will print 106.0
(now(), [x.weight for x in self.got])) yield hold, self, 11 class Widget(Lister): def __init__(self, weight=0): self.weight = weight widgbuf = [] for i in range(10): widgbuf.append(Widget(5)) initialize() buf = Store(capacity=11, initialBuffered=widgbuf, monitored=True) for i in range(3): # define and activate 3 producer objects p = ProducerD() activate(p, p.produce()) for i in range(3): # define and activate 3 consumer objects c = ConsumerD() activate(c, c.consume()) simulate(until=50) print('LenBuffer: %s' % buf.bufferMon) # length of buffer print('getQ: %s' % buf.getQMon) # length of getQ print('putQ %s' % buf.putQMon) # length of putQ
tripleft = self.interruptLeft # time to finish the trip self.interruptReset() # end interrupt state reactivate(br, delay=repairduration) # restart breakdown br yield hold, self, repairduration # delay for repairs print('Bus repaired at %s' % now()) else: break # no more breakdowns, bus finished trip print('Bus has arrived at %s' % now()) class Breakdown(Process): def __init__(self, myBus): Process.__init__(self, name='Breakdown ' + myBus.name) self.bus = myBus def breakBus(self, interval): # process execution method while True: yield hold, self, interval # breakdown interarrivals if self.bus.terminated(): break self.interrupt(self.bus) # breakdown to myBus initialize() b = Bus('Bus') # create a bus object activate(b, b.operate(repairduration=20, triplength=1000)) br = Breakdown(b) # create breakdown br to bus b activate(br, br.breakBus(300)) simulate(until=4000) print('SimPy: No more events at time %s' % now())
from SimPy.Simulation import Process, activate, hold, initialize, simulate class Customer(Process): def buy(self, budget=0): print('Here I am at the shops %s' % self.name) t = 5.0 for i in range(4): yield hold, self, t # executed 4 times at intervals of t time units print('I just bought something %s' % self.name) budget -= 10.00 print('All I have left is %s I am going home %s' % (budget, self.name)) initialize() # create a customer named "Evelyn", C = Customer(name='Evelyn') # and activate her with a budget of 100 activate(C, C.buy(budget=100), at=10.0) simulate(until=100.0)
class Federation(Process): def fight(self): # simulate Federation operations print('Three %s attempting to escape!' % (target.name)) while True: if random.randint(0, 10) < 2: # check for hit on player target.damage += 1 # hit! increment damage to player if target.damage <= 5: # target survives print('Ha! %s hit! Damage= %i' % (target.name, target.damage)) else: if (target.lives - 1) == 0: print('No more %s left!' % (target.name)) else: print('Now only %i %s left!' % (target.lives - 1, target.name)) yield hold, self, 1 initialize() gameOver = 100 # create a Player object named "Romulans" target = Player(lives=3, name='Romulans') activate(target, target.life()) # create a Federation object shooter = Federation() activate(shooter, shooter.fight()) simulate(until=gameOver) print(target.message)
# excess of demand over current stock amount if dd > stock.amount: # can't supply requested amount yield get, self, stock, stock.amount # supply all available amount self.stockout += ds # add unsupplied demand to self.stockout print('day %6.4f, demand = %6.4f, shortfall = %6.4f' % (now(), dd, -ds)) else: # can supply requested amount yield get, self, stock, dd print('day %6.4f, supplied %6.4f, now amount = %6.4f' % (now(), dd, stock.amount)) stock = Level(monitored=True) # 'unbounded' capacity and other defaults seed(99999) initialize() offeror = Deliver() activate(offeror, offeror.deliver()) requester = Demand() activate(requester, requester.demand()) simulate(until=49.9) result = (stock.bufferMon.mean(), requester.stockout) print('') print('Summary of results through end of day %6.4f:' % int(now())) print('average stock = %6.4f, cumulative stockout = %6.4f' % result)
def run(self): # activate every object in the coreOjbects list for object in self.coreObjects: activate(object, object.run()) while 1: yield waituntil, self, self.canAcceptAndIsRequested
from SimPy.Simulation import (activate, hold, initialize, now, request, release, simulate, Process, Resource) """Traditional SimPy API""" # Model components ------------------------------- class Car(Process): def run(self, res): yield request, self, res yield hold, self, 10 yield release, self, res print("Time: %s" % now()) # Model and Experiment --------------------------- initialize() r = Resource(capacity=5) auto = Car() activate(auto, auto.run(res=r)) simulate(until=100)
yield hold, self, servtime # release the resource yield release, self, myServer print('%s done at t = %s' % (self.name, now())) Client.outClients.append(self.name) initialize() # the next line creates the ``server`` Resource object server = Resource(capacity=2) # server defaults to qType==FIFO # the next lines create some Client process objects c1, c2 = Client(name='c1'), Client(name='c2') c3, c4 = Client(name='c3'), Client(name='c4') c5, c6 = Client(name='c5'), Client(name='c6') # in the next lines each client requests # one of the ``server``'s Resource units activate(c1, c1.getserved(servtime=100, priority=1, myServer=server)) activate(c2, c2.getserved(servtime=100, priority=2, myServer=server)) activate(c3, c3.getserved(servtime=100, priority=3, myServer=server)) activate(c4, c4.getserved(servtime=100, priority=4, myServer=server)) activate(c5, c5.getserved(servtime=100, priority=5, myServer=server)) activate(c6, c6.getserved(servtime=100, priority=6, myServer=server)) simulate(until=500) print('Request order: %s' % Client.inClients) print('Service order: %s' % Client.outClients)
from SimPy.Simulation import (PriorityQ, Process, Resource, activate, initialize, hold, now, release, request, simulate) class Client(Process): def __init__(self, name): Process.__init__(self, name) def getserved(self, servtime, priority, myServer): print('%s requests 1 unit at t=%s' % (self.name, now())) yield request, self, myServer, priority yield hold, self, servtime yield release, self, myServer print('%s done at t=%s' % (self.name, now())) initialize() # create the *server* Resource object server = Resource(capacity=1, qType=PriorityQ, preemptable=1) # create some Client process objects c1 = Client(name='c1') c2 = Client(name='c2') activate(c1, c1.getserved(servtime=100, priority=1, myServer=server), at=0) activate(c2, c2.getserved(servtime=100, priority=9, myServer=server), at=50) simulate(until=500)
from SimPy.Simulation import Process, activate, initialize, hold, now, simulate class Firework(Process): def execute(self): print('%s firework launched' % now()) yield hold, self, 10.0 # wait 10.0 time units for i in range(10): yield hold, self, 1.0 print('%s tick' % now()) yield hold, self, 10.0 # wait another 10.0 time units print('%s Boom!!' % now()) initialize() f = Firework() # create a Firework object, and # activate it (with some default parameters) activate(f, f.execute(), at=0.0) simulate(until=100)
print('%s car %s done by %s' % (now(), self.name, whichWash)) class CarGenerator(Process): def generate(self): i = 0 while True: yield hold, self, 2 c = Car('%d' % i) activate(c, c.lifecycle()) i += 1 washtime = 5 initialize() # put four cars into the queue of waiting cars for j in range(1, 5): c = Car(name='%d' % -j) activate(c, c.lifecycle()) waitingCars = Store(capacity=40) for i in range(2): cw = Carwash('Carwash %s' % i) activate(cw, cw.lifecycle()) cg = CarGenerator() activate(cg, cg.generate()) simulate(until=30) print('waitingCars %s' % [x.name for x in waitingCars.theBuffer])
M1.defineRouting([S],[Q1]) Q1.defineRouting([M1],[M2]) M2.defineRouting([Q1],[Q2]) Q2.defineRouting([M2]) argumentDict={'from':'Q2','to':'E1','safetyStock':70,'consumption':20} EG=EventGenerator(id="EV", name="ExcessEntitiesMover" ,start=60, interval=60, method=Globals.moveExcess, argumentDict=argumentDict) G.ObjList=[S,M1,M2,E,Q1,Q2,EG] initialize() #initialize the simulation (SimPy method) for object in G.ObjList: object.initialize() for object in G.ObjList: activate(object, object.run()) G.maxSimTime=400 simulate(until=G.maxSimTime) #run the simulation #carry on the post processing operations for every object in the topology for object in G.ObjList: object.postProcessing() ExcelHandler.outputTrace('TRACE') print "the system produced", E.numOfExits, "parts" print "the waiting ratio of", M1.objName, "is", (M1.totalWaitingTime/G.maxSimTime)*100, "%" print "the waiting ratio of", M2.objName, "is", (M2.totalWaitingTime/G.maxSimTime)*100, "%"
id="EV", name="ExcessEntitiesMover", start=60, interval=60, method=Globals.moveExcess, argumentDict=argumentDict, ) G.ObjList = [S, M1, M2, E, Q1, Q2, EG] initialize() # initialize the simulation (SimPy method) for object in G.ObjList: object.initialize() for object in G.ObjList: activate(object, object.run()) G.maxSimTime = 400 simulate(until=G.maxSimTime) # run the simulation # carry on the post processing operations for every object in the topology for object in G.ObjList: object.postProcessing() ExcelHandler.outputTrace("TRACE") print(("the system produced", E.numOfExits, "parts")) print(( "the waiting ratio of", M1.objName, "is",
def getserved(self, servtime, myServer): print('%s requests 1 unit at t = %s' % (self.name, now())) yield request, self, myServer yield hold, self, servtime yield release, self, myServer print('%s done at t = %s' % (self.name, now())) initialize() server = Resource(capacity=1, monitored=True, monitorType=Monitor) c1, c2 = Client(name='c1'), Client(name='c2') c3, c4 = Client(name='c3'), Client(name='c4') activate(c1, c1.getserved(servtime=100, myServer=server)) activate(c2, c2.getserved(servtime=100, myServer=server)) activate(c3, c3.getserved(servtime=100, myServer=server)) activate(c4, c4.getserved(servtime=100, myServer=server)) simulate(until=500) print('') print('(TimeAverage no. waiting: %s' % server.waitMon.timeAverage()) print('(Number) Average no. waiting: %.4f' % server.waitMon.mean()) print('(Number) Var of no. waiting: %.4f' % server.waitMon.var()) print('(Number) SD of no. waiting: %.4f' % sqrt(server.waitMon.var())) print('(TimeAverage no. in service: %s' % server.actMon.timeAverage()) print('(Number) Average no. in service: %.4f' % server.actMon.mean()) print('(Number) Var of no. in service: %.4f' % server.actMon.var()) print('(Number) SD of no. in service: %.4f' % sqrt(server.actMon.var()))
from SimPy.Simulation import Process, activate, initialize, hold, now, simulate class Message(Process): """A simple Process""" def __init__(self, i, len): Process.__init__(self, name='Message' + str(i)) self.i = i self.len = len def go(self): print('%s %s %s' % (now(), self.i, 'Starting')) yield hold, self, 100.0 print('%s %s %s' % (now(), self.i, 'Arrived')) initialize() p1 = Message(1, 203) # new message activate(p1, p1.go()) # activate it p2 = Message(2, 33) activate(p2, p2.go(), at=6.0) simulate(until=200) print('Current time is %s' % now()) # will print 106.0
def activateObjects(): for j in range(len(G.ObjList)): try: activate(G.ObjList[j],G.ObjList[j].run()) except AttributeError: pass