diff --git a/DySMo/src/Definitions.py b/DySMo/src/Definitions.py index 650d9df..f6d9b8e 100644 --- a/DySMo/src/Definitions.py +++ b/DySMo/src/Definitions.py @@ -22,11 +22,12 @@ from enum import Enum + class Color(Enum): - BLACK = 1; - BLUE = 2; - CYAN = 3; - GREEN = 4; - MAGENTA = 5; - RED = 6; - YELLOW = 7; + BLACK = 1 + BLUE = 2 + CYAN = 3 + GREEN = 4 + MAGENTA = 5 + RED = 6 + YELLOW = 7 diff --git a/DySMo/src/DySMo.py b/DySMo/src/DySMo.py index 929ac25..e1e516c 100644 --- a/DySMo/src/DySMo.py +++ b/DySMo/src/DySMo.py @@ -20,63 +20,65 @@ along with this program. If not, see . """ -#Lib -import os; -import sys; -import PySimLib; -#Local -from Definitions import *; -from exceptions.ModeException import ModeException; -from Mode import Mode; -from Plots import *; -from Transition import Transition; -from VSM import VSM; +# Lib +import os +import sys +import PySimLib +# Local +from Definitions import * +from exceptions.ModeException import ModeException +from Mode import Mode +from Plots import * +from Transition import Transition +from VSM import VSM - -#Functions +# Functions def ExecPythonFile(fileName): - file = open(fileName); - content = file.read(); - code = compile(content, fileName, 'exec'); - exec(code); - -#Functions for config script + file = open(fileName) + content = file.read() + code = compile(content, fileName, 'exec') + exec(code) + +# Functions for config script + + def Solver(name): - return PySimLib.FindSolver(name); - -func = VSM.simulate; - -#Checks + return PySimLib.FindSolver(name) + + +func = VSM.simulate + +# Checks if(len(sys.argv) == 1): - print("Please provide a path to a variable-structure simulatiom description file as argument."); - print("Exiting..."); - exit(); - + print("Please provide a path to a variable-structure simulatiom description file as argument.") + print("Exiting...") + exit() + if(len(sys.argv) == 3): - if(sys.argv[2] == "clean"): - func = VSM.clean; - else: - print("You specified the following unknown argument:", sys.argv[2]); - print("Exiting..."); - exit(); + if(sys.argv[2] == "clean"): + func = VSM.clean + else: + print("You specified the following unknown argument:", sys.argv[2]) + print("Exiting...") + exit() -#paths -configPath = os.path.abspath(sys.argv[1]); +# paths +configPath = os.path.abspath(sys.argv[1]) -#instantiate model -model = VSM(configPath); #The global model instance +# instantiate model +model = VSM(configPath) # The global model instance -#execute config file -ExecPythonFile(sys.argv[1]); +# execute config file +ExecPythonFile(sys.argv[1]) -#run simulation -os.chdir(model.getPath()); #switch to model path +# run simulation +os.chdir(model.getPath()) # switch to model path try: - func(model); + func(model) except ModeException as e: - print("ERROR: ", e); - print("See Log file for details."); - -model.shutdown(); + print("ERROR: ", e) + print("See Log file for details.") + +model.shutdown() diff --git a/DySMo/src/Mode.py b/DySMo/src/Mode.py index cb5be1e..82c6903 100644 --- a/DySMo/src/Mode.py +++ b/DySMo/src/Mode.py @@ -20,200 +20,200 @@ along with this program. If not, see . """ -#Lib -import os; -import PySimLib; -import time; +# Lib +import os +import PySimLib +import time + class Mode: - #Constructor - def __init__(this): - #Private members - this.__vsmModel = None; - this.__id = None; - this.__mdlObj = None; #the PySimLib model object - this.__lastSimNum = None; - this.__simObjs = {}; #dict containing all simulation objects for this mode - - #Public members - this.files = []; - this.modeRef = None; #Identifier of the mode - this.solver = None; #Solver settings for this mode - this.synonym = {}; - this.tool = None; #PySimLib tool object for simulating this mode - this.transitions = []; #Transitions that lead out of this mode - - #Magic methods - def __str__(this): - return "Mode " + str(this.__id); - - #Public methods - #Called by the framework when this mode should compile itself. - #Note that this is called only once when the mode gets used the first time. - # - #Args: None - # - #Returns: Nothing - def compile(this): - print("Compiling mode", this.get_id(), "..."); - - this.tool.Compile(this.__mdlObj); - - #Finds the transition object based on the transition id in the end values of this mode. - # - #Args: None - # - #Returns: Outgoing transition object - def find_transition(this): - transId = int(this.get_endValue("transitionId")); - - if(transId > len(this.transitions)): - from exceptions.InvalidTransitionException import InvalidTransitionException; - raise InvalidTransitionException(this, transId); - - return this.transitions[transId-1]; - - def get_endValue(this, varName): - return this.__mdlObj.variables[varName].final; - - #Args: None - # - #Returns: The id of this mode - def get_id(this): - return this.__id; - - def get_model(this): - return this.__vsmModel; - - def get_parameter(this, key): - return this.__mdlObj.parameters[key]; - - def has_endValue(this, varName): - return varName in this.__mdlObj.variables; - - #Initializes this mode. - #Initializes all transition objects in this mode. - # - #Args: - # model - The model that this mode attaches to - # modeId - Id of this mode - # - #Returns: Nothing - def init(this, model, modeId): - from exceptions.InvalidModeModelException import InvalidModeModelException; - - this.__vsmModel = model; - this.__id = modeId; - - if(this.solver is None): - this.solver = model.default_solver; - - #acquire PySimLib model object - if(this.modeRef is None): - raise InvalidModeModelException(this); - - this.__mdlObj = PySimLib.Model(this.modeRef, this.files); - - if(this.__mdlObj is None): - raise InvalidModeModelException(this); - - #set settings on model object - this.__mdlObj.outputName = 'm' + str(this.get_id()); - this.__mdlObj.outputDir = model.getPath() + os.sep + "output"; - this.__mdlObj.resultDir = model.getPath() + os.sep + "result"; - this.__mdlObj.simDir = model.getPath(); - - #check tool - if(not (this.tool is None)): - this.tool = PySimLib.FindTool(this.tool); - if(this.tool is None): - print("The desired tool for mode " + str(this.__id) + " is not available."); - - if(this.tool is None): #we dont have a tool - if(not(this.__vsmModel.default_tool is None)): #try the default tool - if(this.__vsmModel.default_tool.Accepts(this.__mdlObj)): #if is compatible - this.tool = this.__vsmModel.default_tool; #silent using, as the user specified the default_tool - else: #last try to get some compatible tool - compatibleTools = this.__mdlObj.GetCompatibleTools(); - - if(compatibleTools): #there is at least one simulator - this.tool = compatibleTools[0]; - print("Choosing tool '" + str(this.tool) + "' for mode " + str(this.__id) + "."); #inform which one we use - else: - print("No simulator is available for mode " + str(this.__id) + ". Exiting..."); - exit(1); - - #init transitions - transId = 1; - for t in this.transitions: - t.init(transId); - transId += 1; - - def read_init(this): - from exceptions.MissingTransitionIdException import MissingTransitionIdException; - - this.tool.ReadInit(this.__mdlObj); - - if(not('transitionId' in this.__mdlObj.variables)): - raise MissingTransitionIdException(this); - - #Args: None - # - #Returns: The simulation result of the last simulation on this mode. - def read_last_result(this): - return this.read_result(this.__lastSimNum); - - #Reads and loads a simulation result, based on a simulation number, that this mode produced. - #The result has to be of type SimulationResult or a subclass of it. - # - #Args: - # simNum - Simulation number - # - #Returns: SimulationResult object - def read_result(this, simNum): - return this.tool.ReadResult(this.__simObjs[simNum]); - - def set_initialValue(this, varName, value): - this.__mdlObj.variables[varName].start = value; - - def set_parameter(this, name, value): - this.__mdlObj.parameters[name] = value; - - def set_parameters(this, params): - for key in params: - this.set_parameter(key, params[key]); - - #Simulates the mode and moves the result file to the result folder. - # - #Args: None - # - #Returns: Nothing - def simulate(this): - simObj = PySimLib.Simulation(this.__mdlObj, this.__vsmModel.getCurrentSimulationNumber()); - - simObj.startTime = this.__vsmModel.currentTime; - simObj.stopTime = this.__vsmModel.stopTime; - - print("Running simulation", simObj.GetSimNumber(), "ModeID:", this.get_id(), "Time:", this.__vsmModel.currentTime); - t1 = time.clock(); - this.tool.Simulate(simObj); - t2 = time.clock(); - - - string = "Simulation " + str(simObj.GetSimNumber()) + " of mode " + str(this.get_id()) + " took " + str(t2 - t1) + " seconds"; - PySimLib.Log.Line(string); - - this.__lastSimNum = simObj.GetSimNumber(); - this.__simObjs[this.__lastSimNum] = simObj; - - return t2 - t1; - - #Sets initial values in this mode. - # - #Args: - # inits - Dictionary of (String, Double) that contains variables and their initial values - # - #Returns: Nothing - def write_init(this, inits): - for key in inits: - this.__mdlObj.variables[key].start = inits[key]; + # Constructor + def __init__(this): + # Private members + this.__vsmModel = None + this.__id = None + this.__mdlObj = None # the PySimLib model object + this.__lastSimNum = None + this.__simObjs = {} # dict containing all simulation objects for this mode + + # Public members + this.files = [] + this.modeRef = None # Identifier of the mode + this.solver = None # Solver settings for this mode + this.synonym = {} + this.tool = None # PySimLib tool object for simulating this mode + this.transitions = [] # Transitions that lead out of this mode + + # Magic methods + def __str__(this): + return "Mode " + str(this.__id) + + # Public methods + # Called by the framework when this mode should compile itself. + # Note that this is called only once when the mode gets used the first time. + # + # Args: None + # + # Returns: Nothing + def compile(this): + print("Compiling mode", this.get_id(), "...") + + this.tool.Compile(this.__mdlObj) + + # Finds the transition object based on the transition id in the end values of this mode. + # + # Args: None + # + # Returns: Outgoing transition object + def find_transition(this): + transId = int(this.get_endValue("transitionId")) + + if(transId > len(this.transitions)): + from exceptions.InvalidTransitionException import InvalidTransitionException + raise InvalidTransitionException(this, transId) + + return this.transitions[transId - 1] + + def get_endValue(this, varName): + return this.__mdlObj.variables[varName].final + + # Args: None + # + # Returns: The id of this mode + def get_id(this): + return this.__id + + def get_model(this): + return this.__vsmModel + + def get_parameter(this, key): + return this.__mdlObj.parameters[key] + + def has_endValue(this, varName): + return varName in this.__mdlObj.variables + + # Initializes this mode. + # Initializes all transition objects in this mode. + # + # Args: + # model - The model that this mode attaches to + # modeId - Id of this mode + # + # Returns: Nothing + def init(this, model, modeId): + from exceptions.InvalidModeModelException import InvalidModeModelException + + this.__vsmModel = model + this.__id = modeId + + if(this.solver is None): + this.solver = model.default_solver + + # acquire PySimLib model object + if(this.modeRef is None): + raise InvalidModeModelException(this) + + this.__mdlObj = PySimLib.Model(this.modeRef, this.files) + + if(this.__mdlObj is None): + raise InvalidModeModelException(this) + + # set settings on model object + this.__mdlObj.outputName = 'm' + str(this.get_id()) + this.__mdlObj.outputDir = model.getPath() + os.sep + "output" + this.__mdlObj.resultDir = model.getPath() + os.sep + "result" + this.__mdlObj.simDir = model.getPath() + + # check tool + if(not (this.tool is None)): + this.tool = PySimLib.FindTool(this.tool) + if(this.tool is None): + print("The desired tool for mode " + str(this.__id) + " is not available.") + + if(this.tool is None): # we dont have a tool + if(not(this.__vsmModel.default_tool is None)): # try the default tool + if(this.__vsmModel.default_tool.Accepts(this.__mdlObj)): # if is compatible + this.tool = this.__vsmModel.default_tool # silent using, as the user specified the default_tool + else: # last try to get some compatible tool + compatibleTools = this.__mdlObj.GetCompatibleTools() + + if(compatibleTools): # there is at least one simulator + this.tool = compatibleTools[0] + print("Choosing tool '" + str(this.tool) + "' for mode " + str(this.__id) + ".") # inform which one we use + else: + print("No simulator is available for mode " + str(this.__id) + ". Exiting...") + exit(1) + + # init transitions + transId = 1 + for t in this.transitions: + t.init(transId) + transId += 1 + + def read_init(this): + from exceptions.MissingTransitionIdException import MissingTransitionIdException + + this.tool.ReadInit(this.__mdlObj) + + if(not('transitionId' in this.__mdlObj.variables)): + raise MissingTransitionIdException(this) + + # Args: None + # + # Returns: The simulation result of the last simulation on this mode. + def read_last_result(this): + return this.read_result(this.__lastSimNum) + + # Reads and loads a simulation result, based on a simulation number, that this mode produced. + # The result has to be of type SimulationResult or a subclass of it. + # + # Args: + # simNum - Simulation number + # + # Returns: SimulationResult object + def read_result(this, simNum): + return this.tool.ReadResult(this.__simObjs[simNum]) + + def set_initialValue(this, varName, value): + this.__mdlObj.variables[varName].start = value + + def set_parameter(this, name, value): + this.__mdlObj.parameters[name] = value + + def set_parameters(this, params): + for key in params: + this.set_parameter(key, params[key]) + + # Simulates the mode and moves the result file to the result folder. + # + # Args: None + # + # Returns: Nothing + def simulate(this): + simObj = PySimLib.Simulation(this.__mdlObj, this.__vsmModel.getCurrentSimulationNumber()) + + simObj.startTime = this.__vsmModel.currentTime + simObj.stopTime = this.__vsmModel.stopTime + + print("Running simulation", simObj.GetSimNumber(), "ModeID:", this.get_id(), "Time:", this.__vsmModel.currentTime) + t1 = time.clock() + this.tool.Simulate(simObj) + t2 = time.clock() + + string = "Simulation " + str(simObj.GetSimNumber()) + " of mode " + str(this.get_id()) + " took " + str(t2 - t1) + " seconds" + PySimLib.Log.Line(string) + + this.__lastSimNum = simObj.GetSimNumber() + this.__simObjs[this.__lastSimNum] = simObj + + return t2 - t1 + + # Sets initial values in this mode. + # + # Args: + # inits - Dictionary of (String, Double) that contains variables and their initial values + # + # Returns: Nothing + def write_init(this, inits): + for key in inits: + this.__mdlObj.variables[key].start = inits[key] diff --git a/DySMo/src/Plot.py b/DySMo/src/Plot.py index 341ee69..addbf34 100644 --- a/DySMo/src/Plot.py +++ b/DySMo/src/Plot.py @@ -20,37 +20,38 @@ along with this program. If not, see . """ -from Definitions import *; +from Definitions import * + class Plot: - #Constructor - def __init__(this): - this.drawGrid = True; - this.labelXAxis = ""; - this.labelYAxis = ""; - this.xAxisVar = 'time'; - - #Public methods - def colorToColorString(this, color): - if(color == Color.BLACK): - return 'k'; - if(color == Color.BLUE): - return 'b'; - if(color == Color.CYAN): - return 'c'; - if(color == Color.GREEN): - return 'g'; - if(color == Color.MAGENTA): - return 'm'; - if(color == Color.RED): - return 'r'; - #if(color == Color.WHITE): - #return 'w'; - if(color == Color.YELLOW): - return 'y'; - - raise Exception("illegal color"); - - #Abstract methods - def getColor(this, modeId, simId, varName): - raise NotImplementedError("Method 'getColor' of Class 'Plot' is abstract."); + # Constructor + def __init__(this): + this.drawGrid = True + this.labelXAxis = "" + this.labelYAxis = "" + this.xAxisVar = 'time' + + # Public methods + def colorToColorString(this, color): + if(color == Color.BLACK): + return 'k' + if(color == Color.BLUE): + return 'b' + if(color == Color.CYAN): + return 'c' + if(color == Color.GREEN): + return 'g' + if(color == Color.MAGENTA): + return 'm' + if(color == Color.RED): + return 'r' + # if(color == Color.WHITE): + # return 'w'; + if(color == Color.YELLOW): + return 'y' + + raise Exception("illegal color") + + # Abstract methods + def getColor(this, modeId, simId, varName): + raise NotImplementedError("Method 'getColor' of Class 'Plot' is abstract.") diff --git a/DySMo/src/Plots.py b/DySMo/src/Plots.py index d207b9b..dd64aca 100644 --- a/DySMo/src/Plots.py +++ b/DySMo/src/Plots.py @@ -20,5 +20,5 @@ along with this program. If not, see . """ -from plots.ModePlot import ModePlot; -from plots.VariablePlot import VariablePlot; +from plots.ModePlot import ModePlot +from plots.VariablePlot import VariablePlot diff --git a/DySMo/src/Transition.py b/DySMo/src/Transition.py index a800e5d..d0f1729 100644 --- a/DySMo/src/Transition.py +++ b/DySMo/src/Transition.py @@ -20,32 +20,33 @@ along with this program. If not, see . """ + class Transition: - #Constructor - def __init__(this): - this.__id = None; - - #Public methods - def get_id(this): - return this.__id; - - def init(this, id): - this.__id = id; - - def mapping(this, oldMode, newMode): - valuesToSet = {}; - mapping = this.mapping; - - for key in mapping: - if(key == "*" and mapping[key] == "*"): - this.__mapStar(oldMode, newMode, valuesToSet); - continue; - - if(not oldMode.has_endValue(mapping[key])): - from exceptions.IllegalMappingException import IllegalMappingException; - - raise IllegalMappingException(oldMode, key, this, mapping[key]); - - valuesToSet[key] = oldMode.get_endValue(mapping[key]); - - return valuesToSet; + # Constructor + def __init__(this): + this.__id = None + + # Public methods + def get_id(this): + return this.__id + + def init(this, id): + this.__id = id + + def mapping(this, oldMode, newMode): + valuesToSet = {} + mapping = this.mapping + + for key in mapping: + if(key == "*" and mapping[key] == "*"): + this.__mapStar(oldMode, newMode, valuesToSet) + continue + + if(not oldMode.has_endValue(mapping[key])): + from exceptions.IllegalMappingException import IllegalMappingException + + raise IllegalMappingException(oldMode, key, this, mapping[key]) + + valuesToSet[key] = oldMode.get_endValue(mapping[key]) + + return valuesToSet diff --git a/DySMo/src/VSM.py b/DySMo/src/VSM.py index 685e7e6..52565e5 100644 --- a/DySMo/src/VSM.py +++ b/DySMo/src/VSM.py @@ -20,334 +20,335 @@ along with this program. If not, see . """ -#Lib -import os; -import pylab; -import PySimLib; -import shutil; -import time; +# Lib +import os +import pylab +import PySimLib +import shutil +import time + class VSM: - #Constructor - def __init__(this, configPath): - #Private members - this.__path = os.path.abspath(os.path.join(configPath, os.pardir)); - this.__logPath = configPath + ".log"; - this.__logFile = open(this.__logPath, "w"); - this.__actMode = None; #current mode - this.__compiledModes = {}; - this.__currentNum = 1; #sim counter - this.__observer = {}; - - #Public members - this.currentTime = 0; - this.default_solver = None; - this.default_tool = None; - this.init = {}; - this.modes = []; - this.observe = []; - this.plots = []; - this.startTime = 0; - this.stopTime = 1; - this.translate = True; - - #Init log file - PySimLib.Log.SetTarget(this.__logFile); - - #Private methods - def __compileMode(this, mode): - if(mode not in this.__compiledModes): - if(this.translate): - t1 = time.clock(); - mode.compile(); - PySimLib.Log.Line("Compilation of mode " + str(mode.get_id()) + " took " + str(time.clock() - t1) + " seconds."); - this.__compiledModes[mode] = True; - mode.read_init(); - - def __deleteFileSafe(this, folder): - #check whether the sub directory already exists - if(os.path.exists(folder)): - #delete all files in resultFolder and create an empty folder - os.remove(folder); - - def __deleteFolderSafe(this, folder): - #check whether the sub directory already exists - if(os.path.exists(folder)): - #delete all files in resultFolder and create an empty folder - shutil.rmtree(folder); - - def __drawPlots(this): - show = False; - for p in this.plots: - figure = pylab.figure(); #new plot - for var in this.observe: - for i in range(0, len(this.__observer[var])): - col = p.getColor(this.__observer["modeID"][i], i, var); - if((col is not None) and (this.__observer[var][i])): - #print(this.__observer[var][i]); - #print(var, len(this.__observer[var]), len(this.__observer["time"][i])); - #print(this.__observer['y']); - pylab.plot(this.__observer[p.xAxisVar][i], this.__observer[var][i], p.colorToColorString(col)); - pylab.grid(p.drawGrid); - pylab.xlabel(p.labelXAxis); - pylab.ylabel(p.labelYAxis); - if(hasattr(p, 'fileName')): - pylab.savefig(this.__path + os.sep + "result" + os.sep + p.fileName); - if((not hasattr(p, 'fileName')) or hasattr(p, 'show')): - show = True; - else: - pylab.close(figure); - - if(show): - pylab.show(); - - def __getOutputPath(this): - return this.__path + os.sep + "output"; - - def __getResultPath(this): - return this.__path + os.sep + "result"; - - def __init(this): - #Init observer - for k in this.observe: - this.__observer[k] = []; - this.__observer["time"] = []; - this.__observer["modeID"] = []; - - #check default_tool - if(not(this.default_tool is None)): - name = this.default_tool; - this.default_tool = PySimLib.FindTool(name); - if(this.default_tool is None): - print("The specified default tool '" + name + "' is not available."); - - def __observe(this, simResults): - for k in this.observe: - synonym = None; - if(k in this.__actMode.synonym): - synonym = this.__actMode.synonym[k]; - else: - if(not(this.__actMode.synonym) and (k in simResults)): #direct mapping if no synonyms are given - synonym = k; - - if(synonym is None): - this.__observer[k].append([]); - else: - this.__observer[k].append(simResults[synonym]); - - this.__observer["time"].append(simResults["time"]); - this.__observer["modeID"].append(this.__actMode.get_id()); - - def __prepareFolders(this): - resultPath = this.__getResultPath(); - - this.__deleteFolderSafe(resultPath); - time.sleep(1); #ugly... but somehow os.makedirs fails sometimes with permission error when there is not enough time between shutil.rmtree and os.makedirs - os.makedirs(resultPath); - - #make sure output dir exists - outputPath = this.__getOutputPath(); - if not(os.path.exists(outputPath)): - os.makedirs(outputPath); - - def __preprocess(this): - from exceptions.NoModeException import NoModeException; - - if(not(this.modes)): - raise NoModeException(); - - #Numerate modes - modeId = 1; - for m in this.modes: - m.init(this, modeId); - modeId += 1; - - #TODO - #Run initial mode - this.__actMode = this.modes[0]; - this.__compileMode(this.__actMode); - this.__actMode.write_init(this.init); - - def __save_observer(this): - from PySimLib.Mat.Mat import Mat; - from PySimLib.Mat.OutputStream import OutputStream; - - nan = float("NaN"); - variables = ["time", "modeID"] + this.observe; - lastVariable = variables[len(variables)-1]; - - #get for every simulation the maximum number of datapoints - nDataPointsPerSim = []; - for p in this.__observer["modeID"]: #init all sims with datapoints-length of 1 - nDataPointsPerSim.append(1); - - for key in variables: - if(key == "modeID"): - continue; #unimportant - - for i in range(0, len(nDataPointsPerSim)): - if(len(this.__observer[key][i]) > nDataPointsPerSim[i]): - nDataPointsPerSim[i] = len(this.__observer[key][i]); - nDataPointsSum = 0; - for n in nDataPointsPerSim: - nDataPointsSum += n; - - #write mat - mat = Mat(); - - #names matrix - names = mat.AddTextMatrix("names", len(this.__observer)); - i = 0; - for key in variables: - names.SetString(i, key); - i += 1; - - #values matrix - values = mat.AddMatrix("values", len(this.__observer), nDataPointsSum); - x = 0; - for key in variables: - i = 0; - y = 0; - if(key == "modeID"): #modeID is special... - for p in this.__observer[key]: - for j in range(0, nDataPointsPerSim[i]): - values.SetValue(x, y, p); - y += 1; - i += 1; - else: - for points in this.__observer[key]: - for p in points: - values.SetValue(x, y, p); - y += 1; - for j in range(len(points), nDataPointsPerSim[i]): - values.SetValue(x, y, nan); - y += 1; - i += 1; - x += 1; - - file = open("result" + os.sep + "observer_data.mat", "wb"); - stream = OutputStream(file); - mat.Write(stream); - file.close(); - - #write csv - file = open("result" + os.sep + "observer_data.csv", "w"); - - #var names - for key in variables: - file.write(key); - if(key != lastVariable): - file.write(";"); - file.write("\n"); - - #var values - y = 0; - while(y < nDataPointsSum): - x = 0; - for key in variables: - p = values.GetValue(x, y); - x += 1; - file.write(str(p)); - if(key != lastVariable): - file.write(";"); - file.write("\n"); - y += 1; - file.close(); - - def __transitionActive(this, transition): - from Transition import Transition; - - oldMode = this.__actMode; - this.set_active_mode(transition.post); - this.__compileMode(this.__actMode); - - mappedValues = Transition.mapping(transition, oldMode, this.__actMode); #direct call to class function because the dicts name is also "mapping" - this.__actMode.write_init(mappedValues); - - if(hasattr(transition, "init_function")): - transition.init_function(this.__actMode, oldMode); - - #Public methods - def clean(this): - this.shutdown(); - - this.__deleteFileSafe(this.__logPath); - this.__deleteFolderSafe(this.__getOutputPath()); - this.__deleteFolderSafe(this.__getResultPath()); - - def getCurrentSimulationNumber(this): - return this.__currentNum; - - def getPath(this): - return this.__path; - - def set_active_mode(this, newMode): - this.__actMode = newMode; - - def shutdown(this): - PySimLib.Log.SetTarget(None); - if(not(this.__logFile is None)): - this.__logFile.close(); - - def simulate(this): - simTime = 0; - readTime = 0; - - this.__init(); - this.__prepareFolders(); - this.__preprocess(); - - this.currentTime = this.startTime; - - while(this.currentTime < this.stopTime): - #Run sim - simTime += this.__actMode.simulate(); - t1 = time.clock(); - result = this.__actMode.read_last_result(); - t2 = time.clock(); - dt = t2 - t1; - readTime += dt; - - #process results - this.__observe(result.GetValues()); - - observTime = this.__observer["time"]; - observTime = observTime[len(observTime)-1]; - lastTimeValue = observTime[len(observTime)-1]; - - if(lastTimeValue < this.currentTime): - raise SimulationRanBackwardsException(); - - this.currentTime = lastTimeValue; - string = "Simulation "+ str(this.__currentNum) + " ended at "+ str(this.currentTime) - PySimLib.Log.Line(string+"\n===================================\n\n\n") - print(string); - - if(this.currentTime >= this.stopTime): - print("Simulation done"); - break; - - #find a transition - transition = this.__actMode.find_transition(); - if transition is None: - print("Error, no transition found for mode ", this.__actMode.id); - return; - this.__transitionActive(transition); - - this.__currentNum += 1; #next sim - - PySimLib.Log.Line(""); - PySimLib.Log.Line("Overall timing info"); - PySimLib.Log.Line("Reading simulation results: " + str(readTime) + " seconds."); - PySimLib.Log.Line("Simulation time: " + str(simTime) + " seconds"); - PySimLib.Log.Line("Total: " + str(readTime + simTime) + " seconds"); - #TODO compile time - - this.__save_observer(); - this.__drawPlots(); - - #close tools - for m in this.modes: - m.tool.Close(); - if(not this.default_tool is None): - this.default_tool.Close(); + # Constructor + def __init__(this, configPath): + # Private members + this.__path = os.path.abspath(os.path.join(configPath, os.pardir)) + this.__logPath = configPath + ".log" + this.__logFile = open(this.__logPath, "w") + this.__actMode = None # current mode + this.__compiledModes = {} + this.__currentNum = 1 # sim counter + this.__observer = {} + + # Public members + this.currentTime = 0 + this.default_solver = None + this.default_tool = None + this.init = {} + this.modes = [] + this.observe = [] + this.plots = [] + this.startTime = 0 + this.stopTime = 1 + this.translate = True + + # Init log file + PySimLib.Log.SetTarget(this.__logFile) + + # Private methods + def __compileMode(this, mode): + if(mode not in this.__compiledModes): + if(this.translate): + t1 = time.clock() + mode.compile() + PySimLib.Log.Line("Compilation of mode " + str(mode.get_id()) + " took " + str(time.clock() - t1) + " seconds.") + this.__compiledModes[mode] = True + mode.read_init() + + def __deleteFileSafe(this, folder): + # check whether the sub directory already exists + if(os.path.exists(folder)): + # delete all files in resultFolder and create an empty folder + os.remove(folder) + + def __deleteFolderSafe(this, folder): + # check whether the sub directory already exists + if(os.path.exists(folder)): + # delete all files in resultFolder and create an empty folder + shutil.rmtree(folder) + + def __drawPlots(this): + show = False + for p in this.plots: + figure = pylab.figure() # new plot + for var in this.observe: + for i in range(0, len(this.__observer[var])): + col = p.getColor(this.__observer["modeID"][i], i, var) + if((col is not None) and (this.__observer[var][i])): + # print(this.__observer[var][i]); + #print(var, len(this.__observer[var]), len(this.__observer["time"][i])); + # print(this.__observer['y']); + pylab.plot(this.__observer[p.xAxisVar][i], this.__observer[var][i], p.colorToColorString(col)) + pylab.grid(p.drawGrid) + pylab.xlabel(p.labelXAxis) + pylab.ylabel(p.labelYAxis) + if(hasattr(p, 'fileName')): + pylab.savefig(this.__path + os.sep + "result" + os.sep + p.fileName) + if((not hasattr(p, 'fileName')) or hasattr(p, 'show')): + show = True + else: + pylab.close(figure) + + if(show): + pylab.show() + + def __getOutputPath(this): + return this.__path + os.sep + "output" + + def __getResultPath(this): + return this.__path + os.sep + "result" + + def __init(this): + # Init observer + for k in this.observe: + this.__observer[k] = [] + this.__observer["time"] = [] + this.__observer["modeID"] = [] + + # check default_tool + if(not(this.default_tool is None)): + name = this.default_tool + this.default_tool = PySimLib.FindTool(name) + if(this.default_tool is None): + print("The specified default tool '" + name + "' is not available.") + + def __observe(this, simResults): + for k in this.observe: + synonym = None + if(k in this.__actMode.synonym): + synonym = this.__actMode.synonym[k] + else: + if(not(this.__actMode.synonym) and (k in simResults)): # direct mapping if no synonyms are given + synonym = k + + if(synonym is None): + this.__observer[k].append([]) + else: + this.__observer[k].append(simResults[synonym]) + + this.__observer["time"].append(simResults["time"]) + this.__observer["modeID"].append(this.__actMode.get_id()) + + def __prepareFolders(this): + resultPath = this.__getResultPath() + + this.__deleteFolderSafe(resultPath) + time.sleep(1) # ugly... but somehow os.makedirs fails sometimes with permission error when there is not enough time between shutil.rmtree and os.makedirs + os.makedirs(resultPath) + + # make sure output dir exists + outputPath = this.__getOutputPath() + if not(os.path.exists(outputPath)): + os.makedirs(outputPath) + + def __preprocess(this): + from exceptions.NoModeException import NoModeException + + if(not(this.modes)): + raise NoModeException() + + # Numerate modes + modeId = 1 + for m in this.modes: + m.init(this, modeId) + modeId += 1 + + # TODO + # Run initial mode + this.__actMode = this.modes[0] + this.__compileMode(this.__actMode) + this.__actMode.write_init(this.init) + + def __save_observer(this): + from PySimLib.Mat.Mat import Mat + from PySimLib.Mat.OutputStream import OutputStream + + nan = float("NaN") + variables = ["time", "modeID"] + this.observe + lastVariable = variables[len(variables) - 1] + + # get for every simulation the maximum number of datapoints + nDataPointsPerSim = [] + for p in this.__observer["modeID"]: # init all sims with datapoints-length of 1 + nDataPointsPerSim.append(1) + + for key in variables: + if(key == "modeID"): + continue # unimportant + + for i in range(0, len(nDataPointsPerSim)): + if(len(this.__observer[key][i]) > nDataPointsPerSim[i]): + nDataPointsPerSim[i] = len(this.__observer[key][i]) + nDataPointsSum = 0 + for n in nDataPointsPerSim: + nDataPointsSum += n + + # write mat + mat = Mat() + + # names matrix + names = mat.AddTextMatrix("names", len(this.__observer)) + i = 0 + for key in variables: + names.SetString(i, key) + i += 1 + + # values matrix + values = mat.AddMatrix("values", len(this.__observer), nDataPointsSum) + x = 0 + for key in variables: + i = 0 + y = 0 + if(key == "modeID"): # modeID is special... + for p in this.__observer[key]: + for j in range(0, nDataPointsPerSim[i]): + values.SetValue(x, y, p) + y += 1 + i += 1 + else: + for points in this.__observer[key]: + for p in points: + values.SetValue(x, y, p) + y += 1 + for j in range(len(points), nDataPointsPerSim[i]): + values.SetValue(x, y, nan) + y += 1 + i += 1 + x += 1 + + file = open("result" + os.sep + "observer_data.mat", "wb") + stream = OutputStream(file) + mat.Write(stream) + file.close() + + # write csv + file = open("result" + os.sep + "observer_data.csv", "w") + + # var names + for key in variables: + file.write(key) + if(key != lastVariable): + file.write(";") + file.write("\n") + + # var values + y = 0 + while(y < nDataPointsSum): + x = 0 + for key in variables: + p = values.GetValue(x, y) + x += 1 + file.write(str(p)) + if(key != lastVariable): + file.write(";") + file.write("\n") + y += 1 + file.close() + + def __transitionActive(this, transition): + from Transition import Transition + + oldMode = this.__actMode + this.set_active_mode(transition.post) + this.__compileMode(this.__actMode) + + mappedValues = Transition.mapping(transition, oldMode, this.__actMode) # direct call to class function because the dicts name is also "mapping" + this.__actMode.write_init(mappedValues) + + if(hasattr(transition, "init_function")): + transition.init_function(this.__actMode, oldMode) + + # Public methods + def clean(this): + this.shutdown() + + this.__deleteFileSafe(this.__logPath) + this.__deleteFolderSafe(this.__getOutputPath()) + this.__deleteFolderSafe(this.__getResultPath()) + + def getCurrentSimulationNumber(this): + return this.__currentNum + + def getPath(this): + return this.__path + + def set_active_mode(this, newMode): + this.__actMode = newMode + + def shutdown(this): + PySimLib.Log.SetTarget(None) + if(not(this.__logFile is None)): + this.__logFile.close() + + def simulate(this): + simTime = 0 + readTime = 0 + + this.__init() + this.__prepareFolders() + this.__preprocess() + + this.currentTime = this.startTime + + while(this.currentTime < this.stopTime): + # Run sim + simTime += this.__actMode.simulate() + t1 = time.clock() + result = this.__actMode.read_last_result() + t2 = time.clock() + dt = t2 - t1 + readTime += dt + + # process results + this.__observe(result.GetValues()) + + observTime = this.__observer["time"] + observTime = observTime[len(observTime) - 1] + lastTimeValue = observTime[len(observTime) - 1] + + if(lastTimeValue < this.currentTime): + raise SimulationRanBackwardsException() + + this.currentTime = lastTimeValue + string = "Simulation " + str(this.__currentNum) + " ended at " + str(this.currentTime) + PySimLib.Log.Line(string + "\n===================================\n\n\n") + print(string) + + if(this.currentTime >= this.stopTime): + print("Simulation done") + break + + # find a transition + transition = this.__actMode.find_transition() + if transition is None: + print("Error, no transition found for mode ", this.__actMode.id) + return + this.__transitionActive(transition) + + this.__currentNum += 1 # next sim + + PySimLib.Log.Line("") + PySimLib.Log.Line("Overall timing info") + PySimLib.Log.Line("Reading simulation results: " + str(readTime) + " seconds.") + PySimLib.Log.Line("Simulation time: " + str(simTime) + " seconds") + PySimLib.Log.Line("Total: " + str(readTime + simTime) + " seconds") + # TODO compile time + + this.__save_observer() + this.__drawPlots() + + # close tools + for m in this.modes: + m.tool.Close() + if(not this.default_tool is None): + this.default_tool.Close() diff --git a/DySMo/src/exceptions/IllegalMappingException.py b/DySMo/src/exceptions/IllegalMappingException.py index 35c2365..27b1a1a 100644 --- a/DySMo/src/exceptions/IllegalMappingException.py +++ b/DySMo/src/exceptions/IllegalMappingException.py @@ -20,18 +20,19 @@ along with this program. If not, see . """ -from exceptions.ModeException import ModeException; +from exceptions.ModeException import ModeException + class IllegalMappingException(ModeException): - #Constructor - def __init__(this, fromMode, fromVar, transition, toVar): - ModeException.__init__(this); - - this.__fromMode = fromMode; - this.__fromVar = fromVar; - this.__transition = transition; - this.__toVar = toVar; - - #Magic methods - def __str__(this): - return "Illegal mapping (" + this.__fromVar + " : " + this.__toVar + ") in transition " + str(this.__transition.get_id()) + " from Mode " + str(this.__fromMode.get_id()); + # Constructor + def __init__(this, fromMode, fromVar, transition, toVar): + ModeException.__init__(this) + + this.__fromMode = fromMode + this.__fromVar = fromVar + this.__transition = transition + this.__toVar = toVar + + # Magic methods + def __str__(this): + return "Illegal mapping (" + this.__fromVar + " : " + this.__toVar + ") in transition " + str(this.__transition.get_id()) + " from Mode " + str(this.__fromMode.get_id()) diff --git a/DySMo/src/exceptions/InvalidModeModelException.py b/DySMo/src/exceptions/InvalidModeModelException.py index cc95546..b51a3ca 100644 --- a/DySMo/src/exceptions/InvalidModeModelException.py +++ b/DySMo/src/exceptions/InvalidModeModelException.py @@ -20,15 +20,16 @@ along with this program. If not, see . """ -from exceptions.ModeException import ModeException; +from exceptions.ModeException import ModeException + class InvalidModeModelException(ModeException): - #Constructor - def __init__(this, mode): - ModeException.__init__(this); - - this.__mode = mode; - - #Magic methods - def __str__(this): - return "The model format of " + str(this.__mode) + " can't be determined. Please check if the 'modeRef' and 'files' attributes are set correctly."; + # Constructor + def __init__(this, mode): + ModeException.__init__(this) + + this.__mode = mode + + # Magic methods + def __str__(this): + return "The model format of " + str(this.__mode) + " can't be determined. Please check if the 'modeRef' and 'files' attributes are set correctly." diff --git a/DySMo/src/exceptions/InvalidTransitionException.py b/DySMo/src/exceptions/InvalidTransitionException.py index a30a409..daf3560 100644 --- a/DySMo/src/exceptions/InvalidTransitionException.py +++ b/DySMo/src/exceptions/InvalidTransitionException.py @@ -20,16 +20,17 @@ along with this program. If not, see . """ -from exceptions.ModeException import ModeException; +from exceptions.ModeException import ModeException + class InvalidTransitionException(ModeException): - #Constructor - def __init__(this, mode, transId): - ModeException.__init__(this); - - this.__mode = mode; - this.__transId = transId; - - #Magic methods - def __str__(this): - return str(this.__mode) + " tried to activate transition " + str(this.__transId) + " but does not contain it."; + # Constructor + def __init__(this, mode, transId): + ModeException.__init__(this) + + this.__mode = mode + this.__transId = transId + + # Magic methods + def __str__(this): + return str(this.__mode) + " tried to activate transition " + str(this.__transId) + " but does not contain it." diff --git a/DySMo/src/exceptions/MissingTransitionIdException.py b/DySMo/src/exceptions/MissingTransitionIdException.py index 466d503..9833df1 100644 --- a/DySMo/src/exceptions/MissingTransitionIdException.py +++ b/DySMo/src/exceptions/MissingTransitionIdException.py @@ -20,15 +20,16 @@ along with this program. If not, see . """ -from exceptions.ModeException import ModeException; +from exceptions.ModeException import ModeException + class MissingTransitionIdException(ModeException): - #Constructor - def __init__(this, mode): - ModeException.__init__(this); - - this.__mode = mode; - - #Magic methods - def __str__(this): - return str(this.__mode) + " does not contain the neccessary 'transitionId' variable. Please include it in the model."; + # Constructor + def __init__(this, mode): + ModeException.__init__(this) + + this.__mode = mode + + # Magic methods + def __str__(this): + return str(this.__mode) + " does not contain the neccessary 'transitionId' variable. Please include it in the model." diff --git a/DySMo/src/exceptions/ModeException.py b/DySMo/src/exceptions/ModeException.py index b6908aa..df1b9c2 100644 --- a/DySMo/src/exceptions/ModeException.py +++ b/DySMo/src/exceptions/ModeException.py @@ -20,5 +20,6 @@ along with this program. If not, see . """ + class ModeException(Exception): - pass + pass diff --git a/DySMo/src/exceptions/NoModeException.py b/DySMo/src/exceptions/NoModeException.py index 164a01b..2cd01cb 100644 --- a/DySMo/src/exceptions/NoModeException.py +++ b/DySMo/src/exceptions/NoModeException.py @@ -20,13 +20,14 @@ along with this program. If not, see . """ -from exceptions.ModeException import ModeException; +from exceptions.ModeException import ModeException + class NoModeException(ModeException): - #Constructor - def __init__(this): - ModeException.__init__(this); - - #Magic methods - def __str__(this): - return "The variable structure model has no modes. Did you set 'model.modes'?"; + # Constructor + def __init__(this): + ModeException.__init__(this) + + # Magic methods + def __str__(this): + return "The variable structure model has no modes. Did you set 'model.modes'?" diff --git a/DySMo/src/plots/ModePlot.py b/DySMo/src/plots/ModePlot.py index 15b6f52..5fc50ff 100644 --- a/DySMo/src/plots/ModePlot.py +++ b/DySMo/src/plots/ModePlot.py @@ -20,28 +20,29 @@ along with this program. If not, see . """ -from Definitions import *; -from Plot import Plot; +from Definitions import * +from Plot import Plot + class ModePlot(Plot): - #Constructor - def __init__(this): - Plot.__init__(this); - - this.__counter = 0; - this.__vars = {}; - - #Private methods - def getVarCounter(this, varName): - if(varName not in this.__vars): - this.__vars[varName] = this.__counter; - this.__counter -= 1; - - return this.__vars[varName]; - - #Public methods - def getColor(this, modeId, simId, varName): - colId = ((this.getVarCounter(varName)+ modeId - 1) % 7)+1; - if(varName in this.vars): - return Color(colId); - return None; + # Constructor + def __init__(this): + Plot.__init__(this) + + this.__counter = 0 + this.__vars = {} + + # Private methods + def getVarCounter(this, varName): + if(varName not in this.__vars): + this.__vars[varName] = this.__counter + this.__counter -= 1 + + return this.__vars[varName] + + # Public methods + def getColor(this, modeId, simId, varName): + colId = ((this.getVarCounter(varName) + modeId - 1) % 7) + 1 + if(varName in this.vars): + return Color(colId) + return None diff --git a/DySMo/src/plots/VariablePlot.py b/DySMo/src/plots/VariablePlot.py index 6296416..1fd8c5b 100644 --- a/DySMo/src/plots/VariablePlot.py +++ b/DySMo/src/plots/VariablePlot.py @@ -20,15 +20,16 @@ along with this program. If not, see . """ -from Plot import Plot; +from Plot import Plot + class VariablePlot(Plot): - #Constructor - def __init__(this): - Plot.__init__(this); - - #Public methods - def getColor(this, modeId, simId, varName): - if(varName in this.vars): - return this.vars[varName]; - return None; + # Constructor + def __init__(this): + Plot.__init__(this) + + # Public methods + def getColor(this, modeId, simId, varName): + if(varName in this.vars): + return this.vars[varName] + return None diff --git a/samples/ballSimple/config.py b/samples/ballSimple/config.py index bc772df..d4166a6 100644 --- a/samples/ballSimple/config.py +++ b/samples/ballSimple/config.py @@ -1,53 +1,56 @@ -#Model -model.default_solver = Solver("dassl"); +# Model +model.default_solver = Solver("dassl") #model.default_tool = "Dymola"; -model.translate = True; # compile models -model.init = {}; -model.startTime = 0; -model.stopTime = 30; -model.observe = ['v', 'h']; +model.translate = True # compile models +model.init = {} +model.startTime = 0 +model.stopTime = 30 +model.observe = ['v', 'h'] -#First mode -mode1 = Mode(); +# First mode +mode1 = Mode() #mode1.tool = "OpenModelica"; -mode1.modeRef = "Ball.FlyingBall"; -mode1.files = ["Ball.mo"]; -mode1.synonym = {'v' : 'v', 'h' : 'h'}; +mode1.modeRef = "Ball.FlyingBall" +mode1.files = ["Ball.mo"] +mode1.synonym = {'v': 'v', 'h': 'h'} + +# Transition from mode 1 to mode 1 + -#Transition from mode 1 to mode 1 def bounce(actMode, oldMode): - v = oldMode.get_endValue('v'); - actMode.set_initialValue('v', v * (-1)); - -#Transition from mode 1 to mode 2 -trans1_2 = Transition(); -trans1_2.post = mode1; -trans1_2.mapping = {'h' : 'h'}; -trans1_2.init_function = bounce; - - -mode1.transitions = [trans1_2]; - -#Set the modes -model.modes = [mode1]; - -plot1 = ModePlot(); -plot1.vars = ['h']; -plot1.drawGrid = 1; -plot1.labelXAxis = "time"; -plot1.labelYAxis = "v"; -plot1.fileName = 'v.png'; -plot1.show = True; - -plot2 = VariablePlot(); -plot2.vars = {'v' : Color.MAGENTA}; -plot2.xAxisVar = 'time'; -plot2.drawGrid = 1; #0 = no, 1 = yes -plot2.labelXAxis = "x"; -plot2.labelYAxis = "y"; -plot2.fileName = "xy.png"; -plot2.show = True; - -#Set the plots -model.plots = [plot1, plot2]; + v = oldMode.get_endValue('v') + actMode.set_initialValue('v', v * (-1)) + + +# Transition from mode 1 to mode 2 +trans1_2 = Transition() +trans1_2.post = mode1 +trans1_2.mapping = {'h': 'h'} +trans1_2.init_function = bounce + + +mode1.transitions = [trans1_2] + +# Set the modes +model.modes = [mode1] + +plot1 = ModePlot() +plot1.vars = ['h'] +plot1.drawGrid = 1 +plot1.labelXAxis = "time" +plot1.labelYAxis = "v" +plot1.fileName = 'v.png' +plot1.show = True + +plot2 = VariablePlot() +plot2.vars = {'v': Color.MAGENTA} +plot2.xAxisVar = 'time' +plot2.drawGrid = 1 # 0 = no, 1 = yes +plot2.labelXAxis = "x" +plot2.labelYAxis = "y" +plot2.fileName = "xy.png" +plot2.show = True + +# Set the plots +model.plots = [plot1, plot2] diff --git a/samples/bouncingBall/config.py b/samples/bouncingBall/config.py index 652d788..79197b9 100644 --- a/samples/bouncingBall/config.py +++ b/samples/bouncingBall/config.py @@ -1,57 +1,57 @@ -#Model -model.default_solver = Solver("dassl"); -model.translate = True; -model.init = {}; -model.startTime = 0; -model.stopTime = 10; -model.observe = ['v', 'h']; - -#First mode -mode1 = Mode(); - -mode1.modeRef = "BouncingBall.Ball_struc"; -mode1.files = ["BouncingBall.mo"]; -mode1.synonym = {'v' : 'v', 'h' : 'h'}; - -#Second mode -mode2 = Mode(); - -mode2.modeRef = "BouncingBall.Contact_struc"; -mode2.files = ["BouncingBall.mo"]; -mode2.synonym = {'v' : 'v', 'h' : 'h'}; - -#Transition from mode 1 to mode 2 -trans1_2 = Transition(); -trans1_2.post = mode2; -trans1_2.mapping = { 'damper.v_rel':'v', 'damper.s_rel':'h'}; - -trans2_1 = Transition(); -trans2_1.post = mode1; -trans2_1.mapping = {'v':'damper.v_rel' , 'h':'damper.s_rel'}; - -mode1.transitions = [trans1_2]; -mode2.transitions = [trans2_1]; - -#Set the modes -model.modes = [mode1, mode2]; - - -plot1 = ModePlot(); -plot1.vars = ['h']; -plot1.drawGrid = 1; -plot1.labelXAxis = "time"; -plot1.labelYAxis = "v"; -plot1.fileName = 'v.png'; -plot1.show = True; - -plot2 = VariablePlot(); -plot2.vars = {'v' : Color.MAGENTA}; -plot2.xAxisVar = 'time'; -plot2.drawGrid = 1; #0 = no, 1 = yes -plot2.labelXAxis = "x"; -plot2.labelYAxis = "y"; -plot2.fileName = "xy.png"; -plot2.show = True; - -#Set the plots -model.plots = [plot1, plot2]; +# Model +model.default_solver = Solver("dassl") +model.translate = True +model.init = {} +model.startTime = 0 +model.stopTime = 10 +model.observe = ['v', 'h'] + +# First mode +mode1 = Mode() + +mode1.modeRef = "BouncingBall.Ball_struc" +mode1.files = ["BouncingBall.mo"] +mode1.synonym = {'v': 'v', 'h': 'h'} + +# Second mode +mode2 = Mode() + +mode2.modeRef = "BouncingBall.Contact_struc" +mode2.files = ["BouncingBall.mo"] +mode2.synonym = {'v': 'v', 'h': 'h'} + +# Transition from mode 1 to mode 2 +trans1_2 = Transition() +trans1_2.post = mode2 +trans1_2.mapping = {'damper.v_rel': 'v', 'damper.s_rel': 'h'} + +trans2_1 = Transition() +trans2_1.post = mode1 +trans2_1.mapping = {'v': 'damper.v_rel', 'h': 'damper.s_rel'} + +mode1.transitions = [trans1_2] +mode2.transitions = [trans2_1] + +# Set the modes +model.modes = [mode1, mode2] + + +plot1 = ModePlot() +plot1.vars = ['h'] +plot1.drawGrid = 1 +plot1.labelXAxis = "time" +plot1.labelYAxis = "v" +plot1.fileName = 'v.png' +plot1.show = True + +plot2 = VariablePlot() +plot2.vars = {'v': Color.MAGENTA} +plot2.xAxisVar = 'time' +plot2.drawGrid = 1 # 0 = no, 1 = yes +plot2.labelXAxis = "x" +plot2.labelYAxis = "y" +plot2.fileName = "xy.png" +plot2.show = True + +# Set the plots +model.plots = [plot1, plot2] diff --git a/samples/bouncingWall/config.py b/samples/bouncingWall/config.py index d1d48d4..6e1a5b5 100644 --- a/samples/bouncingWall/config.py +++ b/samples/bouncingWall/config.py @@ -1,73 +1,73 @@ -#Model -model.default_solver = Solver("dassl"); -model.translate = True; -model.init = {}; -model.startTime = 0; -model.stopTime = 5; -model.observe = ['x', 'h']; +# Model +model.default_solver = Solver("dassl") +model.translate = True +model.init = {} +model.startTime = 0 +model.stopTime = 5 +model.observe = ['x', 'h'] -#First mode -mode1 = Mode(); +# First mode +mode1 = Mode() -mode1.modeRef = "bounceWall.Ball_struc"; -mode1.files = ["bounceWall.mo"]; -mode1.synonym = {'x' : 'x', 'h' : 'h'}; +mode1.modeRef = "bounceWall.Ball_struc" +mode1.files = ["bounceWall.mo"] +mode1.synonym = {'x': 'x', 'h': 'h'} -mode2 = Mode(); +mode2 = Mode() -mode2.modeRef = "bounceWall.Contact_struc"; -mode2.files = ["bounceWall.mo"]; -mode2.synonym = {'x':'x','h': 'damper.s_rel'}; +mode2.modeRef = "bounceWall.Contact_struc" +mode2.files = ["bounceWall.mo"] +mode2.synonym = {'x': 'x', 'h': 'damper.s_rel'} -mode3 = Mode(); -mode3.modeRef = "bounceWall.Contact_wall"; -mode3.files = ["bounceWall.mo"]; -mode3.synonym = {'x':'x', 'h':'h'}; +mode3 = Mode() +mode3.modeRef = "bounceWall.Contact_wall" +mode3.files = ["bounceWall.mo"] +mode3.synonym = {'x': 'x', 'h': 'h'} -#Transition from mode 1 to mode 2 -trans1_2 = Transition(); -trans1_2.post = mode2; -trans1_2.mapping = {'x': 'x', 'damper.s_rel':'h', 'vx':'vx', 'damper.v_rel':'vy'}; +# Transition from mode 1 to mode 2 +trans1_2 = Transition() +trans1_2.post = mode2 +trans1_2.mapping = {'x': 'x', 'damper.s_rel': 'h', 'vx': 'vx', 'damper.v_rel': 'vy'} -#Transition from mode 1 to mode 3 -trans1_3 = Transition(); -trans1_3.post = mode3; -trans1_3.mapping = {'damper.s_rel':'x', 'h':'h', 'damper.v_rel':'vx', 'v':'vy'}; +# Transition from mode 1 to mode 3 +trans1_3 = Transition() +trans1_3.post = mode3 +trans1_3.mapping = {'damper.s_rel': 'x', 'h': 'h', 'damper.v_rel': 'vx', 'v': 'vy'} -#Transition from mode 2 to mode 1 -trans2_1 = Transition(); -trans2_1.post = mode1; -trans2_1.mapping = {'h':'damper.s_rel', 'x':'x', 'vx':'vx', 'vy':'damper.v_rel'}; +# Transition from mode 2 to mode 1 +trans2_1 = Transition() +trans2_1.post = mode1 +trans2_1.mapping = {'h': 'damper.s_rel', 'x': 'x', 'vx': 'vx', 'vy': 'damper.v_rel'} -#Transition from mode 3 to mode 1 -trans3_1 = Transition(); -trans3_1.post = mode1; -trans3_1.mapping = {'x':'damper.s_rel', 'vx':'damper.v_rel', 'h':'h', 'vy':'v'}; +# Transition from mode 3 to mode 1 +trans3_1 = Transition() +trans3_1.post = mode1 +trans3_1.mapping = {'x': 'damper.s_rel', 'vx': 'damper.v_rel', 'h': 'h', 'vy': 'v'} -mode1.transitions = [trans1_2, trans1_3]; -mode2.transitions = [trans2_1]; -mode3.transitions = [trans3_1]; -#Set the modes -model.modes = [mode1, mode2, mode3]; +mode1.transitions = [trans1_2, trans1_3] +mode2.transitions = [trans2_1] +mode3.transitions = [trans3_1] +# Set the modes +model.modes = [mode1, mode2, mode3] -plot1 = ModePlot(); -plot1.vars = ['h']; -plot1.drawGrid = 1; -plot1.labelXAxis = "time"; -plot1.labelYAxis = "h"; -plot1.fileName = 'h.png'; -plot1.show = True; +plot1 = ModePlot() +plot1.vars = ['h'] +plot1.drawGrid = 1 +plot1.labelXAxis = "time" +plot1.labelYAxis = "h" +plot1.fileName = 'h.png' +plot1.show = True -plot2 = VariablePlot(); -plot2.vars = {'x' : Color.MAGENTA}; -plot2.xAxisVar = 'time'; -plot2.drawGrid = 1; #0 = no, 1 = yes -plot2.labelXAxis = "x"; -plot2.labelYAxis = "y"; -plot2.fileName = 'xy.png'; -plot2.show = True; +plot2 = VariablePlot() +plot2.vars = {'x': Color.MAGENTA} +plot2.xAxisVar = 'time' +plot2.drawGrid = 1 # 0 = no, 1 = yes +plot2.labelXAxis = "x" +plot2.labelYAxis = "y" +plot2.fileName = 'xy.png' +plot2.show = True -#Set the plots -model.plots = [plot1, plot2]; +# Set the plots +model.plots = [plot1, plot2] diff --git a/samples/domino/config.py b/samples/domino/config.py index 98d8872..a186936 100644 --- a/samples/domino/config.py +++ b/samples/domino/config.py @@ -1,107 +1,110 @@ # Dominostein trifft anderen Stein def crash(act, old): - import math - active = int(old.get_parameter('active') +1) - fallen= int(old.get_parameter('fallen')) - - D_val = old.get_parameter('D') - Z_val = old.get_parameter('stones[1].Z') - - phipush = math.asin(D_val/Z_val); - KO = (1+math.cos(2*phipush))/2; - KR = 1 -math.cos(phipush); - - o = [] - p = [] - for i in range(1,active): - omega = old.get_endValue('stones['+str(i)+'].omega') - phi = old.get_endValue('stones['+str(i)+'].phi') - p.append(phi) - if i == active-1: - o.append(omega*KR) - else: - o.append(omega) - - act.set_parameters({'active':active,'fallen':fallen}); - act.compile() - act.read_init() - - for i in range(1,active): - act.set_initialValue('stones['+str(i)+'].omega', o[i-1]); - act.set_initialValue('stones['+str(i)+'].phi', p[i-1]); - act.set_initialValue('stones['+str(active)+'].omega', o[-1]*KO/KR); - act.set_initialValue('stones['+str(active)+'].phi', 0); - + import math + active = int(old.get_parameter('active') + 1) + fallen = int(old.get_parameter('fallen')) + + D_val = old.get_parameter('D') + Z_val = old.get_parameter('stones[1].Z') + + phipush = math.asin(D_val / Z_val) + KO = (1 + math.cos(2 * phipush)) / 2 + KR = 1 - math.cos(phipush) + + o = [] + p = [] + for i in range(1, active): + omega = old.get_endValue('stones[' + str(i) + '].omega') + phi = old.get_endValue('stones[' + str(i) + '].phi') + p.append(phi) + if i == active - 1: + o.append(omega * KR) + else: + o.append(omega) + + act.set_parameters({'active': active, 'fallen': fallen}) + act.compile() + act.read_init() + + for i in range(1, active): + act.set_initialValue('stones[' + str(i) + '].omega', o[i - 1]) + act.set_initialValue('stones[' + str(i) + '].phi', p[i - 1]) + act.set_initialValue('stones[' + str(active) + '].omega', o[-1] * KO / KR) + act.set_initialValue('stones[' + str(active) + '].phi', 0) + # Dominostein gefallen + + def fall(act, old): - active = int(old.get_endValue('active'))-1 - fallen = int(old.get_endValue('fallen')+1) - - o = [] - p = [] - for i in range(2,active+2): - omega = old.get_endValue('stones['+str(i)+'].omega') - phi = old.get_endValue('stones['+str(i)+'].phi') - o.append(omega) - p.append(phi) - - act.set_parameters({'active':active,'fallen':fallen}); - act.compile() - act.read_init() - - for i in range(1,active+1): - act.set_initialValue('stones['+str(i)+'].omega', o[i-1]); - act.set_initialValue('stones['+str(i)+'].phi', p[i-1]); - - -# Ende der Simulation + active = int(old.get_endValue('active')) - 1 + fallen = int(old.get_endValue('fallen') + 1) + + o = [] + p = [] + for i in range(2, active + 2): + omega = old.get_endValue('stones[' + str(i) + '].omega') + phi = old.get_endValue('stones[' + str(i) + '].phi') + o.append(omega) + p.append(phi) + + act.set_parameters({'active': active, 'fallen': fallen}) + act.compile() + act.read_init() + + for i in range(1, active + 1): + act.set_initialValue('stones[' + str(i) + '].omega', o[i - 1]) + act.set_initialValue('stones[' + str(i) + '].phi', p[i - 1]) + + +# Ende der Simulation def end(act, old): - t = old.get_endValue('time') - act.get_model().stopTime = t + t = old.get_endValue('time') + act.get_model().stopTime = t + -model.translate = True; -model.default_solver = Solver("dassl") # Solver -model.init = {'stones[1].omega': 0.1} # Init -model.stopTime = 5 # Stopzeit -model.startTime = 0 # Startzeit -model.observe = ['stones[1].phi','stones[2].phi','stones[1].omega'] +model.translate = True +model.default_solver = Solver("dassl") # Solver +model.init = {'stones[1].omega': 0.1} # Init +model.stopTime = 5 # Stopzeit +model.startTime = 0 # Startzeit +model.observe = ['stones[1].phi', 'stones[2].phi', 'stones[1].omega'] mode = Mode() -mode.tool = 'Dymola'; #need to be able to set structural parameters -mode.files = ['domino.mo'] # Modelica Dateien -mode.modeRef = "domino.stones" # Modelica-Model -mode.synonym={'stones[1].phi':'stones[1].phi', 'stones[1].omega':'stones[1].omega'} +mode.tool = 'Dymola' # need to be able to set structural parameters +mode.files = ['domino.mo'] # Modelica Dateien +mode.modeRef = "domino.stones" # Modelica-Model +mode.synonym = {'stones[1].phi': 'stones[1].phi', 'stones[1].omega': 'stones[1].omega'} # Stein getroffen -trans1 = Transition() -trans1.post = mode #Wechsel zu sich selbst -trans1.init_function = crash # Funktionsaufruf -trans1.mapping = {}; # Kein Mapping +trans1 = Transition() +trans1.post = mode # Wechsel zu sich selbst +trans1.init_function = crash # Funktionsaufruf +trans1.mapping = {} # Kein Mapping # Stein gefallen trans2 = Transition() -trans2.post = mode #Wechsel zu sich selbst -trans2.init_function = fall # Funktionsaufruf -trans2.mapping = {}; # Kein Mapping +trans2.post = mode # Wechsel zu sich selbst +trans2.init_function = fall # Funktionsaufruf +trans2.mapping = {} # Kein Mapping # Simulationsende trans3 = Transition() -trans3.post = mode #Wechsel zu sich selbst -trans3.init_function = end # Funktionsaufruf -trans3.mapping = {}; # Kein Mapping +trans3.post = mode # Wechsel zu sich selbst +trans3.init_function = end # Funktionsaufruf +trans3.mapping = {} # Kein Mapping -mode.transitions = [trans1, trans2, trans3] +mode.transitions = [trans1, trans2, trans3] model.modes = [mode] -#Create plots -plot1 = VariablePlot(); -plot1.vars = {'stones[1].phi' : Color.MAGENTA}; -plot1.drawGrid = 1; #0 = no, 1 = yes -plot1.labelXAxis = "x-axis"; -plot1.labelYAxis = "y-axis"; -plot1.fileName = 'variableplot.png'; -plot1.show = True; - -#Set the plots -model.plots = [plot1]; +# Create plots +plot1 = VariablePlot() +plot1.vars = {'stones[1].phi': Color.MAGENTA} +plot1.drawGrid = 1 # 0 = no, 1 = yes +plot1.labelXAxis = "x-axis" +plot1.labelYAxis = "y-axis" +plot1.fileName = 'variableplot.png' +plot1.show = True + +# Set the plots +model.plots = [plot1] diff --git a/samples/nailpendulum/config.py b/samples/nailpendulum/config.py index 7590c84..f19702b 100644 --- a/samples/nailpendulum/config.py +++ b/samples/nailpendulum/config.py @@ -1,57 +1,57 @@ -#Model -model.default_solver = Solver("dassl"); -model.default_solver.tolerance = 3e-05; -model.translate = True; -model.init = {}; -model.startTime = 0; -model.stopTime = 8; -model.observe = ['x', 'y']; - -#First mode -mode1 = Mode(); -mode1.modeRef = "NailPendulum.pendulum_struc"; -mode1.files = ["NailPendulum.mo"]; -mode1.synonym = {'x' : 'x', 'y' : 'y'}; - -#Second mode -mode2 = Mode(); -mode2.modeRef = "NailPendulum.ball_struc"; -mode2.files = ["NailPendulum.mo"]; -mode2.synonym = {'x' : 'x', 'y' : 'y'}; - -#Transition from first mode to first mode -trans1_1 = Transition(); -trans1_1.post = mode1; -trans1_1.mapping = {'phi' : 'phi', 'dphi' : 'dphi', 'long' : 'long'}; - -#Transition from first mode to second mode -trans1_2 = Transition(); -trans1_2.post = mode2; -trans1_2.mapping = {'x' : 'x', 'y' : 'y', 'vx' : 'der(x)', 'vy' : 'der(y)', 'L' : 'L', 'n.x' : 'n.x', 'n.y' : 'n.y', 'long' : 'long'}; - -#Set transitions for first mode -mode1.transitions = [trans1_1, trans1_2]; - -#Transition from second mode to first mode -trans2_1 = Transition(); -trans2_1.post = mode1; -trans2_1.mapping = {'phi' : 'phi1', 'dphi' : 'der(phi)', 'long' : 'long'}; - -#Set transitions for second mode -mode2.transitions = [trans2_1]; - -#Set modes -model.modes = [mode1, mode2]; - -#Create Plots -plot1 = ModePlot(); -plot1.vars = {'y'}; -plot1.xAxisVar = 'x'; -plot1.drawGrid = 1; -plot1.labelXAxis = "x"; -plot1.labelYAxis = "y"; -plot1.fileName = 'pendulum.png'; -plot1.show = True; - -#Set Plots -model.plots = [plot1]; +# Model +model.default_solver = Solver("dassl") +model.default_solver.tolerance = 3e-05 +model.translate = True +model.init = {} +model.startTime = 0 +model.stopTime = 8 +model.observe = ['x', 'y'] + +# First mode +mode1 = Mode() +mode1.modeRef = "NailPendulum.pendulum_struc" +mode1.files = ["NailPendulum.mo"] +mode1.synonym = {'x': 'x', 'y': 'y'} + +# Second mode +mode2 = Mode() +mode2.modeRef = "NailPendulum.ball_struc" +mode2.files = ["NailPendulum.mo"] +mode2.synonym = {'x': 'x', 'y': 'y'} + +# Transition from first mode to first mode +trans1_1 = Transition() +trans1_1.post = mode1 +trans1_1.mapping = {'phi': 'phi', 'dphi': 'dphi', 'long': 'long'} + +# Transition from first mode to second mode +trans1_2 = Transition() +trans1_2.post = mode2 +trans1_2.mapping = {'x': 'x', 'y': 'y', 'vx': 'der(x)', 'vy': 'der(y)', 'L': 'L', 'n.x': 'n.x', 'n.y': 'n.y', 'long': 'long'} + +# Set transitions for first mode +mode1.transitions = [trans1_1, trans1_2] + +# Transition from second mode to first mode +trans2_1 = Transition() +trans2_1.post = mode1 +trans2_1.mapping = {'phi': 'phi1', 'dphi': 'der(phi)', 'long': 'long'} + +# Set transitions for second mode +mode2.transitions = [trans2_1] + +# Set modes +model.modes = [mode1, mode2] + +# Create Plots +plot1 = ModePlot() +plot1.vars = {'y'} +plot1.xAxisVar = 'x' +plot1.drawGrid = 1 +plot1.labelXAxis = "x" +plot1.labelYAxis = "y" +plot1.fileName = 'pendulum.png' +plot1.show = True + +# Set Plots +model.plots = [plot1] diff --git a/samples/pendel/config.py b/samples/pendel/config.py index b0db2cd..d8aebf5 100644 --- a/samples/pendel/config.py +++ b/samples/pendel/config.py @@ -1,66 +1,69 @@ -#Model -model.default_solver = Solver("dassl"); -model.default_solver.tolerance = 1e-4; -model.translate = True; -model.init = {}; -model.startTime = 0; -model.stopTime = 10; -model.observe = ['x', 'y']; +# Model +model.default_solver = Solver("dassl") +model.default_solver.tolerance = 1e-4 +model.translate = True +model.init = {} +model.startTime = 0 +model.stopTime = 10 +model.observe = ['x', 'y'] -#First mode -mode1 = Mode(); -mode1.modeRef = "pendulum.Pendulum_struc"; -mode1.files = ["pendulum.mo"]; -mode1.synonym = {'x' : 'x', 'y' : 'y'}; +# First mode +mode1 = Mode() +mode1.modeRef = "pendulum.Pendulum_struc" +mode1.files = ["pendulum.mo"] +mode1.synonym = {'x': 'x', 'y': 'y'} -#Second mode -mode2 = Mode(); -mode2.modeRef = "pendulum.Ball_struc"; -mode2.files = ["pendulum.mo"]; -mode2.synonym = {'x' : 'x', 'y' : 'y'}; +# Second mode +mode2 = Mode() +mode2.modeRef = "pendulum.Ball_struc" +mode2.files = ["pendulum.mo"] +mode2.synonym = {'x': 'x', 'y': 'y'} + +# Transition from mode 1 to mode 2 +trans1_2 = Transition() +trans1_2.post = mode2 +trans1_2.mapping = {'x': 'x', 'y': 'y', 'vx': 'der(x)', 'vy': 'der(y)'} + +# Transition from mode 2 to mode 1 -#Transition from mode 1 to mode 2 -trans1_2 = Transition(); -trans1_2.post = mode2; -trans1_2.mapping = {'x' : 'x', 'y' : 'y', 'vx': 'der(x)' , 'vy':'der(y)'}; -#Transition from mode 2 to mode 1 def speed(actMode, oldMode): - actMode.set_initialValue('dphi', 0.0); + actMode.set_initialValue('dphi', 0.0) + -trans2_1 = Transition(); -trans2_1.post = mode1; -trans2_1.mapping = {'x' : 'x', 'phi' : 'phi'}; -trans2_1.init_function = speed; +trans2_1 = Transition() +trans2_1.post = mode1 +trans2_1.mapping = {'x': 'x', 'phi': 'phi'} +trans2_1.init_function = speed -mode1.transitions = [trans1_2]; -mode2.transitions = [trans2_1]; +mode1.transitions = [trans1_2] +mode2.transitions = [trans2_1] -#Set the modes -model.modes = [mode1, mode2]; +# Set the modes +model.modes = [mode1, mode2] -#Create plots -plot1 = VariablePlot(); -plot1.vars = {'x' : Color.MAGENTA, 'y' : Color.BLACK}; -plot1.drawGrid = 1; #0 = no, 1 = yes -plot1.labelXAxis = "x-axis"; -plot1.labelYAxis = "y-axis"; -plot1.fileName = 'variableplot.png'; +# Create plots +plot1 = VariablePlot() +plot1.vars = {'x': Color.MAGENTA, 'y': Color.BLACK} +plot1.drawGrid = 1 # 0 = no, 1 = yes +plot1.labelXAxis = "x-axis" +plot1.labelYAxis = "y-axis" +plot1.fileName = 'variableplot.png' -plot2 = ModePlot(); -plot2.vars = ['x', 'y']; -plot2.drawGrid = 1; -plot2.labelXAxis = "asd"; -plot2.labelYAxis = "2314"; -plot2.fileName = 'modeplot.png'; -plot2.show = True; +plot2 = ModePlot() +plot2.vars = ['x', 'y'] +plot2.drawGrid = 1 +plot2.labelXAxis = "asd" +plot2.labelYAxis = "2314" +plot2.fileName = 'modeplot.png' +plot2.show = True -plot3 = VariablePlot(); -plot3.vars = {'y' : Color.MAGENTA}; -plot3.xAxisVar = 'x'; -plot3.drawGrid = 1; #0 = no, 1 = yes -plot3.labelXAxis = "x"; -plot3.labelYAxis = "y"; +plot3 = VariablePlot() +plot3.vars = {'y': Color.MAGENTA} +plot3.xAxisVar = 'x' +plot3.drawGrid = 1 # 0 = no, 1 = yes +plot3.labelXAxis = "x" +plot3.labelYAxis = "y" -#Set the plots -model.plots = [plot1, plot2, plot3]; +# Set the plots +model.plots = [plot1, plot2, plot3] diff --git a/samples/pendulumModelicaSimulink/run.py b/samples/pendulumModelicaSimulink/run.py index 101ea73..fb863c2 100644 --- a/samples/pendulumModelicaSimulink/run.py +++ b/samples/pendulumModelicaSimulink/run.py @@ -1,45 +1,45 @@ -model.stopTime = 10; -model.observe = ['x', 'y']; - -#simulink mode -mode1 = Mode(); -mode1.modeRef = "pendel"; -mode1.files = ['pendel.mdl']; - -#modelica mode -mode2 = Mode(); -mode2.modeRef = "PendelScript.ball_struc"; -mode2.files = ['PendelScript.mo']; - -#Transition from mode 1 to mode 2 -trans1_2 = Transition(); -trans1_2.post = mode2; -trans1_2.mapping = {'x' : 'x', 'y' : 'y', 'vx' : 'dx' , 'vy' : 'dy'}; - -#Transition from mode 2 to mode 1 -trans2_1 = Transition(); -trans2_1.post = mode1; -trans2_1.mapping = {'start_phi' : 'phi', 'start_dphi' : 'der(phi)'}; - -#Set transitions -mode1.transitions = [trans1_2]; -mode2.transitions = [trans2_1]; - -#Set the modes -model.modes = [mode1, mode2]; - - -#Create plots -plot1 = ModePlot(); -plot1.vars = ['y']; -plot1.xAxisVar = 'x'; -plot1.fileName = 'position.png'; -plot1.show = True; - -plot2 = ModePlot(); -plot2.vars = ['y']; -plot2.fileName = 'y.png'; -plot2.show = True; - -#Set the plots -model.plots = [plot1, plot2]; +model.stopTime = 10 +model.observe = ['x', 'y'] + +# simulink mode +mode1 = Mode() +mode1.modeRef = "pendel" +mode1.files = ['pendel.mdl'] + +# modelica mode +mode2 = Mode() +mode2.modeRef = "PendelScript.ball_struc" +mode2.files = ['PendelScript.mo'] + +# Transition from mode 1 to mode 2 +trans1_2 = Transition() +trans1_2.post = mode2 +trans1_2.mapping = {'x': 'x', 'y': 'y', 'vx': 'dx', 'vy': 'dy'} + +# Transition from mode 2 to mode 1 +trans2_1 = Transition() +trans2_1.post = mode1 +trans2_1.mapping = {'start_phi': 'phi', 'start_dphi': 'der(phi)'} + +# Set transitions +mode1.transitions = [trans1_2] +mode2.transitions = [trans2_1] + +# Set the modes +model.modes = [mode1, mode2] + + +# Create plots +plot1 = ModePlot() +plot1.vars = ['y'] +plot1.xAxisVar = 'x' +plot1.fileName = 'position.png' +plot1.show = True + +plot2 = ModePlot() +plot2.vars = ['y'] +plot2.fileName = 'y.png' +plot2.show = True + +# Set the plots +model.plots = [plot1, plot2] diff --git a/samples/pipe/config.py b/samples/pipe/config.py index c10a3ad..a48cfe7 100644 --- a/samples/pipe/config.py +++ b/samples/pipe/config.py @@ -1,76 +1,77 @@ -#Model -model.default_solver = Solver("dassl"); -model.default_solver.numberOfIntervals = 500; -model.translate = True; -model.init = {}; -model.startTime = 0; -model.stopTime = 100000; -model.observe = ['T1']; +# Model +model.default_solver = Solver("dassl") +model.default_solver.numberOfIntervals = 500 +model.translate = True +model.init = {} +model.startTime = 0 +model.stopTime = 100000 +model.observe = ['T1'] + def more(actMode, oldMode): - result = oldMode.read_last_result(); - time = result.GetValue('time', 5); - num = 1 - - for i in [1,2]: - T = result.GetValue('m1.T', 5); - for j in range(1,5): - actMode.set_initialValue('m'+ str(num)+'.T', T) - num = num+1 - - actMode.get_model().currentTime = time; + result = oldMode.read_last_result() + time = result.GetValue('time', 5) + num = 1 + + for i in [1, 2]: + T = result.GetValue('m1.T', 5) + for j in range(1, 5): + actMode.set_initialValue('m' + str(num) + '.T', T) + num = num + 1 + + actMode.get_model().currentTime = time + def less(actMode, oldMode): - num = 1 - for i in [1,2]: - Temp = 0 - for j in range(1,5): - Temp = Temp + oldMode.get_endValue('m' + str(num)+'.T'); - num = num + 1 - actMode.set_initialValue('m' + str(i)+'.T', Temp/4); - - -#First mode -mode1 = Mode(); -mode1.modeRef = "pipe.elements2"; -mode1.files = ["pipe.mo"]; -mode1.synonym = {'T1' : 'm1.T', 'CPUtime' : 'CPUtime'}; - - -#Second mode -mode2 = Mode(); -mode2.modeRef = "pipe.elements10"; -mode2.files = ["pipe.mo"]; -mode2.synonym = {'T1' : 'm1.T', 'CPUtime' : 'CPUtime'}; - - - -#Transition from mode 1 to mode 2 -trans1_2 = Transition(); -trans1_2.post = mode2; -trans1_2.mapping = {}; #stern wäre gut + num = 1 + for i in [1, 2]: + Temp = 0 + for j in range(1, 5): + Temp = Temp + oldMode.get_endValue('m' + str(num) + '.T') + num = num + 1 + actMode.set_initialValue('m' + str(i) + '.T', Temp / 4) + + +# First mode +mode1 = Mode() +mode1.modeRef = "pipe.elements2" +mode1.files = ["pipe.mo"] +mode1.synonym = {'T1': 'm1.T', 'CPUtime': 'CPUtime'} + + +# Second mode +mode2 = Mode() +mode2.modeRef = "pipe.elements10" +mode2.files = ["pipe.mo"] +mode2.synonym = {'T1': 'm1.T', 'CPUtime': 'CPUtime'} + + +# Transition from mode 1 to mode 2 +trans1_2 = Transition() +trans1_2.post = mode2 +trans1_2.mapping = {} # stern wäre gut trans1_2.init_function = more -mode1.transitions = [trans1_2]; +mode1.transitions = [trans1_2] -#Transition from mode 2 to mode 3 -trans2_1 = Transition(); -trans2_1.post = mode1; -trans2_1.mapping = {}; #stern wäre gut +# Transition from mode 2 to mode 3 +trans2_1 = Transition() +trans2_1.post = mode1 +trans2_1.mapping = {} # stern wäre gut trans2_1.init_function = less -mode2.transitions = [trans2_1]; +mode2.transitions = [trans2_1] -#Set the modes -model.modes = [mode1, mode2]; +# Set the modes +model.modes = [mode1, mode2] -plot1 = ModePlot(); -plot1.vars = ['T1']; -plot1.drawGrid = 1; -plot1.labelXAxis = "Time[s]"; -plot1.labelYAxis = "Temperature[K]"; -plot1.fileName = 'modeplot.png'; -plot1.show = True; +plot1 = ModePlot() +plot1.vars = ['T1'] +plot1.drawGrid = 1 +plot1.labelXAxis = "Time[s]" +plot1.labelYAxis = "Temperature[K]" +plot1.fileName = 'modeplot.png' +plot1.show = True -#Set the plots -model.plots = [plot1]; +# Set the plots +model.plots = [plot1] diff --git a/samples/satellite/config.py b/samples/satellite/config.py index a0e4e8a..8458ed2 100644 --- a/samples/satellite/config.py +++ b/samples/satellite/config.py @@ -1,93 +1,93 @@ -#Model -model.default_solver = Solver("dassl"); -model.default_solver.intervalLength = 0.001; -model.translate = True; -model.init = {}; -model.startTime = 0; -model.stopTime = 190000; -model.observe = ['x', 'h', 'vx', 'vy', 'v']; - -#First mode -mode1 = Mode(); -mode1.modeRef = "Satellite.PlanetRocket"; -mode1.files = ["Satellite.mo"]; -mode1.synonym = {'x' : 'rocket.x', 'h' : 'rocket.height', 'vx':'rocket.vx', 'vy':'rocket.vy', 'v':'rocket.v'}; - -#Second mode -mode2 = Mode(); -mode2.modeRef = "Satellite.PlanetSatellite"; -mode2.files = ["Satellite.mo"]; -mode2.synonym = {'x' : 'satellite.x', 'h' : 'satellite.y', 'vx':'satellite.vx', 'vy':'satellite.vy', 'v':'satellite.v'}; - - -#Third mode -mode3 = Mode(); -mode3.modeRef = "Satellite.PlanetSatelliteChange"; -mode3.files = ["Satellite1.mo"]; -mode3.synonym = {'x' : 'satellite.x', 'h' : 'satellite.y', 'vx':'satellite.vx', 'vy':'satellite.vy', 'v':'satellite.v'}; - - -#Transition from mode 1 to mode 2 -trans1_2 = Transition(); -trans1_2.post = mode2; -trans1_2.mapping = {'satellite.y' : 'rocket.height' , 'satellite.x' : 'rocket.x', 'satellite.vx' : 'rocket.vx', 'satellite.vy' : 'rocket.vy'}; #stern wäre gut - -mode1.transitions = [trans1_2]; - -#Transition from mode 2 to mode 3 -trans2_3 = Transition(); -trans2_3.post = mode3; -trans2_3.mapping = {'satellite.y':'satellite.y', 'satellite.x': 'satellite.x', 'satellite.vx': 'satellite.vx', 'satellite.vy': 'satellite.vy' }; #stern wäre gut - -mode2.transitions = [trans2_3]; - - -#Transition from mode 3 to mode 2 -trans3_2 = Transition(); -trans3_2.post = mode2; -trans3_2.mapping = {'satellite.y':'satellite.y', 'satellite.x': 'satellite.x', 'satellite.vx': 'satellite.vx', 'satellite.vy': 'satellite.vy' }; #stern wäre gut - -mode3.transitions = [trans3_2]; - - -#Set the modes -model.modes = [mode1, mode2, mode3]; - -plot1 = ModePlot(); -plot1.vars = ['h']; -plot1.drawGrid = 1; -plot1.labelXAxis = "time"; -plot1.labelYAxis = "h"; -plot1.fileName = 'modeplot.png'; -plot1.show = True; - -plot2 = VariablePlot(); -plot2.vars = {'v' : Color.MAGENTA}; -plot2.xAxisVar = 'time'; -plot2.drawGrid = 1; #0 = no, 1 = yes -plot2.labelXAxis = "time"; -plot2.labelYAxis = "v"; - -plot3 = VariablePlot(); -plot3.vars = {'vx' : Color.MAGENTA}; -plot3.xAxisVar = 'time'; -plot3.drawGrid = 1; #0 = no, 1 = yes -plot3.labelXAxis = "time"; -plot3.labelYAxis = "vx"; - -plot4 = VariablePlot(); -plot4.vars = {'vy' : Color.MAGENTA}; -plot4.xAxisVar = 'time'; -plot4.drawGrid = 1; #0 = no, 1 = yes -plot4.labelXAxis = "time"; -plot4.labelYAxis = "vy"; - -plot5 = VariablePlot(); -plot5.vars = {'h' : Color.MAGENTA}; -plot5.xAxisVar = 'x'; -plot5.drawGrid = 1; #0 = no, 1 = yes -plot5.labelXAxis = "x"; -plot5.labelYAxis = "h"; - -#Set the plots -model.plots = [plot1, plot2, plot3, plot4, plot5]; +# Model +model.default_solver = Solver("dassl") +model.default_solver.intervalLength = 0.001 +model.translate = True +model.init = {} +model.startTime = 0 +model.stopTime = 190000 +model.observe = ['x', 'h', 'vx', 'vy', 'v'] + +# First mode +mode1 = Mode() +mode1.modeRef = "Satellite.PlanetRocket" +mode1.files = ["Satellite.mo"] +mode1.synonym = {'x': 'rocket.x', 'h': 'rocket.height', 'vx': 'rocket.vx', 'vy': 'rocket.vy', 'v': 'rocket.v'} + +# Second mode +mode2 = Mode() +mode2.modeRef = "Satellite.PlanetSatellite" +mode2.files = ["Satellite.mo"] +mode2.synonym = {'x': 'satellite.x', 'h': 'satellite.y', 'vx': 'satellite.vx', 'vy': 'satellite.vy', 'v': 'satellite.v'} + + +# Third mode +mode3 = Mode() +mode3.modeRef = "Satellite.PlanetSatelliteChange" +mode3.files = ["Satellite1.mo"] +mode3.synonym = {'x': 'satellite.x', 'h': 'satellite.y', 'vx': 'satellite.vx', 'vy': 'satellite.vy', 'v': 'satellite.v'} + + +# Transition from mode 1 to mode 2 +trans1_2 = Transition() +trans1_2.post = mode2 +trans1_2.mapping = {'satellite.y': 'rocket.height', 'satellite.x': 'rocket.x', 'satellite.vx': 'rocket.vx', 'satellite.vy': 'rocket.vy'} # stern wäre gut + +mode1.transitions = [trans1_2] + +# Transition from mode 2 to mode 3 +trans2_3 = Transition() +trans2_3.post = mode3 +trans2_3.mapping = {'satellite.y': 'satellite.y', 'satellite.x': 'satellite.x', 'satellite.vx': 'satellite.vx', 'satellite.vy': 'satellite.vy'} # stern wäre gut + +mode2.transitions = [trans2_3] + + +# Transition from mode 3 to mode 2 +trans3_2 = Transition() +trans3_2.post = mode2 +trans3_2.mapping = {'satellite.y': 'satellite.y', 'satellite.x': 'satellite.x', 'satellite.vx': 'satellite.vx', 'satellite.vy': 'satellite.vy'} # stern wäre gut + +mode3.transitions = [trans3_2] + + +# Set the modes +model.modes = [mode1, mode2, mode3] + +plot1 = ModePlot() +plot1.vars = ['h'] +plot1.drawGrid = 1 +plot1.labelXAxis = "time" +plot1.labelYAxis = "h" +plot1.fileName = 'modeplot.png' +plot1.show = True + +plot2 = VariablePlot() +plot2.vars = {'v': Color.MAGENTA} +plot2.xAxisVar = 'time' +plot2.drawGrid = 1 # 0 = no, 1 = yes +plot2.labelXAxis = "time" +plot2.labelYAxis = "v" + +plot3 = VariablePlot() +plot3.vars = {'vx': Color.MAGENTA} +plot3.xAxisVar = 'time' +plot3.drawGrid = 1 # 0 = no, 1 = yes +plot3.labelXAxis = "time" +plot3.labelYAxis = "vx" + +plot4 = VariablePlot() +plot4.vars = {'vy': Color.MAGENTA} +plot4.xAxisVar = 'time' +plot4.drawGrid = 1 # 0 = no, 1 = yes +plot4.labelXAxis = "time" +plot4.labelYAxis = "vy" + +plot5 = VariablePlot() +plot5.vars = {'h': Color.MAGENTA} +plot5.xAxisVar = 'x' +plot5.drawGrid = 1 # 0 = no, 1 = yes +plot5.labelXAxis = "x" +plot5.labelYAxis = "h" + +# Set the plots +model.plots = [plot1, plot2, plot3, plot4, plot5] diff --git a/samples/wagon/config.py b/samples/wagon/config.py index d59faf4..15b037f 100644 --- a/samples/wagon/config.py +++ b/samples/wagon/config.py @@ -1,58 +1,58 @@ -#Model -model.default_solver = Solver("dassl"); -model.default_solver.tolerance = 3e-05; -model.translate = True; -model.init = {}; -model.startTime = 0; -model.stopTime = 10; -model.observe = ['y']; - -#First mode -mode1 = Mode(); -mode1.modeRef = "mechanics.vehicle_struc"; -mode1.files = ["mechanics.mo"]; -mode1.synonym = {'y' : 'y'}; - -#Second Mode -mode2 = Mode(); -mode2.modeRef = "mechanics.ball_struc"; -mode2.files = ["mechanics.mo"]; -mode2.synonym = {'y' : 'h'}; - -#Third Mode -mode3 = Mode(); -mode3.modeRef = "mechanics.contact_struc"; -mode3.files = ["mechanics.mo"]; -mode3.synonym = {'y' : 'h'}; - -#Transition from first mode to second mode -trans1_2 = Transition(); -trans1_2.post = mode2; -trans1_2.mapping = {'x' : 'x', 'h' : 'y', 'vx' : 'der(x)', 'vy' : 'der(y)'}; -mode1.transitions = [trans1_2]; - -#Transition from second mode to third mode -trans2_3 = Transition(); -trans2_3.post = mode3; -trans2_3.mapping = {'x' : 'x', 'damper.s_rel' : 'h', 'vx' : 'vx', 'damper.v_rel' : 'vy'}; -mode2.transitions = [trans2_3]; - -#Transition from third mode to second mode -trans3_2 = Transition(); -trans3_2.post = mode2; -trans3_2.mapping = {'x' : 'x', 'h' : 'damper.s_rel', 'vx' : 'vx', 'vy' : 'damper.v_rel'}; -mode3.transitions = [trans3_2]; - -#Set modes -model.modes = [mode1, mode2, mode3]; - -#Plot -plot1 = ModePlot(); -plot1.vars = {'y'}; -plot1.drawGrid = 1; -plot1.labelXAxis = "time"; -plot1.labelYAxis = "y"; -plot1.fileName = 'yplot.png'; -plot1.show = True; - -model.plots = [plot1]; +# Model +model.default_solver = Solver("dassl") +model.default_solver.tolerance = 3e-05 +model.translate = True +model.init = {} +model.startTime = 0 +model.stopTime = 10 +model.observe = ['y'] + +# First mode +mode1 = Mode() +mode1.modeRef = "mechanics.vehicle_struc" +mode1.files = ["mechanics.mo"] +mode1.synonym = {'y': 'y'} + +# Second Mode +mode2 = Mode() +mode2.modeRef = "mechanics.ball_struc" +mode2.files = ["mechanics.mo"] +mode2.synonym = {'y': 'h'} + +# Third Mode +mode3 = Mode() +mode3.modeRef = "mechanics.contact_struc" +mode3.files = ["mechanics.mo"] +mode3.synonym = {'y': 'h'} + +# Transition from first mode to second mode +trans1_2 = Transition() +trans1_2.post = mode2 +trans1_2.mapping = {'x': 'x', 'h': 'y', 'vx': 'der(x)', 'vy': 'der(y)'} +mode1.transitions = [trans1_2] + +# Transition from second mode to third mode +trans2_3 = Transition() +trans2_3.post = mode3 +trans2_3.mapping = {'x': 'x', 'damper.s_rel': 'h', 'vx': 'vx', 'damper.v_rel': 'vy'} +mode2.transitions = [trans2_3] + +# Transition from third mode to second mode +trans3_2 = Transition() +trans3_2.post = mode2 +trans3_2.mapping = {'x': 'x', 'h': 'damper.s_rel', 'vx': 'vx', 'vy': 'damper.v_rel'} +mode3.transitions = [trans3_2] + +# Set modes +model.modes = [mode1, mode2, mode3] + +# Plot +plot1 = ModePlot() +plot1.vars = {'y'} +plot1.drawGrid = 1 +plot1.labelXAxis = "time" +plot1.labelYAxis = "y" +plot1.fileName = 'yplot.png' +plot1.show = True + +model.plots = [plot1]