Example #1
0
def get_sim_data():
    sim = SimRes('demo_results.mat')
    dfDymola = sim.to_pandas([
        'combiTimeTable.y[2]', 'combiTimeTable.y[3]',
        'boiler_system.temperature_sensor_2.T', 'combiTimeTable.y[4]'
    ])

    #getting list of column names: names contain the unit
    df_col = list(dfDymola.columns)

    ##extract unit from column name
    df_col_split = []
    for x in df_col:
        df_col_split = df_col_split + [x.split()[0]]

    #rename columns without units
    for i in range(len(df_col)):
        dfDymola = dfDymola.rename(index=str,
                                   columns={df_col[i]: df_col_split[i]})
    # print(dfDymola)
    dfDymola.index = pd.to_numeric(dfDymola.index)
    dfDymola["time_diff"] = dfDymola.index
    # dfDymola["time_diff"]=pd.to_numeric(dfDymola["time_diff"])
    dfDymola["time_diff"] = (dfDymola["time_diff"].shift(-1) -
                             dfDymola["time_diff"])
    #    dfDymola=dfDymola[~dfDymola.index.duplicated(keep='last')]
    ##    dfDymola.drop_duplicates(keep='last', inplace=True)
    #    max_range = max(dfDymola.index) + 1
    #
    #
    #    dfDymola = dfDymola.reindex(index=range(1, int(max_range)), method='ffill', fill_value=0)
    dfDymola = reindex_int(dfDymola)
    return dfDymola
Example #2
0
 def __init__(self, params):
     '''
     Constructor
     '''
     self._resultFile = SimRes(params[0])
     print self._resultFile
     self._compiler = params[1]
Example #3
0
 def getMin(self, varName):
     if varName in self.variables.keys():
         from modelicares import SimRes
         r = SimRes(self.variables[varName]['matFile'])
         variable = r[self.variables[varName]['path']]
         return variable.min()
     else:
         print('Die Variable ' + varName + ' existiert nicht.')
Example #4
0
def home(request):
    var_const=["Ergebnisse.E_bs_gesamt","Ergebnisse.E_el_gesamt","Ergebnisse.K_gesamt","Ergebnisse.K_bed_an","Ergebnisse.K_kap_an"]
    var_const_expl=["Brennstoffbedarf","Elektrischer Energiebedarf","Gesamtkosten","Annuitäten","Investment"]
    var_var=["Strommarkt.signalBus.Strompreis","Heizkessel.product.y","BHKW_.signalBus_BHKW.P_BHKW","Elektrodenkessel.signalBus_BHKW.P_EK"]
    var_var_expl=["Strompreis","Leistung Heizkessel","Leistung BHKW","Leistung Elektrodenkessel"]
    sim_array=["Waerme_1.mat","Waerme_2.mat","Waerme_3.mat"]
    variables=var_const
    #values=[[0,1,3,4],[32,54,3,45],[23,434,5,4]]

    
    args = {'variables':variables} #Selection for the form 
    for i in range(len(sim_array)):
        sim=SimRes('C:\\Users\\Lukas\\Desktop\\ETA\\'+sim_array[i])

    df_const=pd.DataFrame(columns=['simulation']+var_const)
    df_var=pd.DataFrame(columns=['simulation','time']+var_var)  
    
    # creating the dataframe for the constant/non constant variables
    for i in range(len(sim_array)):
        sim=SimRes('C:\\Users\\Lukas\\Desktop\\ETA\\'+sim_array[i])
        df_const.at[i,'simulation']=sim_array[i]
        df_var.at[i,'simulation']=sim_array[i]
        
        for x in range(len(var_const)):
            df_const.at[i,var_const[x]]=sim[var_const[x]].values()[len(sim[var_const[x]].values())-1]
        for x in range(len(var_var)):
            df_var.at[i,var_var[x]]=sim[var_var[x]].values()   
            df_var.at[i,'time']=sim[var_var[x]][0][0]
    
    # user decides which comparison should be shown by a dropdown
    if request.method=="POST":
        request.session['variable_selected']=request.POST["comp-crit"]
        sort_by=request.session['variable_selected']
        const_sorted=df_const.sort_values(by=[sort_by])
        best_const=const_sorted.iloc[:3,:]
        best_const=best_const.to_json()
        # top 3 dicitonary
        request.session['best_const']=best_const
        df_var=df_var.to_json()
        # dictionary with the variables
        request.session['var_dict']=df_var
    else:
        pass
    
    
    return render(request,'home.html',args)
Example #5
0
    def export(self, output_vars=None):

        sim = SimRes(self.mat_file)

        if self.csv_file is not None:
            self.csv_file = os.path.splitext(self.mat_file)[0] + '.csv'
        else:
            self.csv_file = self.csv_file

        if output_vars is not None:
            self.output_vars = output_vars
            data = sim.to_pandas(self.output_vars)
        else:
            data = sim.to_pandas()

        data = data.loc[~data.index.duplicated(keep='last')]
        data.drop(data.head(1).index, inplace=True)
        data.to_csv(self.csv_file, encoding='utf-8')
Example #6
0
    def get_results(self, name):
        from modelicares import SimRes
        import os
        # Get the simulation result
        sim = SimRes(os.path.join(self.paths.res_path, 'dsres.mat'))

        arr = sim[name].values()
        results = arr.tolist()

        return results
Example #7
0
    def add(self):
        if (self.delete == True):
            return
        print(
            'Was ist der Name der Variable? (Dieser Name wird in der Legende angezeigt)'
        )
        var = raw_input()
        if var in self.variables:
            print(
                'Diese Variable existiert bereits. Funktion "add()" wird beendet...'
            )
            return
        print(
            'In welchem .mat-File ist diese Variable zu finden? (Pfad zum .mat-File angeben)'
        )
        file = raw_input()
        print('Gib den Pfad zur Variable innerhalb des .mat-Files an')
        path = raw_input()

        from modelicares import SimRes
        r = SimRes(file)

        try:
            print('Diese Variable hat die Einheit ' + r[path].unit +
                  '. Einheit aendern? -- Antwort: Y(es), N(o)')
        except LookupError:
            print(
                'Der eingegebene Pfad zur Variable scheint nicht zu existieren. Funktion "add()" wird beendet...'
            )
            return

        antw = raw_input()
        if (antw == 'Y' or antw == 'Yes' or antw == 'y' or antw == 'yes'):
            print('Welche Einheit soll es denn sein?')
            unit = raw_input()
            orig_unit = r[path].unit
        else:
            unit = r[path].unit
            orig_unit = r[path].unit

        print('Soll der Variable noch einen custom Gain hinzugefügt werden?')
        antw = raw_input()
        gain = 1
        if (antw == 'Y' or antw == 'Yes' or antw == 'y' or antw == 'yes'):
            print('Gib den gewünschten Gain ein.')
            gain = num(raw_input())

        self.variables[var] = {
            'matFile': file,
            'path': path,
            'origUnit': orig_unit,
            'displayUnit': unit,
            'customGain': gain
        }
Example #8
0
def check_data(filename_model, filename_results, filename_database, budo_label):
    sim = SimRes(filename_results)
    variable_name_sim = get_complete_variable_name(filename_model, budo_label)
    dfDymola=sim.to_pandas([variable_name_sim]) 
    dfDymola=preprocess_sim_data(dfDymola)
    dfDymola=reindex_int(dfDymola)
    
    "read out of monitoring database"
    "(in real a specialized timeseries database)"
    disk_engine = create_engine('sqlite:///'+filename_database)
    df = pd.read_sql_query('SELECT * FROM timeseries', disk_engine)
    df = preprocess_monitoring_data(df)
    
    (df, dfDymola)=check_length(df, dfDymola)

    predicted_values = dfDymola[variable_name_sim]
    measured_values = df[budo_label]
    (iae_, rmse_, nrmse_)=calculate_values(measured_values, predicted_values)
    print("IAE between real and simulated data is: "+str(iae_))
    print("RMSE between real and simulated data is "+str(rmse_))
    print("NRMSE between real and simulated data is "+str(nrmse_))
