Example #1
0
def main():
    jsonData = getCases()
    for (caseName, data) in jsonData.iteritems():
        # plot totalPowerLoad for each subcase of each case
        params = data[0].iteritems()
        # simulate for each set of variables
        subCaseAmount = len(params.next()[1])
        print("plotting " + str(subCaseAmount) + " subcases for case: " +
              caseName)
        plt.figure()
        for currentSubCase in range(subCaseAmount):
            print(str(currentSubCase + 1) + "/" + str(subCaseAmount))

            matFile = caseName + "_"
            plotLabel = data[1]
            variables = []
            for (varName, valueList) in data[0].iteritems():
                value = valueList[currentSubCase]
                matFile += varName + "_" + str(value)
                plotLabel += "_" + str(value)
                variables.append(varName)

            fileReader = Reader(
                os.path.join("output_" + caseName,
                             matFile.replace(".", "_") + ".mat"), "dymola")
            (t, y) = fileReader.values("totalPowerLoad")
            # seconds to days
            t = [x / 86400 for x in t]
            plt.plot(t, y, label=plotLabel)
        plt.xlabel("Time [d]")
        plt.ylabel("MWh")
        plt.legend()
        if not os.path.exists("plot_" + caseName):
            os.makedirs("plot_" + caseName)
        plt.savefig("plot_" + caseName + "/totalPowerLoad")
    def test_setBooleanParameterValues(self):
        """
        Tests the :mod:`buildingspy.simulate.Dymola.addParameters`
        function for boolean parameters.
        """

        from buildingspy.io.outputfile import Reader
        # Delete output file
        resultFile = os.path.join("BooleanParameters.mat")

        if os.path.exists(resultFile):
            os.remove(resultFile)

        s = Simulator("MyModelicaLibrary.Examples.BooleanParameters",
                      packagePath=self._packagePath)
        s.addParameters({'p1': True})
        s.addParameters({'p2': False})
        s.simulate()

        r = Reader(resultFile, "dymola")

        (_, p) = r.values('p1')
        self.assertEqual(p[0], 1.0)
        (_, p) = r.values('p2')
        self.assertEqual(p[0], 0.0)
        # Delete output files
        s.deleteOutputFiles()
    def test_setBooleanParameterValues(self):
        '''
        Tests the :mod:`buildingspy.simulate.Simulator.addParameters`
        function for boolean parameters.
        '''

        from buildingspy.io.outputfile import Reader
        # Delete output file
        resultFile = os.path.join("BooleanParameters.mat")

        if os.path.exists(resultFile):
            os.remove(resultFile)

        s = Simulator("MyModelicaLibrary.Examples.BooleanParameters", "dymola", packagePath=self._packagePath)
        s.addParameters({'p1' : True})
        s.addParameters({'p2' : False})
        s.simulate()

        r = Reader(resultFile, "dymola")

        (_, p) = r.values('p1')
        self.assertEqual(p[0], 1.0)
        (_, p) = r.values('p2')
        self.assertEqual(p[0], 0.0)
        # Delete output files
        s.deleteOutputFiles()
        s.deleteLogFiles()
Example #4
0
    def test_setResultFilterRegExp(self):
        """
        Tests the :mod:`buildingspy.simulate.Optimica.setResultFilter`
        function.
        """
        from buildingspy.io.outputfile import Reader

        model = "MyModelicaLibrary.Examples.MyStep"
        resultFile = f"{model.replace('.', '_')}_result.mat"

        # Delete output file
        if os.path.exists(resultFile):
            os.remove(resultFile)

        s = Simulator(model, packagePath=self._packagePath)
        s.setResultFilter(["*source.y"])
        s.simulate()
        self.assertTrue(
            os.path.exists(resultFile),
            f"Expected file {resultFile} to exist in test_setResultFilterRegExp."
        )
        r = Reader(resultFile, "dymola")
        (_, _) = r.values('myStep.source.y')
        # This output should not be stored
        with self.assertRaises(KeyError):
            r.values("y")

        # Delete output files
        s.deleteOutputFiles()
Example #5
0
    def run_cdl_simulation(self, model, output_folder, ip_list, op_list,
                           sample_time):
        """function that runs the CDL simulation using OpenModelica; also converts the .mat output file to .csv

        Parameters
        ----------
        model : str
                name of the modelica model
        output_folder : str
                        name of the folder where the generated mat file with the results will be saved
        ip_list : list
                  list of input variables for this model
        op_list : list
                  list of output variables for this model
        sample_time : int
                      sample time in seconds
        Returns
        -------
        simulation_output : pd.DataFrame
                            timeseries of input and output variable values from the CDL simulation
        """
        print("in running cdl simulation")
        omc = OMCSessionZMQ()
        if not omc.sendExpression("loadModel(Modelica)"):
            err = omc.sendExpression("getErrorString()")
            print("error while loading Modelica Standard Library: {}".format(
                err))

        if not omc.sendExpression("loadModel(Buildings)"):
            err = omc.sendExpression("getErrorString()")
            print("error while loading Modelica Buildings Library: {}".format(
                err))

        shutil.move("{}_res.mat".format(model),
                    output_folder + "/{}_res.mat".format(model))
        for file in os.listdir('.'):
            if file.startswith(model):
                os.remove(file)

        r = Reader(output_folder + "/{}_res.mat".format(model), 'dymola')

        df_list = []
        for ip in ip_list:
            values = r.values(ip)
            df = pd.DataFrame(index=values[0], data={ip: values[1]})
            df_list.append(df)
        for op in op_list:
            values = r.values(op)
            df = pd.DataFrame(index=values[0], data={op: values[1]})
            df_list.append(df)

        simulation_output = pd.concat(df_list, axis=1).fillna(method='ffill')
        simulation_output = simulation_output.loc[~simulation_output.index.
                                                  duplicated(keep='first')]
        simulation_output.to_csv(output_folder + "/{}_res.csv".format(model))
        simulation_output.index = simulation_output.index.astype(float)
        simulation_output.index.name = 'time'

        return simulation_output
Example #6
0
def split_plot_variable(var, s, e, x_label, file_name, var_modifier=0.0):
    mat_file = "case_" + case + ".mat"
    # PLOT
    r = Reader(os.path.join("output", mat_file), "dymola")
    (t, y) = r.values(var)
    t = t[s:e]
    y = y[s:e]
    quick_plot(t, [x + var_modifier for x in y], x_label, var, file_name)
Example #7
0
def ReadMat(dirname, matFileName, readVar, pipeList, modellist):#, lifetime, upv_File, co2_rate_file, co2_pricing_file, startYear):
    # read the MAT_Result File of the Modelica Simulation
    TA_data = []
    for case in os.listdir(dirname):
        if 'case' in case:
            matFile = dirname + "/" + case + "/" + matFileName
            r = Reader(matFile, "dymola")
            data = {'name': case}
            for v in readVar:
                if v[1] == 'max':
                    data.update({v[2]: r.max(v[0])})
                elif v[1] == 'min':
                    data.update({v[2]: r.min(v[0])})
                elif v[1] == 'integral':
                    data.update({v[2]: r.integral(v[0])})
            # if pipe is active, add its pipe length to the total pipe length
            pipeLength = 0
            for pipe in pipeList:
                data.update({pipe.name: r.max((pipe.name + ".active"))})
                if data[pipe.name] == 1:
                    pipeLength += r.max((pipe.name + ".length"))
                    pipeDiameter = r.max((pipe.name + ".diameter"))
            data.update({'Total_Pipe_Length': pipeLength})
            for m in modellist:
                data.update({m.name: r.max((m.name + ".connected"))})
            TA_data.append(data)
    return TA_data
