cbd_simulate.alc 15 KB

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