Преглед изворни кода

Add draft of CBD functions and models

Yentl Van Tendeloo пре 7 година
родитељ
комит
e87609e023
4 измењених фајлова са 606 додато и 0 уклоњено
  1. 39 0
      models/cbd_merge.alc
  2. 459 0
      models/cbd_simulate.alc
  3. 49 0
      models/cbd_spring.mvc
  4. 59 0
      models/cbd_toRuntime.alc

+ 39 - 0
models/cbd_merge.alc

@@ -0,0 +1,39 @@
+include "primitives.alh"
+include "modelling.alh"
+include "object_operations.alh"
+
+String function map_P2F(model : Element, name : String):
+	return readAssociationDestination(model, set_pop(allAssociationDestinations(model, name, "P2F_block")))!
+
+Boolean function main(model : Element):
+	Element all_blocks
+	String element_name
+	Float current_time
+
+	all_blocks = allInstances(model, "PartialRuntime/Block")
+	while (set_len(all_blocks) > 0):
+		element_name = set_pop(all_blocks)
+		if (set_len(allOutgoingAssociationInstances(model, element_name, "P2F_block")) > 0):
+			// Element already exists in full, so copy existing attributes
+            if (is_nominal_instance(model, element_name, "ICBlock")):
+                instantiate_attribute(model, element_name, "last_in", read_attribute(model, map_P2F(model, element_name), "last_in"))
+            if (is_nominal_instance(model, element_name, "IntegratorBlock")):
+                instantiate_attribute(model, element_name, "last_out", read_attribute(model, map_P2F(model, element_name), "last_out"))
+            instantiate_attribute(model, element_name, "signal", read_attribute(model, map_P2F(model, element_name)))
+		else:
+			// Element doesn't exist, so initialize with 0.0
+            instantiate_attribute(model, element_name, "signal", 0.0)
+			instantiate_edge(model, "P2F_block", "", element_name, element_name)
+
+	if (set_len(allInstances(model, "FullRuntime/Time")) > 0):
+		// Time already exists, so copy the value
+		current_time = read_attribute(model, set_pop(allInstances(model, "FullRuntime/Time")), "current_time")
+	else:
+		// No time yet, so initialize
+		current_time = 0.0
+
+	time_block = instantiate_node(model, "PartialRuntime/Time", "")
+	instantiate_attribute(model, time_block, "start_time", current_time)
+	instantiate_attribute(model, time_block, "current_time", current_time)
+
+	return True!

+ 459 - 0
models/cbd_simulate.alc