Example #8
0
def main():
    """ Main method that plots the results
    """
    import os

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    from buildingspy.io.outputfile import Reader

    # Optionally, change fonts to use LaTeX fonts
    # from matplotlib import rc
    # rc('text', usetex=True)
    # rc('font', family='serif')

    # Read results
    ofr1 = Reader(os.path.join("buildingspy", "examples", "dymola",
                               "case1", "PIDHysteresis.mat"), "dymola")
    ofr2 = Reader(os.path.join("buildingspy", "examples", "dymola",
                               "case2", "PIDHysteresis.mat"), "dymola")
    (time1, T1) = ofr1.values("cap.T")
    (time1, y1) = ofr1.values("con.y")
    (time2, T2) = ofr2.values("cap.T")
    (time2, y2) = ofr2.values("con.y")

    # Plot figure
    fig = plt.figure()
    ax = fig.add_subplot(211)

    ax.plot(time1 / 3600, T1 - 273.15, 'r', label='$T_1$')
    ax.plot(time2 / 3600, T2 - 273.15, 'b', label='$T_2$')
    ax.set_xlabel('time [h]')
    ax.set_ylabel(r'temperature [$^\circ$C]')
    ax.set_xticks(list(range(25)))
    ax.set_xlim([0, 24])
    ax.legend()
    ax.grid(True)

    ax = fig.add_subplot(212)
    ax.plot(time1 / 3600, y1, 'r', label='$y_1$')
    ax.plot(time2 / 3600, y2, 'b', label='$y_2$')
    ax.set_xlabel('time [h]')
    ax.set_ylabel('y [-]')
    ax.set_xticks(list(range(25)))
    ax.set_xlim([0, 24])
    ax.legend()
    ax.grid(True)

    # Save figure to file
    plt.savefig('plot.pdf')
    plt.savefig('plot.png')
    def test_translate_simulate(self):
        """
        Tests the :mod:`buildingspy.simulate.Simulator.translate` and
        the :mod:`buildingspy.simulate.Simulator.simulate_translated`
        method.
        """
        import numpy as np

        from buildingspy.io.outputfile import Reader

        s = Simulator("MyModelicaLibrary.MyModel", "dymola", packagePath=self._packagePath)
        s.addModelModifier(
            "redeclare Modelica.Blocks.Sources.Step source(offset=-0.1, height=1.1, startTime=0.5)")
        s.setStartTime(-1)
        s.setStopTime(5)
        s.setTimeOut(600)
        s.setTolerance(1e-4)
        s.setSolver("dassl")
        s.setNumberOfIntervals(50)
        s.setResultFile("myResults")
        s.translate()
        s.simulate_translated()

        # Read the result and test their validity
        outDir = s.getOutputDirectory()
        resultFile = os.path.abspath(os.path.join(outDir, "myResults.mat"))
        r = Reader(resultFile, "dymola")
        np.testing.assert_allclose(1.0, r.max('source.y'))
        np.testing.assert_allclose(-0.1, r.min('source.y'))
        np.testing.assert_allclose(0.725, r.mean('source.y'))
        np.testing.assert_allclose(0.725 * 6, r.integral('source.y'))
        # Delete output files
        s.deleteOutputFiles()
        s.deleteLogFiles()

        # Make another simulation, but now the start time is at -2, and the height is 2.1
        s.setStartTime(-2)
        s.addParameters({'source.height': 2.1})
        s.simulate_translated()
        outDir = s.getOutputDirectory()
        resultFile = os.path.abspath(os.path.join(outDir, "myResults.mat"))
        r = Reader(resultFile, "dymola")
        np.testing.assert_allclose(2.0, r.max('source.y'))
        np.testing.assert_allclose(-0.1, r.min('source.y'))
        np.testing.assert_allclose(1.25, r.mean('source.y'))
        np.testing.assert_allclose(7 * 1.25, r.integral('source.y'))

        # clean up translate temporary dir
        s.deleteOutputFiles()
        s.deleteLogFiles()
        s.deleteTranslateDirectory()
Example #10
0
    def _check_model_parametrization(self):
        ''' Method that checks if the parameters set by addParameters function
        for an already translated model are actually overriding the original
        values at compilation time.
        '''
        import os
        import numpy as np
        from buildingspy.io.outputfile import Reader

        def _compare(actual_res, desired_key, desired_value):
            (t, y) = actual_res.values(desired_key)
            del t
            try:
                np.testing.assert_allclose(y[0], desired_value)
            except AssertionError:
                msg = "Parameter " + desired_key + " cannot be re-set after model translation."
                self._reporter.writeError(msg)
                raise IOError

        actual_res = Reader(
            os.path.join(self._outputDir_, self._simulator_['resultFile']) +
            '.mat', 'dymola')
        for key, value in list(self._parameters_.items()):
            if isinstance(value, list):  # lists
                for index, val in enumerate(value):
                    key_string = key + '[' + str(index + 1) + ']'
                    _compare(actual_res, key_string, val)
            else:  # int, floats
                key_string = key
                _compare(actual_res, key_string, value)
    def test_addVectorOfParameterValues(self):
        """
        Tests the :mod:`buildingspy.simulate.Dymola.addParameters`
        function for the situation where values for a parameter that is
        a vector is added.
        """
        import numpy as np
        from buildingspy.io.outputfile import Reader
        # Delete output file
        resultFile = os.path.join("Constants.mat")
        if os.path.exists(resultFile):
            os.remove(resultFile)

        s = Simulator("MyModelicaLibrary.Examples.Constants",
                      packagePath=self._packagePath)
        s.addParameters({'const1.k': [2, 3]})
        s.addParameters({'const2.k': [[1.1, 1.2], [2.1, 2.2], [3.1, 3.2]]})
        s.addParameters({'const3.k': 0})
        s.simulate()

        r = Reader(resultFile, "dymola")

        np.testing.assert_allclose(2, r.max('const1[1].y'))
        np.testing.assert_allclose(3, r.max('const1[2].y'))

        np.testing.assert_allclose(1.1, r.max('const2[1, 1].y'))
        np.testing.assert_allclose(1.2, r.max('const2[1, 2].y'))
        np.testing.assert_allclose(2.1, r.max('const2[2, 1].y'))
        np.testing.assert_allclose(2.2, r.max('const2[2, 2].y'))
        np.testing.assert_allclose(3.1, r.max('const2[3, 1].y'))
        np.testing.assert_allclose(3.2, r.max('const2[3, 2].y'))

        np.testing.assert_allclose(0, r.max('const3.y'))
        # Delete output files
        s.deleteOutputFiles()
    def test_translate_simulate_exception_parameter(self):
        '''
        Tests the :mod:`buildingspy.simulate.Simulator.translate` and
        the :mod:`buildingspy.simulate.Simulator.simulate_translated`
        method.
        This tests whether an exception is thrown if
        one attempts to change a parameter that is fixed after compilation
        '''
        import numpy as np
        from buildingspy.io.outputfile import Reader

        s = Simulator("MyModelicaLibrary.Examples.ParameterEvaluation",
                      "dymola",
                      packagePath=self._packagePath)
        s.translate()
        s.setSolver("dassl")
        desired_value = 0.2
        s.addParameters({'x': desired_value})
        # Simulate the model with new parameter and check in the output file
        # whether the parameter is really set.
        # Dymola 2016 FD01 sets it correctly, but Dymola 2016 does not.
        try:
            s.simulate_translated()
            # No exception. Check results
            actual_res = Reader(os.path.join(".", 'ParameterEvaluation.mat'),
                                'dymola')
            (_, y) = actual_res.values('x')
            (_, n) = actual_res.values('n')
            np.testing.assert_allclose(y[0], desired_value)
            np.testing.assert_allclose(n[0], 5)
        except IOError as e:
            # An IOError was raised. Make sure it is raised by simulate_translated
            print(("Caught IOError with message '{}'".format(e)))
            self.assertRaises(IOError, s.simulate_translated)
        # clean up translate temporary dir
        s.deleteTranslateDirectory()
        # Delete output files
        s.deleteOutputFiles()
        s.deleteLogFiles()
        # This is called to clean up after an exception in simulate_translated().
        s.deleteSimulateDirectory()
    def test_translate_simulate_exception_parameter(self):
        """
        Tests the :mod:`buildingspy.simulate.Simulator.translate` and
        the :mod:`buildingspy.simulate.Simulator.simulate_translated`
        method.
        This tests whether an exception is thrown if
        one attempts to change a parameter that is fixed after compilation
        """
        import numpy as np
        from buildingspy.io.outputfile import Reader

        s = Simulator("MyModelicaLibrary.Examples.ParameterEvaluation",
                      "dymola", packagePath=self._packagePath)
        s.translate()
        s.setSolver("dassl")
        desired_value = 0.2
        s.addParameters({'x': desired_value})
        # Simulate the model with new parameter and check in the output file
        # whether the parameter is really set.
        # Dymola 2016 FD01 sets it correctly, but Dymola 2016 does not.
        try:
            s.simulate_translated()
            # No exception. Check results
            actual_res = Reader(os.path.join(".",
                                             'ParameterEvaluation.mat'),
                                'dymola')
            (_, y) = actual_res.values('x')
            (_, n) = actual_res.values('n')
            np.testing.assert_allclose(y[0], desired_value)
            np.testing.assert_allclose(n[0], 5)
        except IOError as e:
            # An IOError was raised. Make sure it is raised by simulate_translated
            print(("Caught IOError with message '{}'".format(e)))
            self.assertRaises(IOError, s.simulate_translated)
        # clean up translate temporary dir
        s.deleteTranslateDirectory()
        # Delete output files
        s.deleteOutputFiles()
        s.deleteLogFiles()
        # This is called to clean up after an exception in simulate_translated().
        s.deleteSimulateDirectory()
    def test_addVectorOfParameterValues(self):
        '''
        Tests the :mod:`buildingspy.simulate.Simulator.addParameters`
        function for the situation where values for a parameter that is
        a vector is added.
        '''
        import numpy as np
        from buildingspy.io.outputfile import Reader
        # Delete output file
        resultFile = os.path.join("Constants.mat")
        if os.path.exists(resultFile):
            os.remove(resultFile)

        s = Simulator("MyModelicaLibrary.Examples.Constants", "dymola", packagePath=self._packagePath)
        s.addParameters({'const1.k' : [2, 3]})
        s.addParameters({'const2.k' : [[1.1, 1.2], [2.1, 2.2], [3.1, 3.2]]})
        s.addParameters({'const3.k' : 0})
        s.simulate()

        r = Reader(resultFile, "dymola")

        np.testing.assert_allclose(2, r.max('const1[1].y'))
        np.testing.assert_allclose(3, r.max('const1[2].y'))

        np.testing.assert_allclose(1.1, r.max('const2[1, 1].y'))
        np.testing.assert_allclose(1.2, r.max('const2[1, 2].y'))
        np.testing.assert_allclose(2.1, r.max('const2[2, 1].y'))
        np.testing.assert_allclose(2.2, r.max('const2[2, 2].y'))
        np.testing.assert_allclose(3.1, r.max('const2[3, 1].y'))
        np.testing.assert_allclose(3.2, r.max('const2[3, 2].y'))

        np.testing.assert_allclose(0, r.max('const3.y'))
        # Delete output files
        s.deleteOutputFiles()
        s.deleteLogFiles()