Example #9
0
def runEngine(simCity, solverconfig):
    ''' Change path to model folder '''
    simCity.updateSolverConfiguration(solverconfig)
    simCity.numberOfIntervals= solverconfig.numberOfIntervals
    simCity.solver= solverconfig.method
    simCity.startTime= solverconfig.startTime
    simCity.stopTime= solverconfig.stopTime
    simCity.tolerance= solverconfig.tolerance
    simCity.resultFile= sources.modelName
    simCity.simulate()
#     print 'simCity.resultFile ', simCity.resultFile
    __simulationFile= sources.outputFolder+ os.sep+ simCity.resultFile
    __simulationData= SimRes(__simulationFile)
    return [__simulationFile, __simulationData]
Example #10
0
def runEngine(__sources, __solverconfig):
    simCity= EngineOMC(__sources, __solverconfig)
    simCity.numberOfIntervals= __solverconfig.numberOfIntervals
    simCity.solver= __solverconfig.method
    simCity.startTime= __solverconfig.startTime
    simCity.stopTime= __solverconfig.stopTime
    simCity.tolerance= __solverconfig.tolerance
    simCity.resultFile= __sources.modelName
    simCity.simulate()
    ''' TODO get the result file '''
#     print 'simCity.resultFile ', simCity.resultFile
    __simulationFile= sources.outputFolder+ os.sep+ simCity.resultFile
    __simulationData= SimRes(__simulationFile)
    return [__simulationFile, __simulationData]
Example #11
0
    def showRes(self, file=''):
        if (file == ''):
            print(
                'Kein .mat-File angegeben. Welches .mat-File soll untersucht werden? (Pfad zum .mat-File angeben)'
            )
            file = raw_input()

        from modelicares import SimRes
        r = SimRes(file)

        try:
            print(r.names)
        except IOError:
            print(
                'Das angegebene .mat-File scheint es nicht zu geben. Funktion "showRes()" wird beendet...'
            )
            return
Example #12
0
def runLinearization(simCity, solverconfig):
    ''' Change path to model folder '''
    simCity.updateSolverConfiguration(solverconfig)
    simCity.numberOfIntervals = solverconfig.numberOfIntervals
    simCity.solver = solverconfig.method
    simCity.startTime = solverconfig.startTime
    simCity.stopTime = solverconfig.stopTime
    simCity.tolerance = solverconfig.tolerance
    simCity.resultFile = sources.modelName
    #TODO test the call to the function
    simCity.linearize('linearize')
    print 'simCity.resultFile ', simCity.resultFile
    #TODO get the proper result file with ModelicaRes
    __simulationFile = sources.outputFolder + os.sep + simCity.resultFile
    # resultFile = dslin.mat -> we have to extract nx= order, xuyName= list of variables, ABCD
    __simulationData = SimRes(__simulationFile)
    return [__simulationFile, __simulationData]
Example #13
0
    def __init__(self, params, compiler='openmodelica'):
        '''
        Constructor
        _compiler: omc, dymola or jm
        Params 0: output dir; 
        Params 1: .h5 file path;
        Params 2: .mat file path;
        '''
        if (params[0]!= ''):
            os.chdir(params[0])
        self._fileName= params[1]
        if (len(params)> 2):
            self._matfile= SimRes(params[2])
#         fileName= time.strftime("%H_%M_%S")+ 'SimulationOutputs.h5'
        ''' a '''
        self._signals= {}
        self._compiler= compiler
Example #14
0
 def optimizeCoeff(In):
     eps = In[0]
     print 'Current eps:', eps
     s.addParameters({'EuroTrough.eps6': eps})
     s.setResultFile(FileSimulation)
     s.setStartTime(StartModTime[0])
     s.setStopTime(StopModTime[0])
     s.printModelAndTime()
     #s.showGUI(show=True)
     #s.exitSimulator(exitAfterSimulation=False)
     s.simulate_translated()
     Data_Sim = StoreModResult + '/' + FileSimulation + '.mat'
     sim = SimRes(Data_Sim)
     #initialTime = (sim['Time'].IV())
     #FinalTime=(sim['Time'].FV())
     #TimeSim=(((sim['Time'].values(t=(StartModTime[0],StopModTime[0]))-StartModTime[0])))
     #NN = (sim['EuroTrough.N'].values(t=(StartModTime[0])))
     #Tpt_su = ((sim['SensTsu.fluidState.T'].values(t=(StartModTime[0],StopModTime[0])))-273.15)
     #Tpt_ex = ((sim['SensTex.fluidState.T'].values(t=(StartModTime[0],StopModTime[0])))-273.15)
     Delta_T = ((sim['DeltaT.Delta'].values(t=(StartModTime[0] + 600,
                                               StartModTime[0] + 660))))
     print 'Residue:' + str(sum(Delta_T**2))
     return Delta_T
Example #15
0
for tgovernorNumber, tgovernorName in enumerate(tgovernors['names']):
    os.makedirs(f'{tgovernorName}')

