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()
Exemple #2
0
    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()