Example #15
0
    def test_addMethods(self):
        """
        Tests the various add methods.
        """
        import numpy as np

        from buildingspy.io.outputfile import Reader

        s = Simulator("MyModelicaLibrary.MyModel",
                      packagePath=self._packagePath)
        s.addModelModifier(
            "redeclare Modelica.Blocks.Sources.Step source(offset=-0.1, height=1.1, startTime=0.5)"
        )
        s.setStartTime(-1)
        s.setStopTime(5)
        s.setTimeOut(600)
        s.setTolerance(1e-8)
        s.setSolver("Radau5ODE")
        s.setNumberOfIntervals(50)
        s.setResultFile("myResults")
        s.simulate()
        # Read the result and test their validity
        outDir = s.getOutputDirectory()
        resultFile = os.path.abspath(os.path.join(outDir, "myResults.mat"))
        r = Reader(resultFile, "dymola")
        np.testing.assert_allclose(1.0, r.max('source.y'))
        np.testing.assert_allclose(0.725, r.mean('source.y'))
        np.testing.assert_allclose(0.725 * 6, r.integral('source.y'))
        np.testing.assert_allclose(-0.1, r.min('source.y'))
        # Delete output files
        s.deleteOutputFiles()
def _extract_data(matFile, relVal):
    """
    Extract time series data from mat file.

    :param matFile: modelica simulation result path
    :param relVal: list of variables that the data should be extracted
    """
    from buildingspy.io.outputfile import Reader
    from buildingspy.io.postprocess import Plotter
    import re

    nPoi = 8761

    try:
        r = Reader(matFile, TOOL)
    except IOError:
        raise ValueError("Failed to read {}.".format(matFile))

    result = list()
    for var in relVal:
        time = []
        val = []
        try:
            var_mat = var
            # Matrix variables in JModelica are stored in mat file with no space e.g. [1,1].
            var_mat = re.sub(' ', '', var_mat)
            (time, val) = r.values(var_mat)
            tMin = float(min(time))
            tMax = float(max(time))
            ti = _getTimeGrid(tMin, tMax, nPoi)
        except KeyError:
            raise ValueError("Result {} does not have variable {}.".format(
                matFile, var))
        else:
            intVal = Plotter.interpolate(ti, time, val)
        temp = {'variable': var, 'time': ti, 'value': intVal}
        result.append(temp)
    return result
    def test_addMethods(self):
        '''
        Tests the various add methods.
        '''
        import os
        import numpy as np

        from buildingspy.io.outputfile import Reader

        
        s = Simulator("MyModelicaLibrary.MyModel", "dymola")
        s.addPreProcessingStatement("Advanced.StoreProtectedVariables:= true;")
        s.addPostProcessingStatement("Advanced.StoreProtectedVariables:= false;")
        s.addModelModifier('redeclare Modelica.Blocks.Sources.Step source(offset=-0.1, height=1.1, startTime=0.5)')
        s.setStartTime(-1)
        s.setStopTime(5)
        s.setTimeOut(600)
        s.setTolerance(1e-4)
        s.setSolver("dassl")
        s.setNumberOfIntervals(50)
        s.setResultFile("myResults")
        s.exitSimulator(True)
        s.deleteOutputFiles()
        s.showGUI(False)
#        s.printModelAndTime()
        s.showProgressBar(False)
        s.simulate()
        # Read the result and test their validity
        outDir = s.getOutputDirectory()
        resultFile = os.path.abspath(os.path.join(outDir, "myResults.mat"))
        r=Reader(resultFile, "dymola")
        np.testing.assert_allclose(1.0, r.max('source.y'))
        np.testing.assert_allclose(0.725, r.mean('source.y'))
        np.testing.assert_allclose(0.725*6, r.integral('source.y'))
        np.testing.assert_allclose(-0.1, r.min('source.y'))
        # Delete output files
        s.deleteOutputFiles()
        s.deleteLogFiles()
Example #18
0
def main():
    """ Main method that plots the results
    """
    import os

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    from buildingspy.io.outputfile import Reader

    # Optionally, change fonts to use LaTeX fonts
    # from matplotlib import rc
    # rc('text', usetex=True)
    # rc('font', family='serif')

    # Read results
    ofr1 = Reader(
        os.path.join("buildingspy", "examples", "dymola", "case1",
                     "PIDHysteresis.mat"), "dymola")
    ofr2 = Reader(
        os.path.join("buildingspy", "examples", "dymola", "case2",
                     "PIDHysteresis.mat"), "dymola")
    (time1, T1) = ofr1.values("cap.T")
    (time1, y1) = ofr1.values("con.y")
    (time2, T2) = ofr2.values("cap.T")
    (time2, y2) = ofr2.values("con.y")

    # Plot figure
    fig = plt.figure()
    ax = fig.add_subplot(211)

    ax.plot(time1 / 3600, T1 - 273.15, 'r', label='$T_1$')
    ax.plot(time2 / 3600, T2 - 273.15, 'b', label='$T_2$')
    ax.set_xlabel('time [h]')
    ax.set_ylabel(r'temperature [$^\circ$C]')
    ax.set_xticks(list(range(25)))
    ax.set_xlim([0, 24])
    ax.legend()
    ax.grid(True)

    ax = fig.add_subplot(212)
    ax.plot(time1 / 3600, y1, 'r', label='$y_1$')
    ax.plot(time2 / 3600, y2, 'b', label='$y_2$')
    ax.set_xlabel('time [h]')
    ax.set_ylabel('y [-]')
    ax.set_xticks(list(range(25)))
    ax.set_xlim([0, 24])
    ax.legend()
    ax.grid(True)

    # Save figure to file
    plt.savefig('plot.pdf')
    plt.savefig('plot.png')
def ReadMat(dirname, matFileName, resultVar, pipeList, modellist):
    TA_data = []
    for case in os.listdir(dirname):
        if 'case' in case:
            matFile = dirname + "/" + case + "/" + matFileName
            r = Reader(matFile, "dymola")
            data = {'name': case}
            for v in resultVar:
                if v[1] == 'max':
                    data.update({v[0]: r.max(v[0])})
                elif v[1] == 'min':
                    data.update({v[0]: r.min(v[0])})
                elif v[1] == 'integral':
                    data.update({v[0]: r.integral(v[0])})
            pipeLength = 0
            for pipe in pipeList:
                data.update({pipe.name: r.max((pipe.name + ".active"))})
                if data[pipe.name] == 1:
                    pipeLength += r.max((pipe.name + ".length"))
            data.update({'Total_Pipe_Length': pipeLength})
            for m in modellist:
                data.update({m.name: r.max((m.name + ".connected"))})
            TA_data.append(data)
    return TA_data
    def test_addMethods(self):
        '''
        Tests the various add methods.
        '''
        import numpy as np

        from buildingspy.io.outputfile import Reader

        s = Simulator("MyModelicaLibrary.MyModel",
                      "dymola",
                      packagePath=self._packagePath)
        s.addPreProcessingStatement("Advanced.StoreProtectedVariables:= true;")
        s.addPostProcessingStatement(
            "Advanced.StoreProtectedVariables:= false;")
        s.addModelModifier(
            "redeclare Modelica.Blocks.Sources.Step source(offset=-0.1, height=1.1, startTime=0.5)"
        )
        s.setStartTime(-1)
        s.setStopTime(5)
        s.setTimeOut(600)
        s.setTolerance(1e-4)
        s.setSolver("dassl")
        s.setNumberOfIntervals(50)
        s.setResultFile("myResults")
        s.exitSimulator(True)
        # s.deleteOutputFiles()
        s.showGUI(False)
        #        s.printModelAndTime()
        s.showProgressBar(False)
        s.simulate()
        # Read the result and test their validity
        outDir = s.getOutputDirectory()
        resultFile = os.path.abspath(os.path.join(outDir, "myResults.mat"))
        r = Reader(resultFile, "dymola")
        np.testing.assert_allclose(1.0, r.max('source.y'))
        np.testing.assert_allclose(0.725, r.mean('source.y'))
        np.testing.assert_allclose(0.725 * 6, r.integral('source.y'))
        np.testing.assert_allclose(-0.1, r.min('source.y'))
        # Delete output files
        s.deleteOutputFiles()
        s.deleteLogFiles()
from buildingspy.io.outputfile import Reader
import matplotlib.pyplot as plt
from pylab import *
import numpy as np

rcParams['legend.loc'] = 'best'
r=Reader('HotelModel_annual.mat','dymola')
(t1,y1)=r.values('Loa.Loa')
(t2,y2)=r.values('GueRooDomWatDem.y[1]')
(t3,y3)=r.values('KitHotWatDem.y[1]')
y1=y1/1000
t1d=[]
t2d=[]
t3d=[]

y1d=[]
y2d=[]
y3d=[]

for i in range(len(y1)):
   if t1[i]>3715200 and t1[i]<3801600:
    t1d.append(t1[i])
    y1d.append(y1[i])
	