#For loop that will iterate between machines, simulate, and create the .csv file
for tgovernorNumber, tgovernorName in enumerate(tgovernors['names']):
    print(f"Fault {tgovernorName} Simulation Start...")
    try:
        omc.sendExpression(f"cd(\"{FTurbineGovernorsWorkingDir}" +
                           tgovernorName + "\")")
        omc.sendExpression(f"loadFile(\"{OpenIPSLPackage}\")")
        omc.sendExpression("instantiateModel(OpenIPSL)")
        omc.sendExpression(
            f"simulate(OpenIPSL.Examples.Controls.PSSE.TG.{tgovernorName}, stopTime=10.0,method=\"rungekutta\",numberOfIntervals=5000,tolerance=1e-06)"
        )
        sim = SimRes(
            "" + FTurbineGovernorsWorkingDir +
            f"{tgovernorName}/OpenIPSL.Examples.Controls.PSSE.TG.{tgovernorName}_res.mat"
        )
        print(f"{tgovernorName} Simulation Finished...")
    except:
        print(f"{tgovernorName} simulation error or model not found...")
    try:
        #Selecting Variables
        print(".csv Writing Start...")
        try:
            print('Verifying if it is a GENROU model...')
            #Selecting Variables
            variables = [
                'Time', tgovernors['delta'][0], tgovernors['pelec'][0],
                tgovernors['pmech'][0], tgovernors['speed'][0],
                tgovernors['pmechgov'][tgovernorNumber], 'GEN1.V', 'LOAD.V',
                'GEN2.V', 'FAULT.V'
Example #16
0
#!/usr/bin/python
"""Example of SimRes.sankey()
"""

# pylint: disable=I0011, C0103

from modelicares import SimRes

sim = SimRes('ThreeTanks.mat')
sim.sankey(title="Sankey diagrams of Modelica.Fluid.Examples.Tanks.ThreeTanks",
           times=[0, 50, 100, 150], n_rows=2, format='%.1f ',
           names=['tank1.ports[1].m_flow', 'tank2.ports[1].m_flow',
                  'tank3.ports[1].m_flow'],
           labels=['Tank 1', 'Tank 2', 'Tank 3'],
           orientations=[-1, 0, 1],
           scale=0.1, margin=6, offset=1.5,
           pathlengths=2, trunklength=10)
Example #17
0
def static():
    """Create static images for the HTML documentation and the base README.md.
    """
    import matplotlib.pyplot as plt
    from modelicares import SimRes, LinResList, read_params

    join = os.path.join

    # Options
    indir = "../examples"  # Directory with the mat files.
    outdir = "_static"  # Directory where the images should be generated
    dpi = 90  # DPI for the HTML index images
    dpi_small = 30  # DPI for the README images
    kwargs = dict(bbox_inches='tight', format='png')  # Other savefig() options

    # ThreeTanks
    # ----------
    sim = SimRes(join(indir, 'ThreeTanks.mat'))
    sim.sankey(title=("Sankey diagrams of "
                      "Modelica.Fluid.Examples.Tanks.ThreeTanks"),
               times=[0, 50, 100, 150],
               n_rows=2,
               format='%.1f ',
               names=[
                   'tank1.ports[1].m_flow', 'tank2.ports[1].m_flow',
                   'tank3.ports[1].m_flow'
               ],
               labels=['Tank 1', 'Tank 2', 'Tank 3'],
               orientations=[-1, 0, 1],
               scale=0.1,
               margin=6,
               offset=1.5,
               pathlengths=2,
               trunklength=10)
    plt.savefig(join(outdir, 'ThreeTanks.png'), dpi=dpi, **kwargs)
    plt.savefig(join(outdir, 'ThreeTanks-small.png'), dpi=dpi_small, **kwargs)
    plt.close()

    # ChuaCircuit
    # -----------
    sim = SimRes(join(indir, 'ChuaCircuit.mat'))
    ax = sim.plot(ynames1='L.v',
                  ylabel1="Voltage",
                  xname='L.i',
                  xlabel="Current",
                  title=("Modelica.Electrical.Analog.Examples.ChuaCircuit\n"
                         "Current through and voltage across the inductor"))[0]

    # Mark the start and stop points.
    def mark(time, text):
        """Mark a frequency point.
        """
        i = sim['L.i'].values(time)
        v = sim['L.v'].values(time)
        plt.plot(i, v, 'bo')
        ax.annotate(text,
                    xy=(i, v),
                    xytext=(0, -4),
                    ha='center',
                    va='top',
                    textcoords='offset points')

    mark(0, "Start")
    mark(2500, "Stop")
    # Save and close.
    plt.savefig(join(outdir, 'ChuaCircuit.png'), dpi=dpi, **kwargs)
    plt.savefig(join(outdir, 'ChuaCircuit-small.png'), dpi=dpi_small, **kwargs)
    plt.close()

    # PIDs-bode
    # ---------
    lins = LinResList(join(indir, 'PID.mat'), join(indir, 'PID/*/'))
    for lin in lins:
        lin.label = "Td = %g s" % read_params('Td',
                                              join(lin.dirname, 'dsin.txt'))
    lins.sort(key=lambda lin: lin.label)
    lins.bode(title=("Bode plot of Modelica.Blocks.Continuous.PID\n"
                     "with varying differential time constant"))
    plt.savefig(join(outdir, 'PIDs-bode.png'), dpi=dpi, **kwargs)
    plt.savefig(join(outdir, 'PIDs-bode-small.png'), dpi=dpi_small, **kwargs)
    plt.close()
Example #18
0
#!/usr/bin/python
"""Example of SimRes.plot()
"""

# pylint: disable=I0011, C0103

from modelicares import SimRes

sim = SimRes('ChuaCircuit.mat')
sim.plot(ynames1='L.i', ylabel1="Current",
         ynames2='L.der(i)', ylabel2="Derivative of current",
         title="Chua circuit")
Example #19
0
         "Simulation failed or model was not found. Below is the translation log:\n"
     )
     log = dymola.getLastErrorLog()
     print(log)
     try:
         os.chdir(
             f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/TurbineGovernors/{tgovernorName}/"
         )
         os.remove("dsin.txt")
     except:
         pass
 else:
     print(f"{tgovernorName} Simulation OK...")
     print(".csv Writing Start...")
     sim = SimRes(
         f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/TurbineGovernors/{tgovernorName}/{tgovernorName}.mat"
     )
     try:
         print('Verifying if it is a GENROU model...')
         #Selecting Variables
         variables = [
             'Time', tgovernors['delta'][0], tgovernors['pelec'][0],
             tgovernors['speed'][0],
             tgovernors['pmech'][tgovernorNumber], 'GEN1.V', 'LOAD.V',
             'GEN2.V', 'FAULT.V'
         ]
         df_variables = pd.DataFrame([], columns=variables)
         for var in variables:
             df_variables.drop(var, axis=1, inplace=True)
             #Change from Radians to Degrees
             if var == tgovernors['delta'][0]:
Example #20
0
for machineNumber, machineName in enumerate(machines['names']):
    os.makedirs(f'{machineName}')

#For loop that will iterate between machines, simulate, and create the .csv file
for machineNumber, machineName in enumerate(machines['names']):
    print(f"Fault {machineName} Simulation Start...")
    try:
        omc.sendExpression(f"cd(\"{FMachinesWorkingDir}" + machineName + "\")")
        omc.sendExpression(f"loadFile(\"{OpenIPSLPackage}\")")
        omc.sendExpression("instantiateModel(OpenIPSL)")
        if machineName == 'CSVGN1':
            omc.sendExpression(
                f"simulate(OpenIPSL.Examples.Banks.PSSE.{machineName}, stopTime=10.0,method=\"dassl\",numberOfIntervals=500,tolerance=1e-04)"
            )
            sim = SimRes(
                "" + FMachinesWorkingDir +
                f"{machineName}/OpenIPSL.Examples.Banks.PSSE.{machineName}_res.mat"
            )
        else:
            omc.sendExpression(
                f"simulate(OpenIPSL.Examples.Machines.PSSE.{machineName}, stopTime=10.0,method=\"rungekutta\",numberOfIntervals=5000,tolerance=1e-06)"
            )
            sim = SimRes(
                "" + FMachinesWorkingDir +
                f"{machineName}/OpenIPSL.Examples.Machines.PSSE.{machineName}_res.mat"
            )
        print(f"{machineName} Simulation Finished...")
    except:
        print(f"{machineName} simulation error or model not found...")
    try:
        print(".csv Writing Start...")
        if machineName == 'CSVGN1':
# file: plotTestPWM.py
#!/usr/bin/python
import OMPython
import numpy as np
import matplotlib.pyplot as plt 
import pandas; pandas.set_option('display.max_rows', 5)
from modelicares import SimRes

sim = SimRes('Result_res.mat')
print sim['Time'].IV()
print sim['Time'].FV()
pulses = sim.find('pulse*.y')
sim.plot(pulses);
plt.savefig('test.png')
# plt.show()
# sim['pulseWidthVar.y'].array(t=(0, 0.2 ))
Example #22
0
    s.setResultFile(FileSimulation)
    s.setStartTime(StartModTime[KKK])
    s.setStopTime(StopModTime[KKK])
    s.setNumberOfIntervals(500)
    s.setSolver('Dassl')
    s.printModelAndTime()
    #s.showGUI(show=True)
    #s.exitSimulator(exitAfterSimulation=False)
    s.simulate()
    #resultFile=(ResultDirectory+'/'+FileSimulation+".mat")
    #r=Reader(resultFile, "dymola")
    #print r

# --------------------    IMPORT MODELICA RESULT USING MODELICA RES  -----------------------------
Data_Sim = StoreModResult + '/' + FileSimulation + '.mat'
sim = SimRes(Data_Sim)
initialTime = (sim['Time'].IV())
FinalTime = (sim['Time'].FV())
TimeSim = (((sim['Time'].values(t=(StartPlotTime[0], StopPlotTime[0])) -
             (StartPlotTime[0]))))
