cbd_semantics.alc 18 KB

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