simulate.alc 16 KB

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