def timeAdvance(self): from pypdevs.simulator import Simulator model = CoupledGenerator() sim = Simulator(model) sim.setTerminationTime(self.state.processed) #sim.setVerbose(True) sim.simulate() result = max(sim.model.generator.state.generated, 1) return result
def simulate(self, current_time, end_time, agents, receiver_agents, agents_delay_map, contracts, delay_order, delay_notification): start_time = 0.0 market_input_ports = ['in_agent_regulator', 'in_agent_journal'] market_output_ports = ['out_next_journal_agent', 'out_notify_order_journal_agent', 'out_next_regulator_agent'] orderbooks_map = { contract: OrderbookVersion1('ob_' + contract, contract, delay_order, delay_notification) for contract in contracts} market = Version2Exchange('market', current_time, float('inf'), orderbooks_map.values(), market_input_ports, market_output_ports, agents_delay_map, start_time=start_time, end_time=end_time) connections = [((agent.identifier, 'out_order'), (market.identifier, 'in_agent_regulator')) for agent in agents] # Reactive agent observes the output from journal connections += [((market.identifier, 'out_next_journal_agent'), (agent.identifier, 'in_next')) for agent in receiver_agents] connections += [((market.identifier, 'out_notify_order_journal_agent'), (agent.identifier, 'in_notify_order')) for agent in receiver_agents] connections += [((market.identifier, 'out_next_regulator_agent'), (agent.identifier, 'in_notify_order')) for agent in receiver_agents] m = SimpleSystem(market=market, agents=agents, connections=connections) sim = Simulator(m) sim.setClassicDEVS() sim.simulate() return sim
from pypdevs.simulator import Simulator from models import * from pypdevs.tracer import Tracers from tracerX import TracerX model = CQueue() sim = Simulator(model) sim.setTerminationTime(5.0) # tracer configuation - not able to get my custom tracer "registered" or working #sim.setVerbose(None) #sim.tracer.registerTracer(["tracer", "TracerVerbose2", []]) sim.setCustomTracer("tracerX", "TracerX", ["my_output"]) sim.setClassicDEVS() sim.simulate() print("Simulation terminated!")
market = self.addSubModel(Market(contracts)) # TODO: parametrize the creation of each Agent (simple vs. with intermediary vs. more complex, etc.) agents = [self.addSubModel(SimpleAgentToJournal())] # Subscribe agent to market journal for agent in agents: self.connectPorts(agent.out_journal, market.in_agent_journal) # There are two types of agent: # those that receive EVERY message from the market and can decide what to do with it and # those that receive ONLY messages sent to him for agent in agents: if isinstance(agent, SimpleAgentToJournal): self.connectPorts(market.out_journal_agent, agent.in_next_orderbook) self.connectPorts(market.out_regulator_agent, agent.in_notify_order) else: # TODO: create specific port for this agent in the market coupled class pass # Experiment from pypdevs.simulator import Simulator m = Experiment1() sim = Simulator(m) sim.setClassicDEVS() sim.simulate()
# Keep a counter of how many events were sent self.outport = self.addOutPort("outport") self.state = 0 def intTransition(self): # Increment counter return self.state + 1 def outputFnc(self): # Send the amount of messages sent on the output port return {self.outport: [self.state]} def timeAdvance(self): # Fixed 1.0 return 1.0 class Consumer(AtomicDEVS): def __init__(self, count): AtomicDEVS.__init__(self, "Consumer_%i" % count) self.inport = self.addInPort("inport") def extTransition(self, inputs): for inp in inputs[self.inport]: print("Got input %i on model %s" % (inp, self.name)) sim = Simulator(Root()) sim.setTerminationTime(5) sim.simulate()
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import random from pypdevs.simulator import Simulator import time if len(sys.argv) != 3: print("Expected parameters: scheduler size") sys.exit(1) scheduler = sys.argv[1] size = int(sys.argv[2]) from model import FireSpread model = FireSpread(size, size) sim = Simulator(model) sim.setMessageCopy('none') getattr(sim, scheduler)() sim.setTerminationTime(150) sim.simulate()
elif mn == "classicDEVSconnect_local": model = models.AllConnectClassic() args["setClassicDEVS"] = [True] elif mn == "random": model = models.RandomCoupled() elif mn == "random_local": model = models.RandomCoupled_local() elif mn == "stateStop_pull": model = models.Chain(0.66) args["setTerminationCondition"] = [counter_pull] del args["setTerminationTime"] elif mn.startswith("reinit"): model = models.AutoDistChain(3, totalAtomics=500, iterations=1) if "local" in mn: model.forceSequential() sim = Simulator(model) sim.setAllowLocalReinit(True) sim.setTerminationTime(40) sim.setVerbose("output/reinit1") sim.simulate() sim.reinit() sim.setVerbose("output/reinit2") sim.setModelStateAttr(model.generator.generator, "value", 2) sim.simulate() sim.reinit() sim.setVerbose("output/reinit3") sim.setModelStateAttr(model.generator.generator, "value", 3) sim.simulate() run = False elif mn.startswith("multisim"): if "local" in mn:
from pypdevs.simulator import Simulator from System import Factory model = Factory() simulator = Simulator(model) simulator.setVerbose("SimulationOutput.txt") simulator.setClassicDEVS() simulator.setTerminationTime(62.0) simulator.simulate() simulator.model.printStatistics("./statsDeterministic62m.txt")
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pypdevs.simulator import Simulator from trafficLightModel import * model = TrafficLight(name="trafficLight") refs = {"INTERRUPT": model.INTERRUPT} sim = Simulator(model) sim.setRealTime(True) sim.setRealTimeInputFile(None) sim.setRealTimePorts(refs) sim.setVerbose(None) sim.setRealTimePlatformThreads() sim.simulate() # If we get here, simulation will also end, as the sleep calls are daemon threads # (otherwise, they would make the simulation unkillable) while 1: sim.realtime_interrupt(raw_input())
"unknown state <%s> in TrafficLight time advance transition function"\ % state) # ====================================================================== # class TrafficLightSystem(CoupledDEVS): def __init__(self): CoupledDEVS.__init__(self, "System") self.light = self.addSubModel(TrafficLight("Light")) self.observed = self.addOutPort(name="observed") self.connectPorts(self.light.OBSERVED, self.observed) def my_function(event): print("Observed the following event: " + str(event)) from pypdevs.simulator import Simulator model = TrafficLightSystem() sim = Simulator(model) sim.setRealTime() sim.setListenPorts(model.observed, my_function) sim.simulate() import time while 1: time.sleep(0.1)
return {self.outport: [self.state]} def intTransition(self): self.state = None return self.state def extTransition(self, inputs): self.state = inputs[self.inport][0] return self.state class CQueue(CoupledDEVS): def __init__(self): CoupledDEVS.__init__(self, "CQueue") self.generator = self.addSubModel(Generator()) self.queue = self.addSubModel(Queue()) self.connectPorts(self.generator.outport, self.queue.inport) class DQueue(CoupledDEVS): def __init__(self): CoupledDEVS.__init__(self, "DQueue") self.generator = self.addSubModel(Generator()) self.queue1 = self.addSubModel(Queue()) self.queue2 = self.addSubModel(Queue()) self.connectPorts(self.generator.outport, self.queue1.inport) self.connectPorts(self.generator.outport, self.queue2.inport) model = CQueue() sim = Simulator(model) sim.setVerbose() sim.simulate()
elif state == "yellow": v = "red" elif state == "green": v = "yellow" return {self.observe: [v]} def extTransition(self, inputs): inp = inputs[self.interrupt][0] if inp == "manual": return "manual" elif inp == "auto": if self.state == "manual": return "red" def confTransition(self, inputs): self.elapsed = 0.0 self.state = self.intTransition() self.state = self.extTransition(inputs) return self.state ### Experiment from pypdevs.simulator import Simulator model = TrafficLight() sim = Simulator(model) sim.setVerbose() sim.setTerminationTime(500) sim.simulate()
### Model from pypdevs.DEVS import * from trafficlight import TrafficLight from policeman import Policeman class TrafficLightSystem(CoupledDEVS): def __init__(self): CoupledDEVS.__init__(self, "system") self.light = self.addSubModel(TrafficLight()) self.police = self.addSubModel(Policeman()) self.connectPorts(self.police.out, self.light.interrupt) ### Experiment from pypdevs.simulator import Simulator sim = Simulator(TrafficLightSystem()) sim.setVerbose() sim.setTerminationTime(1000) sim.simulate()
#! /bin/env python import time start = time.clock() print("Starting at time " + str(start)) from mpi4py import MPI import models import sys from pypdevs.simulator import Simulator, loadCheckpoint model = models.AutoDistChain(3, totalAtomics=500, iterations=1) sim = Simulator(model) sim.setAllowLocalReinit(True) sim.setTerminationTime(40) sim.setVerbose("output/reinit1") sim1start = time.clock() print("Sim 1 started at " + str(sim1start)) sim.simulate() sim.setReinitStateAttr(model.generator.generator, "value", 2) sim2start = time.clock() sim.setRemoveTracers() sim.setVerbose("output/reinit2") print("Sim 2 started at " + str(sim2start)) sim.simulate() sim.setReinitStateAttr(model.generator.generator, "value", 3) sim3start = time.clock() print("Sim 3 started at " + str(sim3start)) sim.setRemoveTracers() sim.setVerbose("output/reinit3") sim.simulate()
def outputFnc(self): # Send the amount of messages sent on the output port return {self.outport: [self.state]} def timeAdvance(self): # Fixed 1.0 return 1.0 def modelTransition(self, state): # We pass on the ID that we would like to create, which is equal to our counter state["ID"] = self.state # Always create a new element return True class Consumer(AtomicDEVS): def __init__(self, count): AtomicDEVS.__init__(self, "Consumer_%i" % count) self.inport = self.addInPort("inport") def extTransition(self, inputs): for inp in inputs[self.inport]: print("Got input %i on model %s" % (inp, self.name)) sim = Simulator(Root()) sim.setTerminationTime(5) sim.setDSDEVS(True) sim.simulate()
def intTransition(self): return None def extTransition(self, inputs): return inputs[self.inport][0] def outputFnc(self): return {self.outport: [self.state]} def timeAdvance(self): return 0.0 if self.state else float('inf') model = Root() sim = Simulator(model) sim.setRealTime(True) sim.setRealTimePorts({ "input_A": model.listener_A, "input_B": model.mini.listener_B, "input_C": model.mini.model_one.inport, "input_D": model.mini.model_two.inport, "output_A": model.output_A, "output_B": model.mini.output_B, "output_C": model.mini.model_one.outport, "output_D": model.mini.model_two.outport }) sim.setRealTimePlatformThreads() def output_on_A(evt):
self.state = None return self.state def extTransition(self, inputs): self.state = inputs[self.inport][0] return self.state class CQueue(CoupledDEVS): def __init__(self): CoupledDEVS.__init__(self, "CQueue") self.generator = self.addSubModel(Generator()) self.queue = self.addSubModel(Queue()) self.connectPorts(self.generator.outport, self.queue.inport) class DQueue(CoupledDEVS): def __init__(self): CoupledDEVS.__init__(self, "DQueue") self.generator = self.addSubModel(Generator()) self.queue1 = self.addSubModel(Queue()) self.queue2 = self.addSubModel(Queue()) self.connectPorts(self.generator.outport, self.queue1.inport) self.connectPorts(self.generator.outport, self.queue2.inport) model = CQueue() sim = Simulator(model) sim.setVerbose() sim.simulate()
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pypdevs.simulator import Simulator from Tkinter import * from trafficLightModel import * isBlinking = None model = TrafficLight(name="trafficLight") refs = {"INTERRUPT": model.INTERRUPT} root = Tk() sim = Simulator(model) sim.setRealTime(True) sim.setRealTimeInputFile(None) sim.setRealTimePorts(refs) sim.setVerbose(None) sim.setRealTimePlatformTk(root) def toManual(): global isBlinking isBlinking = False sim.realtime_interrupt("INTERRUPT toManual") def toAutonomous(): global isBlinking
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import random if len(sys.argv) != 4: print("Expected parameters: scheduler size randomta") sys.exit(1) scheduler = sys.argv[1] size = int(sys.argv[2]) randomta = True if sys.argv[3].lower() in ["true", "1", "yes"] else False from pypdevs.simulator import Simulator from model import DEVStone random.seed(1) model = DEVStone(3, size, randomta) sim = Simulator(model) sim.setMessageCopy('none') getattr(sim, scheduler)() sim.setTerminationTime(1000) sim.simulate()
def timeAdvance(self): return 1.0 def intTransition(self): return self.state def outputFnc(self): return {self.send_event1: [Event(1)]} class Queue(CoupledDEVS): def __init__(self, width): CoupledDEVS.__init__(self, "Queue") self.generator = self.addSubModel(Generator()) prev = self.generator seeds = [i * 1000 for i in range(width)] for i in range(width): m = self.addSubModel(Processor("Processor%i" % i, seeds[i])) self.connectPorts(prev.send_event1, m.recv_event1) prev = m if __name__ == "__main__": import sys global is_random is_random = (sys.argv[2][0] == "1") m = Queue(int(sys.argv[1])) sim = Simulator(m) sim.setTerminationTime(500.0) sim.simulate()
- 20 nodes (1 LP/node) - [10%-100%] remote events - equivalent of 25ms computation - event containing 1 float """ ### Global imports from pypdevs.simulator import Simulator ### Queue import QueueModel QueueModel.is_random = True m = QueueModel.Queue(10) sim = Simulator(m) sim.setTerminationTime(1) sim.simulate() ### High Interconnect import HighInterconnect from HighInterconnect import HighInterconnect as HighInterconnectModel HighInterconnect.is_random = True m = HighInterconnectModel(10) sim = Simulator(m) sim.setTerminationTime(1) sim.simulate()
from model import TrafficSystem # ====================================================================== # 1. Instantiate the (Coupled or Atomic) DEVS at the root of the # hierarchical model. This effectively instantiates the whole model # thanks to the recursion in the DEVS model constructors (__init__). # trafficSystem = TrafficSystem(name="trafficSystem") # ====================================================================== # 2. Link the model to a DEVS Simulator: # i.e., create an instance of the 'Simulator' class, # using the model as a parameter. sim = Simulator(trafficSystem) # ====================================================================== # 3. Perform all necessary configurations, the most commonly used are: # A. Termination time (or termination condition) # Using a termination condition will execute a provided function at # every simulation step, making it possible to check for certain states # being reached. # It should return True to stop simulation, or Falso to continue. def terminate_whenStateIsReached(clock, model): return model.trafficLight.state.get() == "manual"
from pypdevs.simulator import Simulator from model import TrafficLight model = TrafficLight("TrafficLight") sim = Simulator(model) sim.setTerminationTime(150.0) sim.setVerbose(None) sim.setClassicDEVS() sim.simulate() print("Simulation terminated!")
from pypdevs.DEVS import * from library import Library from user import User class LibrarySystem(CoupledDEVS): def __init__(self): CoupledDEVS.__init__(self, "LibrarySystem") self.library = self.addSubModel(Library()) self.user = self.addSubModel(User()) self.connectPorts(self.user.out, self.library.interrupt) ### simulation from pypdevs.simulator import Simulator sim = Simulator(LibrarySystem()) sim.setVerbose() sim.setTerminationTime(300) sim.setClassicDEVS() sim.simulate()
from model import TrafficSystem # ====================================================================== # 1. Instantiate the (Coupled or Atomic) DEVS at the root of the # hierarchical model. This effectively instantiates the whole model # thanks to the recursion in the DEVS model constructors (__init__). # trafficSystem = TrafficSystem(name="trafficSystem") # ====================================================================== # 2. Link the model to a DEVS Simulator: # i.e., create an instance of the 'Simulator' class, # using the model as a parameter. sim = Simulator(trafficSystem) # ====================================================================== # 3. Perform all necessary configurations, the most commonly used are: # A. Termination time (or termination condition) # Using a termination condition will execute a provided function at # every simulation step, making it possible to check for certain states # being reached. # It should return True to stop simulation, or Falso to continue. def terminate_whenStateIsReached(clock, model): return model.trafficLight.state.get() == "manual" sim.setTerminationCondition(terminate_whenStateIsReached) # A termination time is prefered over a termination condition,
from pypdevs.simulator import Simulator from mymodel import MyModel model = MyModel() simulator = Simulator(model) simulator.setVerbose() simulator.setClassicDEVS() simulator.simulate()
from pypdevs.simulator import Simulator from model2 import TrainNetwork def terminate_whenStateIsReached(clock, model): return len(model.collector.trains) == model.generator.number_of_trains total_railway_length = 100 num_of_segments = 1 num_of_trains = 1 max_velocity = 150 acceleration = 15 iat = 10 trainNetwork = TrainNetwork("TrainNetwork", num_of_trains, max_velocity, num_of_segments, total_railway_length, acceleration, iat) sim = Simulator(trainNetwork) sim.setTerminationCondition(terminate_whenStateIsReached) sim.setClassicDEVS(True) sim.setVerbose(None) # sim.setTerminationTime(20.0) sim.simulate()
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pypdevs.simulator import Simulator from trafficLightModel import * model = TrafficLight(name="trafficLight") refs = {"INTERRUPT": model.INTERRUPT} sim = Simulator(model) sim.setRealTime(True) sim.setRealTimeInputFile(None) sim.setRealTimePorts(refs) sim.setVerbose(None) sim.setRealTimePlatformGameLoop() sim.simulate() import time while 1: before = time.time() sim.realtime_loop_call() time.sleep(0.1 - (before - time.time())) print("Current state: " + str(model.state.get()))
self.send_event1 = self.addOutPort("out_event1") def timeAdvance(self): return 1.0 def intTransition(self): return self.state def outputFnc(self): return {self.send_event1: [Event(1)]} class Queue(CoupledDEVS): def __init__(self, width): CoupledDEVS.__init__(self, "Queue") self.generator = self.addSubModel(Generator()) prev = self.generator seeds = [i * 1000 for i in range(width)] for i in range(width): m = self.addSubModel(Processor("Processor%i" % i, seeds[i])) self.connectPorts(prev.send_event1, m.recv_event1) prev = m if __name__ == "__main__": import sys global is_random is_random = (sys.argv[2][0] == "1") m = Queue(int(sys.argv[1])) sim = Simulator(m) sim.setTerminationTime(500.0) sim.simulate()
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pypdevs.simulator import Simulator from Tkinter import * from trafficLightModel import * isBlinking = None model = TrafficLight(name="trafficLight") refs = {"INTERRUPT": model.INTERRUPT} root = Tk() sim = Simulator(model) sim.setRealTime(True) sim.setRealTimeInputFile(None) sim.setRealTimePorts(refs) sim.setVerbose(None) sim.setRealTimePlatformTk(root) def toManual(): global isBlinking isBlinking = False sim.realtime_interrupt("INTERRUPT toManual") def toAutonomous(): global isBlinking isBlinking = None sim.realtime_interrupt("INTERRUPT toAutonomous")
from pypdevs.simulator import Simulator from city_model import City if __name__ == "__main__": city = City() sim = Simulator(city) #sim.setVerbose(None) sim.setStateSaving("custom") sim.setMessageCopy("custom") sim.simulate()
def __init__(self): CoupledDEVS.__init__(self, "Factory") self.cylinder_source = self.addSubModel(CylinderSource(seed=10.0)) self.cube_source = self.addSubModel(CubeSource(seed=20.0)) self.preassembler = self.addSubModel(Preassembler()) self.assembler = self.addSubModel(Assembler()) self.inspector = self.addSubModel(Inspector()) self.fix = self.addSubModel(Fix()) self.accept = self.addSubModel(Accept()) self.trash = self.addSubModel(Trash()) self.connectPorts(self.cylinder_source.outport, self.preassembler.inport) self.connectPorts(self.cube_source.outport, self.preassembler.inport2) self.connectPorts(self.preassembler.outport, self.assembler.inport) self.connectPorts(self.assembler.outport, self.inspector.inport) self.connectPorts(self.inspector.outport, self.accept.inport) self.connectPorts(self.inspector.outport2, self.fix.inport) self.connectPorts(self.inspector.outport3, self.trash.inport) self.connectPorts(self.fix.outport, self.assembler.inport) if __name__ == '__main__': model = Factory() sim = Simulator(model) # sim.setVerbose(None) sim.setVerbose("myOutputFile") # Required to set Classic DEVS, as we simulate in Parallel DEVS otherwise sim.setClassicDEVS() sim.simulate() print(model.accept.state.products) print(model.trash.state.products)
x3_axis.append(i) temp_y1 = [] temp_y2 = [] temp_y3 = [] for j in range(1, 10): # ======================= # Simulate with fixed set with IAT=(50, 75) numTracks = i trackLength = int(totalTrack / numTracks) trainnetwork = TrainNetwork(name='trainnetwork', numTracks=numTracks, trackLength=trackLength, numTrains=numTrains, iat=(50, 75)) sim = Simulator(trainnetwork) sim.setTerminationCondition(terminate_whenStateIsReached) sim.setClassicDEVS() sim.simulate() # Save Simulation Data temp_y1.append(trainnetwork.getStatistics()) # ======================= # Simulate with fixed set with IAT=(25, 50) numTracks = i trackLength = int(totalTrack / numTracks) trainnetwork = TrainNetwork(name='trainnetwork', numTracks=numTracks, trackLength=trackLength, numTrains=numTrains,
def getPerformance(self): # Average travel time l = self.collector.getTrains() return sum(train.getPerformance() for train in l) / len(l) totalLengths = [5000, 10000, 15000, 20000] segmentsCount = [5, 10, 15, 20, 25, 30] terminationTime = 1000 for length in totalLengths: data = [] fileName = "../data/results{}.dat".format(length) for segCnt in segmentsCount: system = TrainTrafficSystem(segCnt, length) sim = Simulator(system) # sim.setVerbose() sim.setTerminationTime(terminationTime) sim.setClassicDEVS() sim.simulate() c = system.getCost() p = system.getPerformance() data.append((segCnt, c, p)) with open(fileName, "w") as f: f.write("segmentsCount,cost,performance\n") for d in data: f.write("{},{},{}\n".format(d[0], d[1], d[2]))
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at # McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pypdevs.simulator import Simulator from trafficLightModel import * model = TrafficLight(name="trafficLight") sim = Simulator(model) sim.setVerbose(None) sim.simulate()