123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645 |
- include "primitives.alh"
- include "modelling.alh"
- include "object_operations.alh"
- include "utils.alh"
- include "random.alh"
- include "library.alh"
- Void function print_states(model : Element, data : Element):
- Element classes
- Element states
- Element class
- String state
- log("Current states:")
- classes = set_copy(data["classes"])
- while (read_nr_out(classes) > 0):
- class = set_pop(classes)
- log(string_join(string_join(string_join(" ", class["ID"]), " : "), read_attribute(model, class["type"], "name")))
- log(" Attributes: " + dict_to_string(class["attributes"]))
- states = set_copy(class["states"])
- log(" States:")
- while (read_nr_out(states) > 0):
- state = set_pop(states)
- log(string_join(" ", read_attribute(model, state, "name")))
- return!
- Element function filter(model : Element, set : Element, attribute_name : String, attribute_value : Element):
- Element keys
- String key
- Element result
- result = create_node()
- while (read_nr_out(set) > 0):
- key = set_pop(set)
- if (value_eq(read_attribute(model, key, attribute_name), attribute_value)):
- set_add(result, key)
- return result!
- Element function filter_exists(model : Element, set : Element, attribute_name : String):
- Element keys
- String key
- Element result
- result = create_node()
- while (read_nr_out(set) > 0):
- key = set_pop(set)
- if (element_neq(read_attribute(model, key, attribute_name), read_root())):
- set_add(result, key)
- return result!
- Element function expand_current_state(model : Element, state : String, current_states : Element):
- // Find the hierarchy of all current states, and select those that contain the currently selected state
- Element result
- result = create_node()
- current_states = set_copy(current_states)
- Element hierarchy
- String deep_state
- while (read_nr_out(current_states) > 0):
- deep_state = set_pop(current_states)
- hierarchy = find_hierarchy(model, deep_state)
- // Got the hierarchy of one of the states
- if (set_in(hierarchy, state)):
- // This hierarchy contains the root state we are checking for, so add to set
- set_add(result, deep_state)
- return result!
- Element function expand_initial_state(model : Element, state : String):
- String t
- t = read_type(model, state)
- if (t == "SCCD/CompositeState"):
- // Recurse further in the composite
- return expand_composite_state(model, state)!
- elif (t == "SCCD/ParallelState"):
- // Split up all components
- return expand_parallel_state(model, state)!
- else:
- // Probably just an atomic, so return this one only
- Element result
- result = create_node()
- set_add(result, state)
- return result!
- Element function expand_composite_state(model : Element, composite_state : String):
- // Resolve all initial states from a single composite state
- String initial
- // Fetch the initial state
- initial = set_pop(filter(model, allAssociationDestinations(model, composite_state, "SCCD/composite_children"), "isInitial", True))
- // Expand the initial state, depending on what it is
- return expand_initial_state(model, initial)!
- Element function expand_parallel_state(model : Element, parallel_state : String):
- // Resolve all initial states from a single parallel state
- Element children
- Element result
- Element expanded_children
- children = allAssociationDestinations(model, parallel_state, "SCCD/parallel_children")
- result = create_node()
- while (read_nr_out(children) > 0):
- set_merge(result, expand_initial_state(model, set_pop(children)))
- return result!
- Void function delete_class(model : Element, data : Element, identifier : String):
- // Stop a specific class instance, with attached statechart, from executing
- dict_delete(data["classes"], identifier)
- Void function start_class(model : Element, data : Element, class : String, identifier : String, parameters : Element):
- // Start up the class and assign its initial state to it
- // Create the data structure for a running class
- Element class_handle
- class_handle = create_node()
- dict_add(class_handle, "type", class)
- dict_add(class_handle, "ID", identifier)
- dict_add(class_handle, "timers", create_node())
- // Add the current state of the class
- String initial_state
- // Should only be one behaviour linked to it!
- initial_state = set_pop(allAssociationDestinations(model, class, "SCCD/behaviour"))
- dict_add(class_handle, "states", expand_initial_state(model, initial_state))
- // Add all attributes
- Element attributes
- attributes = create_node()
- Element attrs
- attrs = allAssociationDestinations(model, class, "SCCD/class_attributes")
- while (read_nr_out(attrs) > 0):
- dict_add(attributes, read_attribute(model, set_pop(attrs), "name"), read_root())
- dict_add(class_handle, "attributes", attributes)
- // Invoke constructor
- Element constructor
- constructor = read_attribute(model, class, "constructor_body")
- if (element_neq(constructor, read_root())):
- // Constructor, so execute
- constructor = get_func_AL_model(import_node(constructor))
- constructor(attributes, parameters)
- // Execute all entry actions
- Element init
- init = create_node()
- set_add(init, "")
- // Initial state before initialization is the set with an empty hierarchy
- // Empty set would not find any difference between the source and target
- execute_actions(model, init, set_copy(class_handle["states"]), attributes)
- dict_add(data["classes"], class_handle["ID"], class_handle)
- return!
- Element function get_enabled_transitions(model : Element, state : String, data : Element, class : String):
- // Returns all enabled transitions
- Element result
- Element to_filter
- String attr
- String transition
- Element cond
- String evt_name
- Element evt
- Element events
- Element event_names
- Element event_parameters
- result = create_node()
- to_filter = allOutgoingAssociationInstances(model, state, "SCCD/transition")
- event_names = create_node()
- event_parameters = create_node()
- events = set_copy(data["events"])
- while (read_nr_out(events) > 0):
- evt = set_pop(events)
- evt_name = list_read(evt, 0)
- if (bool_not(set_in(event_names, evt_name))):
- // Not yet registered the event
- set_add(event_names, evt_name)
- dict_add(event_parameters, evt_name, create_node())
- // Add event parameters
- set_add(event_parameters[evt_name], list_read(evt, 1))
- while (read_nr_out(to_filter) > 0):
- transition = set_pop(to_filter)
- // Check event
- attr = read_attribute(model, transition, "event")
- if (bool_not(bool_or(element_eq(attr, read_root()), set_in(event_names, attr)))):
- // At least one enabled event is found
- continue!
- // Check after
- // Only an after if there was no event!
- if (bool_and(element_eq(attr, read_root()), read_attribute(model, transition, "after"))):
- if (dict_in(data["classes"][class]["timers"], transition)):
- // Registered timer already, let's check if it has expired
- if (float_gt(data["classes"][class]["timers"][transition], time())):
- // Not enabled yet
- continue!
- else:
- // Not registered even, so not enabled either
- continue!
- // Check condition, but depends on whether there was an event or not
- cond = read_attribute(model, transition, "cond")
- if (element_neq(cond, read_root())):
- // Got a condition, so resolve
- cond = get_func_AL_model(import_node(cond))
- if (element_neq(attr, read_root())):
- // We have an event to take into account!
- Element params
- Element param
- params = set_copy(event_parameters[attr])
- while (read_nr_out(params) > 0):
- param = set_pop(params)
- if (element_neq(cond, read_root())):
- // Got a condition to check first
- if (bool_not(cond(data["classes"][class]["attributes"], param))):
- // Condition failed, so skip
- continue!
- // Fine to add this one with the specified parameters
- set_add(result, create_tuple(transition, param))
- else:
- // No event to think about, just add the transition
- if (element_neq(cond, read_root())):
- // Check the condition first
- if (bool_not(cond(data["classes"][class]["attributes"], read_root()))):
- // Condition false, so skip
- continue!
- // Fine to add this one without event parameters (no event)
- set_add(result, create_tuple(transition, read_root()))
- return result!
- Void function execute_actions(model : Element, source_states : Element, target_states : Element, attributes : Element):
- Element actions
- actions = get_actions_to_execute(model, source_states, target_states)
- while (read_nr_out(actions) > 0):
- Element action
- action = list_pop(actions, 0)
- action(attributes)
- return!
- Element function execute_transition(model : Element, data : Element, class : String, transition_tuple : Element):
- // Execute the script (if any)
- Element script
- String transition
- Element event_parameter
- transition = list_read(transition_tuple, 0)
- event_parameter = list_read(transition_tuple, 1)
- script = read_attribute(model, transition, "script")
- if (element_neq(script, read_root())):
- script = get_func_AL_model(import_node(script))
- script(data["classes"][class]["attributes"], event_parameter)
- // Raise events (if any)
- Element events
- String event
- events = allAssociationDestinations(model, transition, "SCCD/transition_raises")
- while (read_nr_out(events) > 0):
- event = set_pop(events)
- Element parameter_action
- parameter_action = read_attribute(model, event, "parameter")
- if (element_neq(parameter_action, read_root())):
- // Got a parameter to evaluate
- parameter_action = get_func_AL_model(import_node(parameter_action))
- parameter_action = parameter_action(data["classes"][class]["attributes"], event_parameter)
- String scope
- scope = read_attribute(model, event, "scope")
- if (scope == "cd"):
- // Is an event for us internally, so don't append
- // Instead, we process it directly
- String operation
- operation = read_attribute(model, event, "event")
- if (operation == "create_instance"):
- // Start up a new class of the desired type
- // Parameters of this call:
- // class -- type of the class to instantiate
- // identifier -- name of this instance, for future reference
- // parameters -- parameters for constructor
- String class
- String identifier
- Element parameters
- class = set_pop(filter(model, allInstances(model, "SCCD/Class"), "name", list_read(parameter_action, 0)))
- identifier = list_read(parameter_action, 1)
- parameters = list_read(parameter_action, 2)
- start_class(model, data, class, identifier, parameters)
- elif (operation == "delete_instance"):
- // Delete the requested class
- String identifier
- identifier = list_read(parameter_action, 0)
- delete_class(model, data, identifier)
- else:
- set_add(data["events"], create_tuple(read_attribute(model, event, "event"), parameter_action))
- // Find new set of states
- Element target_states
- Element source_states
- source_states = expand_current_state(model, readAssociationSource(model, transition), data["classes"][class]["states"])
- target_states = expand_initial_state(model, readAssociationDestination(model, transition))
- execute_actions(model, source_states, target_states, data["classes"][class]["attributes"])
- return target_states!
- Boolean function step_class(model : Element, data : Element, class : String):
- // Find enabled transitions in a class and execute it, updating the state
- // Iterate over all current states, searching for enabled transitions
- // Search for enabled transitions in higher levels as well!
- Element states
- Element new_states
- String state
- Element transitions
- String transition
- Boolean transitioned
- Element hierarchy
- String current_state
- Boolean found
- states = set_copy(data["classes"][class]["states"])
- new_states = create_node()
- transitioned = False
- while (read_nr_out(states) > 0):
- state = set_pop(states)
- found = False
- // Loop over the hierarchy of this state and try to apply transitions
- hierarchy = find_hierarchy(model, state)
- while (read_nr_out(hierarchy) > 0):
- current_state = list_pop(hierarchy, 0)
- transitions = get_enabled_transitions(model, current_state, data, class)
- if (read_nr_out(transitions) > 0):
- // Found an enabled transition, so store that one
- transition = random_choice(transitions)
-
- // Execute transition
- set_merge(new_states, execute_transition(model, data, class, transition))
- // When leaving an orthogonal component, we must also pop all related states that might be processed in the future!
- Element leaving
- leaving = expand_current_state(model, current_state, data["classes"][class]["states"])
- set_difference(states, leaving)
- transitioned = True
- found = True
- break!
- if (bool_not(found)):
- // Nothing found, so stay in the current state
- set_add(new_states, state)
-
- // Update states
- dict_overwrite(data["classes"][class], "states", new_states)
- reschedule_timeouts(model, data, class)
- return transitioned!
- Void function reschedule_timeouts(model : Element, data : Element, class : String):
- Element timed_transitions
- Element old_timed_transitions
- String transition
- Element states
- String state
- timed_transitions = create_node()
- states = set_copy(data["classes"][class]["states"])
- // Collect all timed transitions that are currently active
- while (read_nr_out(states) > 0):
- state = set_pop(states)
- // NOTE this set_merge does not eliminate duplicates, though this should happen later on when adding the timer (see other NOTE)
- set_merge(timed_transitions, filter_exists(model, allOutgoingAssociationInstances(model, state, "SCCD/transition"), "after"))
- // Remove timers that no longer exist
- old_timed_transitions = dict_keys(data["classes"][class]["timers"])
- while (read_nr_out(old_timed_transitions) > 0):
- transition = set_pop(old_timed_transitions)
- if (bool_not(set_in(timed_transitions, transition))):
- // Transition is no longer scheduled for any state, so remove
- dict_delete(data["classes"][class]["timers"], transition)
- // Schedule timers that are not already scheduled
- while (read_nr_out(timed_transitions) > 0):
- transition = set_pop(timed_transitions)
- // NOTE Normally, a timer will not be added twice here, as the previous occurence will already find it
- if (bool_not(dict_in(data["classes"][class]["timers"], transition))):
- // Not yet scheduled this transition: do so now
- Element after
- Float after_duration
- after = read_attribute(model, transition, "after")
- after = get_func_AL_model(import_node(after))
- after_duration = after(data["classes"][class]["attributes"])
- dict_add(data["classes"][class]["timers"], transition, float_addition(data["start_time"], after_duration))
- return !
- String function get_parent(model : Element, state : String):
- Element tmp_set
- tmp_set = allAssociationOrigins(model, state, "SCCD/composite_children")
- set_merge(tmp_set, allAssociationOrigins(model, state, "SCCD/parallel_children"))
- if (read_nr_out(tmp_set) > 0):
- return set_pop(tmp_set)!
- else:
- return ""!
- Element function find_hierarchy(model : Element, state : String):
- if (state == ""):
- return create_node()!
- else:
- Element result
- String parent
- parent = get_parent(model, state)
- // We have a parent, so take the parent list first
- result = find_hierarchy(model, parent)
- list_append(result, state)
- return result!
- Element function get_actions_to_execute(model : Element, source_states : Element, target_states : Element):
- Element result
- result = create_node()
- source_states = set_copy(source_states)
- target_states = set_copy(target_states)
- // Add all exit and entry actions to the list of actions to execute
- // 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
- // First, find the hierarchy!
- Element hierarchy_sources
- Element hierarchy_targets
- Element all_hierarchies
- hierarchy_sources = create_node()
- while (read_nr_out(source_states) > 0):
- set_add(hierarchy_sources, find_hierarchy(model, set_pop(source_states)))
- hierarchy_targets = create_node()
- while (read_nr_out(target_states) > 0):
- set_add(hierarchy_targets, find_hierarchy(model, set_pop(target_states)))
- all_hierarchies = set_copy(hierarchy_sources)
- set_merge(all_hierarchies, hierarchy_targets)
- // Difference these all lists, finding the first common entry
- Element iter_hierarchies
- Integer i
- String current
- Element hierarchy
- Boolean finished
- i = 0
- finished = False
- while (bool_not(finished)):
- // Check the i-th element in both and see if they are equal
- current = ""
- iter_hierarchies = set_copy(all_hierarchies)
- while (read_nr_out(iter_hierarchies) > 0):
- hierarchy = set_pop(iter_hierarchies)
- // Exhausted one of the lists
- if (i >= list_len(hierarchy)):
- finished = True
- break!
- // First entry, so read out value as reference
- if (current == ""):
- current = list_read(hierarchy, i)
- // Check with reference element
- if (bool_not(value_eq(list_read(hierarchy, i), current))):
- finished = True
- break!
- // i-th element equal for all hierarchies, so go to next element
- if (bool_not(finished)):
- i = i + 1
- // Found the first differing element at position i
- // All elements remaining in hierarchy_source are to be traversed in REVERSE order for the exit actions
- // All elements remaining in hierarchy_target are to be traversed in NORMAL order for the entry actions
- // This is not that simple either, as we need to consider that some actions might already have been added to the list...
- // Add hierarchy_sources actions
- String state
- Element visited
- Element action
- Element spliced_hierarchy
- Element hierarchy_source
- Element hierarchy_target
- visited = create_node()
- while (read_nr_out(hierarchy_sources) > 0):
- // Get one of these hierarchies
- hierarchy_source = set_pop(hierarchy_sources)
- spliced_hierarchy = list_splice(hierarchy_source, i, list_len(hierarchy_source))
- while (list_len(spliced_hierarchy) > 0):
- state = list_pop(spliced_hierarchy, list_len(spliced_hierarchy) - 1)
- if (set_in(visited, state)):
- // Already added this state, so don't bother
- continue!
- else:
- // New state, so prepend it to the list
- // Prepend, instead of append, as we want to do these operations in reverse order!
- // First check if there is any exit action at all
- action = read_attribute(model, state, "onExitScript")
- if (element_neq(action, read_root())):
- // An exit action is found!
- list_insert(result, get_func_AL_model(import_node(action)), 0)
- // Add this state as visited, even though there might not have been an associated action
- set_add(visited, state)
- // Add hierarchy_targets actions
- // Clear visited, just to be safe, though it should not matter
- visited = create_node()
- while (read_nr_out(hierarchy_targets) > 0):
- // Get one of these hierarchies
- hierarchy_target = set_pop(hierarchy_targets)
- spliced_hierarchy = list_splice(hierarchy_target, i, list_len(hierarchy_target))
- while (list_len(spliced_hierarchy) > 0):
- state = list_pop(spliced_hierarchy, list_len(spliced_hierarchy) - 1)
- if (set_in(visited, state)):
- // Already added this state, so don't bother
- continue!
- else:
- // New state, so append it to the list
- // Append, instead of prepend, as we want to do these operations in normal order!
- // First check if there is any entry action at all
- action = read_attribute(model, state, "onEntryScript")
- if (element_neq(action, read_root())):
- // An entry action is found!
- list_append(result, get_func_AL_model(import_node(action)))
- // Add this state as visited, even though there might not have been an associated action
- set_add(visited, state)
- return result!
- Float function step(model : Element, data : Element):
- // Step through all classes
- Element classes
- Element class
- Float t_min
- Float t_current
- Boolean transitioned
- Element keys
- String key
- t_min = time() + 99999.0
- classes = dict_keys(data["classes"])
- // TODO this should use simulated time or something
- dict_overwrite(data, "start_time", time())
- transitioned = False
- while (read_nr_out(classes) > 0):
- class = set_pop(classes)
- if (step_class(model, data, class)):
- transitioned = True
- if (bool_not(transitioned)):
- // Find minimum timer for this class, and store that
- keys = dict_keys(data["classes"][class]["timers"])
- while (read_nr_out(keys) > 0):
- key = set_pop(keys)
- t_current = data["classes"][class]["timers"][key]
- if (t_current < t_min):
- t_min = t_current
- if (transitioned):
- // Do another step, as we can transition
- return 0.0!
- else:
- return float_subtraction(t_min, data["start_time"])!
- Boolean function main(model : Element):
- // Executes the provided SCCD model
- Element data
- data = create_node()
- dict_add(data, "classes", create_node())
- // Prepare for input
- output("Ready for input!")
- // Find initial
- String default_class
- default_class = set_pop(filter(model, allInstances(model, "SCCD/Class"), "default", True))
- // Start up the default class
- start_class(model, data, default_class, "main", read_root())
- Float timeout
- Element interrupt
- timeout = 0.0
- while (True):
- print_states(model, data)
- interrupt = input_timeout(timeout)
- if (value_eq(interrupt, "#EXIT#")):
- // Stop execution
- return True!
- dict_overwrite(data, "events", create_node())
- if (element_neq(interrupt, read_root())):
- // Got interrupt
- log("Got event: " + cast_v2s(interrupt))
- set_add(data["events"], create_tuple(interrupt, read_root()))
- output("Processed event, ready for more!")
- timeout = step(model, data)
- if (read_nr_out(data["classes"]) == 0):
- // No more active classes left: terminate!
- log("Finished SCCD execution")
- break!
- log("Pausing for " + cast_v2s(timeout))
- // We should never get here!
- return False!
|