cbd_semantics.alc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. include "primitives.alh"
  2. include "modelling.alh"
  3. include "object_operations.alh"
  4. include "library.alh"
  5. include "conformance_scd.alh"
  6. include "io.alh"
  7. include "metamodels.alh"
  8. include "compilation_manager.alh"
  9. Void function main():
  10. Element model
  11. String verify_result
  12. while (True):
  13. execute_cbd(instantiate_model(import_node("models/CausalBlockDiagrams_Design")))
  14. Element function retype_to_runtime(design_model : Element):
  15. Element runtime_model
  16. Element all_blocks
  17. Element all_links
  18. String mm_type_name
  19. String element_name
  20. String attr_name
  21. String attr_value
  22. String attribute
  23. String src
  24. String dst
  25. String time
  26. Element all_attributes
  27. runtime_model = instantiate_model(import_node("models/CausalBlockDiagrams_Runtime"))
  28. all_blocks = allInstances(design_model, "Block")
  29. while (list_len(all_blocks) > 0):
  30. element_name = set_pop(all_blocks)
  31. mm_type_name = reverseKeyLookup(design_model["metamodel"]["model"], dict_read_node(design_model["type_mapping"], design_model["model"][element_name]))
  32. element_name = instantiate_node(runtime_model, mm_type_name, element_name)
  33. if (is_nominal_instance(design_model, element_name, "ConstantBlock")):
  34. instantiate_attribute(runtime_model, element_name, "value", read_attribute(design_model, element_name, "value"))
  35. // Don't merge this together with the block conversion, as the destination block might not exist yet!
  36. all_links = allInstances(design_model, "Link")
  37. while (read_nr_out(all_links) > 0):
  38. element_name = set_pop(all_links)
  39. src = reverseKeyLookup(design_model["model"], read_edge_src(design_model["model"][element_name]))
  40. dst = reverseKeyLookup(design_model["model"], read_edge_dst(design_model["model"][element_name]))
  41. instantiate_link(runtime_model, "Link", element_name, src, dst)
  42. all_links = allInstances(design_model, "InitialCondition")
  43. while (read_nr_out(all_links) > 0):
  44. element_name = set_pop(all_links)
  45. src = reverseKeyLookup(design_model["model"], read_edge_src(design_model["model"][element_name]))
  46. dst = reverseKeyLookup(design_model["model"], read_edge_dst(design_model["model"][element_name]))
  47. instantiate_link(runtime_model, "InitialCondition", element_name, src, dst)
  48. return runtime_model!
  49. Element function sanitize(new_runtime_model : Element, old_runtime_model : Element):
  50. Element all_blocks
  51. Element all_links
  52. String element_name
  53. String attr_name
  54. String attr_value
  55. String attribute
  56. String time
  57. Element all_attributes
  58. Float current_time
  59. all_blocks = allInstances(new_runtime_model, "Block")
  60. while (list_len(all_blocks) > 0):
  61. element_name = set_pop(all_blocks)
  62. if (dict_in(old_runtime_model["model"], element_name)):
  63. if (is_nominal_instance(new_runtime_model, element_name, "ICBlock")):
  64. instantiate_attribute(new_runtime_model, element_name, "last_in", read_attribute(old_runtime_model, element_name, "last_in"))
  65. if (is_nominal_instance(new_runtime_model, element_name, "IntegratorBlock")):
  66. instantiate_attribute(new_runtime_model, element_name, "last_out", read_attribute(old_runtime_model, element_name, "last_out"))
  67. instantiate_attribute(new_runtime_model, element_name, "signal", read_attribute(old_runtime_model, element_name, "signal"))
  68. else:
  69. instantiate_attribute(new_runtime_model, element_name, "signal", 0.0)
  70. if (dict_in(old_runtime_model["model"], "time")):
  71. current_time = read_attribute(old_runtime_model, "time", "current_time")
  72. else:
  73. current_time = 0
  74. time = instantiate_node(new_runtime_model, "Time", "time")
  75. instantiate_attribute(new_runtime_model, time, "start_time", current_time)
  76. instantiate_attribute(new_runtime_model, time, "current_time", current_time)
  77. return new_runtime_model!
  78. Element function create_schedule(model : Element):
  79. // Create nice graph first
  80. Element nodes
  81. Element successors
  82. String element_name
  83. Element incoming_links
  84. Element all_blocks
  85. nodes = allInstances(model, "Block")
  86. successors = create_node()
  87. while (read_nr_out(nodes) > 0):
  88. element_name = set_pop(nodes)
  89. if (bool_not(dict_in(successors, element_name))):
  90. dict_add(successors, element_name, create_node())
  91. if (is_nominal_instance(model, element_name, "ICBlock")):
  92. if (element_eq(read_attribute(model, element_name, "last_in"), read_root())):
  93. incoming_links = allIncomingAssociationInstances(model, element_name, "InitialCondition")
  94. else:
  95. incoming_links = create_node()
  96. if (is_nominal_instance(model, element_name, "DerivatorBlock")):
  97. Element new_incoming_links
  98. new_incoming_links = allIncomingAssociationInstances(model, element_name, "Link")
  99. while (read_nr_out(new_incoming_links) > 0):
  100. list_append(incoming_links, set_pop(new_incoming_links))
  101. else:
  102. incoming_links = allIncomingAssociationInstances(model, element_name, "Link")
  103. while (read_nr_out(incoming_links) > 0):
  104. String source
  105. source = readAssociationSource(model, set_pop(incoming_links))
  106. if (bool_not(dict_in(successors, source))):
  107. dict_add(successors, source, create_node())
  108. set_add(successors[source], element_name)
  109. Element values
  110. values = create_node()
  111. dict_add(values, "S", create_node())
  112. dict_add(values, "index", 0)
  113. dict_add(values, "indices", create_node())
  114. dict_add(values, "lowlink", create_node())
  115. dict_add(values, "onStack", create_node())
  116. dict_add(values, "successors", successors)
  117. dict_add(values, "SCC", create_node())
  118. nodes = allInstances(model, "Block")
  119. while (read_nr_out(nodes) > 0):
  120. strongconnect(set_pop(nodes), values)
  121. log("Computed SCC!")
  122. log("Print list:")
  123. Integer i
  124. Integer j
  125. Element lst
  126. i = 0
  127. while (i < read_nr_out(values["SCC"])):
  128. log("[")
  129. lst = list_read(values["SCC"], i)
  130. j = 0
  131. while (j < read_nr_out(lst)):
  132. log(" " + cast_v2s(list_read(lst, j)))
  133. j = j + 1
  134. log("]")
  135. i = i + 1
  136. log("=== END")
  137. return values["SCC"]!
  138. Void function dict_overwrite(d : Element, key : Element, value : Element):
  139. if (dict_in(d, key)):
  140. dict_delete(d, key)
  141. if (dict_in_node(d, key)):
  142. dict_delete_node(d, key)
  143. dict_add(d, key, value)
  144. return !
  145. Integer function min(a : Integer, b : Integer):
  146. if (a < b):
  147. return a!
  148. else:
  149. return b!
  150. Void function strongconnect(v : String, values : Element):
  151. if (dict_in(values["indices"], v)):
  152. return!
  153. log("Compute strong connected components")
  154. log("Source: " + v)
  155. dict_overwrite(values["indices"], v, values["index"])
  156. dict_overwrite(values["lowlink"], v, values["index"])
  157. dict_overwrite(values, "index", cast_s2i(cast_v2s(values["index"])) + 1)
  158. list_append(values["S"], v)
  159. dict_overwrite(values["onStack"], v, True)
  160. Element successors
  161. String w
  162. successors = values["successors"][v]
  163. while (read_nr_out(successors) > 0):
  164. w = set_pop(successors)
  165. log("Found successor " + w)
  166. if (bool_not(dict_in(values["indices"], w))):
  167. strongconnect(w, values)
  168. log("Old lowlink: " + cast_v2s(values["lowlink"][v]))
  169. dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["lowlink"][w]))
  170. log("Set lowlink of " + v)
  171. log(" to " + cast_v2s(values["lowlink"][v]))
  172. elif (dict_in(values["onStack"], w)):
  173. if (values["onStack"][w]):
  174. dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["indices"][w]))
  175. if (value_eq(values["lowlink"][v], values["indices"][v])):
  176. Element scc
  177. scc = create_node()
  178. // It will always differ now
  179. w = list_pop(values["S"])
  180. list_append(scc, w)
  181. while (w != v):
  182. w = list_pop(values["S"])
  183. list_append(scc, w)
  184. dict_overwrite(values["onStack"], w, False)
  185. list_insert(values["SCC"], scc, 0)
  186. return!
  187. Element function list_pop(list : Element):
  188. Integer top
  189. Element t
  190. top = list_len(list) - 1
  191. t = list_read(list, top)
  192. list_delete(list, top)
  193. return t!
  194. String function readType(model : Element, name : String):
  195. return reverseKeyLookup(model["metamodel"]["model"], dict_read_node(model["type_mapping"], model["model"][name]))!
  196. Void function step_simulation(model : Element, schedule : Element):
  197. String time
  198. Float signal
  199. Element incoming
  200. String selected
  201. String block
  202. String elem
  203. String blocktype
  204. Element memory_blocks
  205. Integer i
  206. Float delta_t
  207. time = "time"
  208. delta_t = 0.1
  209. memory_blocks = create_node()
  210. output("SIM_TIME " + cast_v2s(read_attribute(model, time, "current_time")))
  211. i = 0
  212. while (i < read_nr_out(schedule)):
  213. block = list_read(schedule, i)
  214. i = i + 1
  215. // Execute "block"
  216. blocktype = readType(model, block)
  217. if (blocktype == "ConstantBlock"):
  218. signal = read_attribute(model, block, "value")
  219. elif (blocktype == "AdditionBlock"):
  220. signal = 0.0
  221. incoming = allIncomingAssociationInstances(model, block, "Link")
  222. while (read_nr_out(incoming) > 0):
  223. selected = readAssociationSource(model, set_pop(incoming))
  224. signal = signal + cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  225. elif (blocktype == "MultiplyBlock"):
  226. signal = 1.0
  227. incoming = allIncomingAssociationInstances(model, block, "Link")
  228. while (read_nr_out(incoming) > 0):
  229. selected = readAssociationSource(model, set_pop(incoming))
  230. signal = signal * cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  231. elif (blocktype == "NegatorBlock"):
  232. incoming = allIncomingAssociationInstances(model, block, "Link")
  233. signal = 0.0
  234. while (read_nr_out(incoming) > 0):
  235. selected = readAssociationSource(model, set_pop(incoming))
  236. signal = float_neg(cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
  237. elif (blocktype == "InverseBlock"):
  238. signal = 0.0
  239. incoming = allIncomingAssociationInstances(model, block, "Link")
  240. while (read_nr_out(incoming) > 0):
  241. selected = readAssociationSource(model, set_pop(incoming))
  242. signal = float_division(1.0, cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
  243. elif (blocktype == "DelayBlock"):
  244. signal = 0.0
  245. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  246. // No memory yet, so use initial condition
  247. incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
  248. while (read_nr_out(incoming) > 0):
  249. selected = readAssociationSource(model, set_pop(incoming))
  250. signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  251. else:
  252. signal = read_attribute(model, block, "last_in")
  253. unset_attribute(model, block, "last_in")
  254. set_add(memory_blocks, block)
  255. elif (blocktype == "IntegratorBlock"):
  256. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  257. // No history yet, so use initial values
  258. incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
  259. while (read_nr_out(incoming) > 0):
  260. selected = readAssociationSource(model, set_pop(incoming))
  261. signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  262. else:
  263. signal = cast_s2f(cast_v2s(read_attribute(model, block, "last_in"))) + (delta_t * cast_s2f(cast_v2s(read_attribute(model, block, "last_out"))))
  264. unset_attribute(model, block, "last_in")
  265. unset_attribute(model, block, "last_out")
  266. instantiate_attribute(model, block, "last_out", signal)
  267. set_add(memory_blocks, block)
  268. elif (blocktype == "DerivatorBlock"):
  269. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  270. // No history yet, so use initial values
  271. incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
  272. while (read_nr_out(incoming) > 0):
  273. selected = readAssociationSource(model, set_pop(incoming))
  274. signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  275. else:
  276. incoming = allIncomingAssociationInstances(model, block, "Link")
  277. while (read_nr_out(incoming) > 0):
  278. selected = readAssociationSource(model, set_pop(incoming))
  279. signal = (cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))) - cast_s2f(cast_v2s(read_attribute(model, block, "last_in")))) / delta_t
  280. unset_attribute(model, block, "last_in")
  281. set_add(memory_blocks, block)
  282. unset_attribute(model, block, "signal")
  283. instantiate_attribute(model, block, "signal", signal)
  284. output((("SIM_PROBE " + cast_v2s(block)) + " ") + cast_v2s(signal))
  285. output("SIM_END")
  286. while (read_nr_out(memory_blocks) > 0):
  287. block = set_pop(memory_blocks)
  288. // Update memory
  289. incoming = allIncomingAssociationInstances(model, block, "Link")
  290. while (read_nr_out(incoming) > 0):
  291. selected = readAssociationSource(model, set_pop(incoming))
  292. instantiate_attribute(model, block, "last_in", cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
  293. // Increase simulation time
  294. Float new_time
  295. new_time = cast_s2f(cast_v2s(read_attribute(model, time, "current_time"))) + delta_t
  296. unset_attribute(model, time, "current_time")
  297. instantiate_attribute(model, time, "current_time", new_time)
  298. return !
  299. Void function execute_cbd(design_model : Element):
  300. String verify_result
  301. Element runtime_model
  302. Element old_runtime_model
  303. String cmd
  304. Boolean running
  305. Element schedule_init
  306. Element schedule_run
  307. Element schedule
  308. String conforming
  309. old_runtime_model = instantiate_model(import_node("models/CausalBlockDiagrams_Runtime"))
  310. runtime_model = retype_to_runtime(design_model)
  311. runtime_model = sanitize(runtime_model, old_runtime_model)
  312. running = False
  313. conforming = conformance_scd(design_model)
  314. if (conforming == "OK"):
  315. output("CONFORMANCE_OK")
  316. else:
  317. output("CONFORMANCE_FAIL")
  318. schedule_init = create_schedule(runtime_model)
  319. schedule_run = read_root()
  320. while (True):
  321. // If we are running, we just don't block for input and automatically do a step if there is no input
  322. if (running):
  323. if (has_input()):
  324. cmd = input()
  325. else:
  326. cmd = "step"
  327. else:
  328. cmd = input()
  329. // Process input
  330. if (cmd == "simulate"):
  331. // Simulation should toggle running to True, but only if the model is conforming
  332. if (conforming == "OK"):
  333. running = True
  334. else:
  335. output("CONFORMANCE_FAIL " + conforming)
  336. elif (cmd == "step"):
  337. // Stepping should make a single step, but first need to pick the correct schedule to use
  338. if (conforming == "OK"):
  339. if (read_attribute(runtime_model, "time", "start_time") == read_attribute(runtime_model, "time", "current_time")):
  340. schedule = schedule_init
  341. else:
  342. if (element_eq(schedule_run, read_root())):
  343. schedule_run = create_schedule(runtime_model)
  344. schedule = schedule_run
  345. step_simulation(runtime_model, schedule)
  346. else:
  347. output("CONFORMANCE_FAIL " + conforming)
  348. elif (cmd == "pause"):
  349. // Pausing merely stops a running simulation
  350. running = False
  351. elif (cmd == "read_available_attributes"):
  352. // Returns a list of all available attributes
  353. Element attr_list
  354. Element attrs
  355. Element attr
  356. attr_list = getAttributeList(design_model, input())
  357. attrs = dict_keys(attr_list)
  358. while (0 < read_nr_out(attrs)):
  359. attr = set_pop(attrs)
  360. output("AVAILABLE_ATTR_VALUE " + cast_v2s(attr))
  361. output("AVAILABLE_ATTR_TYPE " + cast_v2s(dict_read(attr_list, attr)))
  362. output("AVAILABLE_ATTR_END")
  363. elif (cmd == "read_attribute"):
  364. // Returns the value of an attribute
  365. output("ATTR_VALUE " + cast_v2s(read_attribute(design_model, input(), input())))
  366. elif (bool_or(bool_or(cmd == "set_attribute", cmd == "instantiate_node"), bool_or(cmd == "delete_element", cmd == "instantiate_association"))):
  367. // Modify the structure
  368. if (cmd == "set_attribute"):
  369. // Setting an attribute
  370. String element_name
  371. String attribute_name
  372. element_name = input()
  373. attribute_name = input()
  374. // Delete it if it exists already
  375. if (bool_not(element_eq(read_attribute(design_model, element_name, attribute_name), read_root()))):
  376. unset_attribute(design_model, element_name, attribute_name)
  377. // And finally set it
  378. instantiate_attribute(design_model, element_name, attribute_name, input())
  379. elif (cmd == "instantiate_node"):
  380. // Instantiate a node
  381. instantiate_node(design_model, input(), input())
  382. elif (cmd == "instantiate_association"):
  383. // Instantiate an association
  384. instantiate_link(design_model, input(), input(), input(), input())
  385. elif (cmd == "delete_element"):
  386. // Delete the provided element
  387. model_delete_element(design_model, input())
  388. // After changes, we check whether or not the design model conforms
  389. conforming = conformance_scd(design_model)
  390. if (conforming == "OK"):
  391. // Conforming, so do the retyping and sanitization step
  392. runtime_model = retype_to_runtime(design_model)
  393. runtime_model = sanitize(runtime_model, old_runtime_model)
  394. log("Create schedule")
  395. schedule_init = create_schedule(runtime_model)
  396. log("Remove schedule")
  397. schedule_run = read_root()
  398. old_runtime_model = runtime_model
  399. output("CONFORMANCE_OK")
  400. else:
  401. // Not conforming, so stop simulation and block for input (preferably a modify to make everything consistent again)
  402. running = False
  403. output("CONFORMANCE_FAIL " + conforming)
  404. else:
  405. log("Did not understand command: " + cmd)