for i in range(len(y2)):
   if t2[i]>3715200 and t2[i]<3801600:
    t2d.append(t2[i])
    y2d.append(y2[i])	

for i in range(len(y3)):
   if t3[i]>3715200 and t3[i]<3801600:
Example #22
0
# change result order since energyplus result file is not that same as
indices = [0, 2, 1, 3]
TMax_min = np.array([TMax_min[i] for i in indices])
TMax_max = np.array([TMax_max[i] for i in indices])
TMax_avg = np.array([TMax_Avg[i] for i in indices])
TMax_E_plus = np.array([TMax_E_plus[i] for i in indices])
TMin_min = np.array([TMin_min[i] for i in indices])
TMin_max = np.array([TMin_max[i] for i in indices])
TMin_avg = np.array([TMin_avg[i] for i in indices])
TMin_E_plus = np.array([TMin_E_plus[i] for i in indices])
TAvg_min = np.array([TAvg_min[i] for i in indices])
TAvg_max = np.array([TAvg_max[i] for i in indices])
TAvg_avg = np.array([TAvg_avg[i] for i in indices])
TAvg_E_plus = np.array([TAvg_E_plus[i] for i in indices])

reader = Reader("/tmp/BESTEST.mat", "dymola")

fig = plt.figure(figsize=(10, 3.5))

legendsize = 10
N = 6

#gs = gridspec.GridSpec(4,1,height_ratios=[1,1,1,1])

ax0 = plt.subplot(1, 1, 1)
# print(reader.values("EAnnHea600[1]")[1][-1])
# exit(0)
plot_results(ax0,
             EHeacase600_Avg,
             EHeacase600_Min,
             EHeacase600_Max,
def simulate_in_dymola(heaPum, data, tableName, tableFileName):
    """ Evaluate the heat pump performance from the model in Dymola.

    :param heaPum: Heat pump model (object).
    :param data: Reference performance data (object).
    :param tableName: Name of the combiTimeTable.
    :param tableFileName: Name of the text file containing the combiTimeTable.

    :return: Performance data of the modeled heat pump (object).

    .. note:: Performance data from the model is evaluated at the same
              operating conditions (inlet water temperatures and mass flow
              rates at the source and load sides) as in the reference data.

    """
    import buildingspy.simulate.Simulator as si
    from buildingspy.io.outputfile import Reader
    from scipy.interpolate import interp1d
    from builtins import str
    import getpass
    import os
    import tempfile

    # Find absolute path to buildings library
    packagePath = os.path.normpath(
        os.path.join(os.path.normpath(os.path.dirname(__file__)),
                     '..', '..', '..', '..', '..', '..'))

    # Create temporary directory for simulation files
    dirPrefix = tempfile.gettempprefix()
    tmpDir = tempfile.mkdtemp(prefix=dirPrefix + '-'
                              + 'HeatPumpCalibration' + '-'
                              + getpass.getuser() + '-')

    # Set parameters for simulation in Dymola
    calModelPath = heaPum.modelicaCalibrationModelPath()
    s = si.Simulator(calModelPath,
                     'dymola',
                     outputDirectory=tmpDir,
                     packagePath=packagePath)
    s = heaPum.set_ModelicaParameters(s)
    m1_flow_nominal = min(data.flowSource)
    m2_flow_nominal = min(data.flowLoad)
    tableFilePath = \
        str(os.path.join(tmpDir, tableFileName).replace(os.sep, '/'))
    s.addParameters({'m1_flow_nominal': m1_flow_nominal,
                     'm2_flow_nominal': m2_flow_nominal,
                     'calDat.fileName': tableFilePath})

    # Write CombiTimeTable for dymola
    data.write_modelica_combiTimeTable(tableName, tmpDir,
                                       tableFileName, heaPum.CoolingMode)

    # Simulation parameters
    s.setStopTime(len(data.EWT_Source))
    s.setSolver('dassl')
    # Kill the process if it does not finish in 2 minutes
    s.setTimeOut(120)
    s.showProgressBar(False)
    s.printModelAndTime()
#    s.showGUI(show=True)
#    s.exitSimulator(exitAfterSimulation=False)
    s.simulate()

    # Read results
    modelName = heaPum.modelicaModelName()
    ofr = Reader(os.path.join(tmpDir, modelName), 'dymola')
    (time1, QCon) = ofr.values('heaPum.QCon_flow')
    (time1, QEva) = ofr.values('heaPum.QEva_flow')
    (time1, P) = ofr.values('heaPum.P')

    t = [float(i) + 0.5 for i in range(len(data.EWT_Source))]

    f_P = interp1d(time1, P)
    P = f_P(t)
    f_QCon = interp1d(time1, QCon)
    QCon = f_QCon(t)
    f_QEva = interp1d(time1, QEva)
    QEva = f_QEva(t)

#    # Clean up
#    shutil.rmtree('calibrationModel')
    if heaPum.CoolingMode:
        Capacity = -QEva
        HR = QCon
    else:
        Capacity = QCon
        HR = -QEva
    dymRes = SimulationResults(data.EWT_Source,
                               data.EWT_Load,
                               data.flowSource,
                               data.flowLoad,
                               Capacity,
                               HR,
                               P,
                               'Modelica')
    return dymRes
Example #24
0
                    c, keyword if not keyword else '.' + keyword, v))[1]
                resultsFull[c][v] = temp
                results[c][v] = temp[iGet]

        else:
            print('No results found for {}'.format(c))

    if writeToFile:
        writeValues(components, results, fileName)

    return results


if __name__ == "__main__":
    #    r = Reader('GenericModule3.mat','dymola')
    r = Reader('SouthEast3.mat', 'dymola')

    prefix = 'PHS'

    components_GenericPipe = [
        'core.coolantSubchannel', 'hotLeg', 'coldLeg', 'STHX.tube',
        'STHX.shell'
    ]
    components_SimpleVolume = ['inletPlenum', 'outletPlenum']
    components_Cylinder_FD = [
        'core.fuelModel.region_1', 'core.fuelModel.region_2',
        'core.fuelModel.region_3'
    ]
    components_Conduction_2D = ['STHX.tubeWall']
    components_ExpansionTank_1Port = ['pressurizer']
    components_TeeJunctionVolume = ['pressurizer_tee']
Example #25
0
# Internal heat gains
ep_int_con= \
           df['LIGHTS 1 ROOM 102:Lights Radiant Heating Rate [W](TimeStep)'] + \
           df['LIGHTS 1 ROOM 102_CHRIS:Lights Convective Heating Rate [W](TimeStep)'] + \
           df['ELECEQ 1 ROOM 102:Electric Equipment Radiant Heating Rate [W](TimeStep)'] + \
           df['ROOM 102:Zone Other Equipment Radiant Heating Rate [W](TimeStep)']

ep_int_rad= \
           df['LIGHTS 1 ROOM 102:Lights Convective Heating Rate [W](TimeStep)'] + \
           df['LIGHTS 1 ROOM 102_CHRIS:Lights Convective Heating Rate [W](TimeStep)'] + \
           df['ELECEQ 1 ROOM 102:Electric Equipment Convective Heating Rate [W](TimeStep)'] + \
           df['ROOM 102:Zone Other Equipment Convective Heating Rate [W](TimeStep)']


mo_fil_name="/home/thierry/vmWareLinux/proj/buildings_library/models/modelica/git/71_T/modelica-buildings/Buildings/ElectroChromicWindow.mat"
mof=Reader(mo_fil_name, "dymola")
#(mo_tim, mo_inf) = mof.values("inf.m_flow")
# Heat gains in W/m2 (but they are zero anyway.
(mo_par, mo_qConGai_flow) =  mof.values("qConGai_flow.y")
(mo_par, mo_qRadGai_flow) =  mof.values("qRadGai_flow.y")

###############################################################
# Absorbed solar radiation
ep_AGla=8.71 # Glass area, from 71T_singleRoom_Geometry.txt
ep_qAbs_sol1=df['GLASS:Surface Window Total Absorbed Shortwave Radiation Rate Layer 1 [W](TimeStep)']/ep_AGla
ep_qAbs_sol2=df['GLASS:Surface Window Total Absorbed Shortwave Radiation Rate Layer 2 [W](TimeStep)']/ep_AGla

ep_HTotInc=df['GLASS:Surface Outside Face Incident Solar Radiation Rate per Area [W/m2](TimeStep)']
ep_HBeaInc=df['GLASS:Surface Outside Face Incident Beam Solar Radiation Rate per Area [W/m2](TimeStep)']

Example #26
0
TMax_min = np.array([TMax_min[i] for i in indices])
TMax_max = np.array([TMax_max[i] for i in indices])
TMax_avg = np.array([TMax_Avg[i] for i in indices])
TMax_E_plus = np.array([TMax_E_plus[i] for i in indices])
TMin_min = np.array([TMin_min[i] for i in indices])
TMin_max = np.array([TMin_max[i] for i in indices])
TMin_avg = np.array([TMin_avg[i] for i in indices])
TMin_E_plus = np.array([TMin_E_plus[i] for i in indices])
TAvg_min = np.array([TAvg_min[i] for i in indices])
TAvg_max = np.array([TAvg_max[i] for i in indices])
TAvg_avg = np.array([TAvg_avg[i] for i in indices])
TAvg_E_plus = np.array([TAvg_E_plus[i] for i in indices])