@@ -0,0 +1,459 @@
+include "primitives.alh"
+include "modelling.alh"
+include "object_operations.alh"
+include "conformance_scd.alh"
+include "io.alh"
+include "metamodels.alh"
+
+Boolean function main(model : Element):
+	String cmd
+	Boolean running
+	Element schedule_init
+	Element schedule_run
+	Element schedule
+	String conforming
+
+	schedule_init = create_schedule(model)
+	schedule_run = read_root()
+
+	while (bool_not(has_input())):
+		if (read_attribute(model, "time", "start_time") == read_attribute(model, "time", "current_time")):
+			schedule = schedule_init
+		else:
+			if (element_eq(schedule_run, read_root())):
+				schedule_run = create_schedule(model)
+			schedule = schedule_run
+		//schedule = create_schedule(model)
+		step_simulation(model, schedule)
+
+	log("Finishing simulation, as we got input!")
+	return True!
+
+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, "Block")
+	successors = create_node()
+	while (read_nr_out(nodes) > 0):
+		element_name = set_pop(nodes)
+		if (bool_not(dict_in(successors, element_name))):
+			dict_add(successors, element_name, create_node())
+
+		if (is_nominal_instance(model, element_name, "ICBlock")):
+			if (element_eq(read_attribute(model, element_name, "last_in"), read_root())):
+				incoming_links = allIncomingAssociationInstances(model, element_name, "InitialCondition")
+			else:
+				incoming_links = create_node()
+			if (is_nominal_instance(model, element_name, "DerivatorBlock")):
+				Element new_incoming_links
+				new_incoming_links = allIncomingAssociationInstances(model, element_name, "Link")
+				while (read_nr_out(new_incoming_links) > 0):
+					list_append(incoming_links, set_pop(new_incoming_links))
+		else:
+			incoming_links = allIncomingAssociationInstances(model, element_name, "Link")
+
+		while (read_nr_out(incoming_links) > 0):
+			String source
+			source = readAssociationSource(model, set_pop(incoming_links))
+			if (bool_not(dict_in(successors, source))):
+				dict_add(successors, source, create_node())
+			set_add(successors[source], element_name)
+	
+	Element values
+	values = create_node()
+	dict_add(values, "S", create_node())
+	dict_add(values, "index", 0)
+	dict_add(values, "indices", create_node())
+	dict_add(values, "lowlink", create_node())
+	dict_add(values, "onStack", create_node())
+	dict_add(values, "successors", successors)
+	dict_add(values, "SCC", create_node())
+
+	nodes = allInstances(model, "Block")
+	while (read_nr_out(nodes) > 0):
+		strongconnect(set_pop(nodes), values)
+
+	return values["SCC"]!
+
+Integer function min(a : Integer, b : Integer):
+	if (a < b):
+		return a!
+	else:
+		return b!
+
+Void function strongconnect(v : String, values : Element):
+	if (dict_in(values["indices"], v)):
+		return!
+
+	dict_overwrite(values["indices"], v, values["index"])
+	dict_overwrite(values["lowlink"], v, values["index"])
+	dict_overwrite(values, "index", cast_s2i(cast_v2s(values["index"])) + 1)
+
+	list_append(values["S"], v)
+	dict_overwrite(values["onStack"], v, True)
+	
+	Element successors
+	String w
+	successors = values["successors"][v]
+	while (read_nr_out(successors) > 0):
+		w = set_pop(successors)
+		if (bool_not(dict_in(values["indices"], w))):
+			strongconnect(w, values)
+			dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["lowlink"][w]))
+		elif (dict_in(values["onStack"], w)):
+			if (values["onStack"][w]):
+				dict_overwrite(values["lowlink"], v, min(values["lowlink"][v], values["indices"][w]))
+	
+	if (value_eq(values["lowlink"][v], values["indices"][v])):
+		Element scc
+		scc = create_node()
+		// It will always differ now
+		w = list_pop_final(values["S"])
+		list_append(scc, w)
+		dict_overwrite(values["onStack"], w, False)
+		while (w != v):
+			w = list_pop_final(values["S"])
+			list_append(scc, w)
+			dict_overwrite(values["onStack"], w, False)
+		list_insert(values["SCC"], scc, 0)
+
+	return!
+
+String function readType(model : Element, name : String):
+	return reverseKeyLookup(model["metamodel"]["model"], dict_read_node(model["type_mapping"], model["model"][name]))!
+
+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
+
+	log("Matrix ready!")
+	// Matrix initialized to 0.0
+	i = 0
+	while (i < read_nr_out(scc)):
+		log("Creating matrix row")
+		// First element of scc
+		block = scc[i]
+		blocktype = readType(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 == "AdditionBlock"):
+			constant = 0.0
+		elif (blocktype == "MultiplyBlock"):
+			constant = 1.0
+
+		log("Generating matrix for " + blocktype)
+		log("Block: " + block)
+		incoming = allIncomingAssociationInstances(model, block, "Link")
+
+		Integer index_to_write_constant
+		index_to_write_constant = -1
+		log("Iterating over incoming")
+		while (read_nr_out(incoming) > 0):
+			log("Iteration")
+			selected = readAssociationSource(model, set_pop(incoming))
+
+			if (set_in(scc, selected)):
+				// Part of the loop, so in the index of selected in scc
+				// Five options:
+				if (blocktype == "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 == "MultiplyBlock"):
+					// 2) MultiplyBlock
+					if (index_to_write_constant != -1):
+						return False!
+					index_to_write_constant = list_index_of(scc, selected)
+				elif (blocktype == "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 == "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 == "AdditionBlock"):
+					constant = constant + v2f(read_attribute(model, selected, "signal"))
+					dict_overwrite(m[i], read_nr_out(scc), constant)
+				elif (blocktype == "MultiplyBlock"):
+					constant = constant * v2f(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
+
+	// Constructed a complete matrix, so we can start!
+	log("Constructed matrix to solve:")
+	log(matrix2string(m))
+
+	// 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]
+		unset_attribute(model, block, "signal")
+		instantiate_attribute(model, block, "signal", m[i][read_nr_out(scc)])
+		log((("Solved " + block) + " to ") + cast_v2s(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!
+
+Void function step_simulation(model : Element, schedule : Element):
+	String time
+	Float signal
+	Element incoming
+	String selected
+	String block
+	String elem
+	String blocktype
+	Element memory_blocks
+	Integer i
+	Float delta_t
+	Element scc
+
+	time = "time"
+	delta_t = 0.1
+
+	memory_blocks = create_node()
+	output("SIM_TIME " + cast_v2s(read_attribute(model, time, "current_time")))
+	i = 0
+	while (i < read_nr_out(schedule)):
+		scc = list_read(schedule, i)
+		i = i + 1
+
+		if (list_len(scc) > 1):
+			log("Solving algebraic loop!")
+			if (bool_not(solve_scc(model, scc))):
+				output("ALGEBRAIC_LOOP")
+				return !
+		else:
+			block = set_pop(scc)
+
+			// Execute "block"
+			blocktype = readType(model, block)
+			if (blocktype == "ConstantBlock"):
+				signal = read_attribute(model, block, "value")
+			elif (blocktype == "AdditionBlock"):
+				signal = 0.0
+				incoming = allIncomingAssociationInstances(model, block, "Link")
+				while (read_nr_out(incoming) > 0):
+					selected = readAssociationSource(model, set_pop(incoming))
+					signal = signal + cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
+			elif (blocktype == "MultiplyBlock"):
+				signal = 1.0
+				incoming = allIncomingAssociationInstances(model, block, "Link")
+				while (read_nr_out(incoming) > 0):
+					selected = readAssociationSource(model, set_pop(incoming))
+					signal = signal * cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
+			elif (blocktype == "NegatorBlock"):
+				incoming = allIncomingAssociationInstances(model, block, "Link")
+				signal = 0.0
+				while (read_nr_out(incoming) > 0):
+					selected = readAssociationSource(model, set_pop(incoming))
+					signal = float_neg(cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
+			elif (blocktype == "InverseBlock"):
+				signal = 0.0
+				incoming = allIncomingAssociationInstances(model, block, "Link")
+				while (read_nr_out(incoming) > 0):
+					selected = readAssociationSource(model, set_pop(incoming))
+					signal = float_division(1.0, cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
+			elif (blocktype == "DelayBlock"):
+				signal = 0.0
+				if (element_eq(read_attribute(model, block, "last_in"), read_root())):
+					// No memory yet, so use initial condition
+					incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
+					while (read_nr_out(incoming) > 0):
+						selected = readAssociationSource(model, set_pop(incoming))
+						signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
+				else:
+					signal = read_attribute(model, block, "last_in")
+					unset_attribute(model, block, "last_in")
+				set_add(memory_blocks, block)
+			elif (blocktype == "IntegratorBlock"):
+				if (element_eq(read_attribute(model, block, "last_in"), read_root())):
+					// No history yet, so use initial values
+					incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
+					while (read_nr_out(incoming) > 0):
+						selected = readAssociationSource(model, set_pop(incoming))
+						signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
+				else:
+					signal = cast_s2f(cast_v2s(read_attribute(model, block, "last_in"))) + (delta_t * cast_s2f(cast_v2s(read_attribute(model, block, "last_out"))))
+					unset_attribute(model, block, "last_in")
+					unset_attribute(model, block, "last_out")
+				instantiate_attribute(model, block, "last_out", signal)
+				set_add(memory_blocks, block)
+			elif (blocktype == "DerivatorBlock"):
+				if (element_eq(read_attribute(model, block, "last_in"), read_root())):
+					// No history yet, so use initial values
+					incoming = allIncomingAssociationInstances(model, block, "InitialCondition")
+					while (read_nr_out(incoming) > 0):
+						selected = readAssociationSource(model, set_pop(incoming))
+						signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
+				else:
+					incoming = allIncomingAssociationInstances(model, block, "Link")
+					while (read_nr_out(incoming) > 0):
+						selected = readAssociationSource(model, set_pop(incoming))
+						signal = (cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))) - cast_s2f(cast_v2s(read_attribute(model, block, "last_in")))) / delta_t
+					unset_attribute(model, block, "last_in")
+				set_add(memory_blocks, block)
+			elif (blocktype == "ProbeBlock"):
+				incoming = allIncomingAssociationInstances(model, block, "Link")
+				while (read_nr_out(incoming) > 0):
+					selected = readAssociationSource(model, set_pop(incoming))
+					signal = cast_s2f(cast_v2s(read_attribute(model, selected, "signal")))
+					output((("SIM_PROBE " + cast_v2s(read_attribute(model, block, "name"))) + " ") + cast_v2s(signal))
+
+			unset_attribute(model, block, "signal")
+			instantiate_attribute(model, block, "signal", signal)
+	output("SIM_END")
+	
+	while (read_nr_out(memory_blocks) > 0):
+		block = set_pop(memory_blocks)
+		// Update memory
+		incoming = allIncomingAssociationInstances(model, block, "Link")
+		while (read_nr_out(incoming) > 0):
+			selected = readAssociationSource(model, set_pop(incoming))
+			instantiate_attribute(model, block, "last_in", cast_s2f(cast_v2s(read_attribute(model, selected, "signal"))))
+
+	// Increase simulation time
+	Float new_time
+	new_time = cast_s2f(cast_v2s(read_attribute(model, time, "current_time"))) + delta_t
+	unset_attribute(model, time, "current_time")
+	instantiate_attribute(model, time, "current_time", new_time)
+
+	return !
+
+Float function v2f(i : Element):
+	return cast_s2f(cast_v2s(i))!
+
+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 (v2f(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 (v2f(m[f][j]) == 0.0):
+						// Also zero, so continue
+						f = f + 1
+					else:
+						// Found non-zero, so swap row
+						t = v2f(m[f])
+						dict_overwrite(m, f, v2f(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 = v2f(m[i][j])
+		while (f < read_nr_out(m[i])):
+			dict_overwrite(m[i], f, float_division(v2f(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 = v2f(m[f][j])
+				while (g < read_nr_out(m[f])):
+					dict_overwrite(m[f], g, v2f(m[f][g]) - (divisor * v2f(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_v2s(m[i][j])
+			result = result + ", "
+			j = j + 1
+		i = i + 1
+		result = result + "\n"
+	return result!

+ 49 - 0
models/cbd_spring.mvc

@@ -0,0 +1,49 @@
+ConstantBlock cte_k {
+    value = 1
+}
+
+ConstantBlock cte_g {
+    value = 10
+}
+
+ConstantBlock cte_m {
+    value = 1
+}
+
+ConstantBlock cte_v0 {
+    value = 1
+}
+
+ConstantBlock cte_y0 {
+    value = 20
+}
+
+MultiplicationBlock m0 {}
+MultiplicationBlock m1 {}
+MultiplicationBlock m2 {}
+NegationBlock n0 {}
+InverseBlock i0 {}
+AdditionBlock a0 {}
+IntegratorBlock int0 {}
+IntegratorBlock int1 {}
+
+Probe pv {
+    name = "velocity"
+}
+Probe py {
+    name = "displacement"
+}
+
+Link (cte_k, m0) {}
+Link (int1, m0) {}
+Link (cte_g, m1) {}
+Link (cte_m, m1) {}
+Link (cte_m, i0) {}
+Link (m0, a0) {}
+Link (n0, a0) {}
+Link (i0, m2) {}
+Link (a0, m2) {}
+Link (m2, int0) {}
+Link (int0, int1) {}
+InitialCondition (cte_v0, int0) {}
+InitialCondition (cte_y0, int1) {}

+ 59 - 0
models/cbd_toRuntime.alc

@@ -0,0 +1,59 @@
+include "primitives.alh"
+include "modelling.alh"
+include "object_operations.alh"
+
+String function map_D2P(model : Element, name : String):
+	return readAssociationDestination(model, set_pop(allAssociationDestinations(model, name, "D2P_block")))!
+
+Boolean function main(model : Element):
+	Element all_blocks
+	String element_name
+	String new_element_name
+	String mm_type_name
+
+	all_blocks = allInstances(model, "Design/Block")
+	while (set_len(all_blocks) > 0):
+		element_name = set_pop(all_blocks)
+		mm_type_name = "PartialRuntime/" + cast_string(list_read(string_split(read_type(model, element_name), "/"), 1))
+
+		if (set_len(allOutgoingAssociationInstances(model, element_name, "D2P_block")) == 0):
+			// New design element, so create in partial runtime model as well
+			new_element_name = instantiate_node(model, mm_type_name, "")
+			instantiate_edge(model, "D2P_block", element_name, new_element_name)
+
+		// Always update the value of attributes of PartialRuntime
+		new_element_name = set_pop(readAssociationDestination(model, set_pop(allOutgoingAssociationInstances(model, element_name, "D2P_block"))))
+		if (mm_type_name == "PartialRuntime/ConstantBlock"):
+            instantiate_attribute(model, new_element_name, "value", read_attribute(model, element_name, "value"))
+		elif (mm_type_name == "PartialRuntime/ProbeBlock"):
+            instantiate_attribute(model, new_element_name, "name", read_attribute(model, element_name, "name"))
+
+	all_blocks = allInstances(model, "PartialRuntime/Block")
+	while (set_len(all_blocks) > 0):
+		element_name = set_pop(all_blocks)
+		if (set_len(allIncomingAssociationInstances(model, element_name, "D2P_block")) == 0):
+			// Old partial runtime element, so remove
+			model_delete(model, element_name)
+
+	// Delete all existing links
+	all_links = allInstances(model, "PartialRuntime/Link")
+	while (set_len(all_links) > 0):
+		model_delete_element(model, set_pop(all_links))
+
+	all_links = allInstances(model, "PartialRuntime/InitialCondition")
+	while (set_len(all_links) > 0):
+		model_delete_element(model, set_pop(all_links))
+
+	// Recreate all of them
+    all_links = allInstances(model, "Design/Link")
+    while (read_nr_out(all_links) > 0):
+        element_name = set_pop(all_links)
+        instantiate_link(model, "PartialRuntime/Link", "", map_D2P(model, readAssociationSource(model, element_name)), map_D2P(model, readAssociationDestination(model, element_name)))
+
+    all_links = allInstances(model, "Design/InitialCondition")
+    while (read_nr_out(all_links) > 0):
+        element_name = set_pop(all_links)
+        instantiate_link(model, "PartialRuntime/InitialCondition", "", map_D2P(model, readAssociationSource(model, element_name)), map_D2P(model, readAssociationDestination(model, element_name)))
+
+
+	return True!