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()
Beispiel #3
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()
Beispiel #4
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
Beispiel #5
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')
Beispiel #6
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')
Beispiel #7
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")
Beispiel #8
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)
    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 _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
Beispiel #12
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=(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'))
Beispiel #13
0
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)

plot_results(ax0,
             ECoocase600_Avg,
             ECoocase600_Min,
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:
Beispiel #15
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'))
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)
Beispiel #17
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)
Beispiel #18
0
           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)']


(_, mo_AGla) =  mof.values("roo.conExtWin[1].AGla")
print "Modelica glass area: AGla = {}".format(mo_AGla[0])
(mo_tim, mo_qAbs_sol1) = mof.values("roo.conExtWin[1].QAbsUns_flow[1]")
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]))
    T_suExp.append(Plotter.interpolate(TimeExp[KKK],T_su[KKK][0],T_su[KKK][1]-273.15))
Beispiel #20
0
def _simulate(case):
    """
  Simulate the idf file with name idf_name in Spawn, and return true if successfull, or false otherwise
  """
    from buildingspy.io.outputfile import Reader
    import subprocess

    idf_name = case['idf']
    tmp_dir = os.path.join(TMP_DIR, f"{idf_name.name}")

    idf_full_name = os.path.abspath(os.path.join(tmp_dir, idf_name.name))

    # Create working directory
    if os.path.exists(tmp_dir):
        shutil.rmtree(tmp_dir)
    os.mkdir(tmp_dir)

    # Copy file
    shutil.copyfile(idf_name, idf_full_name)

    #  print("*********************************************************************")
    #  print(f"*** Running {idf_full_name}")
    # Add one more leading slash if it is an absolute path
    mo_name = "TestModel"

    modifier = f"""(
    building(
      idfName=Modelica.Utilities.Files.loadResource(
        \"file:///{idf_full_name}\")))"""
    model = f"Buildings.ThermalZones.EnergyPlus.Validation.OutputVariable.OneEnvironmentOutputVariable{modifier}"
    mo_text = f"""
  model {mo_name}
    extends {model};
    annotation(
      experiment(
        StopTime=86400,
        Tolerance=1e-06));
  end {mo_name};
  """
    with open(os.path.join(tmp_dir, f"{mo_name}.mo"), "w") as m:
        m.write(mo_text)

    cmd = [
        "jm_ipython.sh",
        os.path.join("..", "..", "jmodelica.py"), f"{mo_name}.mo"
    ]

    #print(f"Executing {cmd}")

    def _run(cmd, timeout_sec, cwd, modelica_path):
        from subprocess import Popen, PIPE
        my_env = os.environ.copy()
        my_env["MODELICAPATH"] = modelica_path
        proc = Popen(cmd, stdout=PIPE, stderr=PIPE, cwd=cwd, env=my_env)
        try:
            proc.wait(timeout=timeout_sec)
        except:
            print(f"*** Killing process for {idf_name}")
            proc.kill()

    _run(cmd, timeout_sec=60, cwd=tmp_dir, modelica_path=os.getcwd())

    resultFile = os.path.join(tmp_dir, f"{mo_name}_result.mat")
    logFile = os.path.join(tmp_dir, f"{mo_name}_log.txt")

    # Process output
    if os.path.isfile(logFile):
        #print(f"Reading {logFile}")
        with open(logFile, encoding='ISO-8859-1') as f:
            con = f.read()
            if 'Fatal from EnergyPlus' in con and 'ModelicaError' in con:
                case['result'] = 'Fatal from EnergyPlus'
                return case

    # No fatal error. Check if final time is reached.
    if os.path.isfile(resultFile):
        # Read result file
        try:
            res = Reader(resultFile, "dymola")
            #print(res.varNames())
            (t, TEnePlu) = res.values('TEnePlu.y')
            tMax = max(t)
            #print(f"*** Final time = {tMax}")
            if abs(tMax - 86400.0) < 0.1:
                case['result'] = "Success"
                # In case of success, delete the temporary directory
                shutil.rmtree(tmp_dir)
            else:
                case['result'] = "Error: Did not reach final time"
        except ValueError as e:
            msg = f"Error: ValueError when reading {resultFile}: {e}"
            print(msg)
            case['result'] = msg
    else:
        msg = f"Error: Result file {resultFile} does not exist"
        print(f"*** {msg}")
        case['result'] = msg

    return case
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)
    def test_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:
            time_series_load = TimeSeries(self.sys_params, geojson_load)
            loads.append(time_series_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(time_series_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(time_series_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')
        # NL: changed the line below to be aChiWat (not repeating aHeaWat).
        (_, 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}.mHeaWat_flow_nominal')
        heat_m_flow_nominal = heat_m_flow_nominal[0]
        (_, cool_m_flow_nominal) = mat_results.values(f'{load.id}.mChiWat_flow_nominal')
        cool_m_flow_nominal = cool_m_flow_nominal[0]
        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}%)'
        )
        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}%)'
        )

        # check the thermal load
        (_, load_q_req_hea_flow) = mat_results.values(f'{load.id}.QReqHea_flow')
        (_, load_q_req_coo_flow) = mat_results.values(f'{load.id}.QReqCoo_flow')
        (_, load_q_heat_flow) = mat_results.values(f'{load.id}.QHea_flow')
        (_, load_q_cool_flow) = mat_results.values(f'{load.id}.QCoo_flow')

        # make sure the q flow is positive
        load_q_req_hea_flow, load_q_req_coo_flow = np.abs(load_q_req_hea_flow), np.abs(load_q_req_coo_flow)
        load_q_heat_flow, load_q_cool_flow = np.abs(load_q_heat_flow), np.abs(load_q_cool_flow)

        cool_cvrmsd = self.cvrmsd(load_q_cool_flow, load_q_req_coo_flow)
        heat_cvrmsd = self.cvrmsd(load_q_heat_flow, load_q_req_hea_flow)

        CVRMSD_MAX = 0.3
        # TODO: fix q flows to meet the CVRMSD maximum, then make these assertions rather than warnings
        if cool_cvrmsd >= CVRMSD_MAX:
            print(f'WARNING: The difference between the thermal cooling load of the load and ETS is too large (CVRMSD={cool_cvrmsd}). '
                  'TODO: make this warning an assertion.')
        if heat_cvrmsd >= CVRMSD_MAX:
            print(f'WARNING: The difference between the thermal heating load of the load and ETS is too large (CVRMSD={heat_cvrmsd}). '
                  'TODO: make this warning an assertion.')