reader =Reader("/tmp/BESTEST.mat", "dymola")


fig=plt.figure(figsize=(10,3.5))

legendsize=10
N=6

#gs = gridspec.GridSpec(4,1,height_ratios=[1,1,1,1])

ax0 = plt.subplot(1,1,1)
# print(reader.values("EAnnHea600[1]")[1][-1])
# exit(0)
plot_results(ax0, EHeacase600_Avg, EHeacase600_Min, EHeacase600_Max, EHeacase600_E_plus, np.array([reader.values("EAnnHea600[" + str(i+1) + "]")[1][-1] for i in range(N)]), N, -0.3, marker=r'$\mathrm{E}_H$')
plt.ylabel('Normalized errors $e_i$')
plt.legend(frameon=False,prop={'size':legendsize},loc=2,ncol=3,numpoints=1)
from buildingspy.io.outputfile import Reader
import matplotlib.pyplot as plt
from pylab import figure
import os

# Change fonts to use LaTeX fonts
from matplotlib import rc
rc('text', usetex=True)
rc('font', family='serif')

# Read results
ofr=Reader("Temperature_u.mat", "dymola")
(t, u)    = ofr.values("u")
u /= 1e6
(t, T)    = ofr.values("T")
(t, TMon) = ofr.values("TMonotone")
(t, e)    = ofr.values("errNonMonotone")
(t, eMon) = ofr.values("errMonotone")

# Plot figure
fig = plt.figure()
ax = fig.add_subplot(211)

ax.plot(u, T-273.15, 'r', label='$T$')
ax.plot(u, TMon-273.15, '--b', markevery=5, label='$T_{monotone}$')
ax.set_xlabel('u [MJ/kg]')
ax.set_ylabel('temperature [$^\circ$C]')
#ax.set_xticks(range(25))
#ax.set_xlim([0, 24])
ax.legend(loc='lower right')
ax.grid(True)
Example #28
0
def _profile_dymola(result):
    ''' Run simulation with dymola. The function returns
        CPU time used for compile and simulation.
    '''
    import datetime
    import time

    from buildingspy.simulate.Simulator import Simulator
    from buildingspy.io.outputfile import Reader

    model=result['model']
    modelName = model.split(".")[-1]

    worDir = create_working_directory()
    # Update MODELICAPATH to get the right library version
    s=Simulator(model, "dymola", outputDirectory=worDir)
    s.setSolver(result['solver'])
    s.setStartTime(result['start_time'])
    s.setStopTime(result['stop_time'])
    s.setTolerance(result['tolerance'])
    timeout = result['timeout']
    if float(timeout) > 0.01:
        s.setTimeOut(timeout)
    tstart_tr = datetime.datetime.now()
    s.simulate()
    tend_tr = datetime.datetime.now()
    # total time
    tTotTim = (tend_tr-tstart_tr).total_seconds()
    resultFile = os.path.join(worDir, "{}.mat".format(modelName))

    # In case of timeout or error, the output file may not exist
    if not os.path.exists(resultFile):
        shutil.rmtree(worDir)
        return {'tTra': 0,
            'tCPU': 0,
            'nTimeEvent': 0,
            'nStateEvent': 0,
            'nStepEvent': 0}

    r=Reader(resultFile, "dymola")
    tCPU=r.max("CPUtime")
    tTra = tTotTim-tCPU
    nEve=r.max('EventCounter')

    eveLog = N.zeros(3)
    searchEve = list()
    searchEve.append("Number of (model) time events             :")
    searchEve.append("Number of time    events                 :")
    searchEve.append("Number of step     events                 :")
    # ------ search and retrieve times from compile log file ------
    with open(os.path.join(worDir,'dslog.txt'), "r") as f:
        for line in f:
            for index, strLin in enumerate(searchEve):
                if strLin in line:
                    sect1 = line.split(": ")
                    sect2 = sect1[1].split("\n")
                    eveLog[index] = sect2[0]
    f.close()

    shutil.rmtree(worDir)
    return {'tTra': float(tTra),
            'tCPU': float(tCPU),
            'nTimeEvent': float(eveLog[0]),
            'nStateEvent': float(eveLog[1]),
            'nStepEvent': float(eveLog[2])}
# Used in Tasks 1, 2 for plotting modelica output
# original code from Gregor Henze/Yangyang Fu

from buildingspy.io.outputfile import Reader
import matplotlib.pyplot as plt

Path = "/Users/maggie/Documents/AREN5010-HVAC-Modeling-and-Control/Modeling/OpenModelica/Task1_scenarios/"


resultFile = "LTM_full_excite/LTM-full_excite.mat"
fname = "LTM"

#resultFile = "LightWallTestScenario/LWT.mat"
#fname = "LWT"

r = Reader(Path + resultFile, "dymola")

(time, Ts_ext) = r.values(fname + '.Ts_ext')
(time, Ts_int) = r.values(fname + '.Ts_int')
(time, T_ext) = r.values(fname + '.T_ext')
(time, T_int) = r.values(fname + '.T_int')
(time, qs_ext) = r.values(fname + '.qs_ext')
(time, qs_int) = r.values(fname + '.qs_int')


print(len(time), len(Ts_ext), len(Ts_int), len(T_ext), len(T_int), len(qs_ext), len(qs_int))

# Plot figure
fig = plt.figure()
ax = fig.add_subplot(211)
Example #30
0
    def test_teaser_district_heating_and_cooling_systems(self):
        # create cooling network and plant
        cooling_network = Network2Pipe(self.sys_params)
        cooling_plant = CoolingPlant(self.sys_params)

        # create heating network and plant
        heating_network = Network2Pipe(self.sys_params)
        heating_plant = HeatingPlantWithOptionalCHP(self.sys_params)

        # create our load/ets/stubs
        # store all couplings to construct the District system
        all_couplings = [
            Coupling(cooling_network, cooling_plant),
            Coupling(heating_network, heating_plant),
        ]

        # keep track of separate loads and etses for testing purposes
        loads = []
        heat_etses = []
        cool_etses = []
        for geojson_load in self.gj.buildings:
            teaser_load = Teaser(self.sys_params, geojson_load)
            loads.append(teaser_load)
            geojson_load_id = geojson_load.feature.properties["id"]

            cooling_indirect = CoolingIndirect(self.sys_params,
                                               geojson_load_id)
            cool_etses.append(cooling_indirect)
            all_couplings.append(Coupling(teaser_load, cooling_indirect))
            all_couplings.append(Coupling(cooling_indirect, cooling_network))

            heating_indirect = HeatingIndirect(self.sys_params,
                                               geojson_load_id)
            heat_etses.append(heating_indirect)
            all_couplings.append(Coupling(teaser_load, heating_indirect))
            all_couplings.append(Coupling(heating_indirect, heating_network))

        # create the couplings and graph
        graph = CouplingGraph(all_couplings)

        district = District(root_dir=self.output_dir,
                            project_name=self.project_name,
                            system_parameters=self.sys_params,
                            coupling_graph=graph)
        district.to_modelica()

        root_path = Path(district._scaffold.districts_path.files_dir).resolve()
        self.run_and_assert_in_docker(
            Path(root_path) / 'DistrictEnergySystem.mo',
            project_path=district._scaffold.project_path,
            project_name=district._scaffold.project_name)

        #
        # Validate model outputs
        #
        results_dir = f'{district._scaffold.project_path}_results'
        mat_file = f'{results_dir}/{self.project_name}_Districts_DistrictEnergySystem_result.mat'
        mat_results = Reader(mat_file, 'dymola')

        # check the mass flow rates of the first load are in the expected range
        load = loads[0]
        (_, heat_m_flow
         ) = mat_results.values(f'{load.id}.ports_aHeaWat[1].m_flow')
        (_, cool_m_flow
         ) = mat_results.values(f'{load.id}.ports_aChiWat[1].m_flow')
        self.assertTrue(
            (heat_m_flow >= 0).all(),
            'Heating mass flow rate must be greater than or equal to zero')
        self.assertTrue(
            (cool_m_flow >= 0).all(),
            'Cooling mass flow rate must be greater than or equal to zero')

        # this tolerance determines how much we allow the actual mass flow rate to exceed the nominal value
        M_FLOW_NOMINAL_TOLERANCE = 0.01
        (_, heat_m_flow_nominal
         ) = mat_results.values(f'{load.id}.terUni[1].mLoaHea_flow_nominal')
        heat_m_flow_nominal = heat_m_flow_nominal[0]
        (_, cool_m_flow_nominal
         ) = mat_results.values(f'{load.id}.terUni[1].mLoaCoo_flow_nominal')
        cool_m_flow_nominal = cool_m_flow_nominal[0]
        # TODO: remove try/except this is fixed
        try:
            self.assertTrue(
                (heat_m_flow <= heat_m_flow_nominal +
                 (heat_m_flow_nominal * M_FLOW_NOMINAL_TOLERANCE)).all(),
                f'Heating mass flow rate must be less than nominal mass flow rate ({heat_m_flow_nominal}) '
                f'plus a tolerance ({M_FLOW_NOMINAL_TOLERANCE * 100}%)')
        except Exception as e:
            print(f'WARNING: assertion failed: {e}')
        try:
            self.assertTrue(
                (cool_m_flow <= cool_m_flow_nominal +
                 (cool_m_flow_nominal * M_FLOW_NOMINAL_TOLERANCE)).all(),
                f'Cooling mass flow rate must be less than nominal mass flow rate ({cool_m_flow_nominal}) '
                f'plus a tolerance ({M_FLOW_NOMINAL_TOLERANCE * 100}%)')
        except Exception as e:
            print(f'WARNING: assertion failed: {e}')
    def test_translate_simulate(self):
        '''
        Tests the :mod:`buildingspy.simulate.Simulator.translate` and
        the :mod:`buildingspy.simulate.Simulator.simulate_translated`
        method.
        '''
        import numpy as np

        from buildingspy.io.outputfile import Reader

        s = Simulator("MyModelicaLibrary.MyModel",
                      "dymola",
                      packagePath=self._packagePath)
        s.addModelModifier(
            "redeclare Modelica.Blocks.Sources.Step source(offset=-0.1, height=1.1, startTime=0.5)"
        )
        s.setStartTime(-1)
        s.setStopTime(5)
        s.setTimeOut(600)
        s.setTolerance(1e-4)
        s.setSolver("dassl")
        s.setNumberOfIntervals(50)
        s.setResultFile("myResults")
        s.translate()
        s.simulate_translated()

        # Read the result and test their validity
        outDir = s.getOutputDirectory()
        resultFile = os.path.abspath(os.path.join(outDir, "myResults.mat"))
        r = Reader(resultFile, "dymola")
        np.testing.assert_allclose(1.0, r.max('source.y'))
        np.testing.assert_allclose(-0.1, r.min('source.y'))
        np.testing.assert_allclose(0.725, r.mean('source.y'))
        np.testing.assert_allclose(0.725 * 6, r.integral('source.y'))
        # Delete output files
        s.deleteOutputFiles()
        s.deleteLogFiles()

        # Make another simulation, but now the start time is at -2, and the height is 2.1
        s.setStartTime(-2)
        s.addParameters({'source.height': 2.1})
        s.simulate_translated()
        outDir = s.getOutputDirectory()
        resultFile = os.path.abspath(os.path.join(outDir, "myResults.mat"))
        r = Reader(resultFile, "dymola")
        np.testing.assert_allclose(2.0, r.max('source.y'))
        np.testing.assert_allclose(-0.1, r.min('source.y'))
        np.testing.assert_allclose(1.25, r.mean('source.y'))
        np.testing.assert_allclose(7 * 1.25, r.integral('source.y'))

        # clean up translate temporary dir
        s.deleteOutputFiles()
        s.deleteLogFiles()
        s.deleteTranslateDirectory()
