cbd_simulate.alc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. log("Finishing simulation, as we got input!")
  29. instantiate_attribute(model, time, "current_time", current_time)
  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 (element_eq(read_attribute(model, element_name, "last_in"), read_root())):
  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. log("Matrix ready!")
  161. // Matrix initialized to 0.0
  162. i = 0
  163. while (i < read_nr_out(scc)):
  164. log("Creating matrix row")
  165. // First element of scc
  166. block = scc[i]
  167. blocktype = read_type(model, block)
  168. // First write 1 in the current block
  169. dict_overwrite(m[i], i, 1.0)
  170. // Now check all blocks that are incoming
  171. if (blocktype == "FullRuntime/AdditionBlock"):
  172. constant = 0.0
  173. elif (blocktype == "FullRuntime/MultiplyBlock"):
  174. constant = 1.0
  175. log("Generating matrix for " + blocktype)
  176. log("Block: " + block)
  177. incoming = allIncomingAssociationInstances(model, block, "Link")
  178. Integer index_to_write_constant
  179. index_to_write_constant = -1
  180. log("Iterating over incoming")
  181. while (read_nr_out(incoming) > 0):
  182. log("Iteration")
  183. selected = readAssociationSource(model, set_pop(incoming))
  184. if (set_in(scc, selected)):
  185. // Part of the loop, so in the index of selected in scc
  186. // Five options:
  187. if (blocktype == "FullRuntime/AdditionBlock"):
  188. // 1) AdditionBlock
  189. // Add the negative of this signal, which is as of yet unknown
  190. // x = y + z --> x - y - z = 0
  191. dict_overwrite(m[i], list_index_of(scc, selected), -1.0)
  192. elif (blocktype == "FullRuntime/MultiplyBlock"):
  193. // 2) MultiplyBlock
  194. if (index_to_write_constant != -1):
  195. return False!
  196. index_to_write_constant = list_index_of(scc, selected)
  197. elif (blocktype == "FullRuntime/NegatorBlock"):
  198. // 3) NegatorBlock
  199. // Add the positive of the signal, which is as of yet unknown
  200. dict_overwrite(m[i], list_index_of(scc, selected), 1.0)
  201. elif (blocktype == "FullRuntime/DelayBlock"):
  202. // 5) DelayBlock
  203. // Just copies a single value
  204. dict_overwrite(m[i], list_index_of(scc, selected), -1.0)
  205. else:
  206. // Block that cannot be handled
  207. return False!
  208. else:
  209. // A constant, which we can assume is already computed and thus usable
  210. if (blocktype == "FullRuntime/AdditionBlock"):
  211. constant = constant + cast_float(read_attribute(model, selected, "signal"))
  212. dict_overwrite(m[i], read_nr_out(scc), constant)
  213. elif (blocktype == "FullRuntime/MultiplyBlock"):
  214. constant = constant * cast_float(read_attribute(model, selected, "signal"))
  215. // Not written to constant part, as multiplies a variable
  216. // Any other block is impossible:
  217. // * Constant would never be part of a SCC
  218. // * Delay would never get an incoming constant
  219. // * Negation and Inverse only get 1 input, which is a variable in a loop
  220. // * Integrator and Derivator never get an incoming constant
  221. if (index_to_write_constant != -1):
  222. dict_overwrite(m[i], index_to_write_constant, -constant)
  223. i = i + 1
  224. // Constructed a complete matrix, so we can start!
  225. log("Constructed matrix to solve:")
  226. log(matrix2string(m))
  227. // Solve matrix now
  228. eliminateGaussJordan(m)
  229. // Now go over m and set signals for each element
  230. // Assume that everything worked out...
  231. i = 0
  232. while (i < read_nr_out(m)):
  233. block = scc[i]
  234. instantiate_attribute(model, block, "signal", m[i][read_nr_out(scc)])
  235. log((("Solved " + block) + " to ") + cast_string(m[i][read_nr_out(scc)]))
  236. i = i + 1
  237. return True!
  238. Integer function list_index_of(lst : Element, elem : Element):
  239. Integer i
  240. i = 0
  241. while (i < read_nr_out(lst)):
  242. if (value_eq(list_read(lst, i), elem)):
  243. return i!
  244. else:
  245. i = i + 1
  246. return -1!
  247. Float function step_simulation(model : Element, schedule : Element, time : Float):
  248. Float signal
  249. Element incoming
  250. String selected
  251. String block
  252. String elem
  253. String blocktype
  254. Element memory_blocks
  255. Integer i
  256. Float delta_t
  257. Element scc
  258. delta_t = 0.1
  259. memory_blocks = set_create()
  260. i = 0
  261. while (i < list_len(schedule)):
  262. scc = list_read(schedule, i)
  263. i = i + 1
  264. if (list_len(scc) > 1):
  265. if (bool_not(solve_scc(model, scc))):
  266. output("ALGEBRAIC_LOOP")
  267. return time!
  268. else:
  269. block = list_read(scc, 0)
  270. // Execute "block"
  271. blocktype = read_type(model, block)
  272. if (blocktype == "FullRuntime/ConstantBlock"):
  273. signal = read_attribute(model, block, "value")
  274. elif (blocktype == "FullRuntime/AdditionBlock"):
  275. signal = 0.0
  276. incoming = allAssociationOrigins(model, block, "FullRuntime/Link")
  277. while (set_len(incoming) > 0):
  278. selected = set_pop(incoming)
  279. signal = signal + cast_float(read_attribute(model, selected, "signal"))
  280. elif (blocktype == "FullRuntime/MultiplyBlock"):
  281. signal = 1.0
  282. incoming = allAssociationOrigins(model, block, "FullRuntime/Link")
  283. while (set_len(incoming) > 0):
  284. selected = set_pop(incoming)
  285. signal = signal * cast_float(read_attribute(model, selected, "signal"))
  286. elif (blocktype == "FullRuntime/NegatorBlock"):
  287. signal = 0.0
  288. incoming = allAssociationOrigins(model, block, "FullRuntime/Link")
  289. while (set_len(incoming) > 0):
  290. selected = set_pop(incoming)
  291. signal = float_neg(cast_float(read_attribute(model, selected, "signal")))
  292. elif (blocktype == "FullRuntime/InverseBlock"):
  293. signal = 0.0
  294. incoming = allAssociationOrigins(model, block, "FullRuntime/Link")
  295. while (set_len(incoming) > 0):
  296. selected = set_pop(incoming)
  297. signal = float_division(1.0, cast_float(read_attribute(model, selected, "signal")))
  298. elif (blocktype == "FullRuntime/DelayBlock"):
  299. signal = 0.0
  300. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  301. // No memory yet, so use initial condition
  302. incoming = allAssociationOrigins(model, block, "FullRuntime/InitialCondition")
  303. while (set_len(incoming) > 0):
  304. selected = set_pop(incoming)
  305. signal = cast_float(read_attribute(model, selected, "signal"))
  306. else:
  307. signal = read_attribute(model, block, "last_in")
  308. set_add(memory_blocks, block)
  309. elif (blocktype == "FullRuntime/IntegratorBlock"):
  310. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  311. // No history yet, so use initial values
  312. incoming = allAssociationOrigins(model, block, "FullRuntime/InitialCondition")
  313. while (set_len(incoming) > 0):
  314. selected = set_pop(incoming)
  315. signal = cast_float(read_attribute(model, selected, "signal"))
  316. else:
  317. signal = cast_float(read_attribute(model, block, "last_out")) + (delta_t * cast_float(read_attribute(model, block, "last_in")))
  318. instantiate_attribute(model, block, "last_out", signal)
  319. set_add(memory_blocks, block)
  320. elif (blocktype == "FullRuntime/DerivatorBlock"):
  321. if (element_eq(read_attribute(model, block, "last_in"), read_root())):
  322. // No history yet, so use initial values
  323. incoming = allAssociationOrigins(model, block, "FullRuntime/InitialCondition")
  324. while (set_len(incoming) > 0):
  325. selected = set_pop(incoming)
  326. signal = cast_float(read_attribute(model, selected, "signal"))
  327. else:
  328. incoming = allAssociationOrigins(model, block, "FullRuntime/Link")
  329. while (set_len(incoming) > 0):
  330. selected = set_pop(incoming)
  331. signal = (cast_float(read_attribute(model, selected, "signal")) - cast_float(read_attribute(model, block, "last_in"))) / delta_t
  332. set_add(memory_blocks, block)
  333. elif (blocktype == "FullRuntime/ProbeBlock"):
  334. incoming = allAssociationOrigins(model, block, "FullRuntime/Link")
  335. while (set_len(incoming) > 0):
  336. signal = cast_float(read_attribute(model, set_pop(incoming), "signal"))
  337. output(cast_string(time) + " " + cast_string(read_attribute(model, block, "name")) + " " + cast_string(signal))
  338. instantiate_attribute(model, block, "signal", signal)
  339. while (set_len(memory_blocks) > 0):
  340. block = set_pop(memory_blocks)
  341. // Update memory
  342. incoming = allIncomingAssociationInstances(model, block, "FullRuntime/Link")
  343. while (set_len(incoming) > 0):
  344. selected = readAssociationSource(model, set_pop(incoming))
  345. instantiate_attribute(model, block, "last_in", cast_float(read_attribute(model, selected, "signal")))
  346. // Increase simulation time
  347. return time + delta_t!
  348. Void function eliminateGaussJordan(m : Element):
  349. Integer i
  350. Integer j
  351. Integer f
  352. Integer g
  353. Boolean searching
  354. Element t
  355. Float divisor
  356. i = 0
  357. j = 0
  358. while (i < read_nr_out(m)):
  359. // Make sure pivot m[i][j] != 0, swapping if necessary
  360. while (cast_float(m[i][j]) == 0.0):
  361. // Is zero, so find row which is not zero
  362. f = i + 1
  363. searching = True
  364. while (searching):
  365. if (f >= read_nr_out(m)):
  366. // No longer any rows left, so just increase column counter
  367. searching = False
  368. j = j + 1
  369. else:
  370. if (cast_float(m[f][j]) == 0.0):
  371. // Also zero, so continue
  372. f = f + 1
  373. else:
  374. // Found non-zero, so swap row
  375. t = cast_float(m[f])
  376. dict_overwrite(m, f, cast_float(m[i]))
  377. dict_overwrite(m, i, t)
  378. searching = False
  379. // If we have increased j, we will just start the loop again (possibly), as m[i][j] might be zero again
  380. // Pivot in m[i][j] guaranteed to not be 0
  381. // Now divide complete row by value of m[i][j] to make it equal 1
  382. f = j
  383. divisor = cast_float(m[i][j])
  384. while (f < read_nr_out(m[i])):
  385. dict_overwrite(m[i], f, float_division(cast_float(m[i][f]), divisor))
  386. f = f + 1
  387. // Eliminate all rows in the j-th column, except the i-th row
  388. f = 0
  389. while (f < read_nr_out(m)):
  390. if (bool_not(f == i)):
  391. g = j
  392. divisor = cast_float(m[f][j])
  393. while (g < read_nr_out(m[f])):
  394. dict_overwrite(m[f], g, cast_float(m[f][g]) - (divisor * cast_float(m[i][g])))
  395. g = g + 1
  396. f = f + 1
  397. // Increase row and column
  398. i = i + 1
  399. j = j + 1
  400. return !
  401. String function matrix2string(m : Element):
  402. Integer i
  403. Integer j
  404. String result
  405. result = ""
  406. i = 0
  407. while (i < read_nr_out(m)):
  408. j = 0
  409. while (j < read_nr_out(m[i])):
  410. result = result + cast_string(m[i][j]) + ", "
  411. j = j + 1
  412. i = i + 1
  413. result = result + "\n"
  414. return result!