devstone.py 29 KB

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