Example #32
0
Delta_T = []
DNI = []
m_wf = []
T_amb = []
v_wind = []

DNIExp = []
T_suExp = []
T_exExp = []
m_wfExp = []

vector = [ 0, 1]

for KKK in range(len(StartModTime)):
    resultFile=(ModResults+Days[KKK]+'/'+FileSimulation+".mat")
    r=Reader(resultFile, "dymola")
    DNI.append(r.values('DNI.y'))
    NN.append(r.values('EuroTrough.N'))
    T_su.append(r.values('SensTsu.fluidState.T'))
    T_ex.append(r.values('SensTex.fluidState.T'))



#resultFile='/Users/adriano/Google Drive/GitHub/PSA_SFERAII/Modelling/ModelicaResults/20160629/PTTL_SF_.mat'
#r=Reader(resultFile, "dymola")
#DNI.append(r.values('DNI.y'))
#NN.append(r.values('EuroTrough.N'))
#T_su.append(r.values('SensTsu.fluidState.T'))
#T_ex.append(r.values('SensTex.fluidState.T'))
#TimeSim.append(T_ex[KKK][0])
##T_ex_exp.append(r.values('t_htf_ex.y'))
Example #33
0
from buildingspy.io.outputfile import Reader
import matplotlib.pyplot as plt
import os

# Optionally, change fonts to use LaTeX fonts
#from matplotlib import rc
#rc('text', usetex=True)
#rc('font', family='serif')

# Read results
ofr1=Reader(os.path.join("buildingspy", "examples", "dymola", "case1", "PIDHysteresis.mat"), "dymola")
ofr2=Reader(os.path.join("buildingspy", "examples", "dymola", "case2", "PIDHysteresis.mat"), "dymola")
(time1, T1) = ofr1.values("cap.T")
(time1, y1) = ofr1.values("con.y")
(time2, T2) = ofr2.values("cap.T")
(time2, y2) = ofr2.values("con.y")

# Plot figure
fig = plt.figure()
ax = fig.add_subplot(211)

ax.plot(time1/3600, T1-273.15, 'r', label='$T_1$')
ax.plot(time2/3600, T2-273.15, 'b', label='$T_2$')
ax.set_xlabel('time [h]')
ax.set_ylabel('temperature [$^\circ$C]')
ax.set_xticks(range(25))
ax.set_xlim([0, 24])
ax.legend()
ax.grid(True)

ax = fig.add_subplot(212)
def simulate(dpi=300, plotDirectory='plots'):
    # Set the comparison for dymola results

    dymolaComparisons = ['non-fmu-all', 'fmu-all', 'non-fmu', 'fmu']

    # In[3]:

    # Create plot directory
    # plotDirectory = 'plots'
    plotPath = plotDirectory
    if os.path.exists(plotPath):
        shutil.rmtree(plotPath)

    os.makedirs(plotPath)
    for key in dymolaComparisons:
        os.makedirs(os.path.join(plotPath, key))

    for dymolaComparison in dymolaComparisons:

        # # FMpy Library

        # In[4]:

        fmu_tests = ['Connectors', 'Inputs', 'Parameters']
        for fmu_test in fmu_tests:
            #     fmu_test = fmu_tests[0]
            fmu_path = '../FMUs/' + fmu_test + '/'
            fmu = fmu_path + 'FMIRaven_Models_LorenzSystem_' + fmu_test + '.fmu'

            # In[5]:

            fmpy.dump(fmu)

            # In[6]:

            model_description = fmpy.read_model_description(fmu)

            # In[7]:

            vrs = []
            for variable in model_description.modelVariables:
                vrs.append(variable.name)

            # In[8]:

            vrs

            # In[9]:

            outputs = ['x', 'y', 'z', 'sigma', 'beta', 'rho']
            start_values = {'sigma': 10, 'rho': 28, 'beta': 8 / 3}
            inputs = np.genfromtxt('input_test.txt', delimiter=',', names=True)
            result = fmpy.simulate_fmu(
                fmu, output=outputs, start_values=start_values
            )  #,input=inputs)         # simulate the FMU

            # In[10]:

            from fmpy.util import plot_result  # import the plot function
            # plot_result(result,names=outputs)

            fig, ax = plt.subplots(len(outputs), 1, figsize=[12, 12])
            for i, v in enumerate(outputs):
                ax[i].plot(result['time'], result[v])
                ax[i].set_ylabel(v, rotation=0, labelpad=20)

            fig.savefig(plotPath +
                        '/{}/{}_fmpy.png'.format(dymolaComparison, fmu_test),
                        dpi=dpi)

            # # pyFMI Library

            # In[11]:

            from pyfmi import load_fmu
            model = load_fmu(fmu)
            model.set('sigma', 10)
            model.set('beta', 8 / 3)
            model.set('rho', 28)
            res_pyfmi = model.simulate()

            # In[12]:

            fig, ax = plt.subplots(len(outputs), 1, figsize=[12, 12])
            for i, v in enumerate(outputs):
                ax[i].plot(res_pyfmi['time'], res_pyfmi[v])
                ax[i].set_ylabel(v, rotation=0, labelpad=20)

            fig.savefig(plotPath +
                        '/{}/{}_pyfmi.png'.format(dymolaComparison, fmu_test),
                        dpi=dpi)

            # # Dymola Result File

            # In[13]:

            from buildingspy.io.outputfile import Reader

            # In[14]:

            if dymolaComparison == 'non-fmu-all':
                dymResultPath = 'MATFiles/BasicTest.mat'
                modelName = fmu_test

            elif dymolaComparison == 'fmu-all':
                dymResultPath = 'MATFiles/FMU_BasicTest.mat'
                modelName = fmu_test

            elif dymolaComparison == 'non-fmu':
                dymResultPath = 'MATFiles/{}.mat'.format(fmu_test)
                modelName = 'fmu'

            elif dymolaComparison == 'fmu':
                dymResultPath = 'MATFiles/FMU_{}.mat'.format(fmu_test)
                modelName = 'fmu'

            else:
                raise ValueError('Unsported dymolaComparison')

            res = Reader(dymResultPath, simulator='dymola')

            # In[15]:

            res_dym = {}
            res_dym['time'], res_dym['x'] = res.values(
                '{}.x'.format(modelName))
            _, res_dym['y'] = res.values('{}.y'.format(modelName))
            _, res_dym['z'] = res.values('{}.z'.format(modelName))
            _, res_dym['sigma'] = res.values('{}.sigma'.format(modelName))
            _, res_dym['beta'] = res.values('{}.beta'.format(modelName))
            _, res_dym['rho'] = res.values('{}.rho'.format(modelName))

            # In[16]:

            fig, ax = plt.subplots(len(outputs), 1, figsize=[12, 12])
            for i, v in enumerate(outputs):
                try:
                    ax[i].plot(res_dym['time'], res_dym[v])
                    ax[i].set_ylabel(v, rotation=0, labelpad=20)
                except:
                    pass
            fig.savefig(plotPath +
                        '/{}/{}_dymola.png'.format(dymolaComparison, fmu_test),
                        dpi=dpi)

            # # Result Comparison

            # In[17]:

            fig, ax = plt.subplots(len(outputs), 1, figsize=[12, 12])
            for i, v in enumerate(outputs):
                ax[i].plot(result['time'], result[v], 'k-', label='FMpy')
                ax[i].plot(res_pyfmi['time'],
                           res_pyfmi[v],
                           'b--',
                           label='pyFMI')
                try:
                    ax[i].plot(res_dym['time'],
                               res_dym[v],
                               'r-.',
                               label='Dymola')
                except:
                    pass
                ax[i].legend()
                ax[i].set_ylabel(v, rotation=0, labelpad=20)

            fig.savefig(
                plotPath +
                '/{}/{}_comparison.png'.format(dymolaComparison, fmu_test),
                dpi=dpi)

            # # Diff between FMU and Dymola

            # In[18]:

            fig, ax = plt.subplots(len(outputs), 1, figsize=[12, 12])
            for i, v in enumerate(outputs):
                try:
                    ax[i].plot(result['time'],
                               result[v] - res_dym[v],
                               'k-',
                               label='FMpy - Dymola')
                    ax[i].plot(result['time'],
                               res_pyfmi[v] - res_dym[v],
                               'b--',
                               label='pyFMI - Dymola')
                except:
                    pass
                ax[i].legend()
                ax[i].set_ylabel(v, rotation=0, labelpad=20)

            fig.savefig(plotPath + '/{}/{}_diff_FMUtoDymola.png'.format(
                dymolaComparison, fmu_test),
                        dpi=dpi)

            # # Diff between FMUs

            # In[19]:

            fig, ax = plt.subplots(len(outputs), 1, figsize=[12, 12])
            for i, v in enumerate(outputs):
                try:
                    ax[i].plot(result['time'],
                               result[v] - res_pyfmi[v],
                               'k-',
                               label='FMpy - pyFMI')
                except:
                    pass
                ax[i].legend()
                ax[i].set_ylabel(v, rotation=0, labelpad=20)

            fig.savefig(
                plotPath +
                '/{}/{}_diff_FMUtoFMU.png'.format(dymolaComparison, fmu_test),
                dpi=dpi)

    plt.close('all')
