cbd_semantics.alc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. log("Recurse!")
  168. strongconnect(w, values)
  169. dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["lowlink"][w]))
  170. elif (dict_in(values["onStack"], w)):
  171. log("Check on stack")
  172. if (values["onStack"][w]):
  173. log("Is on stack, so update")
  174. dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["indices"][w]))
  175. log("Done")
  176. if (value_eq(values["lowlink"][v], values["indices"][v])):
  177. log("Start new SCC block")
  178. Element scc
  179. scc = create_node()
  180. // It will always differ now
  181. w = list_pop(values["S"])
  182. list_append(scc, w)
  183. dict_overwrite(values["onStack"], w, False)
  184. log("REMOVE from stack: " + w)
  185. while (w != v):
  186. w = list_pop(values["S"])
  187. list_append(scc, w)
  188. dict_overwrite(values["onStack"], w, False)
  189. log("REMOVE from stack: " + w)
  190. list_insert(values["SCC"], scc, 0)
  191. return!
  192. Element function list_pop(list : Element):
  193. Integer top
  194. Element t
  195. top = list_len(list) - 1
  196. t = list_read(list, top)
  197. list_delete(list, top)
  198. return t!
  199. String function readType(model : Element, name : String):
  200. return reverseKeyLookup(model["metamodel"]["model"], dict_read_node(model["type_mapping"], model["model"][name]))!
  201. Void function step_simulation(model : Element, schedule : Element):
  202. String time
  203. Float signal
  204. Element incoming
  205. String selected
  206. String block
  207. String elem
  208. String blocktype
  209. Element memory_blocks
  210. Integer i
  211. Float delta_t
  212. time = "time"
  213. delta_t = 0.1
  214. memory_blocks = create_node()
  215. output("SIM_TIME " + cast_v2s(read_attribute(model, time, "current_time")))
  216. i = 0
  217. while (i < read_nr_out(schedule)):
  218. block = list_read(schedule, i)
  219. i = i + 1
  220. // Execute "block"
  221. blocktype = readType(model, block)
  222. if (blocktype == "ConstantBlock"):
  223. signal = read_attribute(model, block, "value")
  224. elif (blocktype == "AdditionBlock"):
  225. signal = 0.0
  226. incoming = allIncomingAssociationInstances(model, block, "Link")
  227. while (read_nr_out(incoming) > 0):
  228. selected = readAssociationSource(model, set_pop(incoming))
  229. signal = signal + cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  230. elif (blocktype == "MultiplyBlock"):
  231. signal = 1.0
  232. incoming = allIncomingAssociationInstances(model, block, "Link")
  233. while (read_nr_out(incoming) > 0):
  234. selected = readAssociationSource(model, set_pop(incoming))
  235. signal = signal * cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  236. elif (blocktype == "NegatorBlock"):
  237. incoming = allIncomingAssociationInstances(model, block, "Link")
  238. signal = 0.0
  239. while (read_nr_out(incoming) > 0):
  240. selected = readAssociationSource(model, set_pop(incoming))
  241. signal = float_neg(cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
  242. elif (blocktype == "InverseBlock"):
  243. signal = 0.0
  244. incoming = allIncomingAssociationInstances(model, block, "Link")
  245. while (read_nr_out(incoming) > 0):
  246. selected = readAssociationSource(model, set_pop(incoming))
  247. signal = float_division(1.0, cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
  248. elif (blocktype == "DelayBlock"):
  249. signal = 0.0
  250. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  251. // No memory yet, so use initial condition
  252. incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
  253. while (read_nr_out(incoming) > 0):
  254. selected = readAssociationSource(model, set_pop(incoming))
  255. signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  256. else:
  257. signal = read_attribute(model, block, "last_in")
  258. unset_attribute(model, block, "last_in")
  259. set_add(memory_blocks, block)
  260. elif (blocktype == "IntegratorBlock"):
  261. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  262. // No history yet, so use initial values
  263. incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
  264. while (read_nr_out(incoming) > 0):
  265. selected = readAssociationSource(model, set_pop(incoming))
  266. signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  267. else:
  268. signal = cast_s2f(cast_v2s(read_attribute(model, block, "last_in"))) + (delta_t * cast_s2f(cast_v2s(read_attribute(model, block, "last_out"))))
  269. unset_attribute(model, block, "last_in")
  270. unset_attribute(model, block, "last_out")
  271. instantiate_attribute(model, block, "last_out", signal)
  272. set_add(memory_blocks, block)
  273. elif (blocktype == "DerivatorBlock"):
  274. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  275. // No history yet, so use initial values
  276. incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
  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")))
  280. else:
  281. incoming = allIncomingAssociationInstances(model, block, "Link")
  282. while (read_nr_out(incoming) > 0):
  283. selected = readAssociationSource(model, set_pop(incoming))
  284. signal = (cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))) - cast_s2f(cast_v2s(read_attribute(model, block, "last_in")))) / delta_t
  285. unset_attribute(model, block, "last_in")
  286. set_add(memory_blocks, block)
  287. unset_attribute(model, block, "signal")
  288. instantiate_attribute(model, block, "signal", signal)
  289. output((("SIM_PROBE " + cast_v2s(block)) + " ") + cast_v2s(signal))
  290. output("SIM_END")
  291. while (read_nr_out(memory_blocks) > 0):
  292. block = set_pop(memory_blocks)
  293. // Update memory
  294. incoming = allIncomingAssociationInstances(model, block, "Link")
  295. while (read_nr_out(incoming) > 0):
  296. selected = readAssociationSource(model, set_pop(incoming))
  297. instantiate_attribute(model, block, "last_in", cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
  298. // Increase simulation time
  299. Float new_time
  300. new_time = cast_s2f(cast_v2s(read_attribute(model, time, "current_time"))) + delta_t
  301. unset_attribute(model, time, "current_time")
  302. instantiate_attribute(model, time, "current_time", new_time)
  303. return !
  304. Void function execute_cbd(design_model : Element):
  305. String verify_result
  306. Element runtime_model
  307. Element old_runtime_model
  308. String cmd
  309. Boolean running
  310. Element schedule_init
  311. Element schedule_run
  312. Element schedule
  313. String conforming
  314. old_runtime_model = instantiate_model(import_node("models/CausalBlockDiagrams_Runtime"))
  315. runtime_model = retype_to_runtime(design_model)
  316. runtime_model = sanitize(runtime_model, old_runtime_model)
  317. running = False
  318. conforming = conformance_scd(design_model)
  319. if (conforming == "OK"):
  320. output("CONFORMANCE_OK")
  321. else:
  322. output("CONFORMANCE_FAIL")
  323. schedule_init = create_schedule(runtime_model)
  324. schedule_run = read_root()
  325. while (True):
  326. // If we are running, we just don't block for input and automatically do a step if there is no input
  327. if (running):
  328. if (has_input()):
  329. cmd = input()
  330. else:
  331. cmd = "step"
  332. else:
  333. cmd = input()
  334. // Process input
  335. if (cmd == "simulate"):
  336. // Simulation should toggle running to True, but only if the model is conforming
  337. if (conforming == "OK"):
  338. running = True
  339. else:
  340. output("CONFORMANCE_FAIL " + conforming)
  341. elif (cmd == "step"):
  342. // Stepping should make a single step, but first need to pick the correct schedule to use
  343. if (conforming == "OK"):
  344. if (read_attribute(runtime_model, "time", "start_time") == read_attribute(runtime_model, "time", "current_time")):
  345. schedule = schedule_init
  346. else:
  347. if (element_eq(schedule_run, read_root())):
  348. schedule_run = create_schedule(runtime_model)
  349. schedule = schedule_run
  350. step_simulation(runtime_model, schedule)
  351. else:
  352. output("CONFORMANCE_FAIL " + conforming)
  353. elif (cmd == "pause"):
  354. // Pausing merely stops a running simulation
  355. running = False
  356. elif (cmd == "read_available_attributes"):
  357. // Returns a list of all available attributes
  358. Element attr_list
  359. Element attrs
  360. Element attr
  361. attr_list = getAttributeList(design_model, input())
  362. attrs = dict_keys(attr_list)
  363. while (0 < read_nr_out(attrs)):
  364. attr = set_pop(attrs)
  365. output("AVAILABLE_ATTR_VALUE " + cast_v2s(attr))
  366. output("AVAILABLE_ATTR_TYPE " + cast_v2s(dict_read(attr_list, attr)))
  367. output("AVAILABLE_ATTR_END")
  368. elif (cmd == "read_attribute"):
  369. // Returns the value of an attribute
  370. output("ATTR_VALUE " + cast_v2s(read_attribute(design_model, input(), input())))
  371. elif (bool_or(bool_or(cmd == "set_attribute", cmd == "instantiate_node"), bool_or(cmd == "delete_element", cmd == "instantiate_association"))):
  372. // Modify the structure
  373. if (cmd == "set_attribute"):
  374. // Setting an attribute
  375. String element_name
  376. String attribute_name
  377. element_name = input()
  378. attribute_name = input()
  379. // Delete it if it exists already
  380. if (bool_not(element_eq(read_attribute(design_model, element_name, attribute_name), read_root()))):
  381. unset_attribute(design_model, element_name, attribute_name)
  382. // And finally set it
  383. instantiate_attribute(design_model, element_name, attribute_name, input())
  384. elif (cmd == "instantiate_node"):
  385. // Instantiate a node
  386. instantiate_node(design_model, input(), input())
  387. elif (cmd == "instantiate_association"):
  388. // Instantiate an association
  389. instantiate_link(design_model, input(), input(), input(), input())
  390. elif (cmd == "delete_element"):
  391. // Delete the provided element
  392. model_delete_element(design_model, input())
  393. // After changes, we check whether or not the design model conforms
  394. conforming = conformance_scd(design_model)
  395. if (conforming == "OK"):
  396. // Conforming, so do the retyping and sanitization step
  397. runtime_model = retype_to_runtime(design_model)
  398. runtime_model = sanitize(runtime_model, old_runtime_model)
  399. log("Create schedule")
  400. schedule_init = create_schedule(runtime_model)
  401. log("Remove schedule")
  402. schedule_run = read_root()
  403. old_runtime_model = runtime_model
  404. output("CONFORMANCE_OK")
  405. else:
  406. // Not conforming, so stop simulation and block for input (preferably a modify to make everything consistent again)
  407. running = False
  408. output("CONFORMANCE_FAIL " + conforming)
  409. else:
  410. log("Did not understand command: " + cmd)