NN = (sim['EuroTrough.N'].values(t=(StartPlotTime[0])))
Tpt_su = ((sim['SensTsu.fluidState.T'].values(t=(StartPlotTime[0],
                                                 StopPlotTime[0]))) - 273.15)
Tpt_ex = ((sim['SensTex.fluidState.T'].values(t=(StartPlotTime[0],
                                                 StopPlotTime[0]))) - 273.15)
Delta_T = ((sim['DeltaT.Delta'].values(t=(StartModTime[KKK] + 600,
                                          StartModTime[KKK] + 800))))
DNI = ((sim['DNI.y'].values(t=(StartPlotTime[0], StopPlotTime[0]))))
m_wf = ((sim['m_dot_htf.y'].values(t=(StartPlotTime[0], StopPlotTime[0]))))
T_amb = ((sim['T_amb.y'].values(t=(StartPlotTime[0], StopPlotTime[0]))) -
         273.15)
def plot_sim_results(solver, experiment, fig_name):

    if experiment == 'initialization':
        exp = 1
        b1 = "B2.V"
        b2 = "B4.V"
    elif experiment == 'line_opening':
        exp = 2
        b1 = "B2.V"
        b2 = "B4.V"
    elif experiment == 'bus_faults':
        exp = 3
        b1 = "B4.V"
        b2 = "B14.V"

    # Adjusting number of points
    if solver == 'dassl':
        n_points = 5000
    else:
        n_points = 240000

    current_wd = os.getcwd()

    # Directory of Dymola results
    if solver == 'trapezoid':
        solver_dym = 'Rkfix2'
    elif solver == 'rungekutta':
        solver_dym = 'Rkfix4'
    elif solver == 'euler':
        solver_dym = 'Euler'
    elif solver == 'dassl':
        solver_dym = 'dassl'

    # Directory of Dymola results
    simD_dir = os.path.join(
        current_wd,
        "WorkingDir/Dymola/{s}/{e}/OpenIPSL.IEEE14.IEEE_14_Buses_{e}_{s}.mat".
        format(s=solver_dym, e=exp))
    # Directory of OpenModelica results
    simOM_dir = os.path.join(
        current_wd,
        "WorkingDir/OpenModelica/{s}/OpenIPSL.IEEE14.IEEE_14_Buses_{e}_res.mat"
        .format(s=solver, e=exp))

    # Creating object with Dymola results
    simD = SimRes(simD_dir)
    # Creating object with OpenModelica results
    simOM = SimRes(simOM_dir)

    fig, axes = plt.subplots(figsize=(12, 10), nrows=2, ncols=2)
    fig.suptitle("Time-domain simulation results ({s} - {e})".format(
        s=solver, e=experiment),
                 fontname="Times New Roman",
                 fontsize=22)

    axes[0][0].plot(simD['Time'].values(),
                    simD[b1].values(),
                    label='Dymola',
                    color='indigo')
    axes[0][0].legend()
    axes[0][0].plot(simOM['Time'].values(),
                    simOM[b1].values(),
                    label='OpenModelica',
                    color='salmon')
    axes[0][0].legend(prop={'size': 14, 'family': "Times New Roman"})

    axes[0][1].plot(
        simD['Time'].values()[0:n_points], (1 / n_points) * np.absolute(
            (simD[b1].values()[0:n_points] - simOM[b1].values()[0:n_points])),
        label='NAE',
        color='peru')
    axes[0][1].legend(prop={'size': 14, 'family': "Times New Roman"})
    axes[0][1].ticklabel_format(style='sci', axis='y', scilimits=(0, 0))

    axes[1][0].plot(simD['Time'].values(),
                    simD[b2].values(),
                    label='Dymola',
                    color='indigo')
    axes[1][0].plot(simOM['Time'].values(),
                    simOM[b2].values(),
                    label='OpenModelica',
                    color='salmon')
    axes[1][0].legend(prop={'size': 14, 'family': "Times New Roman"})

    axes[1][1].plot(
        simD['Time'].values()[0:n_points], (1 / n_points) * np.absolute(
            (simD[b2].values()[0:n_points] - simOM[b1].values()[0:n_points])),
        label='NAE',
        color='peru')
    axes[1][1].legend(prop={'size': 14, 'family': "Times New Roman"})
    axes[1][1].ticklabel_format(style='sci', axis='y', scilimits=(0, 0))

    for r in range(0, 2):
        for c in range(0, 2):
            axes[r][c].set_ylabel('Voltage [pu]',
                                  fontname='Times New Roman',
                                  fontsize=16)
            axes[r][c].set_xlabel('Time [s]',
                                  fontname='Times New Roman',
                                  fontsize=16)
            for tick in axes[r][c].xaxis.get_major_ticks():
                tick.label.set_fontsize(15)
                tick.label.set_fontname("Times New Roman")
            for tick in axes[r][c].yaxis.get_major_ticks():
                tick.label.set_fontsize(15)
                tick.label.set_fontname("Times New Roman")

    fig.tight_layout()
    fig.subplots_adjust(top=0.92)

    # Saving figure
    fig.savefig('Figs/01_Tool_Result_Analysis/{}.png'.format(fig_name),
                dpi=300)

    # Printing information about mean errors
    print("{r:=^32}".format(r=""))
    print("{r:^32}".format(r="{s} - {e}".format(s=solver, e=experiment)))
    print("{r:=^32}".format(r=""))

    MSED1B2 = (1 / n_points) * np.sum(
        (simD[b1].values()[0:n_points] - simOM[b1].values()[0:n_points])**2)
    MSED1B4 = (1 / n_points) * np.sum(
        (simD[b2].values()[0:n_points] - simOM[b2].values()[0:n_points])**2)
    MSED2 = (1 / n_points) * np.absolute(
        (simD[b1].values()[0:n_points] - simOM[b1].values()[0:n_points]))
    print('MSE {} ='.format(b1[0:2]), MSED1B2)
    print('MSE {} ='.format(b2[0:2]), MSED1B4)

    print("{r:=^32}".format(r=""))