Beispiel #23
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}')
    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

table1 = table1[24 * 60:]
table1.dropna(how='any')
table1.to_csv('FDD.csv')
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')
def get_values(fpath, varname):
    r = Reader(fpath, 'dymola')
    return r.values(varname)
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)

ax.plot(time / 3600, Ts_ext - 273.15, 'r', label='$T_{s,ext}$')
ax.plot(time / 3600, Ts_int - 273.15, 'b', label='$T_{s,int}$')
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')
Beispiel #29
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
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')
Beispiel #30
0
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)))
    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)
Beispiel #32
0

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)

plot_results(ax0, ECoocase600_Avg, ECoocase600_Min, ECoocase600_Max, ECoocase600_E_plus, np.array([reader.values("EAnnCoo600[" + str(i+1) + "]")[1][-1] for i in range(N)]), N, -0.1, marker='$E_C$')
plot_results(ax0, PHeacase600_Avg, PHeacase600_Min, PHeacase600_Max, PHeacase600_E_plus, np.array([reader.values("QPeaHea600[" + str(i+1) + "]")[1][-1] for i in range(N)]), N, 0.1, marker='$P_H$')
plot_results(ax0, PCoocase600_Avg, PCoocase600_Min, PCoocase600_Max, PCoocase600_E_plus, np.array([reader.values("QPeaCoo600[" + str(i+1) + "]")[1][-1] for i in range(N)]), N, 0.3, marker='$P_C$')

plot_results(ax0, EHeacase900_Avg, EHeacase900_Min, EHeacase900_Max, EHeacase900_E_plus, [reader.values("EAnnHea900[" + str(i+1) + "]")[1][-1] for i in range(N)], N, -0.3 + N, marker='$E_H$')
plot_results(ax0, ECoocase900_Avg, ECoocase900_Min, ECoocase900_Max, ECoocase900_E_plus, [reader.values("EAnnCoo900[" + str(i+1) + "]")[1][-1] for i in range(N)], N, -0.1 + N, marker='$E_C$')
plot_results(ax0, PHeacase900_Avg, PHeacase900_Min, PHeacase900_Max, PHeacase900_E_plus, [reader.values("QPeaHea900[" + str(i+1) + "]")[1][-1] for i in range(N)], N, 0.1 + N, marker='$P_H$')
plot_results(ax0, PCoocase900_Avg, PCoocase900_Min, PCoocase900_Max, PCoocase900_E_plus, [reader.values("QPeaCoo900[" + str(i+1) + "]")[1][-1] for i in range(N)], N, 0.3 + N, marker='$P_C$')

N2=4
plot_results(ax0,  TMin_avg, TMin_min, TMin_max, TMin_E_plus, [reader.values("Tmin[" + str(i+1) + "]")[1][-1] for i in range(N2)], N2, -0.2 + 2*N, marker=r'$\downarrow$')
plot_results(ax0, TAvg_avg, TAvg_min, TAvg_max, TAvg_E_plus, [reader.values("TAnnAvg[" + str(i+1) + "]")[1][-1] for i in range(N2)], N2, 2*N, marker=r'$\bar{T}$')
Beispiel #33
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)

    # Normalize data
    data_norm = {}
    for i, val in enumerate(data):
        data_norm[val] = data[val] / max(abs(data[val]))
Beispiel #34
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 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