fsa_semantics.alc 20 KB

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