Example #24
0
def test(request):
    ### 1. step: loading visulization page --> GET request --> variables are extracted from .mat files and stored in pandas dataframe
    ### 2. step: user chooses comparison-criterion and submits --> POST request --> dataframes are sorted by comparison-criterion + barplots are displayed
    ### 3. step: user chooses simulation to look at in detail --> POST request --> line-plots are displayed

    # time-constant variables
    var_const=["Ergebnisse.E_bs_gesamt","Ergebnisse.E_el_gesamt","Ergebnisse.K_gesamt","Ergebnisse.K_bed_an","Ergebnisse.K_kap_an"]
    var_const_expl=["Brennstoffbedarf","Elektrischer Energiebedarf","Gesamtkosten","Energiekosten","Investment"]

    # non-time-constant variables
    var_var=["Strommarkt.signalBus.Strompreis","Heizkessel.product.y","BHKW_.signalBus_BHKW.P_BHKW","Elektrodenkessel.signalBus_BHKW.P_EK"]
    var_var_expl=["Strompreis","Leistung Heizkessel","Leistung BHKW","Leistung Elektrodenkessel"]

    # Investment 
    invest_var=["Annuitaeten.__ps__an.bhkw","Annuitaeten.__ps__an.ek","Annuitaeten.__ps__an.hk"]
    invest_var_expl=["Annuitaeten BHKW","Annuitaeten Elektrodenkessel","Annuitaeten Heizkessel"]
    
    # Simulation results
    sim_array=["Waerme_1.mat","Waerme_2.mat","Waerme_3.mat","Waerme_4.mat","Waerme_5.mat"]


    if request.method=="GET":
        # visulization page is loaded
        sim_to_dropdown=['']
        request.session['simulation']=''
        request.session['comp_crit']=''
        request.session['sim_detail']=''
        
        # data frame for time-const. vars --> 1. row "simulation" (e.g. waerme_1.mat), following rows containing the name of the variables
        df_const=pd.DataFrame(columns=['simulation']+var_const)

        # data fram for non-time-const. vars --> see upper df
        df_var=pd.DataFrame(columns=['simulation','time']+var_var) 

        # data frame for Investment
        df_invest=pd.DataFrame(columns=['simulation']+invest_var)

        # data is extracted from .mat file and stored in dataframes
        for i in range(len(sim_array)):
            sim=SimRes('C:\\Users\\Lukas\\Desktop\\ETA\\'+sim_array[i])
            df_const.at[i,'simulation']=sim_array[i]
            df_var.at[i,'simulation']=sim_array[i]
            df_invest.at[i,'simulation']=sim_array[i]
            
            for x in range(len(var_const)):
                df_const.at[i,var_const[x]]=sim[var_const[x]].values()[len(sim[var_const[x]].values())-1]
            for x in range(len(var_var)):
                df_var.at[i,var_var[x]]=sim[var_var[x]].values()   
                df_var.at[i,'time']=sim[var_var[x]][0][0] 
            for x in range(len(invest_var)):
                df_invest.at[i,invest_var[x]]=sim[invest_var[x]].values()[len(sim[invest_var[x]].values())-1]   
        print(df_invest)
        # dataframes are stored as session-variables --> not shure if necessary
        df_const=df_const.to_json()
        df_var=df_var.to_json()
        request.session['df_const']=df_const
        request.session['df_var']=df_var

    if request.method=="POST":
        df_const=request.session['df_const']
        df_var=request.session['df_var']
        df_const=pd.read_json(df_const)
        df_var=pd.read_json(df_var)

        # comp_crit is the comparison criterion (e.g. Investment-Cost) which the user has chosen
        comp_crit=request.POST["crit"]
        request.session['comp_crit']=comp_crit

        # dataframe is sorted by comparison-criterion
        const_sorted=df_const.sort_values(by=[comp_crit])
        # top 3 sorting 
        best_const=const_sorted.iloc[:3,:]
        # accessing the simulation names of the top 3 results (e.g. Waerme_32.mat etc)
        sim_to_dropdown=best_const['simulation']
        best_const=best_const.to_json()
        request.session['best_const']=best_const

    if request.method=="POST":
        # sim_detail is the simulation which the user wants to look at in detail
        sim_detail=request.POST["crit2"]
        request.session["sim_detail"]=sim_detail
    
    comp_crit=request.session["comp_crit"]
    sim_detail=request.session["sim_detail"]

    if comp_crit != '':
        # y != '' means the user submitted a comparison criterion

        best_const=request.session['best_const']
        best_const=pd.read_json(best_const)
    
        # each dictionary represents one barplot --> energy and costs   --> still hard coded and ugly
        energy_dict=best_const.iloc[:,:3]
        cost_dict=best_const.iloc[:,[0,3,4,5]]
        # hereee
        # color-stuff ugly and complicated
        energy_palette=[(143,53,71),(34,143,156)]
        cost_palette=[(0,141,180),(0,66,118),(87,101,108)]

        # barplots are created if data is available 
        p = figure(x_range=energy_dict['simulation'], plot_width=800, plot_height=300, title="Energiebedarf",
               toolbar_location="below", tools="hover", tooltips="$name" ": " "@$name")
        p.left[0].formatter.use_scientific = False
        p.vbar_stack(list(energy_dict.columns[1:]), x='simulation', width=0.9, legend=var_const_expl[:len(energy_dict.columns)-1],color=energy_palette, source=energy_dict)
        p.yaxis.axis_label = "Energy in kWh"
        p1 = figure(x_range=cost_dict['simulation'], plot_width=800, plot_height=300, title="Kosten",
               toolbar_location="below", tools="hover", tooltips="$name" ": " "@$name")
        p1.left[0].formatter.use_scientific = False
        p1.vbar_stack(list(cost_dict.columns[1:]), x='simulation', width=0.9,legend=var_const_expl[len(energy_dict)-1:],color=cost_palette, source=cost_dict)
        p1.yaxis.axis_label = "Cost in €"
    else:
        # barplots to display while data not available
       p = figure(plot_width=800, plot_height=300,toolbar_location="below") 
       p.line([0,1,2,3],[0,0,0,0])
       p1 = figure(plot_width=800, plot_height=300, toolbar_location="below") 
       p1.line([0,1,2,3],[0,0,0,0])
    if sim_detail != '':
        # ys2 != '' means user submitted the choice refering the simulation (waerme_1.mat etc)

        # dropdown choice 2 
        request.session['view_detailled']=request.POST["crit2"]
        #var_var_expl=["Strompreis","Leistung Heizkessel","Leistung BHKW","Leistung Elektrodenkessel"]
        #var_var=["Strommarkt.signalBus.Strompreis","Heizkessel.product.y","BHKW_.signalBus_BHKW.P_BHKW","Elektrodenkessel.signalBus_BHKW.P_EK"]
        
        # dataframe of non-time-constant variables is accessed
        var_dict=request.session['df_var']
        base_dict=pd.read_json(var_dict)
        

        # the variables of the chosen simulation are extracted from the whole dataframe
        var_dict=(base_dict[base_dict['simulation']==request.session['view_detailled']])
        
        # converting seconds to days
        time_seconds=var_dict['time'].values[0]
        time_days=[i/(3600*24) for i in time_seconds]
        var_dict['time'].values[0]=time_days
        
        #mypalette=Category10[10]
        #mypalette=mypalette[:len(var_dict.columns)-1]
        mypalette=["cornflowerblue","indianred","indigo"]
        
        p2 = figure(plot_width=800, plot_height=300,toolbar_location="below") 
        p2.xaxis.axis_label = "Time in days"
        p2.left[0].formatter.use_scientific = False
        # change just some things about the y-axes
        p2.yaxis.axis_label = "Power in Watt"
        ## line plots are created by iterating
        for i in range(3,len(var_dict.columns)):
            # there was the need to differentiate between variables with a lot entries and variables with only two entries (e.g. if Power is constant--> only 2 power values at the end/beginning of simulation)
            if len(list(var_dict[var_var[i-2]].values[0]))>2:
        #        print('eins')
                p2.line(list(var_dict['time'].values[0]),list(var_dict[var_var[i-2]].values[0]),legend=var_var_expl[i-2],color=mypalette[i-3])
            else:
        #        print('zwei')
                p2.line(list([var_dict['time'][0][0],var_dict['time'][0][len(var_dict['time'][0])-1]]),list(var_dict[var_var[i-2]].values[0]),legend=var_var_expl[i-2],color=mypalette[i-1])
        # Dominik wanted to have the Strompreis in a several lineplot
        p3 = figure(plot_width=800, plot_height=300,toolbar_location="below") 
        p3.xaxis.axis_label = "Time in days"
        p3.left[0].formatter.use_scientific = False
        # change just some things about the y-axes
        p3.yaxis.axis_label = "Electric-Energy-Price in Euro/kWh"
        p3.line(list(var_dict['time'].values[0]),list(var_dict["Strommarkt.signalBus.Strompreis"].values[0]),legend=var_var_expl[0],color="plum")
    else:
        p2 = figure(plot_width=800, plot_height=300,toolbar_location="below") 
        p2.line([0,1,2,3],[0,0,0,0])
        p3 = figure(plot_width=800, plot_height=300, toolbar_location="below") 
        p3.line([0,1,2,3],[0,0,0,0])
    # stacking of the figures
    a = row(p,p1)
    b = row(p2,p3)
    c = column(a,b)

    script, div = components(c)   
    return render(request, 'test.html',{'script': script, 'div':div, 'variables': var_const, 'simulations': sim_to_dropdown})
