simulate.alc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. include "primitives.alh"
  2. include "modelling.alh"
  3. include "object_operations.alh"
  4. include "conformance_scd.alh"
  5. include "io.alh"
  6. include "metamodels.alh"
  7. include "mini_modify.alh"
  8. include "utils.alh"
  9. Boolean function main(model : Element):
  10. log("Start DTCBD simulation!")
  11. String cmd
  12. Boolean running
  13. Element schedule_init
  14. Element schedule_run
  15. Element schedule
  16. Float current_time
  17. String time
  18. time = set_pop(allInstances(model, "FullRuntime/Time"))
  19. current_time = read_attribute(model, time, "current_time")
  20. log("Fetching time now: " + cast_value(current_time))
  21. schedule_init = create_schedule(model)
  22. schedule_run = read_root()
  23. Element nodes
  24. Element inputs
  25. String node
  26. nodes = allInstances(model, "FullRuntime/Block")
  27. inputs = dict_create()
  28. while (set_len(nodes) > 0):
  29. node = set_pop(nodes)
  30. dict_add(inputs, node, allAssociationOrigins(model, node, "FullRuntime/Link"))
  31. while (bool_not(has_input())):
  32. if (read_attribute(model, time, "start_time") == read_attribute(model, time, "current_time")):
  33. schedule = schedule_init
  34. else:
  35. if (element_eq(schedule_run, read_root())):
  36. schedule_run = create_schedule(model)
  37. schedule = schedule_run
  38. current_time = step_simulation(model, schedule, current_time, inputs)
  39. instantiate_attribute(model, time, "current_time", current_time)
  40. log("CLOSE")
  41. output("CLOSE")
  42. return True!
  43. Element function create_schedule(model : Element):
  44. // Create nice graph first
  45. Element nodes
  46. Element successors
  47. String element_name
  48. Element incoming_links
  49. Element all_blocks
  50. nodes = allInstances(model, "FullRuntime/Block")
  51. successors = set_create()
  52. while (set_len(nodes) > 0):
  53. element_name = set_pop(nodes)
  54. log("Block " + element_name + " : " + read_type(model, element_name))
  55. if (is_nominal_instance(model, element_name, "FullRuntime/ICBlock")):
  56. if (bool_not(is_physical_float(read_attribute(model, element_name, "last_in")))):
  57. incoming_links = allIncomingAssociationInstances(model, element_name, "FullRuntime/InitialCondition")
  58. else:
  59. incoming_links = create_node()
  60. else:
  61. incoming_links = allIncomingAssociationInstances(model, element_name, "FullRuntime/Link")
  62. while (set_len(incoming_links) > 0):
  63. String source
  64. source = readAssociationSource(model, set_pop(incoming_links))
  65. list_append(successors, create_tuple(source, element_name))
  66. log("Found edge: " + source + " --> " + element_name)
  67. Element values
  68. values = create_node()
  69. //dict_add(values, "model", model)
  70. //dict_add(values, "S", create_node())
  71. //dict_add(values, "index", 0)
  72. //dict_add(values, "indices", create_node())
  73. //dict_add(values, "lowlink", create_node())
  74. //dict_add(values, "onStack", create_node())
  75. //dict_add(values, "successors", successors)
  76. //dict_add(values, "predecessors", predecessors)
  77. //dict_add(values, "SCC", create_node())
  78. dict_add(values, "edges", successors)
  79. dict_add(values, "nodes", allInstances(model, "FullRuntime/Block"))
  80. dict_add(values, "dfsCounter", 0)
  81. dict_add(values, "orderNumber", dict_create())
  82. dict_add(values, "visited_topSort", set_create())
  83. dict_add(values, "unvisited_strongComp", set_create())
  84. log("Toposort")
  85. //nodes = get_topolist(values)
  86. //while (list_len(nodes) > 0):
  87. // log("Strong connect")
  88. // strongconnect(list_pop_final(nodes), values)
  89. dict_overwrite(values, "SCC", strongComp(values))
  90. //nodes = allInstances(model, "FullRuntime/Block")
  91. //while (set_len(nodes) > 0):
  92. // strongconnect(set_pop(nodes), values)
  93. log("OK")
  94. return values["SCC"]!
  95. Void function topSort(values : Element):
  96. Element nodes_copy
  97. String node
  98. // for node in graph:
  99. // node.visited = False
  100. dict_overwrite(values, "visited_topSort", set_create())
  101. // for node in graph:
  102. // if not node.visited:
  103. // dfsLabelling(node)
  104. nodes_copy = set_copy(values["nodes"])
  105. while (set_len(nodes_copy) > 0):
  106. node = set_pop(nodes_copy)
  107. if (bool_not(set_in(values["visited_topSort"], node))):
  108. dfsLabelling(values, node)
  109. log("Order: " + dict_to_string(values["orderNumber"]))
  110. return!
  111. Element function get_successors(values : Element, node : String, key : String):
  112. Element edges
  113. Element result
  114. String edge
  115. result = set_create()
  116. edges = list_copy(values[key])
  117. while (list_len(edges) > 0):
  118. edge = list_pop_final(edges)
  119. if (cast_string(edge[0]) == node):
  120. set_add(result, edge[1])
  121. return result!
  122. Void function dfsLabelling(values : Element, node : String):
  123. Element successors
  124. String successor
  125. // if not node.visited
  126. if (bool_not(set_in(values["visited_topSort"], node))):
  127. // node.visited = True
  128. set_add(values["visited_topSort"], node)
  129. // for neighbour in node.out_neighbours:
  130. // dfsLabelling(neighbour, graph)
  131. successors = get_successors(values, node, "edges")
  132. while (set_len(successors) > 0):
  133. successor = set_pop(successors)
  134. dfsLabelling(values, successor)
  135. // node.orderNumber = dfsCounter
  136. dict_overwrite(values["orderNumber"], node, values["dfsCounter"])
  137. // dfsCounter += 1
  138. dict_overwrite(values, "dfsCounter", cast_integer(values["dfsCounter"]) + 1)
  139. return !
  140. Element function dfsCollect(values : Element, start_node : String):
  141. Element result
  142. String successor
  143. Element successors
  144. result = set_create()
  145. // if not node.visited
  146. if (set_in(values["unvisited_strongComp"], start_node)):
  147. list_append(result, start_node)
  148. // node.visited = True
  149. set_remove(values["unvisited_strongComp"], start_node)
  150. // for neighbour in node.out_neighbours:
  151. // dfsLabelling(neighbour, graph)
  152. successors = get_successors(values, start_node, "rev_edges")
  153. while (set_len(successors) > 0):
  154. successor = set_pop(successors)
  155. list_extend(result, dfsCollect(values, successor))
  156. return result!
  157. String function highest_orderNumber(values : Element):
  158. Integer max
  159. String max_element
  160. Element search
  161. String elem
  162. max = -1
  163. search = set_copy(values["unvisited_strongComp"])
  164. while (set_len(search) > 0):
  165. elem = set_pop(search)
  166. if (cast_integer(values["orderNumber"][elem]) > max):
  167. max = values["orderNumber"][elem]
  168. max_element = elem
  169. return max_element!
  170. Element function reverse_edges(edges : Element):
  171. Element result
  172. Element elem
  173. result = list_create()
  174. edges = list_copy(edges)
  175. while (list_len(edges) > 0):
  176. elem = list_pop_final(edges)
  177. list_append(result, create_tuple(elem[1], elem[0]))
  178. return result!
  179. Element function strongComp(values : Element):
  180. Element graph
  181. Element sccs
  182. String start_node
  183. Element strong_components
  184. Element component
  185. sccs = list_create()
  186. topSort(values)
  187. dict_overwrite(values, "unvisited_strongComp", set_copy(values["nodes"]))
  188. dict_overwrite(values, "rev_edges", reverse_edges(values["edges"]))
  189. strong_components = list_create()
  190. while (set_len(values["unvisited_strongComp"]) > 0):
  191. start_node = highest_orderNumber(values)
  192. component = dfsCollect(values, start_node)
  193. list_append(sccs, component)
  194. log("Got strong component: " + list_to_string(component))
  195. return sccs!
  196. Element function get_topolist(values : Element):
  197. Element result
  198. Element predecessors
  199. Element remaining
  200. String current_element
  201. Element cur_predecessors
  202. result = list_create()
  203. predecessors = dict_copy(values["predecessors"])
  204. while (dict_len(predecessors) > 0):
  205. remaining = dict_keys(predecessors)
  206. while (set_len(remaining) > 0):
  207. current_element = set_pop(remaining)
  208. cur_predecessors = predecessors[current_element]
  209. if (set_len(set_overlap(list_to_set(result), cur_predecessors)) == set_len(cur_predecessors)):
  210. // All predecessors of this node have already been visited
  211. dict_delete(predecessors, current_element)
  212. remaining = dict_keys(predecessors)
  213. list_append(result, current_element)
  214. return result!
  215. Integer function min(a : Integer, b : Integer):
  216. if (a < b):
  217. return a!
  218. else:
  219. return b!
  220. Void function strongconnect(v : String, values : Element):
  221. // if (v.index is undefined) then
  222. // strongconnect(V)
  223. if (dict_in(values["indices"], v)):
  224. return!
  225. // v.index := index
  226. dict_overwrite(values["indices"], v, values["index"])
  227. // v.lowlink := indwx
  228. dict_overwrite(values["lowlink"], v, values["index"])
  229. // index := index + 1
  230. dict_overwrite(values, "index", cast_integer(values["index"]) + 1)
  231. // S.push(v)
  232. list_append(values["S"], v)
  233. // v.onStack := true
  234. dict_overwrite(values["onStack"], v, True)
  235. Element successors
  236. String w
  237. successors = values["successors"][v]
  238. while (set_len(successors) > 0):
  239. // for each (v, w) in E do
  240. w = set_pop(successors)
  241. // if (w.index is undefined) then
  242. if (bool_not(dict_in(values["indices"], w))):
  243. // strongconnect(w)
  244. strongconnect(w, values)
  245. // v.lowlink := min(v.lowlink, w.lowlink)
  246. dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["lowlink"][w]))
  247. elif (dict_in(values["onStack"], w)):
  248. // else if (w.onStack)
  249. if (values["onStack"][w]):
  250. // v.lowlink := min(v.lowlink, w.index)
  251. dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["indices"][w]))
  252. // if (v.lowlink == v.index) then
  253. if (value_eq(values["lowlink"][v], values["indices"][v])):
  254. Element scc
  255. // Start a new strongly connected component
  256. scc = create_node()
  257. // It will always differ now
  258. // w := S.pop()
  259. w = list_pop_final(values["S"])
  260. // w.onStack = false
  261. dict_overwrite(values["onStack"], w, False)
  262. // add w to current strongly connected component
  263. list_append(scc, w)
  264. // while w != v
  265. while (w != v):
  266. // w := S.pop()
  267. w = list_pop_final(values["S"])
  268. // w.onStack = false
  269. dict_overwrite(values["onStack"], w, False)
  270. // add w to current strongly connected component
  271. list_append(scc, w)
  272. // output the current strongly connected component
  273. list_insert(values["SCC"], scc, 0)
  274. log("Found new SCC: " + list_to_string(scc))
  275. return!
  276. Boolean function solve_scc(model : Element, scc : Element):
  277. Element m
  278. Integer i
  279. Integer j
  280. String block
  281. String blocktype
  282. Element incoming
  283. String selected
  284. Float constant
  285. Element t
  286. // Construct the matrix first, with as many rows as there are variables
  287. // Number of columns is 1 higher
  288. i = 0
  289. m = create_node()
  290. while (i < read_nr_out(scc)):
  291. j = 0
  292. t = create_node()
  293. while (j < (read_nr_out(scc) + 1)):
  294. list_append(t, 0.0)
  295. j = j + 1
  296. list_append(m, t)
  297. i = i + 1
  298. // Matrix initialized to 0.0
  299. i = 0
  300. while (i < read_nr_out(scc)):
  301. // First element of scc
  302. block = scc[i]
  303. blocktype = read_type(model, block)
  304. // First write 1 in the current block
  305. dict_overwrite(m[i], i, 1.0)
  306. // Now check all blocks that are incoming
  307. if (blocktype == "FullRuntime/AdditionBlock"):
  308. constant = 0.0
  309. elif (blocktype == "FullRuntime/MultiplyBlock"):
  310. constant = 1.0
  311. incoming = allIncomingAssociationInstances(model, block, "FullRuntime/Link")
  312. Integer index_to_write_constant
  313. index_to_write_constant = -1
  314. while (read_nr_out(incoming) > 0):
  315. selected = readAssociationSource(model, set_pop(incoming))
  316. if (list_in(scc, selected)):
  317. // Part of the loop, so in the index of selected in scc
  318. // Five options:
  319. if (blocktype == "FullRuntime/AdditionBlock"):
  320. // 1) AdditionBlock
  321. // Add the negative of this signal, which is as of yet unknown
  322. // x = y + z --> x - y - z = 0
  323. dict_overwrite(m[i], list_index_of(scc, selected), -1.0)
  324. elif (blocktype == "FullRuntime/MultiplyBlock"):
  325. // 2) MultiplyBlock
  326. if (index_to_write_constant != -1):
  327. return False!
  328. index_to_write_constant = list_index_of(scc, selected)
  329. elif (blocktype == "FullRuntime/NegatorBlock"):
  330. // 3) NegatorBlock
  331. // Add the positive of the signal, which is as of yet unknown
  332. dict_overwrite(m[i], list_index_of(scc, selected), 1.0)
  333. elif (blocktype == "FullRuntime/DelayBlock"):
  334. // 5) DelayBlock
  335. // Just copies a single value
  336. dict_overwrite(m[i], list_index_of(scc, selected), -1.0)
  337. else:
  338. // Block that cannot be handled
  339. return False!
  340. else:
  341. // A constant, which we can assume is already computed and thus usable
  342. if (blocktype == "FullRuntime/AdditionBlock"):
  343. constant = constant + cast_float(read_attribute(model, selected, "signal"))
  344. dict_overwrite(m[i], read_nr_out(scc), constant)
  345. elif (blocktype == "FullRuntime/MultiplyBlock"):
  346. constant = constant * cast_float(read_attribute(model, selected, "signal"))
  347. // Not written to constant part, as multiplies a variable
  348. // Any other block is impossible:
  349. // * Constant would never be part of a SCC
  350. // * Delay would never get an incoming constant
  351. // * Negation and Inverse only get 1 input, which is a variable in a loop
  352. // * Integrator and Derivator never get an incoming constant
  353. if (index_to_write_constant != -1):
  354. dict_overwrite(m[i], index_to_write_constant, -constant)
  355. i = i + 1
  356. // Constructed a complete matrix, so we can start!
  357. log(matrix2string(m))
  358. // Solve matrix now
  359. eliminateGaussJordan(m)
  360. // Now go over m and set signals for each element
  361. // Assume that everything worked out...
  362. i = 0
  363. while (i < read_nr_out(m)):
  364. block = scc[i]
  365. instantiate_attribute(model, block, "signal", m[i][read_nr_out(scc)])
  366. log((("Solved " + block) + " to ") + cast_string(m[i][read_nr_out(scc)]))
  367. i = i + 1
  368. return True!
  369. Integer function list_index_of(lst : Element, elem : Element):
  370. Integer i
  371. i = 0
  372. while (i < read_nr_out(lst)):
  373. if (value_eq(list_read(lst, i), elem)):
  374. return i!
  375. else:
  376. i = i + 1
  377. return -1!
  378. Float function step_simulation(model : Element, schedule : Element, time : Float, inputs : Element):
  379. Float signal
  380. Element incoming
  381. String selected
  382. String block
  383. String elem
  384. String blocktype
  385. Element memory_blocks
  386. Integer i
  387. Float delta_t
  388. Element scc
  389. delta_t = 0.1
  390. memory_blocks = set_create()
  391. i = 0
  392. while (i < list_len(schedule)):
  393. scc = list_read(schedule, i)
  394. i = i + 1
  395. if (list_len(scc) > 1):
  396. if (bool_not(solve_scc(model, scc))):
  397. log("ALGEBRAIC_LOOP")
  398. output("ALGEBRAIC_LOOP")
  399. return time!
  400. else:
  401. block = list_read(scc, 0)
  402. // Execute "block"
  403. blocktype = read_type(model, block)
  404. //log("Execute block " + block + " : " + blocktype)
  405. incoming = set_copy(inputs[block])
  406. if (blocktype == "FullRuntime/ConstantBlock"):
  407. signal = cast_float(read_attribute(model, block, "value"))
  408. elif (blocktype == "FullRuntime/AdditionBlock"):
  409. signal = 0.0
  410. while (set_len(incoming) > 0):
  411. selected = set_pop(incoming)
  412. signal = signal + cast_float(read_attribute(model, selected, "signal"))
  413. elif (blocktype == "FullRuntime/MultiplyBlock"):
  414. signal = 1.0
  415. while (set_len(incoming) > 0):
  416. selected = set_pop(incoming)
  417. signal = signal * cast_float(read_attribute(model, selected, "signal"))
  418. elif (blocktype == "FullRuntime/NegatorBlock"):
  419. signal = 0.0
  420. while (set_len(incoming) > 0):
  421. selected = set_pop(incoming)
  422. signal = float_neg(cast_float(read_attribute(model, selected, "signal")))
  423. elif (blocktype == "FullRuntime/InverseBlock"):
  424. signal = 0.0
  425. while (set_len(incoming) > 0):
  426. selected = set_pop(incoming)
  427. signal = float_division(1.0, cast_float(read_attribute(model, selected, "signal")))
  428. elif (blocktype == "FullRuntime/DelayBlock"):
  429. signal = 0.0
  430. if (bool_not(is_physical_float(read_attribute(model, block, "last_in")))):
  431. // No memory yet, so use initial condition
  432. incoming = allAssociationOrigins(model, block, "FullRuntime/InitialCondition")
  433. while (set_len(incoming) > 0):
  434. selected = set_pop(incoming)
  435. signal = cast_float(read_attribute(model, selected, "signal"))
  436. else:
  437. signal = read_attribute(model, block, "last_in")
  438. set_add(memory_blocks, block)
  439. elif (blocktype == "FullRuntime/ProbeBlock"):
  440. signal = 0.0
  441. while (set_len(incoming) > 0):
  442. signal = cast_float(read_attribute(model, set_pop(incoming), "signal"))
  443. output(cast_string(time) + " " + cast_string(read_attribute(model, block, "name")) + " " + cast_string(signal))
  444. log(cast_string(time) + " " + cast_string(read_attribute(model, block, "name")) + " " + cast_string(signal))
  445. instantiate_attribute(model, block, "signal", signal)
  446. while (set_len(memory_blocks) > 0):
  447. block = set_pop(memory_blocks)
  448. // Update memory
  449. incoming = set_copy(inputs[block])
  450. while (set_len(incoming) > 0):
  451. selected = set_pop(incoming)
  452. instantiate_attribute(model, block, "last_in", cast_float(read_attribute(model, selected, "signal")))
  453. // Increase simulation time
  454. return time + delta_t!
  455. Void function eliminateGaussJordan(m : Element):
  456. Integer i
  457. Integer j
  458. Integer f
  459. Integer g
  460. Boolean searching
  461. Element t
  462. Float divisor
  463. i = 0
  464. j = 0
  465. while (i < read_nr_out(m)):
  466. // Make sure pivot m[i][j] != 0, swapping if necessary
  467. while (cast_float(m[i][j]) == 0.0):
  468. // Is zero, so find row which is not zero
  469. f = i + 1
  470. searching = True
  471. while (searching):
  472. if (f >= read_nr_out(m)):
  473. // No longer any rows left, so just increase column counter
  474. searching = False
  475. j = j + 1
  476. else:
  477. if (cast_float(m[f][j]) == 0.0):
  478. // Also zero, so continue
  479. f = f + 1
  480. else:
  481. // Found non-zero, so swap row
  482. t = cast_float(m[f])
  483. dict_overwrite(m, f, cast_float(m[i]))
  484. dict_overwrite(m, i, t)
  485. searching = False
  486. // If we have increased j, we will just start the loop again (possibly), as m[i][j] might be zero again
  487. // Pivot in m[i][j] guaranteed to not be 0
  488. // Now divide complete row by value of m[i][j] to make it equal 1
  489. f = j
  490. divisor = cast_float(m[i][j])
  491. while (f < read_nr_out(m[i])):
  492. dict_overwrite(m[i], f, float_division(cast_float(m[i][f]), divisor))
  493. f = f + 1
  494. // Eliminate all rows in the j-th column, except the i-th row
  495. f = 0
  496. while (f < read_nr_out(m)):
  497. if (bool_not(f == i)):
  498. g = j
  499. divisor = cast_float(m[f][j])
  500. while (g < read_nr_out(m[f])):
  501. dict_overwrite(m[f], g, cast_float(m[f][g]) - (divisor * cast_float(m[i][g])))
  502. g = g + 1
  503. f = f + 1
  504. // Increase row and column
  505. i = i + 1
  506. j = j + 1
  507. return !
  508. String function matrix2string(m : Element):
  509. Integer i
  510. Integer j
  511. String result
  512. result = ""
  513. i = 0
  514. while (i < read_nr_out(m)):
  515. j = 0
  516. while (j < read_nr_out(m[i])):
  517. result = result + cast_string(m[i][j]) + ", "
  518. j = j + 1
  519. i = i + 1
  520. result = result + "\n"
  521. return result!