SCCD_execute.alc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. include "primitives.alh"
  2. include "modelling.alh"
  3. include "object_operations.alh"
  4. include "utils.alh"
  5. include "random.alh"
  6. include "library.alh"
  7. Void function print_states(model : Element, data : Element):
  8. Element classes
  9. Element states
  10. Element class
  11. String state
  12. log("Current states:")
  13. classes = set_copy(data["classes"])
  14. while (read_nr_out(classes) > 0):
  15. class = set_pop(classes)
  16. log(string_join(string_join(string_join(" ", class["ID"]), " : "), read_attribute(model, class["type"], "name")))
  17. log(" Attributes: " + dict_to_string(class["attributes"]))
  18. states = set_copy(class["states"])
  19. log(" States:")
  20. while (read_nr_out(states) > 0):
  21. state = set_pop(states)
  22. log(string_join(" ", read_attribute(model, state, "name")))
  23. return!
  24. Element function filter(model : Element, set : Element, attribute_name : String, attribute_value : Element):
  25. Element keys
  26. String key
  27. Element result
  28. result = create_node()
  29. while (read_nr_out(set) > 0):
  30. key = set_pop(set)
  31. if (value_eq(read_attribute(model, key, attribute_name), attribute_value)):
  32. set_add(result, key)
  33. return result!
  34. Element function filter_exists(model : Element, set : Element, attribute_name : String):
  35. Element keys
  36. String key
  37. Element result
  38. result = create_node()
  39. while (read_nr_out(set) > 0):
  40. key = set_pop(set)
  41. if (element_neq(read_attribute(model, key, attribute_name), read_root())):
  42. set_add(result, key)
  43. return result!
  44. Element function expand_current_state(model : Element, state : String, current_states : Element):
  45. // Find the hierarchy of all current states, and select those that contain the currently selected state
  46. Element result
  47. result = create_node()
  48. current_states = set_copy(current_states)
  49. Element hierarchy
  50. String deep_state
  51. while (read_nr_out(current_states) > 0):
  52. deep_state = set_pop(current_states)
  53. hierarchy = find_hierarchy(model, deep_state)
  54. // Got the hierarchy of one of the states
  55. if (set_in(hierarchy, state)):
  56. // This hierarchy contains the root state we are checking for, so add to set
  57. set_add(result, deep_state)
  58. return result!
  59. Element function expand_initial_state(model : Element, state : String):
  60. String t
  61. t = read_type(model, state)
  62. if (t == "SCCD/CompositeState"):
  63. // Recurse further in the composite
  64. return expand_composite_state(model, state)!
  65. elif (t == "SCCD/ParallelState"):
  66. // Split up all components
  67. return expand_parallel_state(model, state)!
  68. else:
  69. // Probably just an atomic, so return this one only
  70. Element result
  71. result = create_node()
  72. set_add(result, state)
  73. return result!
  74. Element function expand_composite_state(model : Element, composite_state : String):
  75. // Resolve all initial states from a single composite state
  76. String initial
  77. // Fetch the initial state
  78. initial = set_pop(filter(model, allAssociationDestinations(model, composite_state, "SCCD/composite_children"), "isInitial", True))
  79. // Expand the initial state, depending on what it is
  80. return expand_initial_state(model, initial)!
  81. Element function expand_parallel_state(model : Element, parallel_state : String):
  82. // Resolve all initial states from a single parallel state
  83. Element children
  84. Element result
  85. Element expanded_children
  86. children = allAssociationDestinations(model, parallel_state, "SCCD/parallel_children")
  87. result = create_node()
  88. while (read_nr_out(children) > 0):
  89. set_merge(result, expand_initial_state(model, set_pop(children)))
  90. return result!
  91. Void function start_class(model : Element, data : Element, class : String):
  92. // Start up the class and assign its initial state to it
  93. // Create the data structure for a running class
  94. Element class_handle
  95. class_handle = create_node()
  96. dict_add(class_handle, "type", class)
  97. dict_add(class_handle, "ID", cast_id2s(create_node()))
  98. dict_add(class_handle, "timers", create_node())
  99. // Add the current state of the class
  100. String initial_state
  101. // Should only be one behaviour linked to it!
  102. initial_state = set_pop(allAssociationDestinations(model, class, "SCCD/behaviour"))
  103. dict_add(class_handle, "states", expand_initial_state(model, initial_state))
  104. // Add all attributes
  105. Element attributes
  106. attributes = create_node()
  107. Element attrs
  108. attrs = allAssociationDestinations(model, class, "SCCD/class_attributes")
  109. while (read_nr_out(attrs) > 0):
  110. dict_add(attributes, read_attribute(model, set_pop(attrs), "name"), read_root())
  111. dict_add(class_handle, "attributes", attributes)
  112. // Execute all entry actions
  113. Element init
  114. init = create_node()
  115. set_add(init, "")
  116. // Initial state before initialization is the set with an empty hierarchy
  117. // Empty set would not find any difference between the source and target
  118. execute_actions(model, init, set_copy(class_handle["states"]), attributes)
  119. dict_add(data["classes"], class_handle["ID"], class_handle)
  120. return!
  121. Element function get_enabled_transitions(model : Element, state : String, data : Element, class : String):
  122. // Returns all enabled transitions
  123. // TODO ignore conditions and afters
  124. Element result
  125. Element to_filter
  126. String attr
  127. String transition
  128. Element cond
  129. result = create_node()
  130. to_filter = allOutgoingAssociationInstances(model, state, "SCCD/transition")
  131. while (read_nr_out(to_filter) > 0):
  132. transition = set_pop(to_filter)
  133. // Check event
  134. attr = read_attribute(model, transition, "event")
  135. if (bool_not(bool_or(element_eq(attr, read_root()), set_in(data["events"], attr)))):
  136. continue!
  137. // Check after
  138. // Only an after if there was no event!
  139. if (bool_and(element_eq(attr, read_root()), read_attribute(model, transition, "after"))):
  140. if (dict_in(data["classes"][class]["timers"], transition)):
  141. // Registered timer already, let's check if it has expired
  142. if (float_gt(data["classes"][class]["timers"][transition], time())):
  143. // Not enabled yet
  144. continue!
  145. else:
  146. // Not registered even, so not enabled either
  147. continue!
  148. // Check condition
  149. cond = read_attribute(model, transition, "cond")
  150. if (element_neq(cond, read_root())):
  151. cond = get_func_AL_model(import_node(cond))
  152. // Execute condition
  153. if (bool_not(cond(data["classes"][class]["attributes"]))):
  154. // Condition false, so skip
  155. continue!
  156. // All is OK for this transition
  157. set_add(result, transition)
  158. return result!
  159. Void function execute_actions(model : Element, source_states : Element, target_states : Element, attributes : Element):
  160. Element actions
  161. actions = get_actions_to_execute(model, source_states, target_states)
  162. while (read_nr_out(actions) > 0):
  163. Element action
  164. action = list_pop(actions, 0)
  165. action(attributes)
  166. return!
  167. Element function execute_transition(model : Element, data : Element, class : String, transition : String):
  168. // Execute the script (if any)
  169. Element script
  170. script = read_attribute(model, transition, "script")
  171. if (element_neq(script, read_root())):
  172. script = get_func_AL_model(import_node(script))
  173. script(data["classes"][class]["attributes"])
  174. // Raise events (if any)
  175. Element events
  176. String event
  177. events = allAssociationDestinations(model, transition, "SCCD/transition_raises")
  178. while (read_nr_out(events) > 0):
  179. event = set_pop(events)
  180. set_add(data["events"], read_attribute(model, event, "event"))
  181. // Find new set of states
  182. Element target_states
  183. Element source_states
  184. source_states = expand_current_state(model, readAssociationSource(model, transition), data["classes"][class]["states"])
  185. target_states = expand_initial_state(model, readAssociationDestination(model, transition))
  186. log("Source state expanded to: " + set_to_string(source_states))
  187. log("Target state expanded to: " + set_to_string(target_states))
  188. execute_actions(model, source_states, target_states, data["classes"][class]["attributes"])
  189. return target_states!
  190. Boolean function step_class(model : Element, data : Element, class : String):
  191. // Find enabled transitions in a class and execute it, updating the state
  192. // Iterate over all current states, searching for enabled transitions
  193. // Search for enabled transitions in higher levels as well!
  194. Element states
  195. Element new_states
  196. String state
  197. Element transitions
  198. String transition
  199. Boolean transitioned
  200. states = set_copy(data["classes"][class]["states"])
  201. new_states = create_node()
  202. transitioned = False
  203. while (read_nr_out(states) > 0):
  204. state = set_pop(states)
  205. // Fetch transitions in this state specifically (NO parent)
  206. transitions = get_enabled_transitions(model, state, data, class)
  207. if (read_nr_out(transitions) != 0):
  208. // Found an enabled transition, so store that one
  209. transition = random_choice(transitions)
  210. // Execute transition
  211. set_merge(new_states, execute_transition(model, data, class, transition))
  212. transitioned = True
  213. else:
  214. // Try going to the parent
  215. // TODO
  216. // Nothing found, so stay in the current state
  217. set_add(new_states, state)
  218. // Update states
  219. dict_overwrite(data["classes"][class], "states", new_states)
  220. reschedule_timeouts(model, data, class)
  221. return transitioned!
  222. Void function reschedule_timeouts(model : Element, data : Element, class : String):
  223. Element timed_transitions
  224. Element old_timed_transitions
  225. String transition
  226. Element states
  227. String state
  228. timed_transitions = create_node()
  229. states = set_copy(data["classes"][class]["states"])
  230. // Collect all timed transitions that are currently active
  231. while (read_nr_out(states) > 0):
  232. state = set_pop(states)
  233. // NOTE this set_merge does not eliminate duplicates, though this should happen later on when adding the timer (see other NOTE)
  234. set_merge(timed_transitions, filter_exists(model, allOutgoingAssociationInstances(model, state, "SCCD/transition"), "after"))
  235. // Remove timers that no longer exist
  236. old_timed_transitions = dict_keys(data["classes"][class]["timers"])
  237. while (read_nr_out(old_timed_transitions) > 0):
  238. transition = set_pop(old_timed_transitions)
  239. if (bool_not(set_in(timed_transitions, transition))):
  240. // Transition is no longer scheduled for any state, so remove
  241. dict_delete(data["classes"][class]["timers"], transition)
  242. // Schedule timers that are not already scheduled
  243. while (read_nr_out(timed_transitions) > 0):
  244. transition = set_pop(timed_transitions)
  245. // NOTE Normally, a timer will not be added twice here, as the previous occurence will already find it
  246. if (bool_not(dict_in(data["classes"][class]["timers"], transition))):
  247. // Not yet scheduled this transition: do so now
  248. Element after
  249. Float after_duration
  250. after = read_attribute(model, transition, "after")
  251. after = get_func_AL_model(import_node(after))
  252. after_duration = after(data["classes"][class]["attributes"])
  253. dict_add(data["classes"][class]["timers"], transition, float_addition(data["start_time"], after_duration))
  254. return !
  255. String function get_parent(model : Element, state : String):
  256. Element tmp_set
  257. tmp_set = allAssociationOrigins(model, state, "composite_children")
  258. set_merge(tmp_set, allAssociationOrigins(model, state, "parallel_children"))
  259. if (read_nr_out(tmp_set) > 0):
  260. return set_pop(tmp_set)!
  261. else:
  262. return ""!
  263. Element function find_hierarchy(model : Element, state : String):
  264. if (state == ""):
  265. return create_node()!
  266. else:
  267. Element result
  268. String parent
  269. parent = get_parent(model, state)
  270. // We have a parent, so take the parent list first
  271. result = find_hierarchy(model, parent)
  272. list_append(result, state)
  273. return result!
  274. Element function get_actions_to_execute(model : Element, source_states : Element, target_states : Element):
  275. Element result
  276. result = create_node()
  277. source_states = set_copy(source_states)
  278. target_states = set_copy(target_states)
  279. // Add all exit and entry actions to the list of actions to execute
  280. // Do this by finding the common parent, and then doing all exit actions up to that node, and all entry actions up to the target_state
  281. // First, find the hierarchy!
  282. Element hierarchy_sources
  283. Element hierarchy_targets
  284. Element all_hierarchies
  285. hierarchy_sources = create_node()
  286. while (read_nr_out(source_states) > 0):
  287. set_add(hierarchy_sources, find_hierarchy(model, set_pop(source_states)))
  288. hierarchy_targets = create_node()
  289. while (read_nr_out(target_states) > 0):
  290. set_add(hierarchy_targets, find_hierarchy(model, set_pop(target_states)))
  291. all_hierarchies = set_copy(hierarchy_sources)
  292. set_merge(all_hierarchies, hierarchy_targets)
  293. // Difference these all lists, finding the first common entry
  294. Element iter_hierarchies
  295. Integer i
  296. String current
  297. Element hierarchy
  298. Boolean finished
  299. i = 0
  300. finished = False
  301. while (bool_not(finished)):
  302. // Check the i-th element in both and see if they are equal
  303. current = ""
  304. iter_hierarchies = set_copy(all_hierarchies)
  305. while (read_nr_out(iter_hierarchies) > 0):
  306. hierarchy = set_pop(iter_hierarchies)
  307. // Exhausted one of the lists
  308. if (i >= list_len(hierarchy)):
  309. finished = True
  310. break!
  311. // First entry, so read out value as reference
  312. if (current == ""):
  313. current = list_read(hierarchy, i)
  314. // Check with reference element
  315. if (bool_not(value_eq(list_read(hierarchy, i), current))):
  316. finished = True
  317. break!
  318. // i-th element equal for all hierarchies, so go to next element
  319. if (bool_not(finished)):
  320. i = i + 1
  321. log("Found difference at i = " + cast_v2s(i))
  322. // Found the first differing element at position i
  323. // All elements remaining in hierarchy_source are to be traversed in REVERSE order for the exit actions
  324. // All elements remaining in hierarchy_target are to be traversed in NORMAL order for the entry actions
  325. // This is not that simple either, as we need to consider that some actions might already have been added to the list...
  326. // Add hierarchy_sources actions
  327. String state
  328. Element visited
  329. Element action
  330. Element spliced_hierarchy
  331. Element hierarchy_source
  332. Element hierarchy_target
  333. visited = create_node()
  334. while (read_nr_out(hierarchy_sources) > 0):
  335. // Get one of these hierarchies
  336. hierarchy_source = set_pop(hierarchy_sources)
  337. spliced_hierarchy = list_splice(hierarchy_source, i, list_len(hierarchy_source))
  338. while (list_len(spliced_hierarchy) > 0):
  339. state = list_pop(spliced_hierarchy, list_len(spliced_hierarchy) - 1)
  340. if (set_in(visited, state)):
  341. // Already added this state, so don't bother
  342. continue!
  343. else:
  344. // New state, so prepend it to the list
  345. // Prepend, instead of append, as we want to do these operations in reverse order!
  346. // First check if there is any exit action at all
  347. action = read_attribute(model, state, "onExitScript")
  348. if (element_neq(action, read_root())):
  349. // An exit action is found!
  350. list_insert(result, get_func_AL_model(import_node(action)), 0)
  351. // Add this state as visited, even though there might not have been an associated action
  352. set_add(visited, state)
  353. // Add hierarchy_targets actions
  354. // Clear visited, just to be safe, though it should not matter
  355. visited = create_node()
  356. while (read_nr_out(hierarchy_targets) > 0):
  357. // Get one of these hierarchies
  358. hierarchy_target = set_pop(hierarchy_targets)
  359. spliced_hierarchy = list_splice(hierarchy_target, i, list_len(hierarchy_target))
  360. while (list_len(spliced_hierarchy) > 0):
  361. state = list_pop(spliced_hierarchy, list_len(spliced_hierarchy) - 1)
  362. if (set_in(visited, state)):
  363. // Already added this state, so don't bother
  364. continue!
  365. else:
  366. // New state, so append it to the list
  367. // Append, instead of prepend, as we want to do these operations in normal order!
  368. // First check if there is any entry action at all
  369. action = read_attribute(model, state, "onEntryScript")
  370. if (element_neq(action, read_root())):
  371. // An entry action is found!
  372. list_append(result, get_func_AL_model(import_node(action)))
  373. // Add this state as visited, even though there might not have been an associated action
  374. set_add(visited, state)
  375. return result!
  376. Float function step(model : Element, data : Element):
  377. // Step through all classes
  378. Element classes
  379. Element class
  380. Float t_min
  381. Float t_current
  382. Boolean transitioned
  383. Element keys
  384. String key
  385. t_min = time() + 99999.0
  386. classes = dict_keys(data["classes"])
  387. // TODO this should use simulated time or something
  388. dict_overwrite(data, "start_time", time())
  389. transitioned = False
  390. while (read_nr_out(classes) > 0):
  391. class = set_pop(classes)
  392. if (step_class(model, data, class)):
  393. transitioned = True
  394. if (bool_not(transitioned)):
  395. // Find minimum timer for this class, and store that
  396. keys = dict_keys(data["classes"][class]["timers"])
  397. while (read_nr_out(keys) > 0):
  398. key = set_pop(keys)
  399. t_current = data["classes"][class]["timers"][key]
  400. if (t_current < t_min):
  401. t_min = t_current
  402. if (transitioned):
  403. // Do another step, as we can transition
  404. return 0.0!
  405. else:
  406. return float_subtraction(t_min, data["start_time"])!
  407. Boolean function main(model : Element):
  408. // Executes the provided SCCD model
  409. Element data
  410. data = create_node()
  411. dict_add(data, "classes", create_node())
  412. // Prepare for input
  413. output("Ready for input!")
  414. // Find initial
  415. String default_class
  416. default_class = set_pop(filter(model, allInstances(model, "SCCD/Class"), "default", True))
  417. // Start up the default class
  418. start_class(model, data, default_class)
  419. Float timeout
  420. Element interrupt
  421. timeout = 0.0
  422. while (True):
  423. print_states(model, data)
  424. interrupt = input_timeout(timeout)
  425. if (value_eq(interrupt, "#EXIT#")):
  426. // Stop execution
  427. return True!
  428. dict_overwrite(data, "events", create_node())
  429. if (element_neq(interrupt, read_root())):
  430. // Got interrupt
  431. log("Got event: " + cast_v2s(interrupt))
  432. set_add(data["events"], interrupt)
  433. output("Processed event, ready for more!")
  434. timeout = step(model, data)
  435. log("Pausing for " + cast_v2s(timeout))
  436. // We should never get here!
  437. return False!