Example #25
0
for exciterNumber, exciterName in enumerate(exciters['names']):
    os.makedirs(f'{exciterName}')

#For loop that will iterate between machines, simulate, and create the .csv file
for exciterNumber, exciterName in enumerate(exciters['names']):
    print(f"Load Variation {exciterName} Simulation Start...")
    try:
        omc.sendExpression(f"cd(\"{LVExcitersWorkingDir}" + exciterName +
                           "\")")
        omc.sendExpression(f"loadFile(\"{OpenIPSLPackage}\")")
        omc.sendExpression("instantiateModel(OpenIPSL)")
        omc.sendExpression(
            f"simulate(OpenIPSL.Examples.Controls.PSSE.ES.{exciterName}, stopTime=10.0,method=\"rungekutta\",numberOfIntervals=5000,tolerance=1e-06)"
        )
        sim = SimRes(
            "" + LVExcitersWorkingDir +
            f"{exciterName}/OpenIPSL.Examples.Controls.PSSE.ES.{exciterName}_res.mat"
        )
        print(f"{exciterName} Simulation Finished...")
    except:
        print(f"{exciterName} simulation error or model not found...")
    try:
        #Selecting Variables
        print(".csv Writing Start...")
        try:
            print('Verifying if it is a GENROU model...')
            #Selecting Variables
            variables = [
                'Time', exciters['delta'][0], exciters['pelec'][0],
                exciters['pmech'][0], exciters['speed'][0],
                exciters['efd'][exciterNumber], 'GEN1.V', 'LOAD.V', 'GEN2.V',
                'FAULT.V'
Example #26
0
         "Simulation failed or model was not found. Below is the translation log:\n"
     )
     log = dymola.getLastErrorLog()
     print(log)
     try:
         os.chdir(
             f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Exciters/{exciterName}/"
         )
         os.remove("dsin.txt")
     except:
         pass
 else:
     print(f"{exciterName} Simulation OK...")
     print(".csv Writing Start...")
     sim = SimRes(
         f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Exciters/{exciterName}/{exciterName}.mat"
     )
     try:
         print('Verifying if it is a GENROU model...')
         #Selecting Variables
         variables = [
             'Time', exciters['delta'][0], exciters['pelec'][0],
             exciters['speed'][0], exciters['efd'][exciterNumber],
             'GEN1.V', 'LOAD.V', 'GEN2.V', 'FAULT.V'
         ]
         df_variables = pd.DataFrame([], columns=variables)
         for var in variables:
             df_variables.drop(var, axis=1, inplace=True)
             #Change from Radians to Degrees
             if var == exciters['delta'][0]:
                 df_variables[var] = np.array(sim[var].values() *
Example #27
0
for pssNumber, pssName in enumerate(psss['names']):
    os.makedirs(f'{pssName}')

#For loop that will iterate between machines, simulate, and create the .csv file
for pssNumber, pssName in enumerate(psss['names']):
    print(f"Fault {pssName} Simulation Start...")
    try:
        omc.sendExpression(f"cd(\"{FPowerSystemStabilizersWorkingDir}" +
                           pssName + "\")")
        omc.sendExpression(f"loadFile(\"{OpenIPSLPackage}\")")
        omc.sendExpression("instantiateModel(OpenIPSL)")
        omc.sendExpression(
            f"simulate(OpenIPSL.Examples.Controls.PSSE.PSS.{pssName}, stopTime=10.0,method=\"dassl\",numberOfIntervals=5000,tolerance=1e-06)"
        )
        sim = SimRes(
            "" + FPowerSystemStabilizersWorkingDir +
            f"{pssName}/OpenIPSL.Examples.Controls.PSSE.PSS.{pssName}_res.mat")
        print(f"{pssName} Simulation Finished...")
    except:
        print(f"{pssName} simulation error or model not found...")
    try:
        #Selecting Variables
        print(".csv Writing Start...")
        try:
            print('Verifying if it is a GENROU model...')
            #Selecting Variables
            variables = [
                'Time', psss['delta'][0], psss['pelec'][0], psss['pmech'][0],
                psss['speed'][0], psss['vothsg'][pssNumber], 'GEN1.V',
                'LOAD.V', 'GEN2.V', 'FAULT.V'
            ]
Example #28
0
'''
Created on 24 Jul 2018

@author: fran_jo
'''
import sys
from eme.logiclayer.command.viewdata import ViewData
from modelicares import SimRes

if __name__ == '__main__':
    resData = SimRes(sys.argv[1])
    selectedSignals = ViewData.selectData(
        sorted(resData.names()), "Select the signal you want to plot? ")
    ViewData.plotOutputs(selectedSignals)
Example #29
0
def static():
    """Create static images for the HTML documentation and the base README.md.
    """
    import matplotlib.pyplot as plt
    from modelicares import SimRes, LinResList, read_params

    join = os.path.join

    # Options
    indir = "../examples"  # Directory with the mat files.
    outdir = "_static"  # Directory where the images should be generated
    dpi = 90  # DPI for the HTML index images
    dpi_small = 30  # DPI for the README images
    kwargs = dict(bbox_inches='tight', format='png')  # Other savefig() options

    # ThreeTanks
    # ----------
    sim = SimRes(join(indir, 'ThreeTanks.mat'))
    sim.sankey(title=("Sankey diagrams of "
                      "Modelica.Fluid.Examples.Tanks.ThreeTanks"),
               times=[0, 50, 100, 150], n_rows=2, format='%.1f ',
               names=['tank1.ports[1].m_flow', 'tank2.ports[1].m_flow',
                      'tank3.ports[1].m_flow'],
               labels=['Tank 1', 'Tank 2', 'Tank 3'],
               orientations=[-1, 0, 1],
               scale=0.1, margin=6, offset=1.5,
               pathlengths=2, trunklength=10)
    plt.savefig(join(outdir, 'ThreeTanks.png'), dpi=dpi, **kwargs)
    plt.savefig(join(outdir, 'ThreeTanks-small.png'), dpi=dpi_small, **kwargs)
    plt.close()

    # ChuaCircuit
    # -----------
    sim = SimRes(join(indir, 'ChuaCircuit.mat'))
    ax = sim.plot(ynames1='L.v', ylabel1="Voltage",
                  xname='L.i', xlabel="Current",
                  title=("Modelica.Electrical.Analog.Examples.ChuaCircuit\n"
                         "Current through and voltage across the inductor"))[0]
    # Mark the start and stop points.
    def mark(time, text):
        """Mark a frequency point.
        """
        i = sim['L.i'].values(time)
        v = sim['L.v'].values(time)
        plt.plot(i, v, 'bo')
        ax.annotate(text, xy=(i, v), xytext=(0, -4), ha='center', va='top',
                    textcoords='offset points')
    mark(0, "Start")
    mark(2500, "Stop")
    # Save and close.
    plt.savefig(join(outdir, 'ChuaCircuit.png'), dpi=dpi, **kwargs)
    plt.savefig(join(outdir, 'ChuaCircuit-small.png'), dpi=dpi_small, **kwargs)
    plt.close()

    # PIDs-bode
    # ---------
    lins = LinResList(join(indir, 'PID.mat'), join(indir, 'PID/*/'))
    for lin in lins:
        lin.label = "Td = %g s" % read_params('Td', join(lin.dirname,
                                                         'dsin.txt'))
    lins.sort(key=lambda lin: lin.label)
    lins.bode(title=("Bode plot of Modelica.Blocks.Continuous.PID\n"
                     "with varying differential time constant"))
    plt.savefig(join(outdir, 'PIDs-bode.png'), dpi=dpi, **kwargs)
    plt.savefig(join(outdir, 'PIDs-bode-small.png'), dpi=dpi_small, **kwargs)
    plt.close()
Example #30
0
def kennfeld_erzeugen(mp, Root_kennfelder, Root_simulationsergebnisse):
    #ergebnisse sind in mat datei gespeichert und enthalten die Simulationszeit, den SOC , sowie den Zustand, welcher bei 1 laden und 0 entladen bedeutet
    #Simulationsergebnis muss so vorliegen, dass speicher anfangs entladen ist
    sim = SimRes(
        os.path.join(Root_simulationsergebnisse,
                     'simulationsergebnis_mp' + str(mp) + '.mat'))
    zeit = sim['Time']
    zeit = zeit.values()
    SOC = sim['SOC']
    SOC = SOC.values()
    SOC = np.vstack((zeit, SOC))
    SOC = np.transpose(SOC)
    print(SOC)
    zustand = sim['zustand.Q']
    zustand = zustand.values()
    zustand = np.vstack((zeit, zustand))
    #zustand ist array welches zeit und entladezustand enthält
    zustand = np.transpose(zustand)
    print(zustand)
    a = 1
    entladen_start = np.zeros((1, 1))
    #zeitstempel der Entlade-Anfänge werden gesucht
    while a < len(zustand):
        if zustand[a, 1] < zustand[a - 1, 1]:
            entladen_start = np.vstack((entladen_start, zustand[a, 0]))
        a = a + 1

    entladen_start = entladen_start[
        2:, :]  #enthält die Zeitstempel, wann das Entladen beginnt
    print('entladen start:', entladen_start)
    b = 1
    laden_start = np.zeros((1, 1))
    #zeitstempel der Lade-Anfänge werden gesucht
    while b < len(zustand):
        if zustand[b, 1] > zustand[b - 1, 1]:
            laden_start = np.vstack((laden_start, zustand[b, 0]))
        b = b + 1
    laden_start = laden_start[
        2:, :]  #enthält die Zeitstempel, wann das Laden beginnt
    print('laden start:', laden_start)

    #Hier wird das Ladekennfeld erstellt
    anfang_laden = np.where(zustand == laden_start[0])
    anfang_laden = anfang_laden[0]
    anfang_laden = anfang_laden[1]
    print('anfang laden', anfang_laden)

    ende_laden = np.where(zustand == entladen_start[1])
    #print('ende',ende)
    ende_laden = ende_laden[0]
    ende_laden = ende_laden[1]
    print('ende laden', ende_laden)

    laden = np.zeros((ende_laden - anfang_laden + 1, 2))
    laden[:, 0] = zeit[anfang_laden:ende_laden + 1]
    laden[:, 1] = SOC[anfang_laden:ende_laden + 1, 1]
    #print(laden)

    #das hier ist unschön --> glättet aber das Kennfeld des Eissilos
    for i in range(10):
        for i in range(1, len(laden)):
            if laden[i, 1] < laden[i - 1, 1]:
                laden[i - 1, 1] = laden[i, 1]
    Abzug = laden[0, 0]
    for i in range(len(laden)):
        laden[i, 0] = laden[i, 0] - Abzug

    #Hier wird das Entladekennfeld erstellt
    anfang_entladen = np.where(zustand == entladen_start[1])
    #print('anfang entladen', anfang_1)
    anfang_entladen = anfang_entladen[0]
    anfang_entladen = anfang_entladen[1]
    print('anfang entladen', anfang_entladen)
    ende_entladen = np.where(zustand == laden_start[1])
    #print('ende entladen',ende_1)
    ende_entladen = ende_entladen[0]
    ende_entladen = ende_entladen[1]
    print('ende entladen', ende_entladen)
    entladen = np.zeros((ende_entladen - anfang_entladen + 1, 2))
    entladen[:, 0] = zeit[anfang_entladen:ende_entladen + 1]
    entladen[:, 1] = SOC[anfang_entladen:ende_entladen + 1, 1]

    Abzug = entladen[0, 0]
    for i in range(len(entladen)):
        entladen[i, 0] = entladen[i, 0] - Abzug
    Normierung = entladen[len(entladen) - 1, 0]
    for i in range(len(entladen)):
        entladen[i, 0] = Normierung - entladen[i, 0]
    entladen_neu = np.zeros((len(entladen), 2))
    for i in range(len(entladen)):
        entladen_neu[i, 0] = entladen[len(entladen) - 1 - i, 0]
        entladen_neu[i, 1] = entladen[len(entladen) - 1 - i, 1]

    plt.subplot(311)
    plt.plot(laden[:, 0], laden[:, 1])
    plt.subplot(312)
    plt.plot(entladen_neu[:, 1], entladen_neu[:, 0])

    sio.savemat(os.path.join(Root_kennfelder, 'kennfeld_mp' + str(mp)),
                dict(ladekurve=laden, entladekurve=entladen_neu))
    return laden, entladen_neu, SOC
Example #31
0
#!/usr/bin/python
# Example of SimRes.plot()

from modelicares import SimRes

sim = SimRes('ChuaCircuit.mat')
sim.plot(ynames1='L.i', ylabel1="Current",
         ynames2='L.der(i)', ylabel2="Derivative of current",
         title="Chua circuit")
Example #32
0
def Obj(values_DVs, BC, s):
    """
    Function to compute the objective function value
    inputs:
        values_DVs: values of the decision variables
        BC: current boundary conditions
        s: subsystem object
    returns:
        None
    """
    import Init
    import os
    from modelicares import SimRes
    import numpy as np
    import scipy.interpolate as interpolate
    import scipy.io as sio

    # Open dymola library
    TranslateModel(s._model_path, s._name, s.position)

    global dymola
    obj_fnc_val = 'objectiveFunction'
    """ Store two .mat-files that can be read by Dymola """
    #This file contains the input setting BC1/ BC2/..
    BC_array = np.empty([1, len(BC) + 1])
    BC_array[0, 0] = 0
    for i, val in enumerate(BC):
        BC_array[0][i + 1] = val
    """This file contains the decision variable setting DV1/ DV2/.. """
    if isinstance(values_DVs, np.ndarray):
        DV_array = np.empty([1, 2])
        DV_array[0, 0] = 0
        DV_array[0, 1] = float(values_DVs)
    else:
        DV_array = np.empty([1, len(values_DVs) + 1])
        DV_array[0, 0] = 0
        for i2, val2 in enumerate(values_DVs):
            DV_array[0][i2 + 1] = val2
    """Store the decision variables and boundary conditions as .mat files"""
    subsys_path = Init.path_res + '\\' + Init.name_wkdir + '\\' + s._name
    sio.savemat((subsys_path + '\\' + Init.fileName_DVsInputTable + '.mat'),
                {Init.tableName_DVsInputTable: DV_array})
    sio.savemat((subsys_path + '\\' + Init.fileName_BCsInputTable + '.mat'),
                {Init.tableName_BCsInputTable: BC_array})

    final_names = [obj_fnc_val]
    """Run the actual simulations"""
    # Max. 3 attempts to simulate
    # Different function call if no initialization is intended
    if s._model_type == "Modelica":
        for k in range(3):
            try:
                if s._initial_names is None:
                    simStat = dymola.simulateExtendedModel(
                        problem=s._model_path,
                        startTime=Init.start_time,
                        stopTime=Init.stop_time,
                        outputInterval=Init.incr,
                        method="Dassl",
                        tolerance=Init.tol,
                        resultFile=subsys_path + '\dsres',
                        finalNames=final_names,
                    )
                else:
                    simStat = dymola.simulateExtendedModel(
                        problem=s._model_path,
                        startTime=Init.start_time,
                        stopTime=Init.stop_time,
                        outputInterval=Init.incr,
                        method="Dassl",
                        tolerance=Init.tol,
                        resultFile=subsys_path + '\dsres',
                        finalNames=final_names,
                        initialNames=s._initial_names,
                        initialValues=s._initial_values,
                    )

                k = 4

            except:
                if k < 3:
                    print('Repeating simulation attempt')
                else:
                    print('Final simulation error')

                k += 1

        # Get the simulation result
        sim = SimRes(os.path.join(subsys_path, 'dsres.mat'))

        #store output
        output_traj = []
        output_list = []
        if s._output_vars is not None:
            for val in s._output_vars:
                output_vals = sim[val].values()
                output_list.append(output_vals[-1])
                output_traj.append(sim[val].values())

    else:
        command = []
        T_cur = []
        T_prev = []
        T_met_prev_1 = []
        T_met_prev_2 = []
        T_met_prev_3 = []
        T_met_prev_4 = []
        output_traj = []
        output_list = []
        MLPModel = load("C:\\TEMP\Dymola\\" + s._name + ".joblib")
        scaler = load("C:\\TEMP\\Dymola\\" + s._name + "_scaler.joblib")

        for t in range(60):
            T_met_prev_1.append(s._initial_values[0])
            T_met_prev_2.append(s._initial_values[1])
            T_met_prev_3.append(s._initial_values[2])
            T_met_prev_4.append(s._initial_values[3])
            try:
                command.append(values_DVs[0])
            except:
                command.append(values_DVs)
            T_cur.append(BC[0])
            T_prev.append(BC[0])

        x_test = np.stack((command, T_cur, T_prev, T_met_prev_1, T_met_prev_2,
                           T_met_prev_3, T_met_prev_4),
                          axis=1)

        scaled_instances = scaler.transform(x_test)
        traj = MLPModel.predict(scaled_instances)
        traj += 273 * np.ones(len(traj))
        if s._output_vars is not None:
            output_traj = [
                traj, (0.3 + random.uniform(0.0, 0.01)) * np.ones(60)
            ]

            output_list.append(traj[-1])
            output_list.append(0.3 + random.uniform(0.0, 0.01))


#        print(values_DVs[0])
        print(BC[0])
        print(traj)

    if s._output_vars is not None:
        global gl_output
        gl_output = output_list

    cost_total = 0
    """all other subsystems + costs of downstream system"""
    if s._type_subSyst != "consumer":
        x = sio.loadmat(Init.path_res + '\\' + Init.name_wkdir + '\\' +
                        s._name + '\\' + Init.fileName_Cost + '.mat')

        storage_cost = x[Init.tableName_Cost]
        """Interpolation"""
        # Currently, the local cost depends on the relative decision variable
        costs_neighbor = interpolate.interp2d(storage_cost[0, 1:],
                                              storage_cost[1:, 0],
                                              storage_cost[1:, 1:],
                                              kind='linear',
                                              fill_value=10000)
    """all other subsystems + costs of downstream system"""
    if s._type_subSyst != "consumer":
        x = sio.loadmat(Init.path_res + '\\' + Init.name_wkdir + '\\' +
                        s._name + '\\' + Init.fileName_Cost + '.mat')

        storage_cost = x[Init.tableName_Cost]
        """Interpolation"""
        # Currently, the local cost depends on the relative decision variable
        costs_neighbor = interpolate.interp2d(storage_cost[0, 1:],
                                              storage_cost[1:, 0],
                                              storage_cost[1:, 1:],
                                              kind='linear',
                                              fill_value=10000)

        for l, tout in enumerate(output_traj[0]):
            if l > 100 or s._model_type == "MLP":
                # Avoid nan by suppressing operations with small numbers
                if values_DVs > 0.0001:
                    cost_total += values_DVs * s._cost_factor + costs_neighbor(
                        0.008, tout - 273)
                else:
                    cost_total += costs_neighbor(0.008, tout - 273)
        if s._model_type == "Modelica":
            cost_total = cost_total / len(output_traj[0])
        else:
            cost_total = cost_total / len(output_traj[0])
        print(s._name + " actuators : " + str(values_DVs))
        print("cost_total: " + str(cost_total))
        print("output: " + str(tout))
        #time.sleep(2)

    else:
        for l, tout in enumerate(output_traj[0]):
            if l > 100 or s._model_type == "MLP":
                cost_total += 10 * (max(
                    abs(tout - 273 - Init.set_point[0]) - Init.tolerance,
                    0))**2

        cost_total = cost_total / len(output_traj[0])
        print(s._name + " actuators : " + str(values_DVs))
        print("cost_total: " + str(cost_total))
        print("output: " + str(tout))
    '''Temporary objective function value'''
    obj_fnc_vals = [1]
    """ Track Optimizer """
    global gl_res_grid
    step = np.array([[float(values_DVs)], [obj_fnc_vals[-1]]])
    gl_res_grid = np.append(gl_res_grid, step, axis=1)

    return cost_total
Example #33
0
        print(f"{machineName} Simulation Start...")
        dymola.cd("/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Machines/" + machineName)
        resultPath = f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Machines/{machineName}/" + machineName
        result = dymola.simulateModel(machines['path'][machineNumber], 
                                stopTime=10.0,
                                numberOfIntervals = 5000,
                                resultFile = resultPath)
        if not result:
            print("Simulation failed or model was not found. Below is the translation log:\n")
            log = dymola.getLastErrorLog()
            print(log)
        else:
            print(f"{machineName} Simulation OK...")
            print(".csv Writing Start...")
            #Selecting Result File
            sim = SimRes(f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Machines/{machineName}/{machineName}.mat")
            #Selecting Variables
            variables = ['Time', machines['delta'][machineNumber], machines['pelec'][machineNumber], machines['speed'][machineNumber], 'GEN1.V', 'LOAD.V', 'GEN2.V', 'FAULT.V' ]
            df_variables = pd.DataFrame([], columns = variables)
            for var in variables:
                df_variables.drop(var, axis = 1, inplace = True)
                df_variables[var] = np.array(sim[var].values())
            print(f"{machineName} Variables OK...")
            #Changing current directory
            os.chdir(f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Machines/{machineName}/")
            df_variables.to_csv(f'{machineName}.csv', index = False)          
            print(f"{machineName} Write OK...\n")        
    except DymolaException as ex:
        print("Error: " + str(ex))
print('Machine Examples Simulation OK...')
Example #34
0
    MODELS, RESULTS_DIR = write_script(EXPERIMENTS, working_dir=WORKING_DIR,
                                       packages=PACKAGES, fname=FNAME)

    # Ask Dymola to run the script.
    # For Linux:
    os.system('dymola ' + FNAME)
    # TODO: Add support for Windows.
    # For Windows:
    # os.system(r'C:\Program files\Dymola\bin\Dymola.exe ' + FNAME)
else:
    MODELS = [experiment.model[experiment.model.rfind('.') + 1:]
              for experiment in EXPERIMENTS]
    RESULTS_DIR = os.path.split(FNAME)[0]

# Create plots.
# Begin customize--------------------------------------------------------------

for i, model in enumerate(MODELS):
    sim = SimRes(os.path.join(RESULTS_DIR, str(i + 1), 'dsres.mat'))
    sim.plot(title="Chua Circuit with L = %.0f %s" % (sim['L.L'].IV(),
                                                      sim['L.L'].unit),
             ynames1=['L.i'], ylabel1='Current',
             ynames2=['L.der(i)'], ylabel2='Derivative of current',
             label=os.path.join(str(i + 1), model))

# End customize----------------------------------------------------------------

# Save the plots.
saveall(FORMATS)
plt.show()