cbd_simulate.alc 15 KB

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