devstone.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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, target: 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 = target + self.number # total models to generate
  328. # the number of models to generate per cycle is added
  329. # since the internal transition occurs before the
  330. # model transition, otherwise the model generation
  331. # would finish too early
  332. def intTransition(self):
  333. if self.state < self.number:
  334. return 0
  335. return self.state - self.number
  336. def timeAdvance(self):
  337. if self.state <= 0:
  338. return INFINITY
  339. return self.period
  340. def outputFnc(self):
  341. return {}
  342. def modelTransition(self, state):
  343. # every time TA elapses, this will be called on the atomic:
  344. # set a flag the parent coupled can read
  345. # increment counter and request modelTransition (return True)
  346. if self.state < 0:
  347. return False
  348. num2create = self.number
  349. if self.state < self.number:
  350. num2create = self.state
  351. state["generate"] = True
  352. state["create"] = num2create
  353. state["created"] = 0
  354. return True
  355. class Distributer(AtomicDEVS):
  356. def __init__(self, name: str):
  357. super().__init__(name)
  358. self.i_in = self.addInPort("i_in")
  359. self.o_out = self.addOutPort("o_out")
  360. self.state = "passive"
  361. self.received = []
  362. def intTransition(self):
  363. return "passive"
  364. def timeAdvance(self):
  365. if self.state == "active":
  366. return 0
  367. return INFINITY
  368. def outputFnc(self):
  369. if self.state == "active" and self.received:
  370. return {self.o_out: self.received}
  371. return {}
  372. def extTransition(self, inputs):
  373. for key, item in inputs.items():
  374. self.received.append(item[0])
  375. return "active"
  376. class DynamicDEVStoneWrapper(DEVStoneWrapper, ABC):
  377. def __init__(self, name: str, depth: int, width: int, int_delay: float, ext_delay: float,
  378. add_atomic_out_ports: bool = False, /, prep_time=0, stats=False, root=False, mode: str = "", number: int = 1, gen_mode: str="uniform"):
  379. if number <= 0:
  380. raise ValueError("number of models to be generated must be greater than zero")
  381. self.root = root
  382. self.mode = mode
  383. self.created = 0 # keeps track of how many atomic models have been created
  384. self.current_width = 1
  385. self.number = number
  386. self.max_gen = width - 1 # dynamically generate atomic components until width is reached excludes the coupled model
  387. super().__init__(name, depth, width, int_delay, ext_delay, add_atomic_out_ports, prep_time=prep_time,
  388. stats=stats, mode=mode, dynamic=True)
  389. self.connector = self.i_in
  390. if self.depth == 1:
  391. self.generator = self.addSubModel(DynamicGenerator(self.name + "_gen", target=self.max_gen, num=self.number))
  392. def createAtomic(self):
  393. name = f"Atomic_0_{self.current_width}"
  394. if self.depth > 1:
  395. name = f"Atomic_{self.depth-1}_{self.current_width-1}"
  396. p_time = 1 - round(random.uniform((self.current_width - 1) / self.width, ((self.current_width - 1) + 0.5) / self.width), DIGITS)
  397. if self.stats:
  398. atomic = DelayedAtomicStats(name, self.int_delay, self.ext_delay,
  399. add_out_port=self.add_atomic_out_ports, prep_time=p_time,
  400. mode=self.mode)
  401. else:
  402. atomic = DelayedAtomic(name, self.int_delay, self.ext_delay,
  403. add_out_port=self.add_atomic_out_ports, prep_time=p_time,
  404. mode=self.mode)
  405. self.models.append(self.addSubModel(atomic))
  406. return atomic
  407. def modelTransition(self, state):
  408. if state.get("generate", True) and self.depth == 1:
  409. return True
  410. if state.get("generate", True) and self.depth > 1:
  411. number = state.get("create")
  412. for _ in range(number):
  413. atom = self.createAtomic()
  414. self.connectPorts(self.connector, atom.i_in)
  415. if len(self.models) > 1:
  416. prev = self.models[-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, stats=False, root=True, number: int = 1, gen_mode: str = "uniform"):
  440. super().__init__(name, depth, width, int_delay, ext_delay, False, prep_time, stats, mode="LI-Dynamic", root=root, number=number, gen_mode=gen_mode)
  441. def gen_coupled(self):
  442. return dLI("Coupled_%d" % (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, stats=False, root=True, number: int = 1, gen_mode: str = "uniform"):
  449. super().__init__(name, depth, width, int_delay, ext_delay, False, prep_time, stats, mode="LI-Dynamic", root=root, number=number, gen_mode=gen_mode)
  450. intermediate = Distributer("distributer")
  451. self.addSubModel(intermediate)
  452. self.connectPorts(self.i_in, intermediate.i_in)
  453. self.connector = intermediate.o_out
  454. def gen_coupled(self):
  455. return mdLI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  456. prep_time=self.prep_time, stats=self.stats, root=False, number=self.number)
  457. class dHI(DynamicDEVStoneWrapper):
  458. """
  459. A HI model which grows in width
  460. """
  461. 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"):
  462. super().__init__(name, depth, width, int_delay, ext_delay, True, prep_time, stats, mode="HI-Dynamic", root=root, number=number, gen_mode=gen_mode)
  463. def gen_coupled(self):
  464. return dHI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  465. prep_time=self.prep_time, stats=self.stats, root=False, number=self.number)
  466. class mdHI(DynamicDEVStoneWrapper):
  467. """
  468. A HI model which grows in width
  469. """
  470. 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"):
  471. 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)
  472. intermediate = Distributer("distributer")
  473. self.addSubModel(intermediate)
  474. self.connectPorts(self.i_in, intermediate.i_in)
  475. self.connector = intermediate.o_out
  476. def gen_coupled(self):
  477. return mdHI("Coupled_%d" % (self.depth - 1), self.depth - 1, self.width, self.int_delay, self.ext_delay,
  478. prep_time=self.prep_time, stats=self.stats, root=False, number=self.number)
  479. class dHO(DynamicDEVStoneWrapper):
  480. 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"):
  481. 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)
  482. self.i_in2 = self.addInPort("i_in2")
  483. self.o_out2 = self.addOutPort("o_out2")
  484. assert len(self.component_set) > 0
  485. if isinstance(self.component_set[0], CoupledDEVS):
  486. 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??
  487. self.connector = self.i_in2
  488. def gen_coupled(self):
  489. 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)
  490. class mdHO(DynamicDEVStoneWrapper):
  491. 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"):
  492. 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)
  493. self.i_in2 = self.addInPort("i_in2")
  494. self.o_out2 = self.addOutPort("o_out2")
  495. assert len(self.component_set) > 0
  496. if isinstance(self.component_set[0], CoupledDEVS):
  497. 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??
  498. intermediate = Distributer("distributer")
  499. self.addSubModel(intermediate)
  500. self.connectPorts(self.i_in2, intermediate.i_in)
  501. self.connector = intermediate.o_out
  502. def gen_coupled(self):
  503. 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)
  504. class dynamicTest(CoupledDEVS):
  505. def __init__(self):
  506. super().__init__("TEST")
  507. self.i_in = self.addInPort("i_in")
  508. self.o_out = self.addOutPort("o_out")
  509. self.coupled = self.addSubModel(dynamicTest2())
  510. self.model1 = self.addSubModel(DelayedAtomic("root",0, 0, True, 0.1))
  511. self.model2 = self.addSubModel(DelayedAtomic("model1", 0, 0, True, 0.1))
  512. self.model3 = self.addSubModel(DelayedAtomic("model2", 0, 0, True, 0.1))
  513. # self.model4 = self.addSubModel(DelayedAtomic("model3", 0, 0, True, 0.1))
  514. self.connectPorts(self.i_in, self.coupled.i_in)
  515. self.connectPorts(self.coupled.o_out, self.o_out)
  516. self.connectPorts(self.i_in, self.model1.i_in)
  517. self.connectPorts(self.model1.o_out, self.model2.i_in)
  518. # self.connectPorts(self.model1.o_out, self.model3.i_in)
  519. # r - m1 - m2
  520. # \_ m3
  521. # self.generator = self.addSubModel(DynamicGenerator("test"))
  522. def modelTransition(self, state):
  523. if state.get("generate", True):
  524. model3 = self.addSubModel(DelayedAtomic("model3", 0, 0, True, 0.1))
  525. self.connectPorts(self.model1.o_out, model3.i_in)
  526. # model4 = self.addSubModel(DelayedAtomic("model4", 0, 0, True, 0.1))
  527. # self.connectPorts(self.model3.o_out, model4.i_in)
  528. class dynamicTest2(CoupledDEVS):
  529. def __init__(self):
  530. super().__init__("TEST")
  531. self.i_in = self.addInPort("i_in")
  532. self.o_out = self.addOutPort("o_out")
  533. self.generator = self.addSubModel(DynamicGenerator("test"))
  534. def modelTransition(self, state):
  535. if state.get("generate", True):
  536. model1 = self.addSubModel(DelayedAtomic("model3", 0, 0, True, 0.1))
  537. self.connectPorts(self.i_in, model1.i_in)
  538. model2 = self.addSubModel(DelayedAtomic("model2", 0, 0, True, 0.1))