123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574 |
- include "primitives.alh"
- include "modelling.alh"
- include "object_operations.alh"
- include "conformance_scd.alh"
- include "io.alh"
- include "metamodels.alh"
- include "mini_modify.alh"
- include "utils.alh"
- Boolean function main(model : Element):
- String cmd
- Boolean running
- Element schedule_init
- Element schedule_run
- Element schedule
- Float current_time
- String time
- current_time = 0.0
- schedule_init = create_schedule(model)
- schedule_run = read_root()
- Element nodes
- Element inputs
- String node
- model_define_attribute(model["metamodel"], "DTCBD/Block", "signal", True, "DTCBD/Float")
- nodes = allInstances(model, "DTCBD/Block")
- inputs = dict_create()
- while (set_len(nodes) > 0):
- node = set_pop(nodes)
- dict_add(inputs, node, allAssociationOrigins(model, node, "DTCBD/Link"))
- while (bool_not(has_input())):
- if (current_time == 0.0):
- schedule = schedule_init
- else:
- if (element_eq(schedule_run, read_root())):
- schedule_run = create_schedule(model)
- schedule = schedule_run
- current_time = step_simulation(model, schedule, current_time, inputs)
- output("CLOSE")
- return False!
- Element function create_schedule(model : Element):
- // Create nice graph first
- Element nodes
- Element successors
- String element_name
- Element incoming_links
- Element all_blocks
- nodes = allInstances(model, "DTCBD/Block")
- successors = set_create()
- while (set_len(nodes) > 0):
- element_name = set_pop(nodes)
- if (is_nominal_instance(model, element_name, "DTCBD/ICBlock")):
- if (bool_not(is_physical_float(read_attribute(model, element_name, "last_in")))):
- incoming_links = allIncomingAssociationInstances(model, element_name, "DTCBD/InitialCondition")
- else:
- incoming_links = create_node()
- else:
- incoming_links = allIncomingAssociationInstances(model, element_name, "DTCBD/Link")
- while (set_len(incoming_links) > 0):
- String source
- source = readAssociationSource(model, set_pop(incoming_links))
- list_append(successors, create_tuple(source, element_name))
- Element values
- values = create_node()
- dict_add(values, "edges", successors)
- dict_add(values, "nodes", allInstances(model, "DTCBD/Block"))
- dict_add(values, "dfsCounter", 0)
- dict_add(values, "orderNumber", dict_create())
- dict_add(values, "visited_topSort", set_create())
- dict_add(values, "unvisited_strongComp", set_create())
- dict_overwrite(values, "SCC", strongComp(values))
- return values["SCC"]!
- Void function topSort(values : Element):
- Element nodes_copy
- String node
- dict_overwrite(values, "visited_topSort", set_create())
- nodes_copy = set_copy(values["nodes"])
- while (set_len(nodes_copy) > 0):
- node = set_pop(nodes_copy)
- if (bool_not(set_in(values["visited_topSort"], node))):
- dfsLabelling(values, node)
- return!
- Element function get_successors(values : Element, node : String, key : String):
- Element edges
- Element result
- String edge
- result = set_create()
- edges = list_copy(values[key])
- while (list_len(edges) > 0):
- edge = list_pop_final(edges)
- if (cast_string(edge[0]) == node):
- set_add(result, edge[1])
- return result!
- Void function dfsLabelling(values : Element, node : String):
- Element successors
- String successor
- // if not node.visited
- if (bool_not(set_in(values["visited_topSort"], node))):
- // node.visited = True
- set_add(values["visited_topSort"], node)
- // for neighbour in node.out_neighbours:
- // dfsLabelling(neighbour, graph)
- successors = get_successors(values, node, "edges")
- while (set_len(successors) > 0):
- successor = set_pop(successors)
- dfsLabelling(values, successor)
- // node.orderNumber = dfsCounter
- dict_overwrite(values["orderNumber"], node, values["dfsCounter"])
- // dfsCounter += 1
- dict_overwrite(values, "dfsCounter", cast_integer(values["dfsCounter"]) + 1)
- return !
- Element function dfsCollect(values : Element, start_node : String):
- Element result
- String successor
- Element successors
- result = set_create()
- // if not node.visited
- if (set_in(values["unvisited_strongComp"], start_node)):
- list_append(result, start_node)
- // node.visited = True
- set_remove(values["unvisited_strongComp"], start_node)
- // for neighbour in node.out_neighbours:
- // dfsLabelling(neighbour, graph)
- successors = get_successors(values, start_node, "rev_edges")
- while (set_len(successors) > 0):
- successor = set_pop(successors)
- list_extend(result, dfsCollect(values, successor))
- return result!
- String function highest_orderNumber(values : Element):
- Integer max
- String max_element
- Element search
- String elem
- max = -1
- search = set_copy(values["unvisited_strongComp"])
- while (set_len(search) > 0):
- elem = set_pop(search)
- if (cast_integer(values["orderNumber"][elem]) > max):
- max = values["orderNumber"][elem]
- max_element = elem
-
- return max_element!
- Element function reverse_edges(edges : Element):
- Element result
- Element elem
- result = list_create()
- edges = list_copy(edges)
- while (list_len(edges) > 0):
- elem = list_pop_final(edges)
- list_append(result, create_tuple(elem[1], elem[0]))
- return result!
- Element function strongComp(values : Element):
- Element graph
- Element sccs
- String start_node
- Element strong_components
- Element component
- sccs = list_create()
- topSort(values)
- dict_overwrite(values, "unvisited_strongComp", set_copy(values["nodes"]))
- dict_overwrite(values, "rev_edges", reverse_edges(values["edges"]))
- strong_components = list_create()
- while (set_len(values["unvisited_strongComp"]) > 0):
- start_node = highest_orderNumber(values)
- component = dfsCollect(values, start_node)
- list_append(sccs, component)
- return sccs!
- Element function get_topolist(values : Element):
- Element result
- Element predecessors
- Element remaining
- String current_element
- Element cur_predecessors
- result = list_create()
- predecessors = dict_copy(values["predecessors"])
- while (dict_len(predecessors) > 0):
- remaining = dict_keys(predecessors)
- while (set_len(remaining) > 0):
- current_element = set_pop(remaining)
- cur_predecessors = predecessors[current_element]
- if (set_len(set_overlap(list_to_set(result), cur_predecessors)) == set_len(cur_predecessors)):
- // All predecessors of this node have already been visited
- dict_delete(predecessors, current_element)
- remaining = dict_keys(predecessors)
- list_append(result, current_element)
- return result!
- Integer function min(a : Integer, b : Integer):
- if (a < b):
- return a!
- else:
- return b!
- Void function strongconnect(v : String, values : Element):
- // if (v.index is undefined) then
- // strongconnect(V)
- if (dict_in(values["indices"], v)):
- return!
- // v.index := index
- dict_overwrite(values["indices"], v, values["index"])
- // v.lowlink := indwx
- dict_overwrite(values["lowlink"], v, values["index"])
- // index := index + 1
- dict_overwrite(values, "index", cast_integer(values["index"]) + 1)
- // S.push(v)
- list_append(values["S"], v)
- // v.onStack := true
- dict_overwrite(values["onStack"], v, True)
-
- Element successors
- String w
- successors = values["successors"][v]
- while (set_len(successors) > 0):
- // for each (v, w) in E do
- w = set_pop(successors)
- // if (w.index is undefined) then
- if (bool_not(dict_in(values["indices"], w))):
- // strongconnect(w)
- strongconnect(w, values)
- // v.lowlink := min(v.lowlink, w.lowlink)
- dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["lowlink"][w]))
- elif (dict_in(values["onStack"], w)):
- // else if (w.onStack)
- if (values["onStack"][w]):
- // v.lowlink := min(v.lowlink, w.index)
- dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["indices"][w]))
-
- // if (v.lowlink == v.index) then
- if (value_eq(values["lowlink"][v], values["indices"][v])):
- Element scc
- // Start a new strongly connected component
- scc = create_node()
- // It will always differ now
- // w := S.pop()
- w = list_pop_final(values["S"])
- // w.onStack = false
- dict_overwrite(values["onStack"], w, False)
- // add w to current strongly connected component
- list_append(scc, w)
- // while w != v
- while (w != v):
- // w := S.pop()
- w = list_pop_final(values["S"])
- // w.onStack = false
- dict_overwrite(values["onStack"], w, False)
- // add w to current strongly connected component
- list_append(scc, w)
- // output the current strongly connected component
- list_insert(values["SCC"], scc, 0)
- return!
- Boolean function solve_scc(model : Element, scc : Element):
- Element m
- Integer i
- Integer j
- String block
- String blocktype
- Element incoming
- String selected
- Float constant
- Element t
- // Construct the matrix first, with as many rows as there are variables
- // Number of columns is 1 higher
- i = 0
- m = create_node()
- while (i < read_nr_out(scc)):
- j = 0
- t = create_node()
- while (j < (read_nr_out(scc) + 1)):
- list_append(t, 0.0)
- j = j + 1
- list_append(m, t)
- i = i + 1
- // Matrix initialized to 0.0
- i = 0
- while (i < read_nr_out(scc)):
- // First element of scc
- block = scc[i]
- blocktype = read_type(model, block)
- // First write 1 in the current block
- dict_overwrite(m[i], i, 1.0)
- // Now check all blocks that are incoming
- if (blocktype == "DTCBD/AdditionBlock"):
- constant = 0.0
- elif (blocktype == "DTCBD/MultiplyBlock"):
- constant = 1.0
- incoming = allIncomingAssociationInstances(model, block, "DTCBD/Link")
- Integer index_to_write_constant
- index_to_write_constant = -1
- while (read_nr_out(incoming) > 0):
- selected = readAssociationSource(model, set_pop(incoming))
- if (list_in(scc, selected)):
- // Part of the loop, so in the index of selected in scc
- // Five options:
- if (blocktype == "DTCBD/AdditionBlock"):
- // 1) AdditionBlock
- // Add the negative of this signal, which is as of yet unknown
- // x = y + z --> x - y - z = 0
- dict_overwrite(m[i], list_index_of(scc, selected), -1.0)
- elif (blocktype == "DTCBD/MultiplyBlock"):
- // 2) MultiplyBlock
- if (index_to_write_constant != -1):
- return False!
- index_to_write_constant = list_index_of(scc, selected)
- elif (blocktype == "DTCBD/NegatorBlock"):
- // 3) NegatorBlock
- // Add the positive of the signal, which is as of yet unknown
- dict_overwrite(m[i], list_index_of(scc, selected), 1.0)
- elif (blocktype == "DTCBD/DelayBlock"):
- // 5) DelayBlock
- // Just copies a single value
- dict_overwrite(m[i], list_index_of(scc, selected), -1.0)
- else:
- // Block that cannot be handled
- return False!
- else:
- // A constant, which we can assume is already computed and thus usable
- if (blocktype == "DTCBD/AdditionBlock"):
- constant = constant + cast_float(read_attribute(model, selected, "signal"))
- dict_overwrite(m[i], read_nr_out(scc), constant)
- elif (blocktype == "DTCBD/MultiplyBlock"):
- constant = constant * cast_float(read_attribute(model, selected, "signal"))
- // Not written to constant part, as multiplies a variable
- // Any other block is impossible:
- // * Constant would never be part of a SCC
- // * Delay would never get an incoming constant
- // * Negation and Inverse only get 1 input, which is a variable in a loop
- // * Integrator and Derivator never get an incoming constant
- if (index_to_write_constant != -1):
- dict_overwrite(m[i], index_to_write_constant, -constant)
- i = i + 1
- // Solve matrix now
- eliminateGaussJordan(m)
- // Now go over m and set signals for each element
- // Assume that everything worked out...
- i = 0
- while (i < read_nr_out(m)):
- block = scc[i]
- instantiate_attribute(model, block, "signal", m[i][read_nr_out(scc)])
- i = i + 1
- return True!
- Integer function list_index_of(lst : Element, elem : Element):
- Integer i
- i = 0
- while (i < read_nr_out(lst)):
- if (value_eq(list_read(lst, i), elem)):
- return i!
- else:
- i = i + 1
- return -1!
- Float function step_simulation(model : Element, schedule : Element, time : Float, inputs : Element):
- Float signal
- Element incoming
- String selected
- String block
- String elem
- String blocktype
- Element memory_blocks
- Integer i
- Float delta_t
- Element scc
- delta_t = 0.1
- memory_blocks = set_create()
- i = 0
- while (i < list_len(schedule)):
- scc = list_read(schedule, i)
- i = i + 1
- if (list_len(scc) > 1):
- if (bool_not(solve_scc(model, scc))):
- output("ALGEBRAIC_LOOP")
- return time!
- else:
- block = list_read(scc, 0)
- // Execute "block"
- blocktype = read_type(model, block)
- incoming = set_copy(inputs[block])
- if (blocktype == "DTCBD/ConstantBlock"):
- signal = cast_float(read_attribute(model, block, "value"))
- elif (blocktype == "DTCBD/AdditionBlock"):
- signal = 0.0
- while (set_len(incoming) > 0):
- selected = set_pop(incoming)
- signal = signal + cast_float(read_attribute(model, selected, "signal"))
- elif (blocktype == "DTCBD/MultiplyBlock"):
- signal = 1.0
- while (set_len(incoming) > 0):
- selected = set_pop(incoming)
- signal = signal * cast_float(read_attribute(model, selected, "signal"))
- elif (blocktype == "DTCBD/NegatorBlock"):
- signal = 0.0
- while (set_len(incoming) > 0):
- selected = set_pop(incoming)
- signal = float_neg(cast_float(read_attribute(model, selected, "signal")))
- elif (blocktype == "DTCBD/InverseBlock"):
- signal = 0.0
- while (set_len(incoming) > 0):
- selected = set_pop(incoming)
- signal = float_division(1.0, cast_float(read_attribute(model, selected, "signal")))
- elif (blocktype == "DTCBD/DelayBlock"):
- signal = 0.0
- if (bool_not(is_physical_float(read_attribute(model, block, "last_in")))):
- // No memory yet, so use initial condition
- incoming = allAssociationOrigins(model, block, "DTCBD/InitialCondition")
- while (set_len(incoming) > 0):
- selected = set_pop(incoming)
- signal = cast_float(read_attribute(model, selected, "signal"))
- else:
- signal = read_attribute(model, block, "last_in")
- set_add(memory_blocks, block)
- elif (blocktype == "DTCBD/ProbeBlock"):
- signal = 0.0
- while (set_len(incoming) > 0):
- signal = cast_float(read_attribute(model, set_pop(incoming), "signal"))
- output(cast_string(time) + " " + cast_string(read_attribute(model, block, "name")) + " " + cast_string(signal))
- log(cast_string(time) + " " + cast_string(read_attribute(model, block, "name")) + " " + cast_string(signal))
- instantiate_attribute(model, block, "signal", signal)
-
- while (set_len(memory_blocks) > 0):
- block = set_pop(memory_blocks)
- // Update memory
- incoming = set_copy(inputs[block])
- while (set_len(incoming) > 0):
- selected = set_pop(incoming)
- instantiate_attribute(model, block, "last_in", cast_float(read_attribute(model, selected, "signal")))
- // Increase simulation time
- return time + delta_t!
- Void function eliminateGaussJordan(m : Element):
- Integer i
- Integer j
- Integer f
- Integer g
- Boolean searching
- Element t
- Float divisor
- i = 0
- j = 0
- while (i < read_nr_out(m)):
- // Make sure pivot m[i][j] != 0, swapping if necessary
- while (cast_float(m[i][j]) == 0.0):
- // Is zero, so find row which is not zero
- f = i + 1
- searching = True
- while (searching):
- if (f >= read_nr_out(m)):
- // No longer any rows left, so just increase column counter
- searching = False
- j = j + 1
- else:
- if (cast_float(m[f][j]) == 0.0):
- // Also zero, so continue
- f = f + 1
- else:
- // Found non-zero, so swap row
- t = cast_float(m[f])
- dict_overwrite(m, f, cast_float(m[i]))
- dict_overwrite(m, i, t)
- searching = False
- // If we have increased j, we will just start the loop again (possibly), as m[i][j] might be zero again
- // Pivot in m[i][j] guaranteed to not be 0
- // Now divide complete row by value of m[i][j] to make it equal 1
- f = j
- divisor = cast_float(m[i][j])
- while (f < read_nr_out(m[i])):
- dict_overwrite(m[i], f, float_division(cast_float(m[i][f]), divisor))
- f = f + 1
- // Eliminate all rows in the j-th column, except the i-th row
- f = 0
- while (f < read_nr_out(m)):
- if (bool_not(f == i)):
- g = j
- divisor = cast_float(m[f][j])
- while (g < read_nr_out(m[f])):
- dict_overwrite(m[f], g, cast_float(m[f][g]) - (divisor * cast_float(m[i][g])))
- g = g + 1
- f = f + 1
- // Increase row and column
- i = i + 1
- j = j + 1
- return !
- String function matrix2string(m : Element):
- Integer i
- Integer j
- String result
- result = ""
- i = 0
- while (i < read_nr_out(m)):
- j = 0
- while (j < read_nr_out(m[i])):
- result = result + cast_string(m[i][j]) + ", "
- j = j + 1
- i = i + 1
- result = result + "\n"
- return result!
|