cbd_semantics.alc 16 KB

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