state_dsdevs.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from pypdevs.DEVS import AtomicDEVS, CoupledDEVS
  2. from pypdevs.simulator import Simulator
  3. class Root(CoupledDEVS):
  4. def __init__(self):
  5. CoupledDEVS.__init__(self, "Root")
  6. self.models = []
  7. # First model
  8. self.models.append(self.addSubModel(Generator()))
  9. # Second model
  10. self.models.append(self.addSubModel(Consumer(0)))
  11. # And connect them
  12. self.connectPorts(self.models[0].outport, self.models[1].inport)
  13. def modelTransition(self, state):
  14. # We are notified, so are required to add a new model and link it
  15. # We can use the ID provided by the model below us
  16. self.models.append(self.addSubModel(Consumer(state["ID"])))
  17. self.connectPorts(self.models[0].outport, self.models[-1].inport)
  18. # Always returns False, as this is top-level
  19. return False
  20. class Generator(AtomicDEVS):
  21. def __init__(self):
  22. AtomicDEVS.__init__(self, "Generator")
  23. # Keep a counter of how many events were sent
  24. self.outport = self.addOutPort("outport")
  25. self.state = 0
  26. def intTransition(self):
  27. # Increment counter
  28. return self.state + 1
  29. def outputFnc(self):
  30. # Send the amount of messages sent on the output port
  31. return {self.outport: [self.state]}
  32. def timeAdvance(self):
  33. # Fixed 1.0
  34. return 1.0
  35. def modelTransition(self, state):
  36. # We pass on the ID that we would like to create, which is equal to our counter
  37. state["ID"] = self.state
  38. # Always create a new element
  39. return True
  40. class Consumer(AtomicDEVS):
  41. def __init__(self, count):
  42. AtomicDEVS.__init__(self, "Consumer_%i" % count)
  43. self.inport = self.addInPort("inport")
  44. def extTransition(self, inputs):
  45. for inp in inputs[self.inport]:
  46. print("Got input %i on model %s" % (inp, self.name))
  47. sim = Simulator(Root())
  48. sim.setTerminationTime(5)
  49. sim.setDSDEVS(True)
  50. sim.simulate()