예제 #1
0
    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()
예제 #2
0
    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)
예제 #3
0
    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)
예제 #4
0
    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)
예제 #5
0
import sys
from PySimLib.Mat.Mat import Mat
from PySimLib.Mat.TextMatrix import TextMatrix

space = "\t\t"

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("Type", space, "Size", space, "Name")
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)
예제 #6
0
파일: VSM.py 프로젝트: jmoeckel/DySMo2
    def __save_observer(this):
        from PySimLib.Mat.Mat import Mat
        from PySimLib.Mat.OutputStream import OutputStream

        nan = float("NaN")
        variables = ["time", "modeID"] + this.observe
        lastVariable = variables[len(variables) - 1]

        # get for every simulation the maximum number of datapoints
        nDataPointsPerSim = []
        for p in this.__observer[
                "modeID"]:  # init all sims with datapoints-length of 1
            nDataPointsPerSim.append(1)

        for key in variables:
            if (key == "modeID"):
                continue  # unimportant

            for i in range(0, len(nDataPointsPerSim)):
                if (len(this.__observer[key][i]) > nDataPointsPerSim[i]):
                    nDataPointsPerSim[i] = len(this.__observer[key][i])
        nDataPointsSum = 0
        for n in nDataPointsPerSim:
            nDataPointsSum += n

        # write mat
        mat = Mat()

        # names matrix
        names = mat.AddTextMatrix("names", len(this.__observer))
        i = 0
        for key in variables:
            names.SetString(i, key)
            i += 1

        # values matrix
        values = mat.AddMatrix("values", len(this.__observer), nDataPointsSum)
        x = 0
        for key in variables:
            i = 0
            y = 0
            if (key == "modeID"):  # modeID is special...
                for p in this.__observer[key]:
                    for j in range(0, nDataPointsPerSim[i]):
                        values.SetValue(x, y, p)
                        y += 1
                    i += 1
            else:
                for points in this.__observer[key]:
                    for p in points:
                        values.SetValue(x, y, p)
                        y += 1
                    for j in range(len(points), nDataPointsPerSim[i]):
                        values.SetValue(x, y, nan)
                        y += 1
                    i += 1
            x += 1

        file = open("result" + os.sep + "observer_data.mat", "wb")
        stream = OutputStream(file)
        mat.Write(stream)
        file.close()

        # write csv
        file = open("result" + os.sep + "observer_data.csv", "w")

        # var names
        for key in variables:
            file.write(key)
            if (key != lastVariable):
                file.write(";")
        file.write("\n")

        # var values
        y = 0
        while (y < nDataPointsSum):
            x = 0
            for key in variables:
                p = values.GetValue(x, y)
                x += 1
                file.write(str(p))
                if (key != lastVariable):
                    file.write(";")
            file.write("\n")
            y += 1
        file.close()
예제 #7
0
    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 not None):
                value = sim.variables[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()
예제 #8
0
import sys
from PySimLib.Mat.Mat import Mat
from PySimLib.Mat.TextMatrix import TextMatrix

space = "\t\t"

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())
else:
    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))
else:
    for y in range(0, m.GetNumberOfRows()):
        line = ""
        for x in range(0, m.GetNumberOfColumns()):
            line += str(m.GetValue(x, y)) + ", "
        print(line)