devstone.py 28 KB

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