cbd_semantics.alc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. // TODO solve if possible
  198. return !
  199. else:
  200. block = set_pop(scc)
  201. // Execute "block"
  202. blocktype = readType(model, block)
  203. if (blocktype == "ConstantBlock"):
  204. signal = read_attribute(model, block, "value")
  205. elif (blocktype == "AdditionBlock"):
  206. signal = 0.0
  207. incoming = allIncomingAssociationInstances(model, block, "Link")
  208. while (read_nr_out(incoming) > 0):
  209. selected = readAssociationSource(model, set_pop(incoming))
  210. signal = signal + cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  211. elif (blocktype == "MultiplyBlock"):
  212. signal = 1.0
  213. incoming = allIncomingAssociationInstances(model, block, "Link")
  214. while (read_nr_out(incoming) > 0):
  215. selected = readAssociationSource(model, set_pop(incoming))
  216. signal = signal * cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  217. elif (blocktype == "NegatorBlock"):
  218. incoming = allIncomingAssociationInstances(model, block, "Link")
  219. signal = 0.0
  220. while (read_nr_out(incoming) > 0):
  221. selected = readAssociationSource(model, set_pop(incoming))
  222. signal = float_neg(cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
  223. elif (blocktype == "InverseBlock"):
  224. signal = 0.0
  225. incoming = allIncomingAssociationInstances(model, block, "Link")
  226. while (read_nr_out(incoming) > 0):
  227. selected = readAssociationSource(model, set_pop(incoming))
  228. signal = float_division(1.0, cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
  229. elif (blocktype == "DelayBlock"):
  230. signal = 0.0
  231. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  232. // No memory yet, so use initial condition
  233. incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
  234. while (read_nr_out(incoming) > 0):
  235. selected = readAssociationSource(model, set_pop(incoming))
  236. signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  237. else:
  238. signal = read_attribute(model, block, "last_in")
  239. unset_attribute(model, block, "last_in")
  240. set_add(memory_blocks, block)
  241. elif (blocktype == "IntegratorBlock"):
  242. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  243. // No history yet, so use initial values
  244. incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
  245. while (read_nr_out(incoming) > 0):
  246. selected = readAssociationSource(model, set_pop(incoming))
  247. signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
  248. else:
  249. signal = cast_s2f(cast_v2s(read_attribute(model, block, "last_in"))) + (delta_t * cast_s2f(cast_v2s(read_attribute(model, block, "last_out"))))
  250. unset_attribute(model, block, "last_in")
  251. unset_attribute(model, block, "last_out")
  252. instantiate_attribute(model, block, "last_out", signal)
  253. set_add(memory_blocks, block)
  254. elif (blocktype == "DerivatorBlock"):
  255. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  256. // No history yet, so use initial values
  257. incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
  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")))
  261. else:
  262. incoming = allIncomingAssociationInstances(model, block, "Link")
  263. while (read_nr_out(incoming) > 0):
  264. selected = readAssociationSource(model, set_pop(incoming))
  265. signal = (cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))) - cast_s2f(cast_v2s(read_attribute(model, block, "last_in")))) / delta_t
  266. unset_attribute(model, block, "last_in")
  267. set_add(memory_blocks, block)
  268. unset_attribute(model, block, "signal")
  269. instantiate_attribute(model, block, "signal", signal)
  270. output((("SIM_PROBE " + cast_v2s(block)) + " ") + cast_v2s(signal))
  271. output("SIM_END")
  272. while (read_nr_out(memory_blocks) > 0):
  273. block = set_pop(memory_blocks)
  274. // Update memory
  275. incoming = allIncomingAssociationInstances(model, block, "Link")
  276. while (read_nr_out(incoming) > 0):
  277. selected = readAssociationSource(model, set_pop(incoming))
  278. instantiate_attribute(model, block, "last_in", cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
  279. // Increase simulation time
  280. Float new_time
  281. new_time = cast_s2f(cast_v2s(read_attribute(model, time, "current_time"))) + delta_t
  282. unset_attribute(model, time, "current_time")
  283. instantiate_attribute(model, time, "current_time", new_time)
  284. return !
  285. Void function execute_cbd(design_model : Element):
  286. String verify_result
  287. Element runtime_model
  288. Element old_runtime_model
  289. String cmd
  290. Boolean running
  291. Element schedule_init
  292. Element schedule_run
  293. Element schedule
  294. String conforming
  295. old_runtime_model = instantiate_model(import_node("models/CausalBlockDiagrams_Runtime"))
  296. runtime_model = retype_to_runtime(design_model)
  297. runtime_model = sanitize(runtime_model, old_runtime_model)
  298. running = False
  299. conforming = conformance_scd(design_model)
  300. if (conforming == "OK"):
  301. output("CONFORMANCE_OK")
  302. else:
  303. output("CONFORMANCE_FAIL")
  304. schedule_init = create_schedule(runtime_model)
  305. schedule_run = read_root()
  306. while (True):
  307. // If we are running, we just don't block for input and automatically do a step if there is no input
  308. if (running):
  309. if (has_input()):
  310. cmd = input()
  311. else:
  312. cmd = "step"
  313. else:
  314. cmd = input()
  315. // Process input
  316. if (cmd == "simulate"):
  317. // Simulation should toggle running to True, but only if the model is conforming
  318. if (conforming == "OK"):
  319. running = True
  320. else:
  321. output("CONFORMANCE_FAIL " + conforming)
  322. elif (cmd == "step"):
  323. // Stepping should make a single step, but first need to pick the correct schedule to use
  324. if (conforming == "OK"):
  325. if (read_attribute(runtime_model, "time", "start_time") == read_attribute(runtime_model, "time", "current_time")):
  326. schedule = schedule_init
  327. else:
  328. if (element_eq(schedule_run, read_root())):
  329. schedule_run = create_schedule(runtime_model)
  330. schedule = schedule_run
  331. // TODO remove
  332. schedule = create_schedule(runtime_model)
  333. step_simulation(runtime_model, schedule)
  334. else:
  335. output("CONFORMANCE_FAIL " + conforming)
  336. elif (cmd == "pause"):
  337. // Pausing merely stops a running simulation
  338. running = False
  339. elif (cmd == "read_available_attributes"):
  340. // Returns a list of all available attributes
  341. Element attr_list
  342. Element attrs
  343. Element attr
  344. attr_list = getAttributeList(design_model, input())
  345. attrs = dict_keys(attr_list)
  346. while (0 < read_nr_out(attrs)):
  347. attr = set_pop(attrs)
  348. output("AVAILABLE_ATTR_VALUE " + cast_v2s(attr))
  349. output("AVAILABLE_ATTR_TYPE " + cast_v2s(dict_read(attr_list, attr)))
  350. output("AVAILABLE_ATTR_END")
  351. elif (cmd == "read_attribute"):
  352. // Returns the value of an attribute
  353. output("ATTR_VALUE " + cast_v2s(read_attribute(design_model, input(), input())))
  354. elif (bool_or(bool_or(cmd == "set_attribute", cmd == "instantiate_node"), bool_or(cmd == "delete_element", cmd == "instantiate_association"))):
  355. // Modify the structure
  356. if (cmd == "set_attribute"):
  357. // Setting an attribute
  358. String element_name
  359. String attribute_name
  360. element_name = input()
  361. attribute_name = input()
  362. // Delete it if it exists already
  363. if (bool_not(element_eq(read_attribute(design_model, element_name, attribute_name), read_root()))):
  364. unset_attribute(design_model, element_name, attribute_name)
  365. // And finally set it
  366. instantiate_attribute(design_model, element_name, attribute_name, input())
  367. elif (cmd == "instantiate_node"):
  368. // Instantiate a node
  369. instantiate_node(design_model, input(), input())
  370. elif (cmd == "instantiate_association"):
  371. // Instantiate an association
  372. instantiate_link(design_model, input(), input(), input(), input())
  373. elif (cmd == "delete_element"):
  374. // Delete the provided element
  375. model_delete_element(design_model, input())
  376. // After changes, we check whether or not the design model conforms
  377. conforming = conformance_scd(design_model)
  378. if (conforming == "OK"):
  379. // Conforming, so do the retyping and sanitization step
  380. runtime_model = retype_to_runtime(design_model)
  381. runtime_model = sanitize(runtime_model, old_runtime_model)
  382. schedule_init = create_schedule(runtime_model)
  383. schedule_run = read_root()
  384. old_runtime_model = runtime_model
  385. output("CONFORMANCE_OK")
  386. else:
  387. // Not conforming, so stop simulation and block for input (preferably a modify to make everything consistent again)
  388. running = False
  389. output("CONFORMANCE_FAIL " + conforming)
  390. else:
  391. log("Did not understand command: " + cmd)
  392. Void function eliminateGaussJordan(m : Element):
  393. Integer i
  394. Integer j
  395. Integer f
  396. Integer g
  397. Boolean searching
  398. Element t
  399. Float divisor
  400. i = 0
  401. j = 0
  402. while (i < read_nr_out(m)):
  403. // Make sure pivot m[i][j] != 0, swapping if necessary
  404. while (m[i][j] == 0):
  405. // Is zero, so find row which is not zero
  406. f = i + 1
  407. searching = True
  408. while (searching):
  409. if (f >= read_nr_out(m)):
  410. // No longer any rows left, so just increase column counter
  411. searching = False
  412. j = j + 1
  413. else:
  414. if (m[f][j] == 0):
  415. // Also zero, so continue
  416. f = f + 1
  417. else:
  418. // Found non-zero, so swap row
  419. t = m[f]
  420. dict_overwrite(m, f, m[i])
  421. dict_overwrite(m, i, t)
  422. searching = False
  423. // If we have increased j, we will just start the loop again (possibly), as m[i][j] might be zero again
  424. // Pivot in m[i][j] guaranteed to not be 0
  425. // Now divide complete row by value of m[i][j] to make it equal 1
  426. f = j
  427. divisor = m[i][j]
  428. while (f < read_nr_out(m[i])):
  429. dict_overwrite(m[i], f, float_division(m[i][f], divisor))
  430. f = f + 1
  431. // Eliminate all rows in the j-th column, except the i-th row
  432. f = 0
  433. while (f < read_nr_out(m)):
  434. if (bool_not(f == i)):
  435. g = j
  436. divisor = m[f][j]
  437. while (g < read_nr_out(m[f])):
  438. dict_overwrite(m[f], g, m[f][g] - (divisor * m[i][g]))
  439. // Increase row and column
  440. i = i + 1
  441. j = j + 1
  442. return !
  443. String function matrix2string(m : Element):
  444. Integer i
  445. Integer j
  446. String result
  447. result = ""
  448. i = 0
  449. while (i < read_nr_out(m)):
  450. j = 0
  451. while (j < read_nr_out(m[i])):
  452. result = result + cast_v2s(m[i][j])
  453. result = result + ", "
  454. result = result + "\n"
  455. return result!
  456. Void function main():
  457. Element m
  458. Element t
  459. m = create_node()
  460. t = create_node()
  461. list_append(t, -1)
  462. list_append(t, 1)
  463. list_append(t, -4)
  464. list_append(m, t)
  465. list_append(t, 1)
  466. list_append(t, 1)
  467. list_append(t, 0)
  468. list_append(m, t)
  469. log("Before elimination")
  470. log(matrix2string(m))
  471. eliminateGaussJordan(m)
  472. log("After elimination")
  473. log(matrix2string(m))
  474. return !