From 79a57dd680e3706c1ee8418a8ca3c7506f6beb2e Mon Sep 17 00:00:00 2001 From: jmoeckel Date: Thu, 15 Mar 2018 21:05:16 +0100 Subject: [PATCH] Applied several PEP8 Styleguidelines. In detail: # 'E101', # - Reindent all lines. # 'E11 ', # - Fix indentation. (not include E112 and E113) # 'E121', # - Fix indentation to be a multiple of four. # 'E122', # - Add absent indentation for hanging indentation. # 'E123', # - Align closing bracket to match opening bracket. # 'E124', # - Align closing bracket to match visual indentation. # 'E125', # - Indent to distinguish line from next logical line. # 'E126', # - Fix over-indented hanging indentation. # 'E127', # - Fix visual indentation. # 'E128', # - Fix visual indentation. # 'E20 ', # - Remove extraneous whitespace. # 'E211', # - Remove extraneous whitespace. # 'E22 ', # - Fix extraneous whitespace around keywords. # 'E224', # - Remove extraneous whitespace around operator. # 'E226', # - Fix missing whitespace around arithmetic operator. # 'E227', # - Fix missing whitespace around bitwise/shift operator. # 'E228', # - Fix missing whitespace around modulo operator. # 'E231', # - Add missing whitespace. # 'E241', # - Fix extraneous whitespace around keywords. # 'E242', # - Remove extraneous whitespace around operator. # 'E251', # - Remove whitespace around parameter '=' sign. # 'E26 ', # - Fix spacing after comment hash for inline comments. # 'E265', # - Fix spacing after comment hash for block comments. # 'E27 ', # - Fix extraneous whitespace around keywords. # 'E301', # - Add missing blank line. # 'E302', # - Add missing 2 blank lines. # 'E303', # - Remove extra blank lines. # 'E304', # - Remove blank line following function decorator. # 'E306', # - Expected 1 blank line before a nested definition # 'E401', # - Put imports on separate lines. # 'E502', # - Remove extraneous escape of newline. # 'E70 ', # - Put semicolon-separated compound statement on separate lines. # 'W291', # - Remove trailing whitespace. # 'W292', # - Add a single newline at the end of the file. # 'W293', # - Remove trailing whitespace on blank line. # 'W391', # - Remove trailing blank lines. --- PySimLib/Config.py | 91 +-- .../Exceptions/CompilationFailedException.py | 23 +- .../Exceptions/SimulationFailedException.py | 23 +- .../Exceptions/UncompiledModelException.py | 23 +- PySimLib/Log.py | 44 +- PySimLib/Mat/Mat.py | 237 +++---- PySimLib/Mat/Matrix.py | 169 ++--- PySimLib/Mat/MatrixTypeEvaluator.py | 109 +-- PySimLib/Mat/OutputStream.py | 89 +-- PySimLib/Mat/TextMatrix.py | 147 ++-- PySimLib/Model.py | 67 +- PySimLib/Models/ModelicaModel.py | 111 +-- PySimLib/Models/SimulinkModel.py | 45 +- PySimLib/Platform.py | 136 ++-- PySimLib/Plot.py | 67 +- PySimLib/Simulation.py | 83 +-- PySimLib/SimulationResult.py | 51 +- PySimLib/Solver.py | 39 +- PySimLib/Solvers/DASSL.py | 39 +- PySimLib/Solvers/DEABM.py | 39 +- PySimLib/Solvers/LSODAR.py | 39 +- PySimLib/Tool.py | 143 ++-- PySimLib/Tools/Dymola.py | 631 ++++++++--------- PySimLib/Tools/ModelicaTool.py | 125 ++-- PySimLib/Tools/OpenModelica.py | 633 +++++++++--------- PySimLib/Tools/Simulink.py | 315 +++++---- PySimLib/VariableDescriptor.py | 25 +- PySimLib/__init__.py | 206 +++--- info/listSolvers.py | 8 +- info/listTools.py | 8 +- info/mat.py | 32 +- info/matrix.py | 42 +- info/tool.py | 16 +- samples/pendulum/pendulum.py | 32 +- samples/struc_param/struc_param.py | 34 +- .../pendulum to ball/run.py | 110 +-- setup.py | 14 +- 37 files changed, 2045 insertions(+), 2000 deletions(-) diff --git a/PySimLib/Config.py b/PySimLib/Config.py index 71e417f..a37a8f8 100644 --- a/PySimLib/Config.py +++ b/PySimLib/Config.py @@ -20,56 +20,61 @@ along with this program. If not, see . """ -from PySimLib.Platform import *; +from PySimLib.Platform import * + +# Public + -#Public def GetBoolConfigValue(section, key): - global __g_sections; - - return __g_sections[section][key] == "true"; - + global __g_sections + + return __g_sections[section][key] == "true" + + def GetConfigValue(section, key): - global __g_sections; - - return __g_sections[section][key]; - + global __g_sections + + return __g_sections[section][key] + + def HasConfigValue(section, key): - global __g_sections; - - if(section in __g_sections): - return key in __g_sections[section]; - - return False; + global __g_sections + + if(section in __g_sections): + return key in __g_sections[section] + return False -#Internal -__g_sections = {}; +# Internal +__g_sections = {} + def ReadConfigFromFile(): - import os; - import os.path; - import configparser; - - global __g_sections; - - path = GetConfigDirectory() + '/PySimLib.cfg'; - - if(not os.path.isfile(path)): - raise Exception("PySimLib is not configured. Please read the manual to do so."); - - parser = configparser.ConfigParser(); - parser.optionxform = str; #disable lower caseing - parser.read(path); - - for section in parser.sections(): - entries = {}; - for key in parser.options(section): - entries[key] = parser[section][key]; - - if(len(entries) > 0): - __g_sections[section] = entries; - -#read config -ReadConfigFromFile(); + import os + import os.path + import configparser + + global __g_sections + + path = GetConfigDirectory() + '/PySimLib.cfg' + + if(not os.path.isfile(path)): + raise Exception("PySimLib is not configured. Please read the manual to do so.") + + parser = configparser.ConfigParser() + parser.optionxform = str # disable lower caseing + parser.read(path) + + for section in parser.sections(): + entries = {} + for key in parser.options(section): + entries[key] = parser[section][key] + + if(len(entries) > 0): + __g_sections[section] = entries + + +# read config +ReadConfigFromFile() diff --git a/PySimLib/Exceptions/CompilationFailedException.py b/PySimLib/Exceptions/CompilationFailedException.py index e90b384..aeb82bb 100644 --- a/PySimLib/Exceptions/CompilationFailedException.py +++ b/PySimLib/Exceptions/CompilationFailedException.py @@ -20,15 +20,16 @@ along with this program. If not, see . """ + class CompilationFailedException(Exception): - #Constructor - def __init__(this, mdl, tool): - Exception.__init__(this); - - #Private members - this.__mdl = mdl; - this.__tool = tool; - - #Magic methods - def __str__(this): - return 'Compilation of model "' + str(this.__mdl) + '" with tool "' + str(this.__tool) + '" failed.'; + # Constructor + def __init__(this, mdl, tool): + Exception.__init__(this) + + # Private members + this.__mdl = mdl + this.__tool = tool + + # Magic methods + def __str__(this): + return 'Compilation of model "' + str(this.__mdl) + '" with tool "' + str(this.__tool) + '" failed.' diff --git a/PySimLib/Exceptions/SimulationFailedException.py b/PySimLib/Exceptions/SimulationFailedException.py index 5a73265..c8838a7 100644 --- a/PySimLib/Exceptions/SimulationFailedException.py +++ b/PySimLib/Exceptions/SimulationFailedException.py @@ -20,15 +20,16 @@ along with this program. If not, see . """ + class SimulationFailedException(Exception): - #Constructor - def __init__(this, sim, tool): - Exception.__init__(this); - - #Private members - this.__sim = sim; - this.__tool = tool; - - #Magic methods - def __str__(this): - return 'Simulation of model "' + str(this.__sim.GetModel()) + '" with tool "' + str(this.__tool) + '" failed.'; + # Constructor + def __init__(this, sim, tool): + Exception.__init__(this) + + # Private members + this.__sim = sim + this.__tool = tool + + # Magic methods + def __str__(this): + return 'Simulation of model "' + str(this.__sim.GetModel()) + '" with tool "' + str(this.__tool) + '" failed.' diff --git a/PySimLib/Exceptions/UncompiledModelException.py b/PySimLib/Exceptions/UncompiledModelException.py index a745ea4..001d486 100644 --- a/PySimLib/Exceptions/UncompiledModelException.py +++ b/PySimLib/Exceptions/UncompiledModelException.py @@ -20,15 +20,16 @@ along with this program. If not, see . """ + class UncompiledModelException(Exception): - #Constructor - def __init__(this, mdl, tool): - Exception.__init__(this); - - #Private members - this.__mdl = mdl; - this.__tool = tool; - - #Magic methods - def __str__(this): - return 'Model "' + str(this.__mdl) + '" is being used with tool "' + str(this.__tool) + '" but is not compiled.'; + # Constructor + def __init__(this, mdl, tool): + Exception.__init__(this) + + # Private members + this.__mdl = mdl + this.__tool = tool + + # Magic methods + def __str__(this): + return 'Model "' + str(this.__mdl) + '" is being used with tool "' + str(this.__tool) + '" but is not compiled.' diff --git a/PySimLib/Log.py b/PySimLib/Log.py index 45c85d9..8e2a2d9 100644 --- a/PySimLib/Log.py +++ b/PySimLib/Log.py @@ -20,28 +20,34 @@ along with this program. If not, see . """ -#Global -import os; +# Global +import os + +# External + -#External def GetTarget(): - global __target; - - return __target; - + global __target + + return __target + + def Append(string): - global __target; - - __target.write(string); - + global __target + + __target.write(string) + + def Line(string): - Append(string); - Append("\r\n"); - + Append(string) + Append("\r\n") + + def SetTarget(target): - global __target; - - __target = target; + global __target + + __target = target + -#Internals -__target = open(os.devnull, 'w'); #default to not create a log +# Internals +__target = open(os.devnull, 'w') # default to not create a log diff --git a/PySimLib/Mat/Mat.py b/PySimLib/Mat/Mat.py index dfa02aa..dd18921 100644 --- a/PySimLib/Mat/Mat.py +++ b/PySimLib/Mat/Mat.py @@ -20,123 +20,124 @@ along with this program. If not, see . """ -#Global -import struct; -#Local -from PySimLib.Mat.Matrix import *; -from PySimLib.Mat.TextMatrix import *; +# Global +import struct +# Local +from PySimLib.Mat.Matrix import * +from PySimLib.Mat.TextMatrix import * + class Mat: - #Constructor - def __init__(this): - this.__matrices = {}; - - #Magic methods - def __str__(this): - result = ""; - for key in this.__matrices: - m = this.__matrices[key]; - if(type(m) == Matrix): - result = result + key + " " + str(m.GetNumberOfRows()) + "x" + str(m.GetNumberOfColumns()) + ", "; - elif(type(m) == TextMatrix): - result = result + key + " " + str(m.GetNumberOfStrings()) + ", "; - return result; - - #Private methods - def __ReadMatrix(this, input): - type = this.__ReadUInt32(input); - numberFormat = int(type / 1000); - if(not(numberFormat == 0)): - raise Exception("NOT IMPLEMENTED"); - if(not(int((type % 1000) / 100) == 0)): - raise Exception("Not a Matlab v4 file"); - dataFormat = int((type % 100) / 10); - matrixType = type % 10; - rows = this.__ReadUInt32(input); - cols = this.__ReadUInt32(input); - imaginaryFlag = this.__ReadUInt32(input); - if(imaginaryFlag == 1): - raise Exception("NOT IMPLEMENTED"); - nameLength = this.__ReadUInt32(input); - name = this.__ReadMatrixName(input, nameLength); - - if(matrixType == 0): #full numeric matrix - m = this.AddMatrix(name, cols, rows); - elif(matrixType == 1): #text matrix - m = this.AddTextMatrix(name, rows); - - this.__ReadMatrixData(input, dataFormat, rows, cols, m); - - def __ReadMatrixData(this, input, dataFormat, rows, cols, matrix): - for x in range(0, cols): - for y in range(0, rows): - matrix.SetValue(x, y, this.__ReadMatrixDataEntry(input, dataFormat)); - - def __ReadMatrixDataEntry(this, input, dataFormat): - if(dataFormat == 0): #float64 - return struct.unpack('d', input.read(8))[0]; - elif(dataFormat == 1): #float32 - return struct.unpack('f', input.read(4))[0]; - elif(dataFormat == 2): #int32 - return this.__ReadInt32(input); - elif(dataFormat == 5): #uint8 - b = input.read(1); - return b[0]; - else: - raise Exception("NOT IMPLEMENTED" + str(dataFormat)); - - def __ReadMatrixName(this, input, length): - result = ""; - while(length > 1): - b = input.read(1); - result = result + chr(b[0]); - length = length - 1; - input.read(1); #null byte - return result; - - def __ReadInt32(this, input): - raw = input.read(4); - value = (raw[3] << 24) | (raw[2] << 16) | (raw[1] << 8) | raw[0]; - - if(raw[3] & 0x80): - return -0x100000000 + value; - - return value; - - def __ReadUInt32(this, input): - raw = input.read(4); - - return (raw[3] << 24) | (raw[2] << 16) | (raw[1] << 8) | raw[0]; - #return (raw[0] << 24) | (raw[1] << 16) | (raw[2] << 8) | raw[3]; - - #Public methods - def AddMatrix(this, name, columns, rows): - m = Matrix(columns, rows); - this.__matrices[name] = m; - return m; - - def AddTextMatrix(this, name, nStrings): - m = TextMatrix(nStrings); - this.__matrices[name] = m; - return m; - - def GetMatrices(this): - return this.__matrices; - - def GetMatrix(this, name): - return this.__matrices[name]; - - def Load(this, fileName): - file = open(fileName, "rb"); - file.seek(0, 2); #2 = SEEK_END - fileSize = file.tell(); - file.seek(0, 0); #0 = SEEK_SET - - while(file.tell() < fileSize): #Read matrices - this.__ReadMatrix(file); - - file.close(); - - def Write(this, target): - for key in this.__matrices: - this.__matrices[key].Write(key, target); + # Constructor + def __init__(this): + this.__matrices = {} + + # Magic methods + def __str__(this): + result = "" + for key in this.__matrices: + m = this.__matrices[key] + if(type(m) == Matrix): + result = result + key + " " + str(m.GetNumberOfRows()) + "x" + str(m.GetNumberOfColumns()) + ", " + elif(type(m) == TextMatrix): + result = result + key + " " + str(m.GetNumberOfStrings()) + ", " + return result + + # Private methods + def __ReadMatrix(this, input): + type = this.__ReadUInt32(input) + numberFormat = int(type / 1000) + if(not(numberFormat == 0)): + raise Exception("NOT IMPLEMENTED") + if(not(int((type % 1000) / 100) == 0)): + raise Exception("Not a Matlab v4 file") + dataFormat = int((type % 100) / 10) + matrixType = type % 10 + rows = this.__ReadUInt32(input) + cols = this.__ReadUInt32(input) + imaginaryFlag = this.__ReadUInt32(input) + if(imaginaryFlag == 1): + raise Exception("NOT IMPLEMENTED") + nameLength = this.__ReadUInt32(input) + name = this.__ReadMatrixName(input, nameLength) + + if(matrixType == 0): # full numeric matrix + m = this.AddMatrix(name, cols, rows) + elif(matrixType == 1): # text matrix + m = this.AddTextMatrix(name, rows) + + this.__ReadMatrixData(input, dataFormat, rows, cols, m) + + def __ReadMatrixData(this, input, dataFormat, rows, cols, matrix): + for x in range(0, cols): + for y in range(0, rows): + matrix.SetValue(x, y, this.__ReadMatrixDataEntry(input, dataFormat)) + + def __ReadMatrixDataEntry(this, input, dataFormat): + if(dataFormat == 0): # float64 + return struct.unpack('d', input.read(8))[0] + elif(dataFormat == 1): # float32 + return struct.unpack('f', input.read(4))[0] + elif(dataFormat == 2): # int32 + return this.__ReadInt32(input) + elif(dataFormat == 5): # uint8 + b = input.read(1) + return b[0] + else: + raise Exception("NOT IMPLEMENTED" + str(dataFormat)) + + def __ReadMatrixName(this, input, length): + result = "" + while(length > 1): + b = input.read(1) + result = result + chr(b[0]) + length = length - 1 + input.read(1) # null byte + return result + + def __ReadInt32(this, input): + raw = input.read(4) + value = (raw[3] << 24) | (raw[2] << 16) | (raw[1] << 8) | raw[0] + + if(raw[3] & 0x80): + return -0x100000000 + value + + return value + + def __ReadUInt32(this, input): + raw = input.read(4) + + return (raw[3] << 24) | (raw[2] << 16) | (raw[1] << 8) | raw[0] + # return (raw[0] << 24) | (raw[1] << 16) | (raw[2] << 8) | raw[3]; + + # Public methods + def AddMatrix(this, name, columns, rows): + m = Matrix(columns, rows) + this.__matrices[name] = m + return m + + def AddTextMatrix(this, name, nStrings): + m = TextMatrix(nStrings) + this.__matrices[name] = m + return m + + def GetMatrices(this): + return this.__matrices + + def GetMatrix(this, name): + return this.__matrices[name] + + def Load(this, fileName): + file = open(fileName, "rb") + file.seek(0, 2) # 2 = SEEK_END + fileSize = file.tell() + file.seek(0, 0) # 0 = SEEK_SET + + while(file.tell() < fileSize): # Read matrices + this.__ReadMatrix(file) + + file.close() + + def Write(this, target): + for key in this.__matrices: + this.__matrices[key].Write(key, target) diff --git a/PySimLib/Mat/Matrix.py b/PySimLib/Mat/Matrix.py index cabb1dc..0499daf 100644 --- a/PySimLib/Mat/Matrix.py +++ b/PySimLib/Mat/Matrix.py @@ -20,89 +20,90 @@ along with this program. If not, see . """ -#Local -from PySimLib.Mat.MatrixTypeEvaluator import *; +# Local +from PySimLib.Mat.MatrixTypeEvaluator import * + class Matrix: - #Constructor - def __init__(this, columns, rows): - this.__rows = []; - for y in range(0, rows): - row = []; - for x in range(0, columns): - row.append(0); - this.__rows.append(row); - - this.__desiredOutputEncoding = None; - - #Magic methods - def __str__(this): - return str(len(this.__rows[0])) + "x" + str(len(this.__rows)) + "Matrix"; - - #Private methods - def __WriteValue(this, value, target, encoding): - if(encoding == 0): #TYPE_FLOAT64 - target.WriteFloat64(value); - elif(encoding == 1): #TYPE_FLOAT32 - target.WriteFloat32(value); - elif(encoding == 2): #TYPE_INT32 - target.WriteInt32(value); - elif(encoding == 3): #TYPE_INT16 - target.WriteInt16(value); - elif(encoding == 5): #TYPE_UINT8 - target.WriteByte(value); - else: - raise Exception("Not implemented for case " + str(encoding)); - - #Public methods - def GetNumberOfColumns(this): - return len(this.__rows[0]); - - def GetNumberOfRows(this): - return len(this.__rows); - - def GetValue(this, x, y): - #print("y", y); - #print("row[y]", this.__rows[y]); - #print("x", x); - #print("rows[y][x]", this.__rows[y][x]); - return this.__rows[y][x]; - - def SetDesiredOutputPrecision(this, encoding): - this.__desiredOutputEncoding = encoding; - - def SetValue(this, x, y, value): - this.__rows[y][x] = value; - - def Transpose(this): - nCols = this.GetNumberOfColumns(); - nRows = this.GetNumberOfRows(); - rows = this.__rows; - - this.__init__(nRows, nCols); - - for x in range(0, nCols): - for y in range(0, nRows): - this.SetValue(y, x, rows[y][x]); - - def Write(this, matrixName, target): - if(this.__desiredOutputEncoding is None): - evaluator = MatrixTypeEvaluator(this.__rows); - encoding = evaluator.GetType(); - else: - encoding = this.__desiredOutputEncoding; - - target.WriteUInt32(encoding * 10); #type - target.WriteUInt32(this.GetNumberOfRows()); #rows - target.WriteUInt32(this.GetNumberOfColumns()); #cols - target.WriteUInt32(0); #imagf - target.WriteUInt32(len(matrixName)+1); #namelen - target.WriteASCII(matrixName); #name - target.WriteByte(0); #\0 - - #real part - for x in range(0, this.GetNumberOfColumns()): - for y in range(0, this.GetNumberOfRows()): - this.__WriteValue(this.__rows[y][x], target, encoding); - - #no imag part + # Constructor + def __init__(this, columns, rows): + this.__rows = [] + for y in range(0, rows): + row = [] + for x in range(0, columns): + row.append(0) + this.__rows.append(row) + + this.__desiredOutputEncoding = None + + # Magic methods + def __str__(this): + return str(len(this.__rows[0])) + "x" + str(len(this.__rows)) + "Matrix" + + # Private methods + def __WriteValue(this, value, target, encoding): + if(encoding == 0): # TYPE_FLOAT64 + target.WriteFloat64(value) + elif(encoding == 1): # TYPE_FLOAT32 + target.WriteFloat32(value) + elif(encoding == 2): # TYPE_INT32 + target.WriteInt32(value) + elif(encoding == 3): # TYPE_INT16 + target.WriteInt16(value) + elif(encoding == 5): # TYPE_UINT8 + target.WriteByte(value) + else: + raise Exception("Not implemented for case " + str(encoding)) + + # Public methods + def GetNumberOfColumns(this): + return len(this.__rows[0]) + + def GetNumberOfRows(this): + return len(this.__rows) + + def GetValue(this, x, y): + #print("y", y); + #print("row[y]", this.__rows[y]); + #print("x", x); + #print("rows[y][x]", this.__rows[y][x]); + return this.__rows[y][x] + + def SetDesiredOutputPrecision(this, encoding): + this.__desiredOutputEncoding = encoding + + def SetValue(this, x, y, value): + this.__rows[y][x] = value + + def Transpose(this): + nCols = this.GetNumberOfColumns() + nRows = this.GetNumberOfRows() + rows = this.__rows + + this.__init__(nRows, nCols) + + for x in range(0, nCols): + for y in range(0, nRows): + this.SetValue(y, x, rows[y][x]) + + def Write(this, matrixName, target): + if(this.__desiredOutputEncoding is None): + evaluator = MatrixTypeEvaluator(this.__rows) + encoding = evaluator.GetType() + else: + encoding = this.__desiredOutputEncoding + + target.WriteUInt32(encoding * 10) # type + target.WriteUInt32(this.GetNumberOfRows()) # rows + target.WriteUInt32(this.GetNumberOfColumns()) # cols + target.WriteUInt32(0) # imagf + target.WriteUInt32(len(matrixName) + 1) # namelen + target.WriteASCII(matrixName) # name + target.WriteByte(0) # \0 + + # real part + for x in range(0, this.GetNumberOfColumns()): + for y in range(0, this.GetNumberOfRows()): + this.__WriteValue(this.__rows[y][x], target, encoding) + + # no imag part diff --git a/PySimLib/Mat/MatrixTypeEvaluator.py b/PySimLib/Mat/MatrixTypeEvaluator.py index 3c836ea..56aa438 100644 --- a/PySimLib/Mat/MatrixTypeEvaluator.py +++ b/PySimLib/Mat/MatrixTypeEvaluator.py @@ -20,59 +20,60 @@ along with this program. If not, see . """ -TYPE_FLOAT64 = 0; -TYPE_FLOAT32 = 1; -TYPE_INT32 = 2; -TYPE_INT16 = 3; -TYPE_UINT16 = 4; -TYPE_UINT8 = 5; +TYPE_FLOAT64 = 0 +TYPE_FLOAT32 = 1 +TYPE_INT32 = 2 +TYPE_INT16 = 3 +TYPE_UINT16 = 4 +TYPE_UINT8 = 5 + class MatrixTypeEvaluator: - #Constructor - def __init__(this, rows): - this.__type = TYPE_UINT8; - this.__min = 0; - this.__max = 255; - - for row in rows: - for col in row: - if(this.__type == TYPE_FLOAT64): - return; #max precision, no need to continue - this.__NextValue(col); - - #Private methods - def __NextValue(this, value): - if(isinstance(value, float) and (not value.is_integer())): #any float that can't be an int... - this.__type = TYPE_FLOAT64; - return; - - #value is not float from here - - if(this.__type == TYPE_FLOAT32): #we came here because of a very large integer - return; #already highest precision for non float matrix - - #The internal type is some int type - - if(value < this.__min): - this.__min = value; - elif(value > this.__max): - this.__max = value; - - if(this.__min >= 0 and this.__max <= 255): - this.__type = TYPE_UINT8; - return; - if(this.__min >= -32768 and this.__max <= 0x7FFF): - this.__type = TYPE_INT16; - return; - if(this.__min >= 0 and this.__max <= 0xFFFF): - this.__type = TYPE_UINT16; - return; - if(this.__min >= -2147483648 and this.__max <= 0x7FFFFFFF): - this.__type = TYPE_INT32; - return; - - this.__type = TYPE_FLOAT32; #we have only ints but we can't put them in int32 - - #Public methods - def GetType(this): - return this.__type; + # Constructor + def __init__(this, rows): + this.__type = TYPE_UINT8 + this.__min = 0 + this.__max = 255 + + for row in rows: + for col in row: + if(this.__type == TYPE_FLOAT64): + return # max precision, no need to continue + this.__NextValue(col) + + # Private methods + def __NextValue(this, value): + if(isinstance(value, float) and (not value.is_integer())): # any float that can't be an int... + this.__type = TYPE_FLOAT64 + return + + # value is not float from here + + if(this.__type == TYPE_FLOAT32): # we came here because of a very large integer + return # already highest precision for non float matrix + + # The internal type is some int type + + if(value < this.__min): + this.__min = value + elif(value > this.__max): + this.__max = value + + if(this.__min >= 0 and this.__max <= 255): + this.__type = TYPE_UINT8 + return + if(this.__min >= -32768 and this.__max <= 0x7FFF): + this.__type = TYPE_INT16 + return + if(this.__min >= 0 and this.__max <= 0xFFFF): + this.__type = TYPE_UINT16 + return + if(this.__min >= -2147483648 and this.__max <= 0x7FFFFFFF): + this.__type = TYPE_INT32 + return + + this.__type = TYPE_FLOAT32 # we have only ints but we can't put them in int32 + + # Public methods + def GetType(this): + return this.__type diff --git a/PySimLib/Mat/OutputStream.py b/PySimLib/Mat/OutputStream.py index c70ac8f..a9f5b84 100644 --- a/PySimLib/Mat/OutputStream.py +++ b/PySimLib/Mat/OutputStream.py @@ -20,49 +20,50 @@ along with this program. If not, see . """ -import struct; +import struct + class OutputStream: - #Constructor - def __init__(this, target): - this.__target = target; - - #Public methods - def WriteASCII(this, str): - for x in str: - this.WriteByte(x); - - def WriteByte(this, value): - if(type(value) == float): - value = int(value); - if(type(value) == str): - value = ord(value); - - this.__target.write(bytes([value])); - - def WriteFloat32(this, value): - s = struct.pack('f', value); - this.__target.write(s); - - def WriteFloat64(this, value): - s = struct.pack('d', value); - this.__target.write(s); - - def WriteInt16(this, value): - if(type(value) == float): - value = int(value); - - this.WriteByte(value & 0xFF); - this.WriteByte((value >> 8) & 0xFF); - - def WriteInt32(this, value): - this.WriteByte(value & 0xFF); - this.WriteByte((value >> 8) & 0xFF); - this.WriteByte((value >> 16) & 0xFF); - this.WriteByte((value >> 24) & 0xFF); - - def WriteUInt32(this, value): - this.WriteByte(value & 0xFF); - this.WriteByte((value >> 8) & 0xFF); - this.WriteByte((value >> 16) & 0xFF); - this.WriteByte((value >> 24) & 0xFF); + # Constructor + def __init__(this, target): + this.__target = target + + # Public methods + def WriteASCII(this, str): + for x in str: + this.WriteByte(x) + + def WriteByte(this, value): + if(type(value) == float): + value = int(value) + if(type(value) == str): + value = ord(value) + + this.__target.write(bytes([value])) + + def WriteFloat32(this, value): + s = struct.pack('f', value) + this.__target.write(s) + + def WriteFloat64(this, value): + s = struct.pack('d', value) + this.__target.write(s) + + def WriteInt16(this, value): + if(type(value) == float): + value = int(value) + + this.WriteByte(value & 0xFF) + this.WriteByte((value >> 8) & 0xFF) + + def WriteInt32(this, value): + this.WriteByte(value & 0xFF) + this.WriteByte((value >> 8) & 0xFF) + this.WriteByte((value >> 16) & 0xFF) + this.WriteByte((value >> 24) & 0xFF) + + def WriteUInt32(this, value): + this.WriteByte(value & 0xFF) + this.WriteByte((value >> 8) & 0xFF) + this.WriteByte((value >> 16) & 0xFF) + this.WriteByte((value >> 24) & 0xFF) diff --git a/PySimLib/Mat/TextMatrix.py b/PySimLib/Mat/TextMatrix.py index 55d7adf..703d6f4 100644 --- a/PySimLib/Mat/TextMatrix.py +++ b/PySimLib/Mat/TextMatrix.py @@ -20,77 +20,78 @@ along with this program. If not, see . """ + class TextMatrix: - #Constructor - def __init__(this, nStrings): - this.__strings = []; - for i in range(0, nStrings): - this.__strings.append([]); - - #Private methods - def __GetLongestStringLength(this): - length = 0; - for x in this.__strings: - if(len(x) > length): - length = len(x); - - return length; - - #Public methods - def GetNumberOfStrings(this): - return len(this.__strings); - - def GetString(this, row): - result = ""; - str = this.__strings[row]; - for i in range(0, len(str)): - if(str[i] == 0): #end of string - break; - result = result + chr(str[i]); - return result.rstrip(); - - def SetString(this, y, str): - for i in range(0, len(str)): - this.SetValue(i, y, str[i]); - - def SetValue(this, x, y, value): - str = this.__strings[y]; - length = len(str); - while(length <= x): - str.append(0); - length = length + 1; - - if(type(value) == int): - str[x] = value; - else: - str[x] = ord(value); - - def Transpose(this): - nCols = this.__GetLongestStringLength(); - nRows = this.GetNumberOfStrings(); - rows = this.__strings; - - this.__init__(nCols); - - for x in range(0, nCols): - for y in range(0, nRows): - this.SetValue(y, x, rows[y][x]); - - def Write(this, matrixName, target): - target.WriteUInt32(51); #type - target.WriteUInt32(this.GetNumberOfStrings()); #rows - target.WriteUInt32(this.__GetLongestStringLength()); #cols - target.WriteUInt32(0); #imagf - target.WriteUInt32(len(matrixName)+1); #namelen - target.WriteASCII(matrixName); #name - target.WriteByte(0); #\0 - - #real part - for x in range(0, this.__GetLongestStringLength()): - for y in range(0, this.GetNumberOfStrings()): - if(x > len(this.__strings[y])-1): - target.WriteByte(0); - else: - target.WriteByte(this.__strings[y][x]); - - #no imag part + # Constructor + def __init__(this, nStrings): + this.__strings = [] + for i in range(0, nStrings): + this.__strings.append([]) + + # Private methods + def __GetLongestStringLength(this): + length = 0 + for x in this.__strings: + if(len(x) > length): + length = len(x) + + return length + + # Public methods + def GetNumberOfStrings(this): + return len(this.__strings) + + def GetString(this, row): + result = "" + str = this.__strings[row] + for i in range(0, len(str)): + if(str[i] == 0): # end of string + break + result = result + chr(str[i]) + return result.rstrip() + + def SetString(this, y, str): + for i in range(0, len(str)): + this.SetValue(i, y, str[i]) + + def SetValue(this, x, y, value): + str = this.__strings[y] + length = len(str) + while(length <= x): + str.append(0) + length = length + 1 + + if(type(value) == int): + str[x] = value + else: + str[x] = ord(value) + + def Transpose(this): + nCols = this.__GetLongestStringLength() + nRows = this.GetNumberOfStrings() + rows = this.__strings + + this.__init__(nCols) + + for x in range(0, nCols): + for y in range(0, nRows): + this.SetValue(y, x, rows[y][x]) + + def Write(this, matrixName, target): + target.WriteUInt32(51) # type + target.WriteUInt32(this.GetNumberOfStrings()) # rows + target.WriteUInt32(this.__GetLongestStringLength()) # cols + target.WriteUInt32(0) # imagf + target.WriteUInt32(len(matrixName) + 1) # namelen + target.WriteASCII(matrixName) # name + target.WriteByte(0) # \0 + + # real part + for x in range(0, this.__GetLongestStringLength()): + for y in range(0, this.GetNumberOfStrings()): + if(x > len(this.__strings[y]) - 1): + target.WriteByte(0) + else: + target.WriteByte(this.__strings[y][x]) + + # no imag part diff --git a/PySimLib/Model.py b/PySimLib/Model.py index c982641..836ab20 100644 --- a/PySimLib/Model.py +++ b/PySimLib/Model.py @@ -20,38 +20,39 @@ along with this program. If not, see . """ -import os; +import os + class Model: - #Constructor - def __init__(this, name, files): - #Private members - this.__name = name; - - #Public members - this.outputName = name; - this.outputDir = None; - this.resultDir = None; - this.simDir = None; - this.variables = {}; - - if(len(files) == 1): - this.outputDir = os.path.abspath(os.path.dirname(files[0])); - this.resultDir = this.outputDir; - this.simDir = this.outputDir; - - #Public methods - def GetCompatibleTools(this): - from . import GetTools; - - tools = GetTools(); - result = []; - - for tool in tools: - if(tool.Accepts(this)): - result.append(tool); - - return result; - - def GetName(this): - return this.__name; + # Constructor + def __init__(this, name, files): + # Private members + this.__name = name + + # Public members + this.outputName = name + this.outputDir = None + this.resultDir = None + this.simDir = None + this.variables = {} + + if(len(files) == 1): + this.outputDir = os.path.abspath(os.path.dirname(files[0])) + this.resultDir = this.outputDir + this.simDir = this.outputDir + + # Public methods + def GetCompatibleTools(this): + from . import GetTools + + tools = GetTools() + result = [] + + for tool in tools: + if(tool.Accepts(this)): + result.append(tool) + + return result + + def GetName(this): + return this.__name diff --git a/PySimLib/Models/ModelicaModel.py b/PySimLib/Models/ModelicaModel.py index 223a871..12958d1 100755 --- a/PySimLib/Models/ModelicaModel.py +++ b/PySimLib/Models/ModelicaModel.py @@ -20,61 +20,62 @@ along with this program. If not, see . """ -#Lib -import os; -import os.path; -import re; +# Lib +import os +import os.path +import re + +from PySimLib.Model import Model -from PySimLib.Model import Model; class ModelicaModel(Model): - #Constructor - def __init__(this, name, files): - Model.__init__(this, name, files); - - #Private members - this.__files = files; - - #Public members - this.parameters = {}; - - #Magic methods - def __str__(this): - return "Modelica class " + '"' + this.GetModelicaClassString() + '"'; - - #Public methods - def GetFiles(this): - return this.__files; - - def GetModelicaClassString(this, includeVariables = False, source = None): - cmd = this.GetName(); - - def numericSafe(x): - if(type(x) == float and x.is_integer()): - return int(x); - return x; - - if(source is None): - source = this; - - if(this.parameters or source.variables): - cmd = cmd + "("; - for key in this.parameters: - cmd = cmd + key + "=" + str(this.parameters[key]) + ","; - for key in source.variables: - if(source.variables[key].start is None): - continue; - if(re.match("der(.+?)", key)): #skip derivatives - continue; - - cmd += key + "(start=" + str(numericSafe(source.variables[key].start)) + "),"; - cmd = cmd[:-1]; #remove last comma - cmd = cmd + ")"; - - return cmd; - - #Class functions - def Matches(name, files): - extension = os.path.splitext(files[0])[1]; - - return extension == ".mo"; + # Constructor + def __init__(this, name, files): + Model.__init__(this, name, files) + + # Private members + this.__files = files + + # Public members + this.parameters = {} + + # Magic methods + def __str__(this): + return "Modelica class " + '"' + this.GetModelicaClassString() + '"' + + # Public methods + def GetFiles(this): + return this.__files + + def GetModelicaClassString(this, includeVariables=False, source=None): + cmd = this.GetName() + + def numericSafe(x): + if(type(x) == float and x.is_integer()): + return int(x) + return x + + if(source is None): + source = this + + if(this.parameters or source.variables): + cmd = cmd + "(" + for key in this.parameters: + cmd = cmd + key + "=" + str(this.parameters[key]) + "," + for key in source.variables: + if(source.variables[key].start is None): + continue + if(re.match("der(.+?)", key)): # skip derivatives + continue + + cmd += key + "(start=" + str(numericSafe(source.variables[key].start)) + ")," + cmd = cmd[:-1] # remove last comma + cmd = cmd + ")" + + return cmd + + # Class functions + def Matches(name, files): + extension = os.path.splitext(files[0])[1] + + return extension == ".mo" diff --git a/PySimLib/Models/SimulinkModel.py b/PySimLib/Models/SimulinkModel.py index 8c0125e..355876d 100755 --- a/PySimLib/Models/SimulinkModel.py +++ b/PySimLib/Models/SimulinkModel.py @@ -20,28 +20,29 @@ along with this program. If not, see . """ -import os; +import os + +from PySimLib.Model import Model -from PySimLib.Model import Model; class SimulinkModel(Model): - #Constructor - def __init__(this, name, files): - Model.__init__(this, name, files); - - #Private members - this.__file = files[0]; - - #Magic methods - def __str__(this): - return "SimulinkModel(" + this.GetName() + ")"; - - #Public methods - def GetFile(this): - return this.__file; - - #Class functions - def Matches(name, files): - extension = os.path.splitext(files[0])[1]; - - return extension == ".mdl"; + # Constructor + def __init__(this, name, files): + Model.__init__(this, name, files) + + # Private members + this.__file = files[0] + + # Magic methods + def __str__(this): + return "SimulinkModel(" + this.GetName() + ")" + + # Public methods + def GetFile(this): + return this.__file + + # Class functions + def Matches(name, files): + extension = os.path.splitext(files[0])[1] + + return extension == ".mdl" diff --git a/PySimLib/Platform.py b/PySimLib/Platform.py index 78b2a78..5bd2aec 100644 --- a/PySimLib/Platform.py +++ b/PySimLib/Platform.py @@ -20,73 +20,79 @@ along with this program. If not, see . """ -#Global -from enum import Enum; -import os; -import subprocess; +# Global +from enum import Enum +import os +import subprocess + class Platform(Enum): - Windows = 1, - Linux = 2, - -#Interface functions -def Execute(args, blocking = True, workingDirectory = None): - import shlex; - from PySimLib import Log; - - #escape args - for arg in args: - arg = shlex.quote(arg); - - #execute - childProcess = subprocess.Popen(args, shell = False, stdout=Log.GetTarget(), stderr=Log.GetTarget(), cwd = workingDirectory); - if(blocking): - childProcess.wait(); - exitCode = childProcess.returncode; - else: - exitCode = None; - - #call program - #fullCmdLine = ' '.join(args); - #ret = subprocess.call(fullCmdLine, shell = False, stdout=Log_GetTarget(), stderr=Log_GetTarget()); - - return exitCode; - + Windows = 1, + Linux = 2, + +# Interface functions + + +def Execute(args, blocking=True, workingDirectory=None): + import shlex + from PySimLib import Log + + # escape args + for arg in args: + arg = shlex.quote(arg) + + # execute + childProcess = subprocess.Popen(args, shell=False, stdout=Log.GetTarget(), stderr=Log.GetTarget(), cwd=workingDirectory) + if(blocking): + childProcess.wait() + exitCode = childProcess.returncode + else: + exitCode = None + + # call program + #fullCmdLine = ' '.join(args); + #ret = subprocess.call(fullCmdLine, shell = False, stdout=Log_GetTarget(), stderr=Log_GetTarget()); + + return exitCode + + def GetConfigDirectory(): - if(GetPlatform() == Platform.Windows): - return os.environ['LOCALAPPDATA']; - - if(GetPlatform() == Platform.Linux): - return GetUserDirectory() + "/.config"; - - raise NotImplementedError("TODO: other platforms"); - + if(GetPlatform() == Platform.Windows): + return os.environ['LOCALAPPDATA'] + + if(GetPlatform() == Platform.Linux): + return GetUserDirectory() + "/.config" + + raise NotImplementedError("TODO: other platforms") + + def GetExeFileExtension(): - if(GetPlatform() == Platform.Windows): - return ".exe"; - - if(GetPlatform() == Platform.Linux): - return ""; - - raise NotImplementedError("TODO: other platforms"); - - + if(GetPlatform() == Platform.Windows): + return ".exe" + + if(GetPlatform() == Platform.Linux): + return "" + + raise NotImplementedError("TODO: other platforms") + + def GetPlatform(): - import platform; - - ident = platform.system(); - if(ident == "Windows"): - return Platform.Windows; - - if(ident == "Linux"): - return Platform.Linux; - - raise NotImplementedError("PySimLib is not implemented on the currently running platform, which is '" + ident + "'. Contact us for help."); - -def GetUserDirectory(): - if(GetPlatform() == Platform.Linux): - from os.path import expanduser; - - return expanduser("~"); - - raise NotImplementedError("TODO: other platforms"); + import platform + + ident = platform.system() + if(ident == "Windows"): + return Platform.Windows + + if(ident == "Linux"): + return Platform.Linux + + raise NotImplementedError("PySimLib is not implemented on the currently running platform, which is '" + ident + "'. Contact us for help.") + + +def GetUserDirectory(): + if(GetPlatform() == Platform.Linux): + from os.path import expanduser + + return expanduser("~") + + raise NotImplementedError("TODO: other platforms") diff --git a/PySimLib/Plot.py b/PySimLib/Plot.py index e089ef6..ad8e14e 100644 --- a/PySimLib/Plot.py +++ b/PySimLib/Plot.py @@ -20,38 +20,39 @@ along with this program. If not, see . """ -#Global -import pylab; +# Global +import pylab + class Plot: - #Static variables - __figureCounter = 1 - - #Constructor - def __init__(this): - this.__figureId = Plot.__figureCounter; - Plot.__figureCounter += 1; - - pylab.figure(this.__figureId); #create the figure - - #Public methods - def Add(this, x, y, color): - pylab.figure(this.__figureId); #make sure to work on correct figure - pylab.plot(x, y, color); - - def Save(this, fileName): - pylab.figure(this.__figureId); #make sure to work on correct figure - pylab.grid(1); - pylab.savefig(fileName); - - def SetXLabel(this, label): - pylab.figure(this.__figureId); #make sure to work on correct figure - pylab.xlabel(label); - - def SetYLabel(this, label): - pylab.figure(this.__figureId); #make sure to work on correct figure - pylab.ylabel(label); - - def Show(this): - pylab.figure(this.__figureId); #make sure to work on correct figure - pylab.show(); + # Static variables + __figureCounter = 1 + + # Constructor + def __init__(this): + this.__figureId = Plot.__figureCounter + Plot.__figureCounter += 1 + + pylab.figure(this.__figureId) # create the figure + + # Public methods + def Add(this, x, y, color): + pylab.figure(this.__figureId) # make sure to work on correct figure + pylab.plot(x, y, color) + + def Save(this, fileName): + pylab.figure(this.__figureId) # make sure to work on correct figure + pylab.grid(1) + pylab.savefig(fileName) + + def SetXLabel(this, label): + pylab.figure(this.__figureId) # make sure to work on correct figure + pylab.xlabel(label) + + def SetYLabel(this, label): + pylab.figure(this.__figureId) # make sure to work on correct figure + pylab.ylabel(label) + + def Show(this): + pylab.figure(this.__figureId) # make sure to work on correct figure + pylab.show() diff --git a/PySimLib/Simulation.py b/PySimLib/Simulation.py index dd9fd21..cc4c783 100644 --- a/PySimLib/Simulation.py +++ b/PySimLib/Simulation.py @@ -20,45 +20,46 @@ along with this program. If not, see . """ + class Simulation: - #Static variables - __simCounter = 0 - - #Constructor - def __init__(this, mdl, simNumber = None): - import copy; - - if(simNumber is None): - simNumber = Simulation.__simCounter; - - Simulation.__simCounter += 1; - - #Private members - this.__mdl = mdl; - this.__simNumber = simNumber; - - #Public members - this.startTime = mdl.startTime; - this.stopTime = mdl.stopTime; - this.solver = copy.deepcopy(mdl.solver); - this.variables = copy.deepcopy(mdl.variables); - - #Magic methods - def __str__(this): - result = "Simulation("; - result += "startTime: " + str(this.startTime) + ", "; - result += "stopTime: " + str(this.stopTime) + ", "; - result += "solver: " + str(this.solver) + ", "; - result += "vars: {"; - for var in this.variables: - result += "(" + str(var) + ", " + str(this.variables[var]) + ")"; - result += "})"; - - return result; - - #Public methods - def GetModel(this): - return this.__mdl; - - def GetSimNumber(this): - return this.__simNumber; + # Static variables + __simCounter = 0 + + # Constructor + def __init__(this, mdl, simNumber=None): + import copy + + if(simNumber is None): + simNumber = Simulation.__simCounter + + Simulation.__simCounter += 1 + + # Private members + this.__mdl = mdl + this.__simNumber = simNumber + + # Public members + this.startTime = mdl.startTime + this.stopTime = mdl.stopTime + this.solver = copy.deepcopy(mdl.solver) + this.variables = copy.deepcopy(mdl.variables) + + # Magic methods + def __str__(this): + result = "Simulation(" + result += "startTime: " + str(this.startTime) + ", " + result += "stopTime: " + str(this.stopTime) + ", " + result += "solver: " + str(this.solver) + ", " + result += "vars: {" + for var in this.variables: + result += "(" + str(var) + ", " + str(this.variables[var]) + ")" + result += "})" + + return result + + # Public methods + def GetModel(this): + return this.__mdl + + def GetSimNumber(this): + return this.__simNumber diff --git a/PySimLib/SimulationResult.py b/PySimLib/SimulationResult.py index 5928024..d29268c 100644 --- a/PySimLib/SimulationResult.py +++ b/PySimLib/SimulationResult.py @@ -21,7 +21,6 @@ """ - """ This class holds the values that a simulation generates. The values in the object are stored in a dictionary that maps each variable to a vector of values of this variable. @@ -36,28 +35,30 @@ Note: Also the simulation time should be present with the name "time" (CASE SENSITIVE). """ + + class SimulationResult: - #Constructor - #Args: - # values - Simulation result values in a form as illustrated above - def __init__(this, values): - this.__values = values; - - #Magic methods - def __getitem__(this, key): - return this.__values[key]; - - #Public methods - #Returns a datapoint of a trace of a variable - # - #Args: - # varName - variable trace to be read - # nTimesBack - number of time steps to move backwards in time (defaults to 0 meaning last available value) - def GetValue(this, varName, nTimestepsBack = 0): - datapoints = this.__values[varName]; - - return datapoints[len(datapoints) - 1 - nTimestepsBack]; - - #Returns the result dictionary - def GetValues(this): - return this.__values; + # Constructor + # Args: + # values - Simulation result values in a form as illustrated above + def __init__(this, values): + this.__values = values + + # Magic methods + def __getitem__(this, key): + return this.__values[key] + + # Public methods + # Returns a datapoint of a trace of a variable + # + # Args: + # varName - variable trace to be read + # nTimesBack - number of time steps to move backwards in time (defaults to 0 meaning last available value) + def GetValue(this, varName, nTimestepsBack=0): + datapoints = this.__values[varName] + + return datapoints[len(datapoints) - 1 - nTimestepsBack] + + # Returns the result dictionary + def GetValues(this): + return this.__values diff --git a/PySimLib/Solver.py b/PySimLib/Solver.py index 1d10c95..1a3567d 100755 --- a/PySimLib/Solver.py +++ b/PySimLib/Solver.py @@ -20,23 +20,24 @@ along with this program. If not, see . """ + class Solver: - #Constructor - def __init__(this): - #Public members - this.stepSize = 0; - this.tolerance = 1e-6; - - #Magic methods - def __str__(this): - return this.GetName() + "(stepSize: " + str(this.stepSize) + ", tolerance: " + str(this.tolerance) + ")"; - - #Abstract - def GetName(this): - raise NotImplementedError("The method Solver::GetName is abstract."); - - def GetDetailedName(this): - raise NotImplementedError("The method Solver::GetDetailedName is abstract."); - - def Matches(this, pattern): - raise NotImplementedError("The method Solver::Matches is abstract."); + # Constructor + def __init__(this): + # Public members + this.stepSize = 0 + this.tolerance = 1e-6 + + # Magic methods + def __str__(this): + return this.GetName() + "(stepSize: " + str(this.stepSize) + ", tolerance: " + str(this.tolerance) + ")" + + # Abstract + def GetName(this): + raise NotImplementedError("The method Solver::GetName is abstract.") + + def GetDetailedName(this): + raise NotImplementedError("The method Solver::GetDetailedName is abstract.") + + def Matches(this, pattern): + raise NotImplementedError("The method Solver::Matches is abstract.") diff --git a/PySimLib/Solvers/DASSL.py b/PySimLib/Solvers/DASSL.py index 0e23b3f..f013734 100755 --- a/PySimLib/Solvers/DASSL.py +++ b/PySimLib/Solvers/DASSL.py @@ -20,24 +20,25 @@ along with this program. If not, see . """ -from PySimLib.Solver import Solver; +from PySimLib.Solver import Solver + class DASSL(Solver): - #Constructor - def __init__(this): - Solver.__init__(this); - - #Public methods - def GetName(this): - return "DASSL"; - - def GetDetailedName(this): - return "Differential Algebraic System Solver"; - - def Matches(this, pattern): - pattern = pattern.lower(); - names = { - "dassl" #open modelica name - }; - - return pattern in names; + # Constructor + def __init__(this): + Solver.__init__(this) + + # Public methods + def GetName(this): + return "DASSL" + + def GetDetailedName(this): + return "Differential Algebraic System Solver" + + def Matches(this, pattern): + pattern = pattern.lower() + names = { + "dassl" # open modelica name + } + + return pattern in names diff --git a/PySimLib/Solvers/DEABM.py b/PySimLib/Solvers/DEABM.py index f34719b..7719540 100644 --- a/PySimLib/Solvers/DEABM.py +++ b/PySimLib/Solvers/DEABM.py @@ -20,24 +20,25 @@ along with this program. If not, see . """ -from PySimLib.Solver import Solver; +from PySimLib.Solver import Solver + class DEABM(Solver): - #Constructor - def __init__(this): - Solver.__init__(this); - - #Public methods - def GetName(this): - return "DEABM"; - - def GetDetailedName(this): - return "DEABM"; #nobody seems to know what it means... the last three letters could mean Adams-Bashforth-Moulton or Adams-Bashforth-Method - - def Matches(this, pattern): - pattern = pattern.lower(); - names = { - "deabm" #dymola name - }; - - return pattern in names; + # Constructor + def __init__(this): + Solver.__init__(this) + + # Public methods + def GetName(this): + return "DEABM" + + def GetDetailedName(this): + return "DEABM" # nobody seems to know what it means... the last three letters could mean Adams-Bashforth-Moulton or Adams-Bashforth-Method + + def Matches(this, pattern): + pattern = pattern.lower() + names = { + "deabm" # dymola name + } + + return pattern in names diff --git a/PySimLib/Solvers/LSODAR.py b/PySimLib/Solvers/LSODAR.py index d7c3c8f..8b84fa0 100644 --- a/PySimLib/Solvers/LSODAR.py +++ b/PySimLib/Solvers/LSODAR.py @@ -20,24 +20,25 @@ along with this program. If not, see . """ -from PySimLib.Solver import Solver; +from PySimLib.Solver import Solver + class LSODAR(Solver): - #Constructor - def __init__(this): - Solver.__init__(this); - - #Public methods - def GetName(this): - return "LSodar"; - - def GetDetailedName(this): - return "Livermore Solver for Ordinary Differential equations, with Automatic method switching for stiff and nonstiff problems, and with Root-finding"; - - def Matches(this, pattern): - pattern = pattern.lower(); - names = { - "lsodar" #dymola name - }; - - return pattern in names; + # Constructor + def __init__(this): + Solver.__init__(this) + + # Public methods + def GetName(this): + return "LSodar" + + def GetDetailedName(this): + return "Livermore Solver for Ordinary Differential equations, with Automatic method switching for stiff and nonstiff problems, and with Root-finding" + + def Matches(this, pattern): + pattern = pattern.lower() + names = { + "lsodar" # dymola name + } + + return pattern in names diff --git a/PySimLib/Tool.py b/PySimLib/Tool.py index 896c030..1b284ea 100755 --- a/PySimLib/Tool.py +++ b/PySimLib/Tool.py @@ -20,76 +20,77 @@ along with this program. If not, see . """ -import os; +import os + class Tool: - #Constructor - def __init__(this): - pass - - #Magic methods - def __str__(this): - return this.GetName(); - - #Protected methods - def _DeleteFile(this, fileName): - if(os.path.isfile(fileName)): - os.remove(fileName); - - def _DirExists(this, dirPath): - return os.path.isdir(dirPath); - - def _EnsureOutputFolderExists(this, mdl): - if(not this._DirExists(mdl.outputDir)): - os.makedirs(mdl.outputDir); - - def _EnsureResultFolderExists(this, mdl): - if(not this._DirExists(mdl.resultDir)): - os.makedirs(mdl.resultDir); - - def _FileExists(this, fileName): - return os.path.isfile(fileName); - - def _RenameFile(this, fromName, toName): - if(not (os.path.abspath(fromName) == os.path.abspath(toName))): - this._DeleteFile(toName); - os.rename(fromName, toName); - - def _SetDerivedValuesFromSimulationResults(this, sim, resultDict): - mdl = sim.GetModel(); - - #set final values - for key in resultDict: - if(key in sim.variables): - f = resultDict[key][-1]; - sim.variables[key].final = f; - mdl.variables[key].final = f; - - #Abstract - def Accepts(this, mdl): - raise NotImplementedError("The method Tool::Accepts is abstract."); - - def Close(this): - raise NotImplementedError("The method Tool::Close is abstract."); - - def Compile(this, mdl): - raise NotImplementedError("The method Tool::Compile is abstract."); - - def GetCompatibleSolvers(this): - raise NotImplementedError("The method Tool::GetCompatibleSolvers is abstract."); - - def GetDefaultSolver(this): - raise NotImplementedError("The method Tool::GetDefaultSolver is abstract."); - - def GetName(this): - raise NotImplementedError("The method Tool::GetName is abstract."); - - def ReadInit(this, mdl): - raise NotImplementedError("The method Tool::ReadInit is abstract."); - - def Simulate(this, sim): - raise NotImplementedError("The method Tool::Simulate is abstract."); - - #Abstract Functions - def IsAvailable(): - raise NotImplementedError("The function Tool::IsAvailable is abstract."); + # Constructor + def __init__(this): + pass + + # Magic methods + def __str__(this): + return this.GetName() + + # Protected methods + def _DeleteFile(this, fileName): + if(os.path.isfile(fileName)): + os.remove(fileName) + + def _DirExists(this, dirPath): + return os.path.isdir(dirPath) + + def _EnsureOutputFolderExists(this, mdl): + if(not this._DirExists(mdl.outputDir)): + os.makedirs(mdl.outputDir) + + def _EnsureResultFolderExists(this, mdl): + if(not this._DirExists(mdl.resultDir)): + os.makedirs(mdl.resultDir) + + def _FileExists(this, fileName): + return os.path.isfile(fileName) + + def _RenameFile(this, fromName, toName): + if(not (os.path.abspath(fromName) == os.path.abspath(toName))): + this._DeleteFile(toName) + os.rename(fromName, toName) + + def _SetDerivedValuesFromSimulationResults(this, sim, resultDict): + mdl = sim.GetModel() + + # set final values + for key in resultDict: + if(key in sim.variables): + f = resultDict[key][-1] + sim.variables[key].final = f + mdl.variables[key].final = f + + # Abstract + def Accepts(this, mdl): + raise NotImplementedError("The method Tool::Accepts is abstract.") + + def Close(this): + raise NotImplementedError("The method Tool::Close is abstract.") + + def Compile(this, mdl): + raise NotImplementedError("The method Tool::Compile is abstract.") + + def GetCompatibleSolvers(this): + raise NotImplementedError("The method Tool::GetCompatibleSolvers is abstract.") + + def GetDefaultSolver(this): + raise NotImplementedError("The method Tool::GetDefaultSolver is abstract.") + + def GetName(this): + raise NotImplementedError("The method Tool::GetName is abstract.") + + def ReadInit(this, mdl): + raise NotImplementedError("The method Tool::ReadInit is abstract.") + + def Simulate(this, sim): + raise NotImplementedError("The method Tool::Simulate is abstract.") + + # Abstract Functions + def IsAvailable(): + raise NotImplementedError("The function Tool::IsAvailable is abstract.") diff --git a/PySimLib/Tools/Dymola.py b/PySimLib/Tools/Dymola.py index d5780c0..9da9613 100644 --- a/PySimLib/Tools/Dymola.py +++ b/PySimLib/Tools/Dymola.py @@ -20,320 +20,321 @@ along with this program. If not, see . """ -#Local -from PySimLib import Log, Platform; -from PySimLib.Config import *; -from PySimLib.Mat.Mat import Mat; -from PySimLib.Tools.ModelicaTool import ModelicaTool; +# Local +from PySimLib import Log, Platform +from PySimLib.Config import * +from PySimLib.Mat.Mat import Mat +from PySimLib.Tools.ModelicaTool import ModelicaTool + class Dymola(ModelicaTool): - #Static class members - __dymolaIsOpen = False; - __ddeServer = None; - __ddeConversation = None; - __openFiles = {}; - - __solverMap = { - 'deabm' : 1, - 'lsodar' : 4, - 'dassl' : 8 - #TODO THE REST - }; - - #Constructor - def __init__(this): - ModelicaTool.__init__(this); - - if(GetBoolConfigValue("Dymola", "SimByExe") == False): - print("Warning: You're using Dymola with a reduced feature set. Models may won't be simulated altough they're working directly in Dymola (independent of PySimLib). Please make sure you've read and understood section 2.6.4 of the PySimLib user Guide - specifically the part about the 'SimByExe' flag."); - - #Private methods - def __CheckIfModelIsCompiled(this, mdl): - from PySimLib.Exceptions.UncompiledModelException import UncompiledModelException; - - #check if model is compiled - if(not this._FileExists(this.__GetExeFilePath(mdl))): - raise UncompiledModelException(mdl, this); - - def __DeleteUnnecessaryFiles(this): - this._DeleteFile("alistlog.txt"); - this._DeleteFile("buildlog.txt"); - this._DeleteFile("dsfinal.txt"); - this._DeleteFile("dsin.txt"); - this._DeleteFile("dslog.txt"); - this._DeleteFile("dsmodel.c"); - this._DeleteFile("dymosim.exe"); - this._DeleteFile("dymosim.exp"); - this._DeleteFile("dymosim.lib"); - - def __EnsureDymolaIsOpen(this): - if(not Dymola.__dymolaIsOpen): - import win32ui; - import dde; - import time; - from PySimLib import Platform; - - Dymola.__ddeServer = dde.CreateServer(); - Dymola.__ddeServer.Create("TestClient"); - Dymola.__ddeConversation = dde.CreateConversation(Dymola.__ddeServer); - Dymola.__dymolaIsOpen = True; - - Platform.Execute([GetConfigValue("Dymola", "PathExe")], False); - time.sleep(float(GetConfigValue("Dymola", "StartupDelay"))); - Dymola.__ddeConversation.ConnectTo("dymola", " "); - Dymola.__ddeConversation.Exec("OutputCPUtime:=true;"); - - def __GetExeFilePath(this, mdl): - from PySimLib import Platform; - - return mdl.outputDir + os.sep + mdl.outputName + Platform.GetExeFileExtension(); - - def __GetInitFilePath(this, mdl): - return mdl.outputDir + os.sep + mdl.outputName + "_in.mat"; - - def __GetSimInitFilePath(this, sim): - mdl = sim.GetModel(); - return mdl.simDir + os.sep + str(sim.GetSimNumber()) + "_in.mat"; - - def __MapSolver(this, solver): - for key in Dymola.__solverMap: - if(solver.Matches(key)): - return Dymola.__solverMap[key]; - - raise Exception("Illegal solver '" + str(solverNumber) + "'"); - - def __OpenFile(this, mdl, fileName): - path = mdl.simDir + os.sep + fileName; - path = path.replace('\\', '/'); - - if(path not in Dymola.__openFiles): - Dymola.__ddeConversation.Exec("openModel(\"" + path + "\")"); - Dymola.__openFiles[path] = True; - - def __ReadVarsFromMat(this, names, values, varTypeFilter): - from PySimLib.VariableDescriptor import VariableDescriptor; - - result = {}; - - for i in range(0, names.GetNumberOfStrings()): - if(values.GetValue(4, i) in varTypeFilter): - varDesc = VariableDescriptor(); - varDesc.start = values.GetValue(1, i); - result[names.GetString(i)] = varDesc; - - return result; - - def __ReverseMapSolver(this, solverNumber): - from PySimLib import FindSolver; - - solverNumber = int(solverNumber); - for key in Dymola.__solverMap: - if(Dymola.__solverMap[key] == solverNumber): - return FindSolver(key); - - raise Exception("Illegal solver number '" + str(solverNumber) + "'"); - - def __WriteInit(this, sim): - from PySimLib.Mat.OutputStream import OutputStream; - from PySimLib.Mat.MatrixTypeEvaluator import TYPE_INT32; - - mdl = sim.GetModel(); - - mat = Mat(); - mat.Load(this.__GetInitFilePath(mdl)); - - #set experiment values - experiment = mat.GetMatrix("experiment"); - experiment.SetValue(0, 0, sim.startTime); - experiment.SetValue(0, 1, sim.stopTime); - experiment.SetValue(0, 4, sim.solver.tolerance); - experiment.SetValue(0, 6, this.__MapSolver(sim.solver)); - #TODO: STEPSIZE - - #set variable start values - names = mat.GetMatrix("initialName"); - values = mat.GetMatrix("initialValue"); - for i in range(0, names.GetNumberOfStrings()): - name = names.GetString(i); - - if(name not in sim.variables): - continue; - - if(sim.variables[name].start is None): - value = sim.vars[name].start; - values.SetValue(1, i, value); - - #write output - file = open(this.__GetSimInitFilePath(sim), "wb"); - stream = OutputStream(file); - #mat.Write(stream); - - #we need to set precision values for the matrices or dymola wont accept the input - settings = mat.GetMatrix("settings"); - - settings.SetDesiredOutputPrecision(TYPE_INT32); - - mat.GetMatrix("initialDescription").SetString(0, "Dymola"); - - #we need to write the matrices in the exact order or dymola can't read the file - mat.GetMatrix("Aclass").Write("Aclass", stream); - mat.GetMatrix("experiment").Write("experiment", stream); - mat.GetMatrix("method").Write("method", stream); - settings.Write("settings", stream); - mat.GetMatrix("initialName").Write("initialName", stream); - mat.GetMatrix("initialValue").Write("initialValue", stream); - mat.GetMatrix("initialDescription").Write("initialDescription", stream); - - file.close(); - - #Public methods - def Close(this): - if(Dymola.__ddeConversation is not None): - Dymola.__ddeConversation.Exec("exit();"); - Dymola.__ddeConversation = None; - - def Compile(this, mdl): - from PySimLib import Platform; - - this.__EnsureDymolaIsOpen(); - - #open all needed mo files - for x in mdl.GetFiles(): - this.__OpenFile(mdl, x); - - #go to sim dir - Dymola.__ddeConversation.Exec("cd(\"" + mdl.simDir.replace('\\', '/') + "\")"); - - #simulate to run model - Dymola.__ddeConversation.Exec("translateModel(\"" + mdl.GetModelicaClassString() + "\")"); - #Dymola.__ddeConversation.Exec("simulateModel(\"" + mdl.GetModelicaClassString() + "\", stopTime=0)"); #method=\"" + this.solver.name + "\" - - this._EnsureOutputFolderExists(mdl); - - #Convert the dsin - args = [ - GetConfigValue("Dymola", "PathAlist"), - "-b", - mdl.simDir + os.sep + "dsin.txt", - this.__GetInitFilePath(mdl) - ]; - Platform.Execute(args); - - #this._DeleteFile("dsres.mat"); - - #Rename important files - this._RenameFile("dymosim" + Platform.GetExeFileExtension(), this.__GetExeFilePath(mdl)); - - this.__DeleteUnnecessaryFiles(); - - def GetCompatibleSolvers(this): - from PySimLib import FindSolver; - - solvers = []; - - for key in Dymola.__solverMap: - solvers.append(FindSolver(key)); - - return solvers; - - def GetName(this): - return "Dymola"; - - def ReadInit(this, mdl): - this.__CheckIfModelIsCompiled(mdl); - - initMat = Mat(); - initMat.Load(this.__GetInitFilePath(mdl)); - - #read parameters - varTypeFilter = { - 1, #parameters - }; - - parameters = this.__ReadVarsFromMat(initMat.GetMatrix("initialName"), initMat.GetMatrix("initialValue"), varTypeFilter); - for name in parameters: - mdl.parameters[name] = parameters[name].start; - - #read variables - varTypeFilter = { - 2, #state variable - 6, #auxiliary variable - }; - - mdl.variables = this.__ReadVarsFromMat(initMat.GetMatrix("initialName"), initMat.GetMatrix("initialValue"), varTypeFilter); - - #read experiment values - experiment = initMat.GetMatrix("experiment"); - mdl.startTime = experiment.GetValue(0, 0); - mdl.stopTime = experiment.GetValue(0, 1); - mdl.solver = this.__ReverseMapSolver(experiment.GetValue(0, 6)); - #sim.solver.stepSize = TODO: ??? - mdl.solver.tolerance = experiment.GetValue(0, 4); - - def Simulate(this, sim): - mdl = sim.GetModel(); - - #paths - dsinPaths = mdl.simDir + os.sep + "dsin.txt"; - - #error checks - this.__CheckIfModelIsCompiled(mdl); - - this._EnsureResultFolderExists(mdl); - - #prepare init file - this.__WriteInit(sim); - - #simulate - if(GetBoolConfigValue("Dymola", "SimByExe")): - from PySimLib import Log, Platform; - - args = [this.__GetExeFilePath(mdl), this.__GetSimInitFilePath(sim)]; - Platform.Execute(args, True, mdl.simDir); - else: - from PySimLib import Log, Platform; - #convert back to dsin - args = [ - GetConfigValue("Dymola", "PathAlist"), - "-a", - this.__GetSimInitFilePath(sim), - dsinPaths - ]; - #Platform.Execute(args); - - #load simulation config --- apparently not working like this - #Dymola.__ddeConversation.Exec("importInitial(\"" + this.__GetSimInitFilePath(sim).replace('\\', '/') + "\")"); - - #run - this.__EnsureDymolaIsOpen(); - Dymola.__ddeConversation.Exec("simulateModel(\"" + mdl.GetModelicaClassString(True, sim) + "\", startTime=" + str(sim.startTime) + ", stopTime=" + str(sim.stopTime) + ", method=\"" + str(sim.solver.GetName()) + "\", tolerance=" + str(sim.solver.tolerance) + ")"); - - #we always need to close the model, so that dymola recompiles it - Dymola.__ddeConversation.Exec("closeModel();"); - - #delete dsin - this._DeleteFile(dsinPaths); - - failed = False; - if(this._FileExists("failure")): - failed = True; - - #keep things clean - #this._DeleteFile("status"); - #this._DeleteFile("success"); - #this._DeleteFile("failure"); - - if(failed): - this._DeleteFile("dsres.mat"); - raise SimulationFailedException(); - - this._DeleteFile(this.__GetSimInitFilePath(sim)); - - #rename results - this._RenameFile(mdl.simDir + os.sep + "dsres.mat", this._GetSimResultFilePath(sim)); - - this.__DeleteUnnecessaryFiles(); - - #Class functions - def IsAvailable(): - return HasConfigValue("Dymola", "PathExe") and HasConfigValue("Dymola", "StartupDelay") and HasConfigValue("Dymola", "PathAlist") and HasConfigValue("Dymola", "SimByExe"); + # Static class members + __dymolaIsOpen = False + __ddeServer = None + __ddeConversation = None + __openFiles = {} + + __solverMap = { + 'deabm': 1, + 'lsodar': 4, + 'dassl': 8 + # TODO THE REST + } + + # Constructor + def __init__(this): + ModelicaTool.__init__(this) + + if(GetBoolConfigValue("Dymola", "SimByExe") == False): + print("Warning: You're using Dymola with a reduced feature set. Models may won't be simulated altough they're working directly in Dymola (independent of PySimLib). Please make sure you've read and understood section 2.6.4 of the PySimLib user Guide - specifically the part about the 'SimByExe' flag.") + + # Private methods + def __CheckIfModelIsCompiled(this, mdl): + from PySimLib.Exceptions.UncompiledModelException import UncompiledModelException + + # check if model is compiled + if(not this._FileExists(this.__GetExeFilePath(mdl))): + raise UncompiledModelException(mdl, this) + + def __DeleteUnnecessaryFiles(this): + this._DeleteFile("alistlog.txt") + this._DeleteFile("buildlog.txt") + this._DeleteFile("dsfinal.txt") + this._DeleteFile("dsin.txt") + this._DeleteFile("dslog.txt") + this._DeleteFile("dsmodel.c") + this._DeleteFile("dymosim.exe") + this._DeleteFile("dymosim.exp") + this._DeleteFile("dymosim.lib") + + def __EnsureDymolaIsOpen(this): + if(not Dymola.__dymolaIsOpen): + import win32ui + import dde + import time + from PySimLib import Platform + + Dymola.__ddeServer = dde.CreateServer() + Dymola.__ddeServer.Create("TestClient") + Dymola.__ddeConversation = dde.CreateConversation(Dymola.__ddeServer) + Dymola.__dymolaIsOpen = True + + Platform.Execute([GetConfigValue("Dymola", "PathExe")], False) + time.sleep(float(GetConfigValue("Dymola", "StartupDelay"))) + Dymola.__ddeConversation.ConnectTo("dymola", " ") + Dymola.__ddeConversation.Exec("OutputCPUtime:=true;") + + def __GetExeFilePath(this, mdl): + from PySimLib import Platform + + return mdl.outputDir + os.sep + mdl.outputName + Platform.GetExeFileExtension() + + def __GetInitFilePath(this, mdl): + return mdl.outputDir + os.sep + mdl.outputName + "_in.mat" + + def __GetSimInitFilePath(this, sim): + mdl = sim.GetModel() + return mdl.simDir + os.sep + str(sim.GetSimNumber()) + "_in.mat" + + def __MapSolver(this, solver): + for key in Dymola.__solverMap: + if(solver.Matches(key)): + return Dymola.__solverMap[key] + + raise Exception("Illegal solver '" + str(solverNumber) + "'") + + def __OpenFile(this, mdl, fileName): + path = mdl.simDir + os.sep + fileName + path = path.replace('\\', '/') + + if(path not in Dymola.__openFiles): + Dymola.__ddeConversation.Exec("openModel(\"" + path + "\")") + Dymola.__openFiles[path] = True + + def __ReadVarsFromMat(this, names, values, varTypeFilter): + from PySimLib.VariableDescriptor import VariableDescriptor + + result = {} + + for i in range(0, names.GetNumberOfStrings()): + if(values.GetValue(4, i) in varTypeFilter): + varDesc = VariableDescriptor() + varDesc.start = values.GetValue(1, i) + result[names.GetString(i)] = varDesc + + return result + + def __ReverseMapSolver(this, solverNumber): + from PySimLib import FindSolver + + solverNumber = int(solverNumber) + for key in Dymola.__solverMap: + if(Dymola.__solverMap[key] == solverNumber): + return FindSolver(key) + + raise Exception("Illegal solver number '" + str(solverNumber) + "'") + + def __WriteInit(this, sim): + from PySimLib.Mat.OutputStream import OutputStream + from PySimLib.Mat.MatrixTypeEvaluator import TYPE_INT32 + + mdl = sim.GetModel() + + mat = Mat() + mat.Load(this.__GetInitFilePath(mdl)) + + # set experiment values + experiment = mat.GetMatrix("experiment") + experiment.SetValue(0, 0, sim.startTime) + experiment.SetValue(0, 1, sim.stopTime) + experiment.SetValue(0, 4, sim.solver.tolerance) + experiment.SetValue(0, 6, this.__MapSolver(sim.solver)) + # TODO: STEPSIZE + + # set variable start values + names = mat.GetMatrix("initialName") + values = mat.GetMatrix("initialValue") + for i in range(0, names.GetNumberOfStrings()): + name = names.GetString(i) + + if(name not in sim.variables): + continue + + if(sim.variables[name].start is None): + value = sim.vars[name].start + values.SetValue(1, i, value) + + # write output + file = open(this.__GetSimInitFilePath(sim), "wb") + stream = OutputStream(file) + # mat.Write(stream); + + # we need to set precision values for the matrices or dymola wont accept the input + settings = mat.GetMatrix("settings") + + settings.SetDesiredOutputPrecision(TYPE_INT32) + + mat.GetMatrix("initialDescription").SetString(0, "Dymola") + + # we need to write the matrices in the exact order or dymola can't read the file + mat.GetMatrix("Aclass").Write("Aclass", stream) + mat.GetMatrix("experiment").Write("experiment", stream) + mat.GetMatrix("method").Write("method", stream) + settings.Write("settings", stream) + mat.GetMatrix("initialName").Write("initialName", stream) + mat.GetMatrix("initialValue").Write("initialValue", stream) + mat.GetMatrix("initialDescription").Write("initialDescription", stream) + + file.close() + + # Public methods + def Close(this): + if(Dymola.__ddeConversation is not None): + Dymola.__ddeConversation.Exec("exit();") + Dymola.__ddeConversation = None + + def Compile(this, mdl): + from PySimLib import Platform + + this.__EnsureDymolaIsOpen() + + # open all needed mo files + for x in mdl.GetFiles(): + this.__OpenFile(mdl, x) + + # go to sim dir + Dymola.__ddeConversation.Exec("cd(\"" + mdl.simDir.replace('\\', '/') + "\")") + + # simulate to run model + Dymola.__ddeConversation.Exec("translateModel(\"" + mdl.GetModelicaClassString() + "\")") + # Dymola.__ddeConversation.Exec("simulateModel(\"" + mdl.GetModelicaClassString() + "\", stopTime=0)"); #method=\"" + this.solver.name + "\" + + this._EnsureOutputFolderExists(mdl) + + # Convert the dsin + args = [ + GetConfigValue("Dymola", "PathAlist"), + "-b", + mdl.simDir + os.sep + "dsin.txt", + this.__GetInitFilePath(mdl) + ] + Platform.Execute(args) + + # this._DeleteFile("dsres.mat"); + + # Rename important files + this._RenameFile("dymosim" + Platform.GetExeFileExtension(), this.__GetExeFilePath(mdl)) + + this.__DeleteUnnecessaryFiles() + + def GetCompatibleSolvers(this): + from PySimLib import FindSolver + + solvers = [] + + for key in Dymola.__solverMap: + solvers.append(FindSolver(key)) + + return solvers + + def GetName(this): + return "Dymola" + + def ReadInit(this, mdl): + this.__CheckIfModelIsCompiled(mdl) + + initMat = Mat() + initMat.Load(this.__GetInitFilePath(mdl)) + + # read parameters + varTypeFilter = { + 1, # parameters + } + + parameters = this.__ReadVarsFromMat(initMat.GetMatrix("initialName"), initMat.GetMatrix("initialValue"), varTypeFilter) + for name in parameters: + mdl.parameters[name] = parameters[name].start + + # read variables + varTypeFilter = { + 2, # state variable + 6, # auxiliary variable + } + + mdl.variables = this.__ReadVarsFromMat(initMat.GetMatrix("initialName"), initMat.GetMatrix("initialValue"), varTypeFilter) + + # read experiment values + experiment = initMat.GetMatrix("experiment") + mdl.startTime = experiment.GetValue(0, 0) + mdl.stopTime = experiment.GetValue(0, 1) + mdl.solver = this.__ReverseMapSolver(experiment.GetValue(0, 6)) + # sim.solver.stepSize = TODO: ??? + mdl.solver.tolerance = experiment.GetValue(0, 4) + + def Simulate(this, sim): + mdl = sim.GetModel() + + # paths + dsinPaths = mdl.simDir + os.sep + "dsin.txt" + + # error checks + this.__CheckIfModelIsCompiled(mdl) + + this._EnsureResultFolderExists(mdl) + + # prepare init file + this.__WriteInit(sim) + + # simulate + if(GetBoolConfigValue("Dymola", "SimByExe")): + from PySimLib import Log, Platform + + args = [this.__GetExeFilePath(mdl), this.__GetSimInitFilePath(sim)] + Platform.Execute(args, True, mdl.simDir) + else: + from PySimLib import Log, Platform + # convert back to dsin + args = [ + GetConfigValue("Dymola", "PathAlist"), + "-a", + this.__GetSimInitFilePath(sim), + dsinPaths + ] + # Platform.Execute(args); + + # load simulation config --- apparently not working like this + #Dymola.__ddeConversation.Exec("importInitial(\"" + this.__GetSimInitFilePath(sim).replace('\\', '/') + "\")"); + + # run + this.__EnsureDymolaIsOpen() + Dymola.__ddeConversation.Exec("simulateModel(\"" + mdl.GetModelicaClassString(True, sim) + "\", startTime=" + str(sim.startTime) + ", stopTime=" + str(sim.stopTime) + ", method=\"" + str(sim.solver.GetName()) + "\", tolerance=" + str(sim.solver.tolerance) + ")") + + # we always need to close the model, so that dymola recompiles it + Dymola.__ddeConversation.Exec("closeModel();") + + # delete dsin + this._DeleteFile(dsinPaths) + + failed = False + if(this._FileExists("failure")): + failed = True + + # keep things clean + # this._DeleteFile("status"); + # this._DeleteFile("success"); + # this._DeleteFile("failure"); + + if(failed): + this._DeleteFile("dsres.mat") + raise SimulationFailedException() + + this._DeleteFile(this.__GetSimInitFilePath(sim)) + + # rename results + this._RenameFile(mdl.simDir + os.sep + "dsres.mat", this._GetSimResultFilePath(sim)) + + this.__DeleteUnnecessaryFiles() + + # Class functions + def IsAvailable(): + return HasConfigValue("Dymola", "PathExe") and HasConfigValue("Dymola", "StartupDelay") and HasConfigValue("Dymola", "PathAlist") and HasConfigValue("Dymola", "SimByExe") diff --git a/PySimLib/Tools/ModelicaTool.py b/PySimLib/Tools/ModelicaTool.py index ac7d114..4904f6d 100644 --- a/PySimLib/Tools/ModelicaTool.py +++ b/PySimLib/Tools/ModelicaTool.py @@ -20,67 +20,68 @@ along with this program. If not, see . """ -#Global -import os; -#Local -from PySimLib.Tool import Tool; +# Global +import os +# Local +from PySimLib.Tool import Tool + class ModelicaTool(Tool): - #Protected methods - def _GetSimResultFilePath(this, sim): - mdl = sim.GetModel(); - - return mdl.resultDir + os.sep + str(sim.GetSimNumber()) + "_" + mdl.outputName + ".mat"; - - #Public methods - def Accepts(this, mdl): - from PySimLib.Models.ModelicaModel import ModelicaModel; - - return isinstance(mdl, ModelicaModel); - - def GetDefaultSolver(this): - from PySimLib import FindSolver; - - return FindSolver("dassl"); - - def ReadResult(this, sim): - from PySimLib.Mat.Mat import Mat; - from PySimLib.SimulationResult import SimulationResult; - - mdl = sim.GetModel(); - - result = {}; - m_res = Mat(); - m_res.Load(this._GetSimResultFilePath(sim)); - - #dsres matrices are all transposed-.- - names = m_res.GetMatrix("name"); - names.Transpose(); - dataInfo = m_res.GetMatrix("dataInfo"); - dataInfo.Transpose(); - - for i in range(0, names.GetNumberOfStrings()): - if(i == 0 and dataInfo.GetValue(0, i) == 0): - dataMatrixIndex = 2; #hm... this is not necessarily the case... we need the biggest abscissa - else: - dataMatrixIndex = dataInfo.GetValue(0, i); - dataMatrix = m_res.GetMatrix("data_" + str(dataMatrixIndex)); - k = dataInfo.GetValue(1, i); - col = abs(k)-1; - if(k > 0): - sign = 1; - else: - sign = -1; - - currentVar = []; - for j in range(0, dataMatrix.GetNumberOfColumns()): - currentVar.append(sign * dataMatrix.GetValue(j, col)); - - if(names.GetString(i) == "Time"): - result["time"] = currentVar; - else: - result[names.GetString(i)] = currentVar; - - this._SetDerivedValuesFromSimulationResults(sim, result); - - return SimulationResult(result); + # Protected methods + def _GetSimResultFilePath(this, sim): + mdl = sim.GetModel() + + return mdl.resultDir + os.sep + str(sim.GetSimNumber()) + "_" + mdl.outputName + ".mat" + + # Public methods + def Accepts(this, mdl): + from PySimLib.Models.ModelicaModel import ModelicaModel + + return isinstance(mdl, ModelicaModel) + + def GetDefaultSolver(this): + from PySimLib import FindSolver + + return FindSolver("dassl") + + def ReadResult(this, sim): + from PySimLib.Mat.Mat import Mat + from PySimLib.SimulationResult import SimulationResult + + mdl = sim.GetModel() + + result = {} + m_res = Mat() + m_res.Load(this._GetSimResultFilePath(sim)) + + # dsres matrices are all transposed-.- + names = m_res.GetMatrix("name") + names.Transpose() + dataInfo = m_res.GetMatrix("dataInfo") + dataInfo.Transpose() + + for i in range(0, names.GetNumberOfStrings()): + if(i == 0 and dataInfo.GetValue(0, i) == 0): + dataMatrixIndex = 2 # hm... this is not necessarily the case... we need the biggest abscissa + else: + dataMatrixIndex = dataInfo.GetValue(0, i) + dataMatrix = m_res.GetMatrix("data_" + str(dataMatrixIndex)) + k = dataInfo.GetValue(1, i) + col = abs(k) - 1 + if(k > 0): + sign = 1 + else: + sign = -1 + + currentVar = [] + for j in range(0, dataMatrix.GetNumberOfColumns()): + currentVar.append(sign * dataMatrix.GetValue(j, col)) + + if(names.GetString(i) == "Time"): + result["time"] = currentVar + else: + result[names.GetString(i)] = currentVar + + this._SetDerivedValuesFromSimulationResults(sim, result) + + return SimulationResult(result) diff --git a/PySimLib/Tools/OpenModelica.py b/PySimLib/Tools/OpenModelica.py index df4ddb1..0500ca1 100644 --- a/PySimLib/Tools/OpenModelica.py +++ b/PySimLib/Tools/OpenModelica.py @@ -20,327 +20,328 @@ along with this program. If not, see . """ -#Global -import shutil; -import os; -import xml.dom.minidom; -#Local -from PySimLib.Config import *; -from PySimLib import Log, Platform; -from PySimLib.Tools.ModelicaTool import ModelicaTool; +# Global +import shutil +import os +import xml.dom.minidom +# Local +from PySimLib.Config import * +from PySimLib import Log, Platform +from PySimLib.Tools.ModelicaTool import ModelicaTool + class OpenModelica(ModelicaTool): - #Private methods - def __AssertModelCompiled(this, mdl): - from PySimLib.Exceptions.UncompiledModelException import UncompiledModelException; - - if(not this._FileExists(this.__GetInitFilePath(mdl))): - raise UncompiledModelException(mdl, this); - - def __FindValueFromXMLVar(this, var): - from PySimLib.VariableDescriptor import VariableDescriptor; - store = False; - - varName = var.getAttribute("name"); - #if(var.getAttribute("isValueChangeable") == "false"): - #return None; - - for node in var.childNodes: #find the value - if(node.nodeType == xml.dom.Node.ELEMENT_NODE): - varDesc = VariableDescriptor(); - - if(node.getAttribute("useStart") == "true"): - start = node.getAttribute("start"); - if(start == ""): - varDesc.start = 0; - elif(start == "true"): - varDesc.start = True; - elif(start == "false"): - varDesc.start = False; - else: - varDesc.start = float(start); - else: - varDesc.start = None; - - return varName, varDesc; - - return None; - - def __GetExeFilePath(this, mdl): - return mdl.outputDir + os.sep + mdl.outputName + Platform.GetExeFileExtension(); - - def __GetInfoFilePath(this, mdl): - return mdl.outputDir + os.sep + mdl.outputName + "_info.json"; - - def __GetInitFilePath(this, mdl): - return mdl.outputDir + os.sep + mdl.outputName + "_init.xml"; - - def __GetInitFileXML(this, mdl): - this.__AssertModelCompiled(mdl); - - return xml.dom.minidom.parse(this.__GetInitFilePath(mdl)); - - def __GetSimInitFilePath(this, sim): - mdl = sim.GetModel(); - - return mdl.simDir + os.sep + str(sim.GetSimNumber()) + ".xml"; - - def __GetSolverString(this, solver): - if(solver.Matches("dassl")): - return "dassl"; - - raise NotImplementedError("OpenModelica::__GetSolverString"); - - def __ReadVarsFromXML(this, mv, classTypeFilter): - result = {}; - - for var in mv.childNodes: - if(var.nodeType == xml.dom.Node.ELEMENT_NODE): - if(var.getAttribute("classType") in classTypeFilter): - nameAndValue = this.__FindValueFromXMLVar(var); - - if(not(nameAndValue is None)): - varName, value = nameAndValue; - result[varName] = value; - - return result; - - def __WriteInit(this, sim): - mdl = sim.GetModel(); - - initDom = this.__GetInitFileXML(mdl); - mv = initDom.getElementsByTagName("ModelVariables")[0]; - de = initDom.getElementsByTagName("DefaultExperiment")[0]; - - if(sim.solver.stepSize == 0): - sim.solver.stepSize = 1e-6; #this is bad... but else OM simulates endlessly - - #Set experiment values - de.setAttribute("startTime", str(sim.startTime)); - de.setAttribute("stopTime", str(sim.stopTime)); - de.setAttribute("stepSize", str(sim.solver.stepSize)); - de.setAttribute("tolerance", str(sim.solver.tolerance)); - de.setAttribute("solver", this.__GetSolverString(sim.solver)); - - #Set initial variables - for var in mv.childNodes: - if(var.nodeType == xml.dom.Node.ELEMENT_NODE): - varName = var.getAttribute("name"); - - if(varName not in sim.variables): - continue; - - for node in var.childNodes: #find the value - if(node.nodeType == xml.dom.Node.ELEMENT_NODE): - if(sim.variables[varName].start is None): - node.setAttribute("useStart", "false"); - else: - node.setAttribute("useStart", "true"); - node.setAttribute("start", str(sim.variables[varName].start)); - #node.setAttribute("fixed", "true"); - break; - - this._DeleteFile(this.__GetSimInitFilePath(sim)); - file = open(this.__GetSimInitFilePath(sim), "w"); - initDom.writexml(file); - file.close(); - - #Public methods - def Close(this): - #we don't use any open process - pass - - def Compile(this, mdl): - from PySimLib.Exceptions.CompilationFailedException import CompilationFailedException; - - #write a mos file to be executed by openmodelica - SCRIPTNAME = mdl.simDir + os.sep + mdl.outputName + ".mos"; - mosfile = open(SCRIPTNAME, 'w', 1); - mosfile.write("loadModel(Modelica);\r\n"); - - for item in mdl.GetFiles(): - mosfile.write("loadFile(\"" + item + "\");\r\n"); - - #evaluate parameters - #TODO looks like structural parameters cant be set in openmodelica - overrideString = ""; - """ + # Private methods + def __AssertModelCompiled(this, mdl): + from PySimLib.Exceptions.UncompiledModelException import UncompiledModelException + + if(not this._FileExists(this.__GetInitFilePath(mdl))): + raise UncompiledModelException(mdl, this) + + def __FindValueFromXMLVar(this, var): + from PySimLib.VariableDescriptor import VariableDescriptor + store = False + + varName = var.getAttribute("name") + # if(var.getAttribute("isValueChangeable") == "false"): + # return None; + + for node in var.childNodes: # find the value + if(node.nodeType == xml.dom.Node.ELEMENT_NODE): + varDesc = VariableDescriptor() + + if(node.getAttribute("useStart") == "true"): + start = node.getAttribute("start") + if(start == ""): + varDesc.start = 0 + elif(start == "true"): + varDesc.start = True + elif(start == "false"): + varDesc.start = False + else: + varDesc.start = float(start) + else: + varDesc.start = None + + return varName, varDesc + + return None + + def __GetExeFilePath(this, mdl): + return mdl.outputDir + os.sep + mdl.outputName + Platform.GetExeFileExtension() + + def __GetInfoFilePath(this, mdl): + return mdl.outputDir + os.sep + mdl.outputName + "_info.json" + + def __GetInitFilePath(this, mdl): + return mdl.outputDir + os.sep + mdl.outputName + "_init.xml" + + def __GetInitFileXML(this, mdl): + this.__AssertModelCompiled(mdl) + + return xml.dom.minidom.parse(this.__GetInitFilePath(mdl)) + + def __GetSimInitFilePath(this, sim): + mdl = sim.GetModel() + + return mdl.simDir + os.sep + str(sim.GetSimNumber()) + ".xml" + + def __GetSolverString(this, solver): + if(solver.Matches("dassl")): + return "dassl" + + raise NotImplementedError("OpenModelica::__GetSolverString") + + def __ReadVarsFromXML(this, mv, classTypeFilter): + result = {} + + for var in mv.childNodes: + if(var.nodeType == xml.dom.Node.ELEMENT_NODE): + if(var.getAttribute("classType") in classTypeFilter): + nameAndValue = this.__FindValueFromXMLVar(var) + + if(not(nameAndValue is None)): + varName, value = nameAndValue + result[varName] = value + + return result + + def __WriteInit(this, sim): + mdl = sim.GetModel() + + initDom = this.__GetInitFileXML(mdl) + mv = initDom.getElementsByTagName("ModelVariables")[0] + de = initDom.getElementsByTagName("DefaultExperiment")[0] + + if(sim.solver.stepSize == 0): + sim.solver.stepSize = 1e-6 # this is bad... but else OM simulates endlessly + + # Set experiment values + de.setAttribute("startTime", str(sim.startTime)) + de.setAttribute("stopTime", str(sim.stopTime)) + de.setAttribute("stepSize", str(sim.solver.stepSize)) + de.setAttribute("tolerance", str(sim.solver.tolerance)) + de.setAttribute("solver", this.__GetSolverString(sim.solver)) + + # Set initial variables + for var in mv.childNodes: + if(var.nodeType == xml.dom.Node.ELEMENT_NODE): + varName = var.getAttribute("name") + + if(varName not in sim.variables): + continue + + for node in var.childNodes: # find the value + if(node.nodeType == xml.dom.Node.ELEMENT_NODE): + if(sim.variables[varName].start is None): + node.setAttribute("useStart", "false") + else: + node.setAttribute("useStart", "true") + node.setAttribute("start", str(sim.variables[varName].start)) + #node.setAttribute("fixed", "true"); + break + + this._DeleteFile(this.__GetSimInitFilePath(sim)) + file = open(this.__GetSimInitFilePath(sim), "w") + initDom.writexml(file) + file.close() + + # Public methods + def Close(this): + # we don't use any open process + pass + + def Compile(this, mdl): + from PySimLib.Exceptions.CompilationFailedException import CompilationFailedException + + # write a mos file to be executed by openmodelica + SCRIPTNAME = mdl.simDir + os.sep + mdl.outputName + ".mos" + mosfile = open(SCRIPTNAME, 'w', 1) + mosfile.write("loadModel(Modelica);\r\n") + + for item in mdl.GetFiles(): + mosfile.write("loadFile(\"" + item + "\");\r\n") + + # evaluate parameters + # TODO looks like structural parameters cant be set in openmodelica + overrideString = "" + """ if(mdl.parameters): overrideString = ', simflags="-override '; for k in mdl.parameters: overrideString += k + "=" + str(mdl.parameters[k]) + " "; overrideString += '"'; """ - - # do a dummy simulation since it is not yet possible to do a translation only - #mosfile.write("simulate(" + mdl.GetModelicaClassString() + ", startTime = " + str(0) + ", stopTime = " + str(1) + ", method = \"" + "dassl" + "\", outputFormat=\"mat\");\r\n"); - mosfile.write("simulate(" + mdl.GetName() + ", startTime = " + str(0) + ", stopTime = " + str(1) + ", method = \"" + "dassl" + "\", outputFormat=\"mat\"" + overrideString + ");\r\n"); - mosfile.close(); - - #call the open modelica compiler - omcArgs = [ - GetConfigValue("OpenModelica", "PathExe"), - os.path.abspath(SCRIPTNAME), - "Modelica" - ]; - - this._DeleteFile(mdl.outputName + Platform.GetExeFileExtension()); #delete old exe to be sure that a new one is created - - Platform.Execute(omcArgs); #omc seems to return always 0 - - this._DeleteFile(SCRIPTNAME); #we don't need the mos script anymore - if(not this._FileExists(mdl.GetName() + Platform.GetExeFileExtension())): #if simulation failed there will be no exe - raise CompilationFailedException(mdl, this); - - #make sure output folder exists - if(not this._DirExists(mdl.outputDir)): - os.makedirs(mdl.outputDir); - - #Remove unnecessary files - this._DeleteFile(mdl.GetName() + ".c"); - this._DeleteFile(mdl.GetName() + ".libs"); - this._DeleteFile(mdl.GetName() + ".log"); - this._DeleteFile(mdl.GetName() + ".makefile"); - this._DeleteFile(mdl.GetName() + ".o"); - this._DeleteFile(mdl.GetName() + "_01exo.c"); - this._DeleteFile(mdl.GetName() + "_01exo.o"); - this._DeleteFile(mdl.GetName() + "_02nls.c"); - this._DeleteFile(mdl.GetName() + "_02nls.o"); - this._DeleteFile(mdl.GetName() + "_03lsy.c"); - this._DeleteFile(mdl.GetName() + "_03lsy.o"); - this._DeleteFile(mdl.GetName() + "_04set.c"); - this._DeleteFile(mdl.GetName() + "_04set.o"); - this._DeleteFile(mdl.GetName() + "_05evt.c"); - this._DeleteFile(mdl.GetName() + "_05evt.o"); - this._DeleteFile(mdl.GetName() + "_06inz.c"); - this._DeleteFile(mdl.GetName() + "_06inz.o"); - this._DeleteFile(mdl.GetName() + "_07dly.c"); - this._DeleteFile(mdl.GetName() + "_07dly.o"); - this._DeleteFile(mdl.GetName() + "_08bnd.c"); - this._DeleteFile(mdl.GetName() + "_08bnd.o"); - this._DeleteFile(mdl.GetName() + "_09alg.c"); - this._DeleteFile(mdl.GetName() + "_09alg.o"); - this._DeleteFile(mdl.GetName() + "_10asr.c"); - this._DeleteFile(mdl.GetName() + "_10asr.o"); - this._DeleteFile(mdl.GetName() + "_11mix.c"); - this._DeleteFile(mdl.GetName() + "_11mix.o"); - this._DeleteFile(mdl.GetName() + "_11mix.h"); - this._DeleteFile(mdl.GetName() + "_12jac.c"); - this._DeleteFile(mdl.GetName() + "_12jac.h"); - this._DeleteFile(mdl.GetName() + "_12jac.o"); - this._DeleteFile(mdl.GetName() + "_13opt.c"); - this._DeleteFile(mdl.GetName() + "_13opt.o"); - this._DeleteFile(mdl.GetName() + "_13opt.h"); - this._DeleteFile(mdl.GetName() + "_14lnz.c"); - this._DeleteFile(mdl.GetName() + "_14lnz.o"); - this._DeleteFile(mdl.GetName() + "_15syn.c"); - this._DeleteFile(mdl.GetName() + "_15syn.o"); - this._DeleteFile(mdl.GetName() + "_16dae.h"); - this._DeleteFile(mdl.GetName() + "_16dae.c"); - this._DeleteFile(mdl.GetName() + "_16dae.o"); - this._DeleteFile(mdl.GetName() + "_functions.c"); - this._DeleteFile(mdl.GetName() + "_functions.h"); - this._DeleteFile(mdl.GetName() + "_functions.o"); - this._DeleteFile(mdl.GetName() + "_includes.h"); - this._DeleteFile(mdl.GetName() + "_literals.h"); - this._DeleteFile(mdl.GetName() + "_model.h"); - this._DeleteFile(mdl.GetName() + "_records.c"); - this._DeleteFile(mdl.GetName() + "_records.o"); - this._DeleteFile(mdl.GetName() + "_res.mat"); - - #Rename important files - this._RenameFile(mdl.GetName() + Platform.GetExeFileExtension(), this.__GetExeFilePath(mdl)); - this._RenameFile(mdl.GetName() + "_init.xml", this.__GetInitFilePath(mdl)); - this._RenameFile(mdl.GetName() + "_info.json", this.__GetInfoFilePath(mdl)); - - def GetCompatibleSolvers(this): - from PySimLib import FindSolver; - - solvers = []; - - solvers.append(FindSolver("dassl")); - solvers.append(FindSolver("euler")); - - return solvers; - - def GetName(this): - return "OpenModelica"; - - def ReadInit(this, mdl): - from PySimLib import FindSolver; - - initDom = this.__GetInitFileXML(mdl); - mv = initDom.getElementsByTagName("ModelVariables")[0]; - de = initDom.getElementsByTagName("DefaultExperiment")[0]; - - #read parameters - classTypeFilter = { - "iPar", #integer parameter - "rPar", #real parameter - }; - - parameters = this.__ReadVarsFromXML(mv, classTypeFilter); - for name in parameters: - mdl.parameters[name] = parameters[name].start; - - #read variables - classTypeFilter = { - "bAlg", #boolean algebraic - "iAlg", #integer algebraic - "rAlg", #real algebraic - "rSta", #state variables - }; - - mdl.variables = this.__ReadVarsFromXML(mv, classTypeFilter); - - #read experiment values - mdl.startTime = de.getAttribute("startTime"); - mdl.stopTime = de.getAttribute("stopTime"); - mdl.solver = FindSolver(de.getAttribute("solver")); - mdl.solver.stepSize = float(de.getAttribute("stepSize")); - mdl.solver.tolerance = float(de.getAttribute("tolerance")); - - def Simulate(this, sim): - from PySimLib.Exceptions.SimulationFailedException import SimulationFailedException; - - mdl = sim.GetModel(); - - #paths - simInfoFilePath = mdl.simDir + os.sep + mdl.GetName() + "_info.json"; - - #check if model is compiled - this.__AssertModelCompiled(mdl); - - #make sure result folder exists - if(not this._DirExists(mdl.resultDir)): - os.makedirs(mdl.resultDir); - - #prepare init file - this.__WriteInit(sim); - - #info file can't be specified as arg to openmodelica - if(not(mdl.outputName == mdl.GetName()) or not(mdl.simDir == mdl.outputDir)): - shutil.copyfile(this.__GetInfoFilePath(mdl), simInfoFilePath); - - #run compiled model - simArgs = [ - this.__GetExeFilePath(mdl), - "-f", - this.__GetSimInitFilePath(sim), - ]; - - exitCode = Platform.Execute(simArgs, True, mdl.simDir); - if(not(exitCode == 0)): - raise SimulationFailedException(sim, this); - - #keep things clean - if(not(mdl.outputName == mdl.GetName()) or not(mdl.simDir == mdl.outputDir)): - this._DeleteFile(simInfoFilePath); - this._DeleteFile(this.__GetSimInitFilePath(sim)); - - #rename results - this._RenameFile(mdl.simDir + os.sep + mdl.GetName() + "_res.mat", this._GetSimResultFilePath(sim)); - - #Class functions - def IsAvailable(): - return HasConfigValue("OpenModelica", "PathExe"); + + # do a dummy simulation since it is not yet possible to do a translation only + #mosfile.write("simulate(" + mdl.GetModelicaClassString() + ", startTime = " + str(0) + ", stopTime = " + str(1) + ", method = \"" + "dassl" + "\", outputFormat=\"mat\");\r\n"); + mosfile.write("simulate(" + mdl.GetName() + ", startTime = " + str(0) + ", stopTime = " + str(1) + ", method = \"" + "dassl" + "\", outputFormat=\"mat\"" + overrideString + ");\r\n") + mosfile.close() + + # call the open modelica compiler + omcArgs = [ + GetConfigValue("OpenModelica", "PathExe"), + os.path.abspath(SCRIPTNAME), + "Modelica" + ] + + this._DeleteFile(mdl.outputName + Platform.GetExeFileExtension()) # delete old exe to be sure that a new one is created + + Platform.Execute(omcArgs) # omc seems to return always 0 + + this._DeleteFile(SCRIPTNAME) # we don't need the mos script anymore + if(not this._FileExists(mdl.GetName() + Platform.GetExeFileExtension())): # if simulation failed there will be no exe + raise CompilationFailedException(mdl, this) + + # make sure output folder exists + if(not this._DirExists(mdl.outputDir)): + os.makedirs(mdl.outputDir) + + # Remove unnecessary files + this._DeleteFile(mdl.GetName() + ".c") + this._DeleteFile(mdl.GetName() + ".libs") + this._DeleteFile(mdl.GetName() + ".log") + this._DeleteFile(mdl.GetName() + ".makefile") + this._DeleteFile(mdl.GetName() + ".o") + this._DeleteFile(mdl.GetName() + "_01exo.c") + this._DeleteFile(mdl.GetName() + "_01exo.o") + this._DeleteFile(mdl.GetName() + "_02nls.c") + this._DeleteFile(mdl.GetName() + "_02nls.o") + this._DeleteFile(mdl.GetName() + "_03lsy.c") + this._DeleteFile(mdl.GetName() + "_03lsy.o") + this._DeleteFile(mdl.GetName() + "_04set.c") + this._DeleteFile(mdl.GetName() + "_04set.o") + this._DeleteFile(mdl.GetName() + "_05evt.c") + this._DeleteFile(mdl.GetName() + "_05evt.o") + this._DeleteFile(mdl.GetName() + "_06inz.c") + this._DeleteFile(mdl.GetName() + "_06inz.o") + this._DeleteFile(mdl.GetName() + "_07dly.c") + this._DeleteFile(mdl.GetName() + "_07dly.o") + this._DeleteFile(mdl.GetName() + "_08bnd.c") + this._DeleteFile(mdl.GetName() + "_08bnd.o") + this._DeleteFile(mdl.GetName() + "_09alg.c") + this._DeleteFile(mdl.GetName() + "_09alg.o") + this._DeleteFile(mdl.GetName() + "_10asr.c") + this._DeleteFile(mdl.GetName() + "_10asr.o") + this._DeleteFile(mdl.GetName() + "_11mix.c") + this._DeleteFile(mdl.GetName() + "_11mix.o") + this._DeleteFile(mdl.GetName() + "_11mix.h") + this._DeleteFile(mdl.GetName() + "_12jac.c") + this._DeleteFile(mdl.GetName() + "_12jac.h") + this._DeleteFile(mdl.GetName() + "_12jac.o") + this._DeleteFile(mdl.GetName() + "_13opt.c") + this._DeleteFile(mdl.GetName() + "_13opt.o") + this._DeleteFile(mdl.GetName() + "_13opt.h") + this._DeleteFile(mdl.GetName() + "_14lnz.c") + this._DeleteFile(mdl.GetName() + "_14lnz.o") + this._DeleteFile(mdl.GetName() + "_15syn.c") + this._DeleteFile(mdl.GetName() + "_15syn.o") + this._DeleteFile(mdl.GetName() + "_16dae.h") + this._DeleteFile(mdl.GetName() + "_16dae.c") + this._DeleteFile(mdl.GetName() + "_16dae.o") + this._DeleteFile(mdl.GetName() + "_functions.c") + this._DeleteFile(mdl.GetName() + "_functions.h") + this._DeleteFile(mdl.GetName() + "_functions.o") + this._DeleteFile(mdl.GetName() + "_includes.h") + this._DeleteFile(mdl.GetName() + "_literals.h") + this._DeleteFile(mdl.GetName() + "_model.h") + this._DeleteFile(mdl.GetName() + "_records.c") + this._DeleteFile(mdl.GetName() + "_records.o") + this._DeleteFile(mdl.GetName() + "_res.mat") + + # Rename important files + this._RenameFile(mdl.GetName() + Platform.GetExeFileExtension(), this.__GetExeFilePath(mdl)) + this._RenameFile(mdl.GetName() + "_init.xml", this.__GetInitFilePath(mdl)) + this._RenameFile(mdl.GetName() + "_info.json", this.__GetInfoFilePath(mdl)) + + def GetCompatibleSolvers(this): + from PySimLib import FindSolver + + solvers = [] + + solvers.append(FindSolver("dassl")) + solvers.append(FindSolver("euler")) + + return solvers + + def GetName(this): + return "OpenModelica" + + def ReadInit(this, mdl): + from PySimLib import FindSolver + + initDom = this.__GetInitFileXML(mdl) + mv = initDom.getElementsByTagName("ModelVariables")[0] + de = initDom.getElementsByTagName("DefaultExperiment")[0] + + # read parameters + classTypeFilter = { + "iPar", # integer parameter + "rPar", # real parameter + } + + parameters = this.__ReadVarsFromXML(mv, classTypeFilter) + for name in parameters: + mdl.parameters[name] = parameters[name].start + + # read variables + classTypeFilter = { + "bAlg", # boolean algebraic + "iAlg", # integer algebraic + "rAlg", # real algebraic + "rSta", # state variables + } + + mdl.variables = this.__ReadVarsFromXML(mv, classTypeFilter) + + # read experiment values + mdl.startTime = de.getAttribute("startTime") + mdl.stopTime = de.getAttribute("stopTime") + mdl.solver = FindSolver(de.getAttribute("solver")) + mdl.solver.stepSize = float(de.getAttribute("stepSize")) + mdl.solver.tolerance = float(de.getAttribute("tolerance")) + + def Simulate(this, sim): + from PySimLib.Exceptions.SimulationFailedException import SimulationFailedException + + mdl = sim.GetModel() + + # paths + simInfoFilePath = mdl.simDir + os.sep + mdl.GetName() + "_info.json" + + # check if model is compiled + this.__AssertModelCompiled(mdl) + + # make sure result folder exists + if(not this._DirExists(mdl.resultDir)): + os.makedirs(mdl.resultDir) + + # prepare init file + this.__WriteInit(sim) + + # info file can't be specified as arg to openmodelica + if(not(mdl.outputName == mdl.GetName()) or not(mdl.simDir == mdl.outputDir)): + shutil.copyfile(this.__GetInfoFilePath(mdl), simInfoFilePath) + + # run compiled model + simArgs = [ + this.__GetExeFilePath(mdl), + "-f", + this.__GetSimInitFilePath(sim), + ] + + exitCode = Platform.Execute(simArgs, True, mdl.simDir) + if(not(exitCode == 0)): + raise SimulationFailedException(sim, this) + + # keep things clean + if(not(mdl.outputName == mdl.GetName()) or not(mdl.simDir == mdl.outputDir)): + this._DeleteFile(simInfoFilePath) + this._DeleteFile(this.__GetSimInitFilePath(sim)) + + # rename results + this._RenameFile(mdl.simDir + os.sep + mdl.GetName() + "_res.mat", this._GetSimResultFilePath(sim)) + + # Class functions + def IsAvailable(): + return HasConfigValue("OpenModelica", "PathExe") diff --git a/PySimLib/Tools/Simulink.py b/PySimLib/Tools/Simulink.py index 560a152..edc66fc 100644 --- a/PySimLib/Tools/Simulink.py +++ b/PySimLib/Tools/Simulink.py @@ -20,163 +20,162 @@ along with this program. If not, see . """ -#Local -from PySimLib.Config import *; -from PySimLib.Mat.Mat import Mat; -from PySimLib.Tool import Tool; +# Local +from PySimLib.Config import * +from PySimLib.Mat.Mat import Mat +from PySimLib.Tool import Tool + class Simulink(Tool): - #Static class members - __matlabConnection = None; - __matlabStarted = False; - - #Constructor - def __init__(this): - from pymatbridge import Matlab; - - Tool.__init__(this); - - Simulink.__matlabConnection = Matlab(executable=GetConfigValue('Simulink', 'PathExe')); - - #Private methods - def __EnsureMatlabConnectionIsSetup(this): - if(Simulink.__matlabStarted == False): - Simulink.__matlabConnection.start(); - Simulink.__matlabStarted = True; - - def __GetSimResultFilePath(this, sim): - mdl = sim.GetModel(); - - return mdl.resultDir + os.sep + str(sim.GetSimNumber()) + "_" + mdl.outputName + ".mat"; - - #Public methods - def Accepts(this, mdl): - from PySimLib.Models.SimulinkModel import SimulinkModel; - - return isinstance(mdl, SimulinkModel); - - def Close(this): - if(Simulink.__matlabStarted): - Simulink.__matlabConnection.stop(); - Simulink.__matlabStarted = False; - - - def Compile(this, mdl): - pass #nothing to be done here - - def GetName(this): - return "Simulink"; - - def ReadInit(this, mdl): - from PySimLib import FindSolver; - from PySimLib.VariableDescriptor import VariableDescriptor; - - mdl.startTime = None; - mdl.stopTime = None; - mdl.solver = FindSolver("dassl"); #TODO!!!! - - this.__EnsureMatlabConnectionIsSetup(); - - cmd = "clear;"; #make sure workspace is clean - cmd += "cd " + mdl.simDir + ";"; #go to sim dir - Simulink.__matlabConnection.run_code(cmd); - - #exec init file - if(this._FileExists(mdl.simDir + os.sep + mdl.GetName() + "_init.m")): - Simulink.__matlabConnection.run_code(mdl.GetName() + "_init;"); - - #get all variables - varList = Simulink.__matlabConnection.get_variable('who'); - for x in varList: - name = x[0][0]; - value = Simulink.__matlabConnection.get_variable(x[0][0]); - - var = VariableDescriptor(); - var.start = value; - - mdl.variables[name] = var; - - def ReadResult(this, sim): - from PySimLib.SimulationResult import SimulationResult; - - mdl = sim.GetModel(); - - result = {}; - m_res = Mat(); - m_res.Load(this.__GetSimResultFilePath(sim)); - - for key in m_res.GetMatrices(): - m = m_res.GetMatrix(key); - data = []; - for y in range(0, m.GetNumberOfRows()): - data.append(m.GetValue(0, y)); - - result[key] = data; - - this._SetDerivedValuesFromSimulationResults(sim, result); - - return SimulationResult(result); - - - def Simulate(this, sim): - from PySimLib.Mat.OutputStream import OutputStream; - - mdl = sim.GetModel(); - - this.__EnsureMatlabConnectionIsSetup(); - - #make sure result folder exists - if(not this._DirExists(mdl.resultDir)): - os.makedirs(mdl.resultDir); - - #preparations - cmd = "clear"; #clean up workspace - cmd += "cd " + mdl.simDir + ";"; #go to sim dir - Simulink.__matlabConnection.run_code(cmd); - - #send variables - cmd = ""; - for name in mdl.variables: - cmd += name + "=" + str(mdl.variables[name].start) + ";"; - Simulink.__matlabConnection.run_code(cmd); - - #simulate - cmd = "sim('" + mdl.GetFile() + "'"; - if(not(mdl.startTime is None)): - cmd += ", 'StartTime', " + str(mdl.startTime); - if(not(mdl.stopTime is None)): - cmd += ", 'StopTime', " + str(mdl.stopTime); - cmd += ");"; - cmd += "logsout.unpack('all');"; #make all variables to top levels - cmd += "clear logsout;"; #discard simulation results, as we have direct access to vars now - Simulink.__matlabConnection.run_code(cmd); - - #get all timeserieses - outMat = Mat(); - varList = Simulink.__matlabConnection.get_variable('who'); - time = None; - for x in varList: - data = Simulink.__matlabConnection.get_variable(x[0][0] + ".Data"); - if(not(data is None)): - matrix = outMat.AddMatrix(x[0][0], 1, len(data)); - for y in range(0, len(data)): - matrix.SetValue(0, y, data[y][0].item()); - - tmp = Simulink.__matlabConnection.get_variable(x[0][0] + ".Time"); - if((time is None) or (len(tmp) > len(time))): - time = tmp; - - #add time - matrix = outMat.AddMatrix('time', 1, len(time)); - for y in range(0, len(time)): - matrix.SetValue(0, y, time[y][0].item()); - - #write mat file - file = open(this.__GetSimResultFilePath(sim), "wb"); - stream = OutputStream(file); - outMat.Write(stream); - file.close(); - - #Class functions - def IsAvailable(): - return HasConfigValue("Simulink", "PathExe"); + # Static class members + __matlabConnection = None + __matlabStarted = False + + # Constructor + def __init__(this): + from pymatbridge import Matlab + + Tool.__init__(this) + + Simulink.__matlabConnection = Matlab(executable=GetConfigValue('Simulink', 'PathExe')) + + # Private methods + def __EnsureMatlabConnectionIsSetup(this): + if(Simulink.__matlabStarted == False): + Simulink.__matlabConnection.start() + Simulink.__matlabStarted = True + + def __GetSimResultFilePath(this, sim): + mdl = sim.GetModel() + + return mdl.resultDir + os.sep + str(sim.GetSimNumber()) + "_" + mdl.outputName + ".mat" + + # Public methods + def Accepts(this, mdl): + from PySimLib.Models.SimulinkModel import SimulinkModel + + return isinstance(mdl, SimulinkModel) + + def Close(this): + if(Simulink.__matlabStarted): + Simulink.__matlabConnection.stop() + Simulink.__matlabStarted = False + + def Compile(this, mdl): + pass # nothing to be done here + + def GetName(this): + return "Simulink" + + def ReadInit(this, mdl): + from PySimLib import FindSolver + from PySimLib.VariableDescriptor import VariableDescriptor + + mdl.startTime = None + mdl.stopTime = None + mdl.solver = FindSolver("dassl") # TODO!!!! + + this.__EnsureMatlabConnectionIsSetup() + + cmd = "clear;" # make sure workspace is clean + cmd += "cd " + mdl.simDir + ";" # go to sim dir + Simulink.__matlabConnection.run_code(cmd) + + # exec init file + if(this._FileExists(mdl.simDir + os.sep + mdl.GetName() + "_init.m")): + Simulink.__matlabConnection.run_code(mdl.GetName() + "_init;") + + # get all variables + varList = Simulink.__matlabConnection.get_variable('who') + for x in varList: + name = x[0][0] + value = Simulink.__matlabConnection.get_variable(x[0][0]) + + var = VariableDescriptor() + var.start = value + + mdl.variables[name] = var + + def ReadResult(this, sim): + from PySimLib.SimulationResult import SimulationResult + + mdl = sim.GetModel() + + result = {} + m_res = Mat() + m_res.Load(this.__GetSimResultFilePath(sim)) + + for key in m_res.GetMatrices(): + m = m_res.GetMatrix(key) + data = [] + for y in range(0, m.GetNumberOfRows()): + data.append(m.GetValue(0, y)) + + result[key] = data + + this._SetDerivedValuesFromSimulationResults(sim, result) + + return SimulationResult(result) + + def Simulate(this, sim): + from PySimLib.Mat.OutputStream import OutputStream + + mdl = sim.GetModel() + + this.__EnsureMatlabConnectionIsSetup() + + # make sure result folder exists + if(not this._DirExists(mdl.resultDir)): + os.makedirs(mdl.resultDir) + + # preparations + cmd = "clear" # clean up workspace + cmd += "cd " + mdl.simDir + ";" # go to sim dir + Simulink.__matlabConnection.run_code(cmd) + + # send variables + cmd = "" + for name in mdl.variables: + cmd += name + "=" + str(mdl.variables[name].start) + ";" + Simulink.__matlabConnection.run_code(cmd) + + # simulate + cmd = "sim('" + mdl.GetFile() + "'" + if(not(mdl.startTime is None)): + cmd += ", 'StartTime', " + str(mdl.startTime) + if(not(mdl.stopTime is None)): + cmd += ", 'StopTime', " + str(mdl.stopTime) + cmd += ");" + cmd += "logsout.unpack('all');" # make all variables to top levels + cmd += "clear logsout;" # discard simulation results, as we have direct access to vars now + Simulink.__matlabConnection.run_code(cmd) + + # get all timeserieses + outMat = Mat() + varList = Simulink.__matlabConnection.get_variable('who') + time = None + for x in varList: + data = Simulink.__matlabConnection.get_variable(x[0][0] + ".Data") + if(not(data is None)): + matrix = outMat.AddMatrix(x[0][0], 1, len(data)) + for y in range(0, len(data)): + matrix.SetValue(0, y, data[y][0].item()) + + tmp = Simulink.__matlabConnection.get_variable(x[0][0] + ".Time") + if((time is None) or (len(tmp) > len(time))): + time = tmp + + # add time + matrix = outMat.AddMatrix('time', 1, len(time)) + for y in range(0, len(time)): + matrix.SetValue(0, y, time[y][0].item()) + + # write mat file + file = open(this.__GetSimResultFilePath(sim), "wb") + stream = OutputStream(file) + outMat.Write(stream) + file.close() + + # Class functions + def IsAvailable(): + return HasConfigValue("Simulink", "PathExe") diff --git a/PySimLib/VariableDescriptor.py b/PySimLib/VariableDescriptor.py index ea81701..b129e9d 100644 --- a/PySimLib/VariableDescriptor.py +++ b/PySimLib/VariableDescriptor.py @@ -20,16 +20,17 @@ along with this program. If not, see . """ + class VariableDescriptor: - #Constructor - def __init__(this): - #Public members - this.start = None; - this.final = None; - - #Magic methods - def __str__(this): - result = "start: " + str(this.start) + ", "; - result += "final: " + str(this.final); - - return result; + # Constructor + def __init__(this): + # Public members + this.start = None + this.final = None + + # Magic methods + def __str__(this): + result = "start: " + str(this.start) + ", " + result += "final: " + str(this.final) + + return result diff --git a/PySimLib/__init__.py b/PySimLib/__init__.py index 986f184..2779aee 100644 --- a/PySimLib/__init__.py +++ b/PySimLib/__init__.py @@ -20,119 +20,125 @@ along with this program. If not, see . """ -#Import what user might need -from PySimLib import Log; -from PySimLib.Plot import Plot; -from PySimLib.Simulation import Simulation; +# Import what user might need +from PySimLib import Log +from PySimLib.Plot import Plot +from PySimLib.Simulation import Simulation + +# Internal +__g_tools = [] +__g_modelClasses = [] +__g_solvers = {} # we need to store instances and its classes -#Internal -__g_tools = []; -__g_modelClasses = []; -__g_solvers = {}; #we need to store instances and its classes def __RegisterTool(toolClass): - if(toolClass.IsAvailable()): - global __g_tools; - - __g_tools.append(toolClass()); + if(toolClass.IsAvailable()): + global __g_tools + + __g_tools.append(toolClass()) + def __RegisterTools(): - #Dymola - from PySimLib.Tools.Dymola import Dymola; - __RegisterTool(Dymola); - - #OpenModelica - from PySimLib.Tools.OpenModelica import OpenModelica; - __RegisterTool(OpenModelica); - - #Simulink - from PySimLib.Tools.Simulink import Simulink; - __RegisterTool(Simulink); - + # Dymola + from PySimLib.Tools.Dymola import Dymola + __RegisterTool(Dymola) + + # OpenModelica + from PySimLib.Tools.OpenModelica import OpenModelica + __RegisterTool(OpenModelica) + + # Simulink + from PySimLib.Tools.Simulink import Simulink + __RegisterTool(Simulink) + + def __RegisterModelRepresentationClasses(): - global __g_modelClasses; - - #Modelica - from PySimLib.Models.ModelicaModel import ModelicaModel; - __g_modelClasses.append(ModelicaModel); - - #Simulink - from PySimLib.Models.SimulinkModel import SimulinkModel; - __g_modelClasses.append(SimulinkModel); - + global __g_modelClasses + + # Modelica + from PySimLib.Models.ModelicaModel import ModelicaModel + __g_modelClasses.append(ModelicaModel) + + # Simulink + from PySimLib.Models.SimulinkModel import SimulinkModel + __g_modelClasses.append(SimulinkModel) + + def __RegisterSolvers(): - global __g_solvers; - - #DEABM - from PySimLib.Solvers.DEABM import DEABM; - __g_solvers[DEABM()] = DEABM; - - #DASSL - from PySimLib.Solvers.DASSL import DASSL; - __g_solvers[DASSL()] = DASSL; - - #Euler #TODO: REENABLE ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - #from PySimLib.Solvers.Euler import Euler; - #__g_solvers[Euler()] = Euler; - - #LSODAR - from PySimLib.Solvers.LSODAR import LSODAR; - __g_solvers[LSODAR()] = LSODAR; - -Model = None; - -__RegisterTools(); -__RegisterSolvers(); -__RegisterModelRepresentationClasses(); - - -#Interface + global __g_solvers + + # DEABM + from PySimLib.Solvers.DEABM import DEABM + __g_solvers[DEABM()] = DEABM + + # DASSL + from PySimLib.Solvers.DASSL import DASSL + __g_solvers[DASSL()] = DASSL + + # Euler #TODO: REENABLE ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + #from PySimLib.Solvers.Euler import Euler; + #__g_solvers[Euler()] = Euler; + + # LSODAR + from PySimLib.Solvers.LSODAR import LSODAR + __g_solvers[LSODAR()] = LSODAR + + +Model = None + +__RegisterTools() +__RegisterSolvers() +__RegisterModelRepresentationClasses() + + +# Interface def Model(name, files): - global __g_modelClasses; - - if(not (type(files) == list)): - files = [files]; - if(not(files)): #if files is empty - return None; - - for mdlClass in __g_modelClasses: - if(mdlClass.Matches(name, files)): - return mdlClass(name, files); + global __g_modelClasses + + if(not (type(files) == list)): + files = [files] + if(not(files)): # if files is empty + return None + + for mdlClass in __g_modelClasses: + if(mdlClass.Matches(name, files)): + return mdlClass(name, files) def FindSolver(pattern): - from PySimLib.Tool import Tool; - - solvers = GetSolvers(); - for solver in solvers: - if(solver.Matches(pattern)): - return solver; - - return None; - + from PySimLib.Tool import Tool + + solvers = GetSolvers() + for solver in solvers: + if(solver.Matches(pattern)): + return solver + + return None + + def FindTool(pattern): - tools = GetTools(); - - pattern = pattern.lower(); - for tool in tools: - if(tool.GetName().lower() == pattern): - return tool; - - return None; + tools = GetTools() + + pattern = pattern.lower() + for tool in tools: + if(tool.GetName().lower() == pattern): + return tool + + return None def GetSolvers(): - global __g_solvers; - - result = []; - - for solver in __g_solvers: - result.append(__g_solvers[solver]()); - - return result; - - + global __g_solvers + + result = [] + + for solver in __g_solvers: + result.append(__g_solvers[solver]()) + + return result + + def GetTools(): - global __g_tools; - - return __g_tools; + global __g_tools + + return __g_tools diff --git a/info/listSolvers.py b/info/listSolvers.py index 0a9301f..2b1aea8 100644 --- a/info/listSolvers.py +++ b/info/listSolvers.py @@ -1,9 +1,9 @@ -from PySimLib import *; +from PySimLib import * -space = "\t"; +space = "\t" print("Name", space, "Detailed name") -print("----"); +print("----") for solver in GetSolvers(): - print(solver.GetName(), space, solver.GetDetailedName()); \ No newline at end of file + print(solver.GetName(), space, solver.GetDetailedName()) diff --git a/info/listTools.py b/info/listTools.py index 471d388..1ef3855 100644 --- a/info/listTools.py +++ b/info/listTools.py @@ -1,9 +1,9 @@ -from PySimLib import *; +from PySimLib import * -space = "\t"; +space = "\t" print("Name") -print("----"); +print("----") for tool in GetTools(): - print(tool.GetName()); \ No newline at end of file + print(tool.GetName()) diff --git a/info/mat.py b/info/mat.py index a79ecee..6cac985 100644 --- a/info/mat.py +++ b/info/mat.py @@ -1,22 +1,22 @@ -import sys; -from PySimLib.Mat.Mat import Mat; -from PySimLib.Mat.TextMatrix import TextMatrix; +import sys +from PySimLib.Mat.Mat import Mat +from PySimLib.Mat.TextMatrix import TextMatrix -space = "\t\t"; +space = "\t\t" -mat = Mat(); -mat.Load(sys.argv[1]); -matrices = mat.GetMatrices(); +mat = Mat() +mat.Load(sys.argv[1]) +matrices = mat.GetMatrices() -print("Size is either 'Rows x Columns' or, for a Textmatrix, the number of strings"); +print("Size is either 'Rows x Columns' or, for a Textmatrix, the number of strings") print("Type", space, "Size", space, "Name") -print("----"); +print("----") for key in matrices: - if(type(matrices[key]) == TextMatrix): - t = "TextMatrix\t"; - size = matrices[key].GetNumberOfStrings(); - else: - t = "Matrix\t\t"; - size = str(matrices[key].GetNumberOfRows()) + "x" + str(matrices[key].GetNumberOfColumns()); - print(t, size, space, key); \ No newline at end of file + if(type(matrices[key]) == TextMatrix): + t = "TextMatrix\t" + size = matrices[key].GetNumberOfStrings() + else: + t = "Matrix\t\t" + size = str(matrices[key].GetNumberOfRows()) + "x" + str(matrices[key].GetNumberOfColumns()) + print(t, size, space, key) diff --git a/info/matrix.py b/info/matrix.py index 3d12781..dd2e0e3 100644 --- a/info/matrix.py +++ b/info/matrix.py @@ -1,29 +1,29 @@ -import sys; -from PySimLib.Mat.Mat import Mat; -from PySimLib.Mat.TextMatrix import TextMatrix; +import sys +from PySimLib.Mat.Mat import Mat +from PySimLib.Mat.TextMatrix import TextMatrix -space = "\t\t"; +space = "\t\t" -mat = Mat(); -mat.Load(sys.argv[1]); -m = mat.GetMatrix(sys.argv[2]); +mat = Mat() +mat.Load(sys.argv[1]) +m = mat.GetMatrix(sys.argv[2]) if(type(m) == TextMatrix): - t = 1; - print("Type: ", "TextMatrix"); - print("Number of strings: ", m.GetNumberOfStrings()); + t = 1 + print("Type: ", "TextMatrix") + print("Number of strings: ", m.GetNumberOfStrings()) else: - t = 0; - print("Type: ", "Matrix"); - print("Size ('Rows'x'Columns'): ", str(m.GetNumberOfRows()) + "x" + str(m.GetNumberOfColumns())); -print("----"); + t = 0 + print("Type: ", "Matrix") + print("Size ('Rows'x'Columns'): ", str(m.GetNumberOfRows()) + "x" + str(m.GetNumberOfColumns())) +print("----") if(t == 1): - for i in range(0, m.GetNumberOfStrings()): - print(m.GetString(i)); + for i in range(0, m.GetNumberOfStrings()): + print(m.GetString(i)) else: - for y in range(0, m.GetNumberOfRows()): - line = ""; - for x in range(0, m.GetNumberOfColumns()): - line += str(m.GetValue(x, y)) + ", "; - print(line); \ No newline at end of file + for y in range(0, m.GetNumberOfRows()): + line = "" + for x in range(0, m.GetNumberOfColumns()): + line += str(m.GetValue(x, y)) + ", " + print(line) diff --git a/info/tool.py b/info/tool.py index 498e40a..d72ec21 100644 --- a/info/tool.py +++ b/info/tool.py @@ -1,12 +1,12 @@ -import sys; -from PySimLib import *; +import sys +from PySimLib import * -tool = FindTool(sys.argv[1]); +tool = FindTool(sys.argv[1]) -print("Name: ", tool.GetName()); +print("Name: ", tool.GetName()) -print("Compatible Solvers:"); +print("Compatible Solvers:") for solver in tool.GetCompatibleSolvers(): - print(' ', solver.GetName()); - -print("Default Solver: ", tool.GetDefaultSolver().GetName()); \ No newline at end of file + print(' ', solver.GetName()) + +print("Default Solver: ", tool.GetDefaultSolver().GetName()) diff --git a/samples/pendulum/pendulum.py b/samples/pendulum/pendulum.py index 81dffed..eab7900 100644 --- a/samples/pendulum/pendulum.py +++ b/samples/pendulum/pendulum.py @@ -1,24 +1,24 @@ -from PySimLib import *; +from PySimLib import * -Log.SetTarget(open("sim.log", "w")); +Log.SetTarget(open("sim.log", "w")) -mdl = Model("pendulum", "pendulum.mo"); -mdl.outputDir += "/output"; -mdl.resultDir += "/result"; +mdl = Model("pendulum", "pendulum.mo") +mdl.outputDir += "/output" +mdl.resultDir += "/result" -tool = mdl.GetCompatibleTools()[0]; -tool.Compile(mdl); -tool.ReadInit(mdl); +tool = mdl.GetCompatibleTools()[0] +tool.Compile(mdl) +tool.ReadInit(mdl) -sim = Simulation(mdl); -sim.stopTime = 10; -tool.Simulate(sim); -result = tool.ReadResult(sim); +sim = Simulation(mdl) +sim.stopTime = 10 +tool.Simulate(sim) +result = tool.ReadResult(sim) -p = Plot(); -p.Add(result["time"], result["derPhi"], "r"); -p.Show(); +p = Plot() +p.Add(result["time"], result["derPhi"], "r") +p.Show() -tool.Close(); +tool.Close() diff --git a/samples/struc_param/struc_param.py b/samples/struc_param/struc_param.py index 0cfedd1..95524af 100644 --- a/samples/struc_param/struc_param.py +++ b/samples/struc_param/struc_param.py @@ -1,24 +1,24 @@ -from PySimLib import *; +from PySimLib import * -Log.SetTarget(open("sim.log", "w")); +Log.SetTarget(open("sim.log", "w")) -mdl = Model("struc_param", "struc_param.mo"); -mdl.outputDir += "/output"; -mdl.resultDir += "/result"; -mdl.parameters["N"] = 2; +mdl = Model("struc_param", "struc_param.mo") +mdl.outputDir += "/output" +mdl.resultDir += "/result" +mdl.parameters["N"] = 2 -tool = mdl.GetCompatibleTools()[0]; -tool.Compile(mdl); -tool.ReadInit(mdl); +tool = mdl.GetCompatibleTools()[0] +tool.Compile(mdl) +tool.ReadInit(mdl) -sim = Simulation(mdl); -sim.stopTime = 10; -tool.Simulate(sim); +sim = Simulation(mdl) +sim.stopTime = 10 +tool.Simulate(sim) -result = tool.ReadResult(sim); +result = tool.ReadResult(sim) -p = Plot(); -p.Add(result["time"], result["v[1]"], "r"); -p.Add(result["time"], result["v[2]"], "b"); -p.Show(); +p = Plot() +p.Add(result["time"], result["v[1]"], "r") +p.Add(result["time"], result["v[2]"], "b") +p.Show() diff --git a/samples/variable-structure samples/pendulum to ball/run.py b/samples/variable-structure samples/pendulum to ball/run.py index 4a3903f..34ea3e3 100644 --- a/samples/variable-structure samples/pendulum to ball/run.py +++ b/samples/variable-structure samples/pendulum to ball/run.py @@ -1,71 +1,71 @@ -from PySimLib import *; -from math import *; +from PySimLib import * +from math import * -Log.SetTarget(open("sim.log", "w")); +Log.SetTarget(open("sim.log", "w")) -#setup models and tool and then compile -pendulum = Model("pendulum", "pendulum.mo"); -ball = Model("ball", "ball.mo"); +# setup models and tool and then compile +pendulum = Model("pendulum", "pendulum.mo") +ball = Model("ball", "ball.mo") -pendulum.outputDir += "/output"; -pendulum.resultDir += "/result"; -ball.outputDir += "/output"; -ball.resultDir += "/result"; +pendulum.outputDir += "/output" +pendulum.resultDir += "/result" +ball.outputDir += "/output" +ball.resultDir += "/result" -tool = pendulum.GetCompatibleTools()[0]; -tool.Compile(pendulum); -tool.Compile(ball); -tool.ReadInit(pendulum); -tool.ReadInit(ball); +tool = pendulum.GetCompatibleTools()[0] +tool.Compile(pendulum) +tool.Compile(ball) +tool.ReadInit(pendulum) +tool.ReadInit(ball) -#simulate pendulum until we find a force less than zero -sim = Simulation(pendulum); -sim.stopTime = 1; +# simulate pendulum until we find a force less than zero +sim = Simulation(pendulum) +sim.stopTime = 1 -derPhi = 0; -index = None; +derPhi = 0 +index = None while index is None: - derPhi += 1; - - sim.variables["derPhi"].start = derPhi; - tool.Simulate(sim); - result = tool.ReadResult(sim); - - for i in range(0, len(result["F"])): - if(result["F"][i] < 0): - index = i; #got it - break; - -print("derPhi: ", derPhi); - - -#calc x and y for pendulum -x = []; -y = []; + derPhi += 1 + + sim.variables["derPhi"].start = derPhi + tool.Simulate(sim) + result = tool.ReadResult(sim) + + for i in range(0, len(result["F"])): + if(result["F"][i] < 0): + index = i # got it + break + +print("derPhi: ", derPhi) + + +# calc x and y for pendulum +x = [] +y = [] for i in range(0, index): - v = result["phi"][i]; - x.append(sin(v) * pendulum.parameters["L"]); - y.append(-cos(v) * pendulum.parameters["L"]); - + v = result["phi"][i] + x.append(sin(v) * pendulum.parameters["L"]) + y.append(-cos(v) * pendulum.parameters["L"]) + -#run ball sim -sim = Simulation(ball); +# run ball sim +sim = Simulation(ball) -sim.stopTime = 0.6; -sim.variables["x"].start = sin(result["phi"][index]); -sim.variables["y"].start = -cos(result["phi"][index]); -sim.variables["vx"].start = cos(result["phi"][index]) * result["derPhi"][index] * pendulum.parameters["L"]; -sim.variables["vy"].start = sin(result["phi"][index]) * result["derPhi"][index] * pendulum.parameters["L"]; +sim.stopTime = 0.6 +sim.variables["x"].start = sin(result["phi"][index]) +sim.variables["y"].start = -cos(result["phi"][index]) +sim.variables["vx"].start = cos(result["phi"][index]) * result["derPhi"][index] * pendulum.parameters["L"] +sim.variables["vy"].start = sin(result["phi"][index]) * result["derPhi"][index] * pendulum.parameters["L"] -tool.Simulate(sim); -result2 = tool.ReadResult(sim); +tool.Simulate(sim) +result2 = tool.ReadResult(sim) -p = Plot(); -p.Add(x, y, "r"); -p.Add(result2["x"], result2["y"], "b"); -p.Save(pendulum.outputDir + "/pendulumToBall.png"); +p = Plot() +p.Add(x, y, "r") +p.Add(result2["x"], result2["y"], "b") +p.Save(pendulum.outputDir + "/pendulumToBall.png") -tool.Close(); +tool.Close() diff --git a/setup.py b/setup.py index 6408001..50752ca 100644 --- a/setup.py +++ b/setup.py @@ -20,21 +20,21 @@ along with this program. If not, see . """ -from setuptools import setup, find_packages; +from setuptools import setup, find_packages setup( name="PySimLib", version="1.0.0b6", description="The Python Simulation Library allows to simulate Modelica and Simulink models in a platform-independent way.", - url = "https://gitlab.tubit.tu-berlin.de/a.mehlhase/PySimulationLibrary", + url="https://gitlab.tubit.tu-berlin.de/a.mehlhase/PySimulationLibrary", author="Alexandra Mehlhase", author_email="a.mehlhase@tu-berlin.de", - packages = ["PySimLib", "PySimLib.Exceptions", "PySimLib.Mat", "PySimLib.Models", "PySimLib.Solvers", "PySimLib.Tools"], - license = "GPL", - - install_requires = [ + packages=["PySimLib", "PySimLib.Exceptions", "PySimLib.Mat", "PySimLib.Models", "PySimLib.Solvers", "PySimLib.Tools"], + license="GPL", + + install_requires=[ "matplotlib", - "pymatbridge" #needs "zmq" + "pymatbridge" # needs "zmq" ], )