Example #35
0
        # Account for values with only a start/stop value
        if np.size(r.values(val)) == 4:
            yRaw = np.ones(len(time)) * yRaw[0]

        y = removeRepeats((time, yRaw), 0, True)

        yint, tint = uniformData(t, y, tstart, tstop, nt)
        data[val] = yint
    data['time'] = tint

    return data


if __name__ == "__main__":

    r = Reader('dsres.mat', 'dymola')

    varNames_param_base = []
    varNames_var_base = []
    for i, val in enumerate(r.varNames()):
        if np.size(r.values(val)) == 4:
            varNames_param_base.append(val)
        else:
            varNames_var_base.append(val)

    varNames_param = varNames_param_base
    varNames_var = varNames_var_base

    params = cleanDataParam(r, varNames_param)
    data = cleanDataTime(r, varNames_var, 0, 1, 201)
from buildingspy.io.outputfile import Reader
import matplotlib.pyplot as plt
from pylab import *
import numpy as np

rcParams['legend.loc'] = 'best'
r=Reader('HotelModel_Annual.mat','dymola')
(t1,y1)=r.values('realExpression.y')
(t2,y2)=r.values('supCon.y')


y1=y1*100
xlabind=[]
xlab=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Dec','Nov']
x=(t1[len(t1)-1]-t1[0])/12
for i in range(12):
   xlabind.append(t1[0]+x*(0.5+i))
   xlab.append(str(i))

ax1 = plt.subplot(2,1,1)
ax1.scatter(t2,y2,color='black',s=0.2)
ax1.set_ylabel('Stage')
ylim(0,8)
xtic=[1]
xticks(xtic,'')

ax2 = plt.subplot(2,1,2)
ax2.scatter(t1,y1,color='black',s=0.2)
ax2.set_ylabel('Hot Energy saving ratio(%)')
ylim(0,35)
ax2.legend(fontsize='10')
T_ex_exp = []
Delta_T = []
DNI = []
m_wf = []
T_amb = []
v_wind = []

DNIExp = []
T_suExp = []
T_exExp = []
m_wfExp = []


for KKK in range(len(StartModTime)):
    resultFile=('/Users/adriano/Dropbox/GitHub/PSA_SFERAII/Modelling/ModelicaResults/'+Days[KKK]+'/'+FileSimulation+".mat")
    r=Reader(resultFile, "dymola")
    DNI.append(r.values('DNI.y'))
    NN.append(r.values('EuroTrough.N'))
    T_su.append(r.values('SensTsu.fluidState.T'))
    T_ex.append(r.values('SensTex.fluidState.T'))
    TimeSim.append(T_ex[KKK][0])
    T_ex_exp.append(r.values('t_htf_ex.y'))
    Delta_T.append(r.values('DeltaT.Delta'))
    m_wf.append(r.values('m_dot_htf.y'))


    # Create a time vector which values every 10 seconds
    TimeExp.append(np.linspace(StartModTime[KKK],StopModTime[KKK],num=int((StopModTime[KKK]-StartModTime[KKK])/10)))

    # Interpolate the Modelica results over the Time vector
    DNIExp.append(Plotter.interpolate(TimeExp[KKK], DNI[KKK][0], DNI[KKK][1]))
Example #38
0
DNI = []
m_wf = []
T_amb = []
v_wind = []

DNIExp = []
T_suExp = []
T_exExp = []
m_wfExp = []

vector = [0, 1]
for KKK in range(len(StartModTime)):
    resultFile = (
        '/Users/adriano/Google Drive/GitHub/PSA_SFERAII/Modelling/ModelicaResults/'
        + Days[KKK] + '/' + FileSimulation + ".mat")
    r = Reader(resultFile, "dymola")
    DNI.append(r.values('DNI.y'))
    NN.append(r.values('EuroTrough.N'))
    T_su.append(r.values('SensTsu.fluidState.T'))
    T_ex.append(r.values('SensTex.fluidState.T'))
    TimeSim.append(T_ex[KKK][0])
    T_ex_exp.append(r.values('t_htf_ex.y'))
    Delta_T.append(r.values('DeltaT.Delta'))
    m_wf.append(r.values('m_dot_htf.y'))

    # Create a time vector which values every 5 seconds

    TimeExp.append(
        np.linspace(StartModTime[KKK],
                    StopModTime[KKK],
                    num=int((StopModTime[KKK] - StartModTime[KKK]) / 10)))
Example #39
0
Delta_T = []
DNI = []
m_wf = []
T_amb = []
v_wind = []

DNIExp = []
T_suExp = []
T_exExp = []
m_wfExp = []

vector = [0, 1]

for KKK in range(len(StartModTime)):
    resultFile = (ModResults + Days[KKK] + '/' + FileSimulation + ".mat")
    r = Reader(resultFile, "dymola")
    DNI.append(r.values('DNI.y'))
    NN.append(r.values('EuroTrough.N'))
    T_su.append(r.values('SensTsu.fluidState.T'))
    T_ex.append(r.values('SensTex.fluidState.T'))

#resultFile='/Users/adriano/Google Drive/GitHub/PSA_SFERAII/Modelling/ModelicaResults/20160629/PTTL_SF_.mat'
#r=Reader(resultFile, "dymola")
#DNI.append(r.values('DNI.y'))
#NN.append(r.values('EuroTrough.N'))
#T_su.append(r.values('SensTsu.fluidState.T'))
#T_ex.append(r.values('SensTex.fluidState.T'))
#TimeSim.append(T_ex[KKK][0])
##T_ex_exp.append(r.values('t_htf_ex.y'))
#Delta_T.append(r.values('DeltaT.Delta'))
#m_wf.append(r.values('m_dot_htf.y'))
    table['time'] = new_x
    for i in range(len(x)):
        x[i] = int(x[i])
    table2 = pd.DataFrame()
    table2['time'] = x
    table2[name] = y
    table2 = table2.drop_duplicates(['time'])
    table = table.merge(table2, how='left')

    return table


baseline = '0'
season = 'summer1'
#ofr1=Reader('Airflow_Network_baseline'+baseline+ '_'+season, "dymola")
ofr1 = Reader('AHU', "dymola")

data_list = pd.read_csv('data_list_FDD.csv', header=None, names=['id', 'name'])

print data_list

index = 1
for i in range(len(data_list)):

    (time, temp) = ofr1.values(data_list['id'].iloc[i].replace('\n', ''))
    tab = sample(time, temp, data_list['name'].iloc[i])
    if index == 1:
        table1 = tab
    else:
        table1 = table1.merge(tab, how='inner')
    index = index + 1
Example #41
0
from buildingspy.io.outputfile import Reader
import matplotlib.pyplot as plt
from pylab import figure
import os

# Change fonts to use LaTeX fonts
from matplotlib import rc
rc('text', usetex=True)
rc('font', family='serif')

# Read results
ofr1 = Reader(os.path.join("case1", "PIDHysteresis.mat"), "dymola")
ofr2 = Reader(os.path.join("case2", "PIDHysteresis.mat"), "dymola")
(time1, T1) = ofr1.values("cap.T")
(time1, y1) = ofr1.values("con.y")
(time2, T2) = ofr2.values("cap.T")
(time2, y2) = ofr2.values("con.y")

# Plot figure
fig = plt.figure()
ax = fig.add_subplot(211)

ax.plot(time1 / 3600, T1 - 273.15, 'r', label='$T_1$')
ax.plot(time2 / 3600, T2 - 273.15, 'b', label='$T_2$')
ax.set_xlabel('time [h]')
ax.set_ylabel('temperature [$^\circ$C]')
ax.set_xticks(range(25))
ax.set_xlim([0, 24])
ax.legend()
ax.grid(True)
Example #42
0
def simulate_in_dymola(heaPum, data, tableName, tableFileName):
    """ Evaluate the heat pump performance from the model in Dymola.

    :param heaPum: Heat pump model (object).
    :param data: Reference performance data (object).
    :param tableName: Name of the combiTimeTable.
    :param tableFileName: Name of the text file containing the combiTimeTable.

    :return: Performance data of the modeled heat pump (object).

    .. note:: Performance data from the model is evaluated at the same
              operating conditions (inlet water temperatures and mass flow
              rates at the source and load sides) as in the reference data.

    """
    import buildingspy.simulate.Simulator as si
    from buildingspy.io.outputfile import Reader
    from scipy.interpolate import interp1d
    from builtins import str
    import getpass
    import os
    import tempfile

    # Find absolute path to buildings library
    packagePath = os.path.normpath(
        os.path.join(os.path.normpath(os.path.dirname(__file__)), '..', '..',
                     '..', '..', '..', '..'))

    # Create temporary directory for simulation files
    dirPrefix = tempfile.gettempprefix()
    tmpDir = tempfile.mkdtemp(prefix=dirPrefix + '-' + 'HeatPumpCalibration' +
                              '-' + getpass.getuser() + '-')

    # Set parameters for simulation in Dymola
    calModelPath = heaPum.modelicaCalibrationModelPath()
    s = si.Simulator(calModelPath,
                     'dymola',
                     outputDirectory=tmpDir,
                     packagePath=packagePath)
    s = heaPum.set_ModelicaParameters(s)
    m1_flow_nominal = min(data.flowSource)
    m2_flow_nominal = min(data.flowLoad)
    tableFilePath = \
        str(os.path.join(tmpDir, tableFileName).replace(os.sep, '/'))
    s.addParameters({
        'm1_flow_nominal': m1_flow_nominal,
        'm2_flow_nominal': m2_flow_nominal,
        'calDat.fileName': tableFilePath
    })

    # Write CombiTimeTable for dymola
    data.write_modelica_combiTimeTable(tableName, tmpDir, tableFileName,
                                       heaPum.CoolingMode)

    # Simulation parameters
    s.setStopTime(len(data.EWT_Source))
    s.setSolver('dassl')
    # Kill the process if it does not finish in 2 minutes
    s.setTimeOut(120)
    s.showProgressBar(False)
    s.printModelAndTime()
    #    s.showGUI(show=True)
    #    s.exitSimulator(exitAfterSimulation=False)
    s.simulate()

    # Read results
    modelName = heaPum.modelicaModelName()
    ofr = Reader(os.path.join(tmpDir, modelName), 'dymola')
    (time1, QCon) = ofr.values('heaPum.QCon_flow')
    (time1, QEva) = ofr.values('heaPum.QEva_flow')
    (time1, P) = ofr.values('heaPum.P')

    t = [float(i) + 0.5 for i in range(len(data.EWT_Source))]

    f_P = interp1d(time1, P)
    P = f_P(t)
    f_QCon = interp1d(time1, QCon)
    QCon = f_QCon(t)
    f_QEva = interp1d(time1, QEva)
    QEva = f_QEva(t)

    #    # Clean up
    #    shutil.rmtree('calibrationModel')
    if heaPum.CoolingMode:
        Capacity = -QEva
        HR = QCon
    else:
        Capacity = QCon
        HR = -QEva
    dymRes = SimulationResults(data.EWT_Source, data.EWT_Load, data.flowSource,
                               data.flowLoad, Capacity, HR, P, 'Modelica')
    return dymRes
    def test_mft_time_series_to_modelica_and_run(self):
        project_name = "time_series_massflow"
        self.data_dir, self.output_dir = self.set_up(os.path.dirname(__file__),
                                                     project_name)

        # load in the example geojson with a single office building
        filename = os.path.join(self.data_dir, "time_series_ex1.json")
        self.gj = UrbanOptGeoJson(filename)

        # load system parameter data
        filename = os.path.join(self.data_dir,
                                "time_series_system_params_massflow_ex1.json")
        sys_params = SystemParameters(filename)

        # create the load, ETSes and their couplings
        time_series_mft_load = TimeSeriesMFT(sys_params, self.gj.buildings[0])
        geojson_load_id = self.gj.buildings[0].feature.properties["id"]

        heating_indirect_system = HeatingIndirect(sys_params, geojson_load_id)
        ts_hi_coupling = Coupling(time_series_mft_load,
                                  heating_indirect_system)

        cooling_indirect_system = CoolingIndirect(sys_params, geojson_load_id)
        ts_ci_coupling = Coupling(time_series_mft_load,
                                  cooling_indirect_system)

        # create network stubs for the ETSes
        heated_water_stub = NetworkHeatedWaterStub(sys_params)
        hi_hw_coupling = Coupling(heating_indirect_system, heated_water_stub)

        chilled_water_stub = NetworkChilledWaterStub(sys_params)
        ci_cw_coupling = Coupling(cooling_indirect_system, chilled_water_stub)

        # build the district system
        district = District(root_dir=self.output_dir,
                            project_name=project_name,
                            system_parameters=sys_params,
                            coupling_graph=CouplingGraph([
                                ts_hi_coupling,
                                ts_ci_coupling,
                                hi_hw_coupling,
                                ci_cw_coupling,
                            ]))
        district.to_modelica()

        root_path = os.path.abspath(
            os.path.join(district._scaffold.districts_path.files_dir))
        mo_file_name = os.path.join(root_path, 'DistrictEnergySystem.mo')
        # set the run time to 31536000 (full year in seconds)
        mofile = Model(mo_file_name)
        mofile.update_model_annotation({"experiment": {"StopTime": 31536000}})
        mofile.save()
        self.run_and_assert_in_docker(
            mo_file_name,
            project_path=district._scaffold.project_path,
            project_name=district._scaffold.project_name)

        # Check the results
        results_dir = f'{district._scaffold.project_path}_results'
        mat_file = f'{results_dir}/time_series_massflow_Districts_DistrictEnergySystem_result.mat'
        mat_results = Reader(mat_file, 'dymola')

        # hack to get the name of the loads (rather the 8 character connector shas)
        timeseries_load_var = None
        coolflow_var = None
        heatflow_var = None
        for var in mat_results.varNames():
            m = re.match("TimeSerMFTLoa_(.{8})", var)
            if m:
                timeseries_load_var = m[1]
                continue

            m = re.match("cooInd_(.{8})", var)
            if m:
                coolflow_var = m[1]
                continue

            m = re.match("heaInd_(.{8})", var)
            if m:
                heatflow_var = m[1]
                continue

            if None not in (timeseries_load_var, coolflow_var, heatflow_var):
                break

        (time1, ts_hea_load) = mat_results.values(
            f"TimeSerMFTLoa_{timeseries_load_var}.ports_aChiWat[1].m_flow")
        (_time1, ts_chi_load) = mat_results.values(
            f"TimeSerMFTLoa_{timeseries_load_var}.ports_aHeaWat[1].m_flow")
        (_time1,
         cool_q_flow) = mat_results.values(f"cooInd_{coolflow_var}.Q_flow")
        (_time1,
         heat_q_flow) = mat_results.values(f"heaInd_{heatflow_var}.Q_flow")

        # if any of these assertions fail, then it is likely that the change in the timeseries massflow model
        # has been updated and we need to revalidate the models.
        self.assertEqual(ts_hea_load.min(), 0)
        self.assertAlmostEqual(ts_hea_load.max(), 51, delta=1)
        self.assertAlmostEqual(ts_hea_load.mean(), 4, delta=1)

        self.assertEqual(ts_chi_load.min(), 0)
        self.assertAlmostEqual(ts_chi_load.max(), 61, delta=1)
        self.assertAlmostEqual(ts_chi_load.mean(), 4, delta=1)

        self.assertAlmostEqual(cool_q_flow.min(), -51750, delta=10)
        self.assertAlmostEqual(cool_q_flow.max(), 354100, delta=10)
        self.assertAlmostEqual(cool_q_flow.mean(), 3160, delta=10)

        self.assertAlmostEqual(heat_q_flow.min(), -343210, delta=10)
        self.assertAlmostEqual(heat_q_flow.max(), 39475, delta=10)
        self.assertAlmostEqual(heat_q_flow.mean(), -23270, delta=10)