devstone.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. from abc import ABC, abstractmethod
  2. from collections import defaultdict
  3. from pystone import pystones
  4. from pypdevs.DEVS import AtomicDEVS, CoupledDEVS
  5. from pypdevs.infinity import INFINITY
  6. from pypdevs.simulator import Simulator
  7. from graphviz import Source
  8. import time
  9. import random
  10. random.seed(42)
  11. DIGITS = 3
  12. class DelayedAtomic(AtomicDEVS):
  13. def __init__(self, name: str, int_delay: float, ext_delay: float, add_out_port: bool = False, prep_time=0.0, mode: str = ""):
  14. super().__init__(name)
  15. self.state = "passive"
  16. self.int_delay = int_delay
  17. self.ext_delay = ext_delay
  18. self.prep_time = prep_time
  19. self.i_in = self.addInPort("i_in")
  20. if add_out_port: # for HI and HO models
  21. self.o_out = self.addOutPort("o_out")
  22. # Dynamic Structure extras
  23. self.mode = mode
  24. self.out_ports = [] # used for dynamic structure model LI2HI
  25. def intTransition(self):
  26. if self.int_delay:
  27. pystones(self.int_delay)
  28. return "passive"
  29. def timeAdvance(self):
  30. if self.state == "active":
  31. return self.prep_time
  32. else:
  33. return INFINITY
  34. def outputFnc(self):
  35. if hasattr(self, "o_out") and self.o_out is not None:
  36. return {self.o_out: [0]}
  37. # for DSDEVS LI2HI
  38. if len(self.out_ports) == 1 and self.out_ports[0].outline != []:
  39. return {self.out_ports[0]: [0]}
  40. return {}
  41. def extTransition(self, inputs):
  42. if self.ext_delay:
  43. pystones(self.ext_delay)
  44. return "active"
  45. def modelTransition(self, state):
  46. result = False
  47. if self.mode == "LI2HI":
  48. result = self.LI2HI(state)
  49. elif self.mode == "HI2LI":
  50. result = self.HI2LI(state)
  51. return result
  52. def LI2HI(self, state):
  53. if len(self.out_ports) == 0 and not hasattr(self, "o_out"):
  54. # every automic dev gets the extra out port
  55. # even though the last atomic could miss it see fig
  56. # except the atomic model in the coupled model at max depth
  57. # which has a output port by default
  58. state["LI2HI"] = True
  59. state["name"] = self.name
  60. self.out_ports.append(self.addOutPort("o_HI")) # standard LI model doesn't have by default
  61. # print(f"{self.name}: should be first call!!")
  62. return True # send to the parent to connect ports
  63. return False
  64. def HI2LI(self, state):
  65. if hasattr(self, "o_out") and self.o_out is not None:
  66. state["HI2LI"] = True
  67. state["name"] = self.name
  68. self.removePort(self.o_out)
  69. self.o_out = None
  70. return False
  71. class DelayedAtomicStats(DelayedAtomic):
  72. def __init__(self, name: str, int_delay: float, ext_delay: float, add_out_port: bool = False, prep_time=0, mode:str = ""):
  73. super().__init__(name, int_delay, ext_delay, add_out_port, prep_time, mode)
  74. self.int_count = 0
  75. self.ext_count = 0
  76. def intTransition(self):
  77. self.int_count += 1
  78. return super().intTransition()
  79. def extTransition(self, inputs):
  80. self.ext_count += 1
  81. return super().extTransition(inputs)
  82. class DEVStoneWrapper(CoupledDEVS, ABC):
  83. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float,
  84. add_atomic_out_ports: bool = False, prep_time=0, stats=False, mode: str = "", dynamic: bool = False):
  85. super().__init__(name)
  86. self.depth = depth
  87. self.width = width
  88. self.int_delay = int_delay
  89. self.ext_delay = ext_delay
  90. self.prep_time = prep_time
  91. self.stats = stats
  92. self.add_atomic_out_ports = add_atomic_out_ports
  93. self.i_in = self.addInPort("i_in")
  94. self.o_out = self.addOutPort("o_out")
  95. self.models = [] # stores all models part of the coupled model
  96. # added to deal with DS DEVS which don't keep it all in the component_set
  97. if depth < 1:
  98. raise ValueError("Invalid depth")
  99. if width < 1:
  100. raise ValueError("Invalid width")
  101. if int_delay < 0:
  102. raise ValueError("Invalid int_delay")
  103. if ext_delay < 0:
  104. raise ValueError("Invalid ext_delay")
  105. if depth == 1:
  106. p_time = round(random.uniform(1.0, 2.0), 3)
  107. if self.stats:
  108. atomic = DelayedAtomicStats("Atomic_0_0", int_delay, ext_delay, add_out_port=True, prep_time=p_time, mode=mode)
  109. else:
  110. atomic = DelayedAtomic("Atomic_0_0", int_delay, ext_delay, add_out_port=True, prep_time=p_time, mode=mode)
  111. self.models.append(self.addSubModel(atomic))
  112. self.connectPorts(self.i_in, atomic.i_in)
  113. self.connectPorts(atomic.o_out, self.o_out)
  114. else:
  115. coupled = self.gen_coupled()
  116. self.addSubModel(coupled)
  117. self.connectPorts(self.i_in, coupled.i_in)
  118. self.connectPorts(coupled.o_out, self.o_out)
  119. if dynamic:
  120. return # width will be dynamically generated
  121. # + (idx * 1e-6) to address too many transitions at the same time
  122. # => problem for Classic DEVS only it seems
  123. for idx in range(width - 1):
  124. p_time = 1 - round(random.uniform(idx/self.width, (idx + 0.5)/self.width), DIGITS)
  125. if self.stats:
  126. atomic = DelayedAtomicStats("Atomic_%d_%d" % (depth - 1, idx), int_delay, ext_delay,
  127. add_out_port=add_atomic_out_ports, prep_time=p_time, mode=mode)
  128. else:
  129. atomic = DelayedAtomic("Atomic_%d_%d" % (depth - 1, idx), int_delay, ext_delay,
  130. add_out_port=add_atomic_out_ports, prep_time=p_time, mode=mode)
  131. self.models.append(self.addSubModel(atomic))
  132. def dot(self, name) -> None:
  133. result = ("\n\ndigraph {\n\tlayout=dot;"
  134. "\n\tnodesep=0.25;"
  135. "\n\tranksep=0.2;"
  136. "\n\trankdir=LR;"
  137. "\n\tsplines=ortho;\n")
  138. result += f"\tCoupled_{self.depth}[shape=box, label=\"C_{self.depth}\"];\n"
  139. coupled = self.component_set[0]
  140. result += f"\t{coupled.name}[shape=box, label=\"{'C_' + '_'.join(coupled.name.split('_')[1:3])}\"];\n"
  141. for model in self.models:
  142. result += f"\t{model.name}[shape=ellipse, label=\"{'A_' + '_'.join(model.name.split('_')[1:3])}\"];\n"
  143. for connections in self.i_in.outline:
  144. result += f"\tCoupled_{self.depth}:i_in -> {str(connections).split('.')[-2]}:{connections.name};\n"
  145. for model in self.models:
  146. if not hasattr(model, "o_out"):
  147. continue
  148. for connections in model.o_out.outline:
  149. result += f"\t{model.name}:o_out -> {str(connections).split('.')[2]}:{connections.name};\n"
  150. result += "}\n"
  151. src = Source(result)
  152. src.view(filename=f'{name}_{self.depth}')
  153. def getStats(self, display=True):
  154. total_i = 0
  155. total_e = 0
  156. if isinstance(self.component_set[0], CoupledDEVS):
  157. i, e = self.component_set[0].getStats(False)
  158. total_i += i
  159. total_e += e
  160. for m in self.models:
  161. if not (hasattr(m, "int_count") and hasattr(m, "ext_count")):
  162. continue
  163. total_i += m.int_count
  164. total_e += m.ext_count
  165. if display:
  166. print(f"Total internal transitions during simulation: {total_i}")
  167. print(f"Total external transitions during simulation: {total_e}")
  168. print(f"Total Number of Transitions: {total_i + total_e}")
  169. return total_i, total_e
  170. @abstractmethod
  171. def gen_coupled(self):
  172. """ :return a coupled method with i_in and o_out ports"""
  173. pass
  174. class LI(DEVStoneWrapper):
  175. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, prep_time=0, stats=False):
  176. super().__init__(name, depth, width, int_delay, ext_delay, add_atomic_out_ports=False, prep_time=prep_time,
  177. stats=stats)
  178. for idx in range(1, len(self.component_set)):
  179. assert isinstance(self.component_set[idx], AtomicDEVS)
  180. self.connectPorts(self.i_in, self.component_set[idx].i_in)
  181. def gen_coupled(self):
  182. return LI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  183. prep_time=self.prep_time, stats=self.stats)
  184. class HI(DEVStoneWrapper):
  185. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, prep_time=0, stats=False):
  186. super().__init__(name, depth, width, int_delay, ext_delay, add_atomic_out_ports=True, prep_time=prep_time,
  187. stats=stats)
  188. if len(self.component_set) > 1:
  189. assert isinstance(self.component_set[-1], AtomicDEVS)
  190. self.connectPorts(self.i_in, self.component_set[-1].i_in)
  191. for idx in range(1, len(self.component_set) - 1):
  192. assert isinstance(self.component_set[idx], AtomicDEVS)
  193. self.connectPorts(self.component_set[idx].o_out, self.component_set[idx + 1].i_in)
  194. self.connectPorts(self.i_in, self.component_set[idx].i_in)
  195. def gen_coupled(self):
  196. return HI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  197. prep_time=self.prep_time, stats=self.stats)
  198. class HO(DEVStoneWrapper):
  199. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, prep_time=0, stats=False):
  200. super().__init__(name, depth, width, int_delay, ext_delay, add_atomic_out_ports=True, prep_time=prep_time,
  201. stats=stats)
  202. self.i_in2 = self.addInPort("i_in2")
  203. self.o_out2 = self.addOutPort("o_out2")
  204. assert len(self.component_set) > 0
  205. if isinstance(self.component_set[0], CoupledDEVS):
  206. self.connectPorts(self.i_in, self.component_set[0].i_in2) # seems wrong i_in -> i_in and i_in2 -> i_in2 not criss-crossed??
  207. if len(self.component_set) > 1:
  208. assert isinstance(self.component_set[-1], AtomicDEVS)
  209. self.connectPorts(self.i_in2, self.component_set[-1].i_in)
  210. self.connectPorts(self.component_set[-1].o_out, self.o_out2)
  211. for idx in range(1, len(self.component_set) - 1):
  212. assert isinstance(self.component_set[idx], AtomicDEVS)
  213. self.connectPorts(self.component_set[idx].o_out, self.component_set[idx + 1].i_in)
  214. self.connectPorts(self.i_in2, self.component_set[idx].i_in)
  215. self.connectPorts(self.component_set[idx].o_out, self.o_out2)
  216. def gen_coupled(self):
  217. return HO("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  218. prep_time=self.prep_time, stats=self.stats)
  219. class HOmod(CoupledDEVS):
  220. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, prep_time=0, stats=False):
  221. super().__init__(name)
  222. self.depth = depth
  223. self.width = width
  224. self.int_delay = int_delay
  225. self.ext_delay = ext_delay
  226. self.prep_time = prep_time
  227. self.stats = stats
  228. self.i_in = self.addInPort("i_in")
  229. self.i_in2 = self.addInPort("i_in2")
  230. self.o_out = self.addOutPort("o_out")
  231. if depth < 1:
  232. raise ValueError("Invalid depth")
  233. if width < 1:
  234. raise ValueError("Invalid width")
  235. if int_delay < 0:
  236. raise ValueError("Invalid int_delay")
  237. if ext_delay < 0:
  238. raise ValueError("Invalid ext_delay")
  239. if depth == 1:
  240. if self.stats:
  241. atomic = DelayedAtomicStats("Atomic_0_0", int_delay, ext_delay, add_out_port=True, prep_time=prep_time)
  242. else:
  243. atomic = DelayedAtomic("Atomic_0_0", int_delay, ext_delay, add_out_port=True, prep_time=prep_time)
  244. self.addSubModel(atomic)
  245. self.connectPorts(self.i_in, atomic.i_in)
  246. self.connectPorts(atomic.o_out, self.o_out)
  247. else:
  248. coupled = HOmod("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay, prep_time=prep_time, stats=stats)
  249. self.addSubModel(coupled)
  250. self.connectPorts(self.i_in, coupled.i_in)
  251. self.connectPorts(coupled.o_out, self.o_out)
  252. if width >= 2:
  253. atomics = defaultdict(list)
  254. # Generate atomic components
  255. for i in range(width):
  256. min_row_idx = 0 if i < 2 else i - 1
  257. for j in range(min_row_idx, width - 1):
  258. if self.stats:
  259. atomic = DelayedAtomicStats("Atomic_%d_%d_%d" % (depth - 1, i, j), int_delay, ext_delay,
  260. add_out_port=True, prep_time=prep_time)
  261. else:
  262. atomic = DelayedAtomic("Atomic_%d_%d_%d" % (depth - 1, i, j), int_delay, ext_delay,
  263. add_out_port=True, prep_time=prep_time)
  264. self.addSubModel(atomic)
  265. atomics[i].append(atomic)
  266. # Connect EIC
  267. for atomic in atomics[0]:
  268. self.connectPorts(self.i_in2, atomic.i_in)
  269. for i in range(1, width):
  270. atomic_set = atomics[i]
  271. self.connectPorts(self.i_in2, atomic_set[0].i_in)
  272. # Connect IC
  273. for atomic in atomics[0]: # First row to coupled component
  274. self.connectPorts(atomic.o_out, coupled.i_in2)
  275. for i in range(len(atomics[1])): # Second to first rows
  276. for j in range(len(atomics[0])):
  277. self.connectPorts(atomics[1][i].o_out, atomics[0][j].i_in)
  278. for i in range(2, width): # Rest of rows
  279. for j in range(len(atomics[i])):
  280. self.connectPorts(atomics[i][j].o_out, atomics[i - 1][j + 1].i_in)
  281. class LI2HI(DEVStoneWrapper):
  282. """
  283. Dynamic DEVStone variant that starts as an LI
  284. and (gradually??) transforms into an HI model
  285. """
  286. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, prep_time=0, stats=False):
  287. super().__init__(name, depth, width, int_delay, ext_delay, add_atomic_out_ports=False, prep_time=prep_time,
  288. stats=stats, mode="LI2HI")
  289. for idx in range(1, len(self.component_set)):
  290. assert isinstance(self.component_set[idx], AtomicDEVS)
  291. self.connectPorts(self.i_in, self.component_set[idx].i_in)
  292. def gen_coupled(self):
  293. return LI2HI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  294. prep_time=self.prep_time, stats=self.stats)
  295. def modelTransition(self, state):
  296. if state.get("LI2HI", True):
  297. for i in range(len(self.component_set) - 1): # -1 because the last model can't be connected
  298. # basically checks if it is an atomic model and if it got the extra output port
  299. if hasattr(self.component_set[i], "out_ports") and len(self.component_set[i].out_ports) == 1:
  300. # print(f"Connect {self.component_set[i].name} to {self.component_set[i+1].name}")
  301. self.connectPorts(self.component_set[i].out_ports[0], self.component_set[i + 1].i_in)
  302. return False
  303. return False
  304. class HI2LI(DEVStoneWrapper):
  305. """
  306. Dynamic DEVStone variant that starts as an HI
  307. and (gradually??) transforms into an LI model
  308. """
  309. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, prep_time=0, stats=False):
  310. super().__init__(name, depth, width, int_delay, ext_delay, add_atomic_out_ports=True, prep_time=prep_time,
  311. stats=stats, mode="HI2LI")
  312. if len(self.component_set) > 1:
  313. assert isinstance(self.component_set[-1], AtomicDEVS)
  314. self.connectPorts(self.i_in, self.component_set[-1].i_in)
  315. for idx in range(1, len(self.component_set) - 1):
  316. assert isinstance(self.component_set[idx], AtomicDEVS)
  317. self.connectPorts(self.component_set[idx].o_out, self.component_set[idx + 1].i_in)
  318. self.connectPorts(self.i_in, self.component_set[idx].i_in)
  319. def gen_coupled(self):
  320. return HI2LI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  321. prep_time=self.prep_time, stats=self.stats)
  322. class DynamicGenerator(AtomicDEVS):
  323. def __init__(self, name: str, period: float = 1, cycles: int = 1, num: int = 1):
  324. super().__init__(name)
  325. self.period = period
  326. self.number = num # how many models need to be generated per cycle
  327. self.state = cycles + 1 # total generation cycles
  328. def intTransition(self):
  329. return self.state - 1
  330. def timeAdvance(self):
  331. if self.state <= 0:
  332. return INFINITY
  333. return self.period
  334. def outputFnc(self):
  335. return {}
  336. def modelTransition(self, state):
  337. # every time TA elapses, this will be called on the atomic:
  338. # set a flag the parent coupled can read
  339. # increment counter and request modelTransition (return True)
  340. if self.state < 0:
  341. return False
  342. num2create = self.number
  343. if self.state < self.number:
  344. num2create = self.state
  345. state["generate"] = True
  346. state["create"] = num2create
  347. state["created"] = 0
  348. return True
  349. class Distributer(AtomicDEVS):
  350. def __init__(self, name: str):
  351. super().__init__(name)
  352. self.i_in = self.addInPort("i_in")
  353. self.o_out = self.addOutPort("o_out")
  354. self.state = "passive"
  355. self.received = []
  356. def intTransition(self):
  357. return "passive"
  358. def timeAdvance(self):
  359. if self.state == "active":
  360. return 0
  361. return INFINITY
  362. def outputFnc(self):
  363. if self.state == "active" and self.received:
  364. return {self.o_out: self.received}
  365. return {}
  366. def extTransition(self, inputs):
  367. for key, item in inputs.items():
  368. self.received.append(item[0])
  369. return "active"
  370. class DynamicDEVStoneWrapper(DEVStoneWrapper, ABC):
  371. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float,
  372. add_atomic_out_ports: bool = False, /, prep_time=0, stats=False, root=False, mode: str = "", number: int = 1, gen_mode: str="uniform"):
  373. if number <= 0:
  374. raise ValueError("number of models to be generated must be greater than zero")
  375. self.root = root
  376. self.mode = mode
  377. self.created = 0 # keeps track of how many atomic models have been created
  378. self.current_width = 1
  379. self.number = number
  380. self.max_gen = width - 1 # dynamically generate atomic components until width is reached excludes the coupled model
  381. super().__init__(name, depth, width, int_delay, ext_delay, add_atomic_out_ports, prep_time=prep_time,
  382. stats=stats, mode=mode, dynamic=True)
  383. self.connector = self.i_in
  384. if self.depth == 1:
  385. self.generator = self.addSubModel(DynamicGenerator(self.name + "_gen", cycles=self.max_gen, num=self.number))
  386. def createAtomic(self):
  387. name = f"Atomic_0_{self.current_width}"
  388. if self.depth > 1:
  389. name = f"Atomic_{self.depth-1}_{self.current_width-1}"
  390. p_time = 1 - round(random.uniform((self.current_width - 1) / self.width, ((self.current_width - 1) + 0.5) / self.width), DIGITS)
  391. if self.stats:
  392. atomic = DelayedAtomicStats(name, self.int_delay, self.ext_delay,
  393. add_out_port=self.add_atomic_out_ports, prep_time=p_time,
  394. mode=self.mode)
  395. else:
  396. atomic = DelayedAtomic(name, self.int_delay, self.ext_delay,
  397. add_out_port=self.add_atomic_out_ports, prep_time=p_time,
  398. mode=self.mode)
  399. self.models.append(self.addSubModel(atomic))
  400. return atomic
  401. def modelTransition(self, state):
  402. if state.get("generate", True) and self.depth == 1:
  403. return True
  404. if state.get("generate", True) and self.depth > 1:
  405. number = state.get("create")
  406. for _ in range(number):
  407. atom = self.createAtomic()
  408. self.connectPorts(self.connector, atom.i_in)
  409. if len(self.models) > 1:
  410. prev = self.models[-2] # new model was already added so the previous one isn't the last in the list anymore
  411. if isinstance(prev, AtomicDEVS) and hasattr(prev, "o_out"):
  412. self.connectPorts(prev.o_out, atom.i_in)
  413. if hasattr(self, "o_out2"):
  414. self.connectPorts(atom.o_out, self.o_out2)
  415. self.current_width += 1
  416. if self.current_width > self.width:
  417. raise RuntimeError(f"The width has grown beyond what was specified!"
  418. f"\n current width: {self.current_width}"
  419. f"\n specified width: {self.width}")
  420. # enables visualisation of each level (coupled model)
  421. # if self.current_width == self.width:
  422. # self.dot(f"dLI_{self.depth}")
  423. if not self.root:
  424. state["created"] += number
  425. return True
  426. self.created += state["created"] + number
  427. return False
  428. return False
  429. class dLI(DynamicDEVStoneWrapper):
  430. """
  431. A LI model which grows in width
  432. """
  433. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, /, prep_time=0, stats=False, root=True, number: int = 1, gen_mode: str = "uniform"):
  434. super().__init__(name, depth, width, int_delay, ext_delay, False, prep_time, stats, mode="LI-Dynamic", root=root, number=number, gen_mode=gen_mode)
  435. def gen_coupled(self):
  436. return dLI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  437. prep_time=self.prep_time, stats=self.stats, root=False, number=self.number)
  438. class mdLI(DynamicDEVStoneWrapper):
  439. """
  440. A LI model which grows in width
  441. """
  442. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, /, prep_time=0, stats=False, root=True, number: int = 1, gen_mode: str = "uniform"):
  443. super().__init__(name, depth, width, int_delay, ext_delay, False, prep_time, stats, mode="LI-Dynamic", root=root, number=number, gen_mode=gen_mode)
  444. intermediate = Distributer("distributer")
  445. self.addSubModel(intermediate)
  446. self.connectPorts(self.i_in, intermediate.i_in)
  447. self.connector = intermediate.o_out
  448. def gen_coupled(self):
  449. return mdLI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  450. prep_time=self.prep_time, stats=self.stats, root=False, number=self.number)
  451. class dHI(DynamicDEVStoneWrapper):
  452. """
  453. A HI model which grows in width
  454. """
  455. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, /, prep_time=0, stats=False, root=True, number: int = 1, gen_mode: str = "uniform"):
  456. super().__init__(name, depth, width, int_delay, ext_delay, True, prep_time, stats, mode="HI-Dynamic", root=root, number=number, gen_mode=gen_mode)
  457. def gen_coupled(self):
  458. return dHI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  459. prep_time=self.prep_time, stats=self.stats, root=False, number=self.number)
  460. class mdHI(DynamicDEVStoneWrapper):
  461. """
  462. A HI model which grows in width
  463. """
  464. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, /, prep_time=0, stats=False, root: bool = True, number: int = 1, gen_mode: str = "uniform"):
  465. super().__init__(name, depth, width, int_delay, ext_delay, True, prep_time=prep_time, stats=stats, mode="HI-Dynamic", root=root, number=number, gen_mode=gen_mode)
  466. intermediate = Distributer("distributer")
  467. self.addSubModel(intermediate)
  468. self.connectPorts(self.i_in, intermediate.i_in)
  469. self.connector = intermediate.o_out
  470. def gen_coupled(self):
  471. return mdHI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  472. prep_time=self.prep_time, stats=self.stats, root=False, number=self.number)
  473. class dHO(DynamicDEVStoneWrapper):
  474. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, prep_time=0, stats=False, root: bool = True, number: int = 1, gen_mode: str = "uniform"):
  475. super().__init__(name, depth, width, int_delay, ext_delay, True, prep_time=prep_time, stats=stats, mode="HO-dynamic", root=root, number=number, gen_mode=gen_mode)
  476. self.i_in2 = self.addInPort("i_in2")
  477. self.o_out2 = self.addOutPort("o_out2")
  478. assert len(self.component_set) > 0
  479. if isinstance(self.component_set[0], CoupledDEVS):
  480. self.connectPorts(self.i_in, self.component_set[0].i_in2) # seems wrong i_in -> i_in and i_in2 -> i_in2 not criss-crossed??
  481. self.connector = self.i_in2
  482. def gen_coupled(self):
  483. return dHO("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay, self.prep_time, self.stats, root=False, number=self.number)
  484. class mdHO(DynamicDEVStoneWrapper):
  485. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float, prep_time=0, stats=False, root: bool = True, number: int = 1, gen_mode: str = "uniform"):
  486. super().__init__(name, depth, width, int_delay, ext_delay, True, prep_time=prep_time, stats=stats, mode="HO-dynamic", root=root, number=number, gen_mode=gen_mode)
  487. self.i_in2 = self.addInPort("i_in2")
  488. self.o_out2 = self.addOutPort("o_out2")
  489. assert len(self.component_set) > 0
  490. if isinstance(self.component_set[0], CoupledDEVS):
  491. self.connectPorts(self.i_in, self.component_set[0].i_in2) # seems wrong i_in -> i_in and i_in2 -> i_in2 not criss-crossed??
  492. intermediate = Distributer("distributer")
  493. self.addSubModel(intermediate)
  494. self.connectPorts(self.i_in2, intermediate.i_in)
  495. self.connector = intermediate.o_out
  496. def gen_coupled(self):
  497. return mdHO("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay, self.prep_time, self.stats, root=False, number=self.number)
  498. class dynamicTest(CoupledDEVS):
  499. def __init__(self):
  500. super().__init__("TEST")
  501. self.i_in = self.addInPort("i_in")
  502. self.o_out = self.addOutPort("o_out")
  503. self.coupled = self.addSubModel(dynamicTest2())
  504. self.model1 = self.addSubModel(DelayedAtomic("root",0, 0, True, 0.1))
  505. self.model2 = self.addSubModel(DelayedAtomic("model1", 0, 0, True, 0.1))
  506. self.model3 = self.addSubModel(DelayedAtomic("model2", 0, 0, True, 0.1))
  507. # self.model4 = self.addSubModel(DelayedAtomic("model3", 0, 0, True, 0.1))
  508. self.connectPorts(self.i_in, self.coupled.i_in)
  509. self.connectPorts(self.coupled.o_out, self.o_out)
  510. self.connectPorts(self.i_in, self.model1.i_in)
  511. self.connectPorts(self.model1.o_out, self.model2.i_in)
  512. # self.connectPorts(self.model1.o_out, self.model3.i_in)
  513. # r - m1 - m2
  514. # \_ m3
  515. # self.generator = self.addSubModel(DynamicGenerator("test"))
  516. def modelTransition(self, state):
  517. if state.get("generate", True):
  518. model3 = self.addSubModel(DelayedAtomic("model3", 0, 0, True, 0.1))
  519. self.connectPorts(self.model1.o_out, model3.i_in)
  520. # model4 = self.addSubModel(DelayedAtomic("model4", 0, 0, True, 0.1))
  521. # self.connectPorts(self.model3.o_out, model4.i_in)
  522. class dynamicTest2(CoupledDEVS):
  523. def __init__(self):
  524. super().__init__("TEST")
  525. self.i_in = self.addInPort("i_in")
  526. self.o_out = self.addOutPort("o_out")
  527. self.generator = self.addSubModel(DynamicGenerator("test"))
  528. def modelTransition(self, state):
  529. if state.get("generate", True):
  530. model1 = self.addSubModel(DelayedAtomic("model3", 0, 0, True, 0.1))
  531. self.connectPorts(self.i_in, model1.i_in)
  532. model2 = self.addSubModel(DelayedAtomic("model2", 0, 0, True, 0.1))