Пример #1
0
def run_OpenModelica_CLI(model=None):
    """Run simulations with calls to the OpenModelica command line."""
    # Create a subdirectory for the simulation
    sim_dir = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        'sim_' + sys.platform  # separate windows and linux
    )

    if os.path.exists(sim_dir) is False:
        os.mkdir(sim_dir)

    omc = OMCSessionZMQ()
    base_path = omc.sendExpression('getInstallationDirectoryPath()')
    file = os.path.join(base_path, r'lib/omlibrary/AixLib 0.9.1/package.mo')

    model = "AixLib.FastHVAC.Examples.{}".format(model)
    cmds = [
        'setCommandLineOptions("-d=newInst")',
        'loadFile("{}")'.format(file),
        'cd("{}")'.format(sim_dir),
        'isPackage({})'.format(model),
        'isModel({})'.format(model),
        'checkModel({})'.format(model),
        'simulate({})'.format(model),
        # 'plot(temperatureSensor_after.T)',
        # 'plot(innerCycle.QCon)',
    ]

    for cmd in cmds:
        print(cmd)
        answer = omc.sendExpression(cmd)
        pprint.pprint(answer)
        print()
Пример #2
0
def run_ModelicaSystem():
    '''Create a ``ModelicaSystem`` object which provides functions to
    load, configure and simulate a model. Plotting is done with Python.

    For this example, we run the simulations for different heights 'h' from
    where the bouncing ball is dropped.
    '''

    # Setup the Modelica session and load the module
    omc = OMCSessionZMQ()
    model_path = (omc.sendExpression('getInstallationDirectoryPath()')
                  + '/share/doc/omc/testmodels/')
    mod = ModelicaSystem(model_path + 'BouncingBall.mo', 'BouncingBall')
    # Set some simulation options
    mod.setSimulationOptions(stepSize=.05, stopTime=2.0)

    # Print some useful information
    quant = pd.DataFrame(mod.getQuantities())
    print(quant)

    # Modify and run simulations
    for h_start in [1, 2, 3]:
        mod.setContinuous(h=h_start)  # `h` is a `continuous` variable
        mod.simulate()
        time, h = mod.getSolutions('time', 'h')

        plt.plot(time, h, label='h_start = {0} m'.format(h_start))

    plt.legend()
    plt.xlabel(r'time $t$ in [s]')
    plt.ylabel(r'height $h$ in [m]')
    plt.show(block=False)
 def run(self):
   global omc
   del(omc)
   omc = OMCSessionZMQ()
   omc.sendExpression("setModelicaPath(\""+omhome+"/lib/omlibrary\")")
   omc.sendExpression('cd("tmp")')
   return []
Пример #4
0
 def __init__(self, rootPath):
     '''
     Constructor starts omc and loads MSL
     '''
     self.rootPath = rootPath
     self.omc = OMCSessionZMQ()
     os.chdir(self.rootPath)
     self.omc.sendExpression("loadModel(Modelica)")
Пример #5
0
 def make_fmu():
     '''Create an FMU from the Modelica model to use for testing
     '''
     # Setup the Modelica session and load the module
     omc = OMCSessionZMQ()
     model_path = (omc.sendExpression('getInstallationDirectoryPath()')
                   + '/share/doc/omc/testmodels/')
     mod = ModelicaSystem(model_path + 'BouncingBall.mo', 'BouncingBall')
     # Convert model to FMU 'BouncingBall.fmu'
     mod.convertMo2Fmu()
Пример #6
0
def run_OpenModelica_CLI():
    '''Use calls to the OpenModelica command line interface to load,
    simulate and plot a model.
    '''
    omc = OMCSessionZMQ()
    cmds = [
      ('loadFile(getInstallationDirectoryPath()'
       + ' + "/share/doc/omc/testmodels/BouncingBall.mo")'),
      'simulate(BouncingBall)',
      'plot(h)',
      ]
    for cmd in cmds:
        answer = omc.sendExpression(cmd)
        print('\n{}:\n{}'.format(cmd, answer))
Пример #7
0
    def simulate(self, ds_test: TestDataSet):

        omc = OMCSessionZMQ()
        # path = inspect.getfile(omc.__class__)

        mod = ModelicaSystem(sep.join([self.path_model, "package.mo"]),
                             "Steps.Test.TestPCHXMeshram", ["Modelica 3.2.1"])
        # options for simulation - steady state simulation, no iteration required, so set numberOfIntervals = 2
        mod.setSimulationOptions('stepSize  = 0.2')

        for test in ds_test:
            cfg = test.cfg
            print('prepare to simulate:' + cfg.full_name)
            mod.setParameters(test.gen_sim_param())

            mod.simulate()

            print('simulation {0} done, retrieving result'.format(
                cfg.full_name))
            result = test.result

            # collect data in solutions
            for sol_key in result:
                sol = mod.getSolutions(sol_key)
                if not sol is None:
                    result.set_result(sol_key, sol)
                else:
                    print("solution with key = {0} not exsits".format(sol_key))

            # result.update_cal_columns()

        print('all simulation(s) done, save result next')

        self.save_results(ds_test)
Пример #8
0
 def __init__(self, rootPath):
     '''
     Constructor starts omc and loads MSL
     '''
     self.rootPath = rootPath
     self.omc = OMCSessionZMQ()
     os.chdir(self.rootPath)
     self.omc.sendExpression("loadModel(Modelica)")
Пример #9
0
def run_ModelicaSystem():
    """Create a ``ModelicaSystem`` object and run a simulation.

    For this example, we run the simulations for different heights 'h' from
    where the bouncing ball is dropped. Plotting is done with Python.

    """
    # Setup the Modelica session and load the module
    omc = OMCSessionZMQ()
    model_path = (omc.sendExpression('getInstallationDirectoryPath()') +
                  '/share/doc/omc/testmodels/')
    mod = ModelicaSystem(model_path + 'BouncingBall.mo',
                         'BouncingBall',
                         commandLineOptions='-d=newInst')

    # Set some simulation options
    stepSize = 0.05
    stopTime = 2.0

    text = ["stepSize={}".format(stepSize), "stopTime={}".format(stopTime)]
    mod.setSimulationOptions(text)

    # Print some useful information
    quantities = pd.DataFrame(mod.getQuantities())
    print(quantities)

    # Modify and run simulations
    for h_start in [1, 2, 3]:
        # `h` is a `continuous` variable
        mod.setContinuous("h={}".format(h_start))
        mod.simulate()  # Run the actual simulation

        solution_list = ['time', 'h']
        solution_data = mod.getSolutions(solution_list)  # read solutions
        df = pd.DataFrame(data=solution_data.T, columns=solution_list)

        plt.plot(df.time, df.h, label='h_start = {0} m'.format(h_start))

    plt.legend()
    plt.xlabel(r'time $t$ in [s]')
    plt.ylabel(r'height $h$ in [m]')
    plt.show(block=False)
Пример #10
0
def linearize_model(
        model_info: ModelicaModelInfo,
        initial_parameters: ModelVariables = dict(),
        control_df: t.Optional[pd.DataFrame] = None) -> fmi.FMUModelCS2:
    omc = OMCSessionZMQ()
    is_loaded: bool = omc.sendExpression(f'loadFile("{model_info.location}")')
    if not is_loaded:
        raise RuntimeError("Could not load model: ")
    stopTime = 100
    path_to_csv = None
    if control_df is not None:
        path_to_csv = _generate_control_csv(control_df.reset_index())
        stopTime = control_df.index[-1]

    initial_parameters_flags = "".join(
        [f'-override {var}={val}' for var, val in initial_parameters.items()])
    input_file_flags = f"-csvInput {path_to_csv}" if path_to_csv is not None else ""

    linearization_result = omc.sendExpression(
        f'linearize({model_info.name}, startTime=0, stopTime={stopTime}, stepSize=10, simflags="{initial_parameters_flags} {input_file_flags}", outputFormat="csv")'
    )

    if path_to_csv is not None:
        os.remove(path_to_csv)

    if linearization_result is None or not len(
            linearization_result['resultFile']):
        print(linearization_result)
        raise RuntimeError("Could not linearize a model: ")

    fmu_path = FmuSource.from_modelica(
        ModelicaModelInfo(Path("linearized_model.mo"),
                          "linearized_model")).fmu_path
    model = load_fmu(str(fmu_path))

    # FMU exported from OpenModelica doesn't estimate from time 0,
    # so simulation from 0 to 0 helps
    opts = model.simulate_options()
    opts['silent_mode'] = True
    model.simulate(0, 0, options=opts)

    return model
Пример #11
0
class CITests():
    '''
    Python class used to run CI tests
    '''
    def __init__(self, rootPath):
        '''
        Constructor starts omc and loads MSL
        '''
        self.rootPath = rootPath
        self.omc = OMCSessionZMQ()
        os.chdir(self.rootPath)
        self.omc.sendExpression("loadModel(Modelica)")

    def loadLib(self, libName, libPath):
        # Attempt to load the library
        if self.omc.sendExpression('loadFile("%s")' %
                                   (self.rootPath + libPath)):
            print("Load success: %s" % libName)
        else:
            errmsg = libName + " was not loaded! Check the library path:\n" + libPath
            raise Exception(errmsg)

    def runSyntaxCheck(self, libName, libPath):
        # Load library
        self.loadLib(libName, libPath)
        '''
        Checks all of the models in the library and returns number of faild checks
        '''
        # Get the list of all classes in OpenIPSL
        test_list = self.omc.sendExpression(
            'getClassNames(%s,recursive=true)' % libName)
        nFailed = 0
        nPassed = 0

        # Run the check for all classes that are model and print result msgs
        for test in test_list:
            if self.omc.sendExpression("isModel(%s)" %
                                       (test)):  # Check if a class is a model
                passMsg = self.omc.sendExpression("checkModel(%s)" % (test))
                if "completed successfully." in passMsg:
                    nPassed += 1
                else:
                    failMsg = self.omc.sendExpression("getErrorString()")
                    print(failMsg)
                    nFailed += 1
        # Print a check summary
        if nFailed == 0:
            str1 = "== %s ----------------------" % libName
            print("%s OK! == Models checked: %s" % (str1[:22], nPassed))
        else:
            print("==== Check Summary for %s ====" % libName)
            print("Number of models that passed the check is: %s" % nPassed)
            print("Number of models that failed the check is: %s" % nFailed)

        # Return test result
        return (nFailed == 0)
Пример #12
0
 def run(self):
     global omc
     del (omc)
     omc = OMCSessionZMQ()
     omc.sendExpression("setModelicaPath(\"" + omhome + "/lib/omlibrary\")")
     omc.sendExpression('cd("tmp")')
     return []
Пример #13
0
class CITests():
    '''
    Python class used to run CI tests
    '''
    def __init__(self, rootPath):
        '''
        Constructor starts omc and loads MSL
        '''
        self.rootPath = rootPath
        self.omc = OMCSessionZMQ()
        os.chdir(self.rootPath)
        self.omc.sendExpression("loadModel(Modelica)")


    def loadLib(self, libName, libPath):
        # Attempt to load the library
        if self.omc.sendExpression('loadFile("%s")' % (self.rootPath + libPath)):
            print "Load success: %s" % libName
        else:
            errmsg = libName + " was not loaded! Check the library path:\n" + libPath
            raise Exception(errmsg)

    def runSyntaxCheck(self, libName, libPath):
        # Load library
        self.loadLib(libName,libPath)
        '''
        Checks all of the models in the library and returns number of faild checks
        '''
        # Get the list of all classes in OpenIPSL
        test_list = self.omc.sendExpression('getClassNames(%s,recursive=true)' % libName)
        nFailed = 0
        nPassed = 0

        # Run the check for all classes that are model and print result msgs
        for test in test_list:
            if self.omc.sendExpression("isModel(%s)" % (test)):  # Check if a class is a model
                passMsg = self.omc.sendExpression("checkModel(%s)" % (test))
                if "completed successfully." in passMsg:
                    nPassed += 1
                else:
                    failMsg = self.omc.sendExpression("getErrorString()")
                    print failMsg
                    nFailed += 1
        # Print a check summary
        if nFailed == 0:
            str1 = "== %s ----------------------" % libName
            print "%s OK! == Models checked: %s" % (str1[:22], nPassed)
        else:
            print "==== Check Summary for %s ===="  % libName
            print "Number of models that passed the check is: %s" % nPassed
            print "Number of models that failed the check is: %s" % nFailed

        # Return test result
        return (nFailed == 0)
Пример #14
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
Пример #15
0
 def __init__(self, path_file, name, display_errors):
     self.path_file = os.path.abspath(path_file)
     self.path = os.path.dirname(self.path_file)
     self.name = name
     self.display_errors = display_errors
     #        os.chdir(self.path)
     #        os.chdir("../")
     print("Working directory is " + os.getcwd() + "\n")
     self.stop_time = 0
     self.omc = OMCSessionZMQ()
     print self.omc.sendExpression("getVersion()")
     self.print_err()
     print self.omc.sendExpression(
         "setCommandLineOptions(\"+g=PDEModelica --demoMode=true\")")
     self.print_err()
     print self.omc.sendExpression("loadModel(Modelica)")
     self.print_err()
     print self.omc.sendExpression("loadFile(\"" + path_file + "\")")
     self.print_err()
     #create empty init file for case no parameters will be changed:
     #init_file = open("./WorkingDir/init_file.txt", "w")
     init_file = open("init_file.txt", "w")
     init_file.write("\n")
     init_file.close()
Пример #16
0
#!/usr/bin/env python
# coding: utf-8

from OMPython import OMCSessionZMQ
omc = OMCSessionZMQ()
from modelicares import SimRes
import pandas as pd
import numpy as np
import os
import shutil

# get current directory and set it to the beginning of the repository 
RepoDir = os.getcwd() 
#This is intended to be used in the manuelnvro Dell using Dymola 2020
ReferenceStep = RepoDir + "/ReferenceStep/"

#Run Exciters
print('---------------------------------------------------------- Reference Step Open Modelica Exciters Testing ----------------------------------------------------------')
try:
    os.chdir(f""+ReferenceStep+"")
    exec(open("ReferenceStepExcitersOpenModelica.py").read())
    print('Reference Step Open Modelica Exciters Testing OK...')
except:
    print('Error in Reference Step Open Modelica Exciters Testing...')

#Run Machines
print('---------------------------------------------------------- Reference Step Open Modelica Machines Testing ----------------------------------------------------------')
print('No Reference Step Open Modelica in Machines Testing...')

#Run Turbine Governors
print('---------------------------------------------------------- Reference Step Open Modelica Turbine Governors Testing ----------------------------------------------------------')
Пример #17
0
        * False to stop
</inp>

RETURN:
----------
    <out>
        output : output from commands
    </out>



"""

#For example
#cmds = ['loadFile(getInstallationDirectoryPath() + "/share/doc/omc/testmodels/BouncingBall.mo")',
#"simulate(BouncingBall)",
#"plot(h)"]
#Run = True

from OMPython import OMCSessionZMQ
if Run:
    omc = OMCSessionZMQ()
    output = []
    for command in CMDs:
        #change parentheses
        command = command.replace("[", "{").replace("]", "}")
        answer = omc.sendExpression(command)
        #print(cmd)
        output.append("\n{}:\n{}".format(command, answer))
else:
    output = "False"
Пример #18
0
import os
import sys
import math
import numpy as np
import time
import os.path

from OMPython import OMCSessionZMQ


os.system("rm -f ./System")      # .... to be on the safe side


omc = OMCSessionZMQ()
omc.sendExpression("getVersion()")
omc.sendExpression("cd()")

omc.sendExpression("loadModel(Modelica)")
omc.sendExpression("getErrorString()")

omc.sendExpression("loadFile(\"randomGenerator.mo\")")
omc.sendExpression("getErrorString()")

omc.sendExpression("loadFile(\"connectors.mo\")")
omc.sendExpression("getErrorString()")

omc.sendExpression("loadFile(\"aule.mo\")")
omc.sendExpression("getErrorString()")

omc.sendExpression("loadFile(\"studenti.mo\")")
omc.sendExpression("getErrorString()")
Пример #19
0
def generateOverviewHTML(crossCheckDir, platform, omsVersion, omsVersionShort, timeStart, totalTime, sysInfo):

  # Remove html directory
  shutil.rmtree(htmlResultDir, ignore_errors=True)

  # Generate data frame
  result_df = constructDF(crossCheckDir, platform, omsVersionShort)

  # Create directories for HTML files
  for dirs in [htmlResultDir, os.path.join(htmlResultDir,filesDir)]:
    if not os.path.exists(dirs):
      os.mkdir(dirs)

  # Read result data frame
  numFmus = len(result_df["OMS can import FMU"])
  fmusSimulated = list(result_df["OMS can import FMU"]).count(True)
  fmusVerified = list(result_df["Results Correct"]).count(True)

  # Generate result table
  resultsTable = ""
  for index, row in result_df.iterrows():
    fmiVersion = row["FMI Version"]
    fmiType = row["FMI Type"]
    exportingToolID = row["Exporting Tool"]
    exportingToolVersion = row["Exporting Tool Version"]
    modelName = row["Model Name"]
    testFMUDir = os.path.join(crossCheckDir, "fmus", fmiVersion, fmiType, platform,         \
                              exportingToolID, exportingToolVersion, modelName)
    resultDir = os.path.join(crossCheckDir, "results", fmiVersion, fmiType,                 \
                              platform, "OMSimulator", omsVersionShort,                     \
                              exportingToolID, exportingToolVersion, modelName)
    fileName = row["FMI Version"].replace(".", "") + "."              \
             + row["FMI Type"] + "."                                  \
             + row["Exporting Tool"].replace(".", "_") + "."          \
             + row["Exporting Tool Version"].replace(".", "_") + "."  \
             + row["Model Name"]

    # Create directory for model
    modelDir = os.path.join(htmlResultDir, filesDir, fileName)
    if not os.path.exists(modelDir):
      os.mkdir(modelDir)

    modelLog = generateSimLogHTML(row, testFMUDir ,resultDir, modelDir, fileName)

    if row["OMS can import FMU"]:
      simulated = "<td bgcolor=\"#SimulationColor#\">Yes</td>"
    else:
      simulated = "<td bgcolor=\"#FFCC66\">No</td>"

    if not row["OMS can import FMU"]:
      verified = "<td bgcolor=\"#FFCC66\"></td>"
    elif row["Results Correct"]:
      verified =  "<td bgcolor=\"#VerificationColor#\">Yes</td>"
    else:
      linkTarget = generateFailedVerificationHTML(row, testFMUDir, resultDir, modelDir, fileName)
      vailedVars = str(len(row["Failed Variables"]))
      totalVars = str(int(row["Toal Variables"]))
      verified = "<td bgcolor=\"#FFCC66\">"                 \
               + "<a href=\"" + linkTarget + "\">"          \
               + vailedVars+"/"+totalVars+" failed</td>"    \
               + "</a>"                                     \
               + "</td>\n"
      # TODO Add verivifaction time

    simTime = str(round(row["Simulation Time"],2))

    row = "      <tr>\n"                                                \
        + "        <td>" + fmiVersion + "</td>\n"                       \
        + "        <td>" + fmiType + "</td>\n"                          \
        + "        <td>" + exportingToolID + "</td>\n"                  \
        + "        <td>" + exportingToolVersion + "</td>\n"             \
        + "        <td>" + modelLog + "</td>\n"                         \
        + "        " + verified + "\n"                                  \
        + "        " + simulated + "\n"                                 \
        + "        <td>" + simTime + "</td>\n"                          \
        + "      </tr>\n"
    resultsTable = resultsTable + row

  commitshort = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=crossCheckDir).decode('utf-8')
  commitfull = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=crossCheckDir).decode('utf-8')

  if re.search(r"-g.+-",omsVersion):
    omscommitshort = re.search(r"-g.+-",omsVersion).group()[2:9]
  else:
    omscommitshort = "unknown"

  htmltpl=open("fmi-cross-check.html.tpl").read()

  # Replace keywords from HTML template
  htmltpl = htmltpl.replace("#Total#", str(numFmus))
  htmltpl = htmltpl.replace("#Simulation#", str(fmusSimulated))
  htmltpl = htmltpl.replace("#Verification#", str(fmusVerified))

  htmltpl = htmltpl.replace("#commitshort#", str(commitshort))
  htmltpl = htmltpl.replace("#commitfull#", str(commitfull))
  htmltpl = htmltpl.replace("#omscommitshort#", str(omscommitshort))

  htmltpl = htmltpl.replace("#totalTime#", time.strftime("%M:%S", time.gmtime(totalTime)))
  htmltpl = htmltpl.replace("#sysInfo#", sysInfo)
  htmltpl = htmltpl.replace("#omsVersion#", omsVersion)
  htmltpl = htmltpl.replace("#timeStart#", str(timeStart))
  htmltpl = htmltpl.replace("#ulimitOMSimulator#", str(ulimitOMSimulator))
  htmltpl = htmltpl.replace("#default_tolerance#", str(default_tolerance))
  omc = OMCSessionZMQ()
  omcVersion = omc.sendExpression("getVersion()")
  htmltpl = htmltpl.replace("#referenceTool#", omcVersion + " with function diffSimulationResults")

  htmltpl = htmltpl.replace("      #testsHTML#", resultsTable)

  resultHTML = os.path.join(htmlResultDir,"fmi-cross-check.html")
  open(resultHTML, "w").write(htmltpl)

  # Copy dygraph.js into html/
  shutil.copyfile("dygraph.js", os.path.join(htmlResultDir,"dygraph.js"))

  return resultHTML
Пример #20
0
class OpenModelicaKernel(Kernel):
    implementation = 'openmodelica_kernel'
    implementation_version = '1.0'
    language = 'openmodelica'
    language_version = '1.0'
    language_info = {
        'name': "modelica",
        'version': "1.0",
        'mimetype': 'text/x-modelica',
    }
    banner = "openmodelicakernel - for evaluating modelica codes in jupyter notebook"

    def __init__(self, **kwargs):
        Kernel.__init__(self, **kwargs)
        self.omc = OMCSessionZMQ()
        self.matfile = None

    def do_execute(self,
                   code,
                   silent,
                   store_history=True,
                   user_expressions=None,
                   allow_stdin=True):
        # print code

        z1 = "".join(filter(lambda x: not re.match(r'^\s*$', x), code))
        plotcommand = z1.replace(' ', '').startswith('plot(') and z1.replace(
            ' ', '').endswith(')')

        # print self.execution_count
        if (plotcommand):
            l1 = z1.replace(' ', '')
            l = l1[0:-1]
            plotvar = l[5:].replace('{', '').replace('}', '')
            plotdivid = str(self.execution_count)
            finaldata = plotgraph(plotvar, plotdivid, self.omc, self.matfile)
            # f = open("demofile.html", "w")
            # f.write(finaldata)
            # f.close()
            if not silent:
                '''
                stream_content = {'name': 'stdout','text':ouptut}
                self.send_response(self.iopub_socket, 'stream', stream_content) '''
                display_content = {
                    'source': 'kernel',
                    'data': {
                        'text/html': finaldata
                    },
                    'metadata': {}
                }
                self.send_response(self.iopub_socket, 'display_data',
                                   display_content)
        else:
            try:
                val = self.omc.sendExpression(code)
                try:
                    self.matfile = val['resultFile']
                except BaseException:
                    pass

            except BaseException:
                val = self.omc.sendExpression(code, parsed=False)

            # print self.matfile
            if not silent:
                display_content = {
                    'source': 'kernel',
                    'data': {
                        'text/plain': str(val)
                    },
                    'metadata': {}
                }
                self.send_response(self.iopub_socket, 'display_data',
                                   display_content)

        return {
            'status': 'ok',
            # The base class increments the execution count
            'execution_count': self.execution_count,
            'payload': [],
            'user_expressions': {},
        }

    def do_shutdown(self, restart):
        try:
            self.omc.__del__()
        except BaseException:
            pass
except ImportError:
    from io import StringIO
import subprocess

#from sphinx.util.compat import Directive
from docutils.parsers.rst import Directive
from docutils import nodes
from docutils.parsers.rst.directives.misc import Include as BaseInclude
from sphinx import directives
from docutils.parsers.rst import directives as rstdirectives
import docutils.parsers.rst.directives.images
from docutils.statemachine import ViewList

from OMPython import OMCSessionZMQ

omc = OMCSessionZMQ()
omhome = omc.sendExpression("getInstallationDirectoryPath()")
omc.sendExpression("setModelicaPath(\""+omhome+"/lib/omlibrary\")")
omc.sendExpression('mkdir("tmp/source")')
dochome = omc.sendExpression('cd("tmp")')

class ExecDirective(Directive):
  """Execute the specified python code and insert the output into the document"""
  has_content = True

  def run(self):
    oldStdout, sys.stdout = sys.stdout, StringIO()
    try:
      exec('\n'.join(self.content))
      return [nodes.paragraph(text = sys.stdout.getvalue())]
    except Exception as e:
Пример #22
0
 def __init__(self, rootPath):
     self.rootPath = rootPath
     self.omc = OMCSessionZMQ()
     os.chdir(rootPath)
     self.omc.sendExpression("loadModel(Modelica)")
Пример #23
0
class unitTests():
    def __init__(self, rootPath):
        self.rootPath = rootPath
        self.omc = OMCSessionZMQ()
        os.chdir(rootPath)
        self.omc.sendExpression("loadModel(Modelica)")

    def loadLibrary(self, libraryName, libraryPath):
        # Attempt to load the library
        if self.omc.sendExpression('loadFile("%s")' % (libraryPath)):
            print("Load success: %s" % libraryName)
        else:
            errorMessage = libraryName + " was not loaded! Check the library path:\n" + libraryPath
            print(errorMessage)
            raise Exception(errorMessage)

    def runModelCheck(self, libraryName, libraryPath):
        # Load library
        self.loadLibrary(libraryName, libraryPath)
        print("Model Check Start...")
        totalFailed = 0
        #testList = self.omc.sendExpression('getClassNames(%s,recursive=true)' % libraryName)
        testList = {
            'exciters': [
                "OpenIPSL.Examples.Controls.PSSE.ES.ESAC1A",
                "OpenIPSL.Examples.Controls.PSSE.ES.ESAC2A",
                "OpenIPSL.Examples.Controls.PSSE.ES.ESDC1A",
                "OpenIPSL.Examples.Controls.PSSE.ES.ESST1A",
                "OpenIPSL.Examples.Controls.PSSE.ES.ESST4B",
                "OpenIPSL.Examples.Controls.PSSE.ES.EXAC1",
                "OpenIPSL.Examples.Controls.PSSE.ES.EXAC2",
                "OpenIPSL.Examples.Controls.PSSE.ES.EXST1",
                "OpenIPSL.Examples.Controls.PSSE.ES.IEEET1",
                "OpenIPSL.Examples.Controls.PSSE.ES.IEEET2",
                "OpenIPSL.Examples.Controls.PSSE.ES.SCRX",
                "OpenIPSL.Examples.Controls.PSSE.ES.SEXS"
            ],
            'machines': [
                "OpenIPSL.Examples.Machines.PSSE.GENROU",
                "OpenIPSL.Examples.Machines.PSSE.GENSAL",
                "OpenIPSL.Examples.Machines.PSSE.GENCLS",
                "OpenIPSL.Examples.Machines.PSSE.GENROE",
                "OpenIPSL.Examples.Machines.PSSE.GENSAE",
                "OpenIPSL.Examples.Banks.PSSE.CSVGN1"
            ],
            'turbinegovernors': [
                "OpenIPSL.Examples.Controls.PSSE.TG.GAST",
                "OpenIPSL.Examples.Controls.PSSE.TG.HYGOV",
                "OpenIPSL.Examples.Controls.PSSE.TG.IEEEG1",
                "OpenIPSL.Examples.Controls.PSSE.TG.IEESGO",
                "OpenIPSL.Examples.Controls.PSSE.TG.TGOV1"
            ],
            'powersystemstabilizers': [
                "OpenIPSL.Examples.Controls.PSSE.PSS.PSS2A",
                "OpenIPSL.Examples.Controls.PSSE.PSS.PSS2B"
            ],
            'windturbines': [
                "OpenIPSL.Examples.Wind.PSSE.WT4G.WT4G1",
                "OpenIPSL.Examples.Wind.PSSE.WT4G.WT4E1"
            ]
        }
        #Exciter check
        print("Exciter Model Check Start...")
        totalModels = 0
        testsFailed = 0
        testsPassed = 0
        for test in testList['exciters']:
            totalModels += 1
            if self.omc.sendExpression("isModel(%s)" % (test)):
                passMessage = self.omc.sendExpression("checkModel(%s)" %
                                                      (test))
                if "completed successfully." in passMessage:
                    testsPassed += 1
                else:
                    testFailed += 1
                    totalFailed += 1
        print(
            str(testsPassed) + " have passed out of " + str(totalModels) +
            " Exciter Models.")
        #Machine check
        print("Machine Model Check Start...")
        totalModels = 0
        testsFailed = 0
        testsPassed = 0
        for test in testList['machines']:
            totalModels += 1
            if self.omc.sendExpression("isModel(%s)" % (test)):
                passMessage = self.omc.sendExpression("checkModel(%s)" %
                                                      (test))
                if "completed successfully." in passMessage:
                    testsPassed += 1
                else:
                    testFailed += 1
                    totalFailed += 1
        print(
            str(testsPassed) + " have passed out of " + str(totalModels) +
            " Machine Models.")
        #Turbine Governor check
        print("Turbine Governor Model Check Start...")
        totalModels = 0
        testsFailed = 0
        testsPassed = 0
        for test in testList['turbinegovernors']:
            totalModels += 1
            if self.omc.sendExpression("isModel(%s)" % (test)):
                passMessage = self.omc.sendExpression("checkModel(%s)" %
                                                      (test))
                if "completed successfully." in passMessage:
                    testsPassed += 1
                else:
                    testFailed += 1
                    totalFailed += 1
        print(
            str(testsPassed) + " have passed out of " + str(totalModels) +
            " Turbine Governor Models.")
        #Power System Stabilizer check
        print("Power System Stabilizer Model Check Start...")
        totalModels = 0
        testsFailed = 0
        testsPassed = 0
        for test in testList['powersystemstabilizers']:
            totalModels += 1
            if self.omc.sendExpression("isModel(%s)" % (test)):
                passMessage = self.omc.sendExpression("checkModel(%s)" %
                                                      (test))
                if "completed successfully." in passMessage:
                    testsPassed += 1
                else:
                    testFailed += 1
                    totalFailed += 1
        print(
            str(testsPassed) + " have passed out of " + str(totalModels) +
            " Power System Stabilizer Models.")
        #Wind Turbine check
        print("Wind Turbine Model Check Start...")
        totalModels = 0
        testsFailed = 0
        testsPassed = 0
        for test in testList['windturbines']:
            totalModels += 1
            if self.omc.sendExpression("isModel(%s)" % (test)):
                passMessage = self.omc.sendExpression("checkModel(%s)" %
                                                      (test))
                if "completed successfully." in passMessage:
                    testsPassed += 1
                else:
                    testFailed += 1
                    totalFailed += 1
        print(
            str(testsPassed) + " have passed out of " + str(totalModels) +
            " Wind Turbine Models.")
        return (testsFailed)
Пример #24
0
except ImportError:
    from io import StringIO
import subprocess

#from sphinx.util.compat import Directive
from docutils.parsers.rst import Directive
from docutils import nodes
from docutils.parsers.rst.directives.misc import Include as BaseInclude
from sphinx import directives
from docutils.parsers.rst import directives as rstdirectives
import docutils.parsers.rst.directives.images
from docutils.statemachine import ViewList

from OMPython import OMCSessionZMQ

omc = OMCSessionZMQ()
omhome = omc.sendExpression("getInstallationDirectoryPath()")
omc.sendExpression("setModelicaPath(\"" + omhome + "/lib/omlibrary\")")
omc.sendExpression('mkdir("tmp/source")')
dochome = omc.sendExpression('cd("tmp")')


class ExecDirective(Directive):
    """Execute the specified python code and insert the output into the document"""
    has_content = True

    def run(self):
        oldStdout, sys.stdout = sys.stdout, StringIO()
        try:
            exec('\n'.join(self.content))
            return [nodes.paragraph(text=sys.stdout.getvalue())]
def om_simulation(model_info, solver):

    root_path = model_info['root_path']
    library_path = model_info['library_path']
    model_path = model_info['model_path']
    model_name = model_info['model_name']
    output_path = model_info['output_path']

    omc = OMCSessionZMQ()
    print(omc.sendExpression("getVersion()"))

    try:
        if not os.path.exists(output_path):
            os.makedirs(output_path)
            print("Working directory created")
    except OSError as ex:
        print("1: Failed to create folder for working directory")

    # Changing working directory
    omc.sendExpression(f"cd(\"{output_path}\")")

    # Opening library
    omc.sendExpression(f"parseFile(\"{library_path}\", \"UTF-8\")")
    omc.sendExpression(f"loadFile(\"{library_path}\", \"UTF-8\", true)")
    omc.sendExpression("instantiateModel(OpenIPSL)")

    if solver == "dassl":
        omc.sendExpression("setCommandLineOptions(\"daeMode=true\")")
        print("DAE setting changed for dassl")

    # Setting the number of cores for computation to 1
    omc.sendExpression("setCommandLineOptions(\"-n=1\")")

    if solver in ["euler", "trapezoid", "rungekutta"]:
        print("Running simulation...")
        flag = omc.sendExpression(
            f"simulate({model_name},stopTime=120,method=\"{solver}\",numberOfIntervals=240000,tolerance=1e-06)"
        )
        print(flag)
    else:
        print("Running simulation...")
        flag = omc.sendExpression(
            f"simulate({model_name},stopTime=120,method=\"{solver}\",numberOfIntervals=5000,tolerance=1e-06)"
        )
        print(flag)

    omc.sendExpression("quit()")

    if omc is not None:
        omc = None
Пример #26
0
rmlStyle=False

# Try to make the processes a bit nicer...
os.environ["GC_MARKERS"]="1"
if ompython_omhome != "":
  # Use a different OMC for running OMPython than for running the tests
  omhome = os.environ["OPENMODELICAHOME"]
  try:
    omc_version = subprocess.check_output(["%s/bin/omc" % omhome, "--version"], stderr=subprocess.STDOUT).strip()
  except:
    omc_version = subprocess.check_output(["%s/bin/omc" % omhome, "+version"], stderr=subprocess.STDOUT).strip()
    version_cmd = "+version"
    rmlStyle=True
    print("Work-around for RML-style command-line arguments (+version)")
  os.environ["OPENMODELICAHOME"] = ompython_omhome
  omc = OMCSessionZMQ()
  ompython_omc_version=omc.sendExpression('getVersion()')
  os.environ["OPENMODELICAHOME"] = omhome
else:
  omc = FindBestOMCSession()
  omhome=omc.sendExpression('getInstallationDirectoryPath()')
  omc_version=omc.sendExpression('getVersion()')
  ompython_omc_version=omc_version
ompython_omc_version=ompython_omc_version.replace("OMCompiler","").strip()

def timeSeconds(f):
  return cgi.escape("%.2f" % f)

omc.sendExpression('setModelicaPath("%s/lib/omlibrary")' % omhome)
omc_exe=os.path.join(omhome,"bin","omc")
dygraphs=os.path.join(ompython_omhome or omhome,"share","doc","omc","testmodels","dygraph-combined.js")
Пример #27
0
 def __init__(self, **kwargs):
     Kernel.__init__(self, **kwargs)
     self.omc = OMCSessionZMQ()
     self.matfile = None
Пример #28
0
#!/usr/bin/env python3

import os
import sys
import xmltodict

from OMPython import OMCSessionZMQ
omc = OMCSessionZMQ()
omc.execute('loadModel(Modelica)')

for file in os.listdir('.'):  #elenco elementi in directory
    if os.path.isfile(file):  #controllo se elemento e' file
        if file.endswith('.mo'):  #prendo solo i .mo
            omc.execute('loadFile("' + file + '")')

if (len(sys.argv) > 2):
    className = sys.argv[2] + '.' + sys.argv[1]
else:
    className = sys.argv[1]

omc.execute('dumpXMLDAE(' + className +
            ', translationLevel="backEnd", addMathMLCode=true)')

with open(className + '.xml') as fd:
    doc = xmltodict.parse(fd.read())
print(doc)
Пример #29
0
 def __init__(self, **kwargs):
     Kernel.__init__(self, **kwargs)
     self.omc = OMCSessionZMQ()
     self.matfile = None
def createOmcSession():
    return OMCSession(
        docker=docker, dockerExtraArgs=dockerExtraArgs,
        timeout=5) if corbaStyle else OMCSessionZMQ(
            docker=docker, dockerExtraArgs=dockerExtraArgs, timeout=5)
Пример #31
0
class OpenModelicaKernel(Kernel):
    implementation = 'openmodelica_kernel'
    implementation_version = '1.0'
    language = 'openmodelica'
    language_version = '1.0'
    language_info = {
        'name': "modelica",
        'version': "1.0",
        'mimetype': 'text/x-modelica',
    }
    banner = "openmodelicakernel - for evaluating modelica codes in jupyter notebook"

    def __init__(self, **kwargs):
        Kernel.__init__(self, **kwargs)
        self.omc = OMCSessionZMQ()
        self.matfile = None

    def do_execute(self, code, silent, store_history=True, user_expressions=None,
                   allow_stdin=True):
        # print code

        z1 = "".join(filter(lambda x: not re.match(r'^\s*$', x), code))
        plotcommand = z1.replace(' ', '').startswith('plot(') and z1.replace(' ', '').endswith(')')
        
        # print self.execution_count
        if (plotcommand):
            l1 = z1.replace(' ', '')
            l = l1[0:-1]
            plotvar = l[5:].replace('{', '').replace('}', '')
            plotdivid = str(self.execution_count)
            finaldata = plotgraph(plotvar, plotdivid, self.omc, self.matfile)
            # f = open("demofile.html", "w")
            # f.write(finaldata)
            # f.close()
            if not silent:
                '''
                stream_content = {'name': 'stdout','text':ouptut}
                self.send_response(self.iopub_socket, 'stream', stream_content) '''
                display_content = {'source': 'kernel',
                                   'data': {'text/html': finaldata
                                            }
                                   }
                self.send_response(self.iopub_socket, 'display_data', display_content)
        else:
            try:
                val = self.omc.sendExpression(code)
                try:
                    self.matfile = val['resultFile']
                except BaseException:
                    pass

            except BaseException:
                val = self.omc.sendExpression(code, parsed=False)

            # print self.matfile
            if not silent:
                display_content = {'source': 'kernel',
                                   'data': {'text/plain': str(val)
                                            }
                                   }
                self.send_response(self.iopub_socket, 'display_data', display_content)

        return {'status': 'ok',
                # The base class increments the execution count
                'execution_count': self.execution_count,
                'payload': [],
                'user_expressions': {},
                }

    def do_shutdown(self, restart):
        try:
            self.omc.__del__()
        except BaseException:
            pass
def createOmcSessionNew():
    if ompython_omhome != "":
        os.environ["OPENMODELICAHOME"] = ompython_omhome
        return OMCSessionZMQ()
    else:
        return createOmcSession()
  if conf["simCodeTarget"]=="Cpp" and not conf["haveFMICpp"]:
    with open(errFile, 'a+') as fp:
      fp.write("C++ FMI runtime not supported in this installation (HelloWorld failed or did not respect fileNamePrefix)")
    writeResultAndExit(0)
  elif conf["simCodeTarget"]=="C" and not conf["haveFMI"]:
    with open(errFile, 'a+') as fp:
      fp.write("C FMI runtime not supported in this installation (HelloWorld failed or did not respect fileNamePrefix)")
    writeResultAndExit(0)

omhome = conf["omhome"]
os.environ["OPENMODELICAHOME"] = omhome

omc = FindBestOMCSession()
if ompython_omhome != "":
  os.environ["OPENMODELICAHOME"] = ompython_omhome
  omc_new = OMCSessionZMQ()
else:
  omc_new = omc

cmd = 'setCommandLineOptions("%s")' % conf["single_thread_cmd"]
if not omc.sendExpression(cmd):
  raise Exception('Could not send %s' % cmd)

try:
  os.unlink("%s.tmpfiles" % conf["fileName"])
except:
  pass
#cmd = 'setCommandLineOptions("--running-testsuite=%s.tmpfiles")' % conf["fileName"]
runningTestsuiteFiles = False
#if omc.sendExpression(cmd):
#  runningTestsuiteFiles = True
Пример #34
0
import os
import sys
import traceback

import pandas as pd
from OMPython import OMCSessionZMQ

# Start omc
omc = OMCSessionZMQ()
omc.sendExpression('getVersion()')

# Global vars
ignoreNotCompliantWithLatestRules = True

default_tolerance = 1e-8
reltolDiffMinMax = 1e-4
rangeDelta = 0.002


def filterResultFile(resultFile, referenceFile, resultDir):
    """Filter result file from OMSimulator to contain same variables as reference file.
  Remove prefixes from varaible names.
  """
    # Only save columns from fmu and remove ".fmu" and "\"" from variable names
    csv_res = pd.read_csv(resultFile)
    fmu_vars = [
        s for s in list(csv_res.columns.values)
        if (s.startswith(" \"fmu.") or s == "time")
    ]
    csv_res = csv_res[fmu_vars]
Пример #35
0
#!/usr/bin/env python
# coding: utf-8

from OMPython import OMCSessionZMQ

omc = OMCSessionZMQ()
from modelicares import SimRes
import pandas as pd
import numpy as np
import os
import shutil

# get current directory and set it to the beginning of the repository
RepoDir = os.getcwd()
RepoDir = os.path.abspath(os.path.join(RepoDir, os.pardir))
RepoDir = os.path.abspath(os.path.join(RepoDir, os.pardir))

#OpenIPSL Location
OpenIPSL = RepoDir + "/OpenIPSL/"
OpenIPSLPackage = RepoDir + "/OpenIPSL/OpenIPSL/package.mo"
#Working Directory
LVExcitersWorkingDir = RepoDir + "/WorkingDir/LoadVariation/Exciters/"
#Load Variation Folder Locations
LoadVariationSource = RepoDir + "/CI/LoadVariation/AuxiliaryModels/Load_variation.mo"
LoadVariationDestinationPath = RepoDir + "/OpenIPSL/OpenIPSL/Electrical/Loads/PSSE/Load_variation.mo"
# Power Fault Folder Locations
PowerFaultSource = RepoDir + "/CI/LoadVariation/AuxiliaryModels/PwFault.mo"
PowerFaultDestinationPath = RepoDir + "/OpenIPSL/OpenIPSL/Electrical/Events/"
PowerFaultDestination = RepoDir + "/OpenIPSL/OpenIPSL/Electrical/Events/PwFault.mo"
# SMIB Partial Folder Location
SMIBPartialSource = RepoDir + "/CI/LoadVariation/AuxiliaryModels/SMIBpartial.mo"
Пример #36
0
class ModelicaModel:
    def __init__(self, path_file, name, display_errors):
        self.path_file = os.path.abspath(path_file)
        self.path = os.path.dirname(self.path_file)
        self.name = name
        self.display_errors = display_errors
        #        os.chdir(self.path)
        #        os.chdir("../")
        print("Working directory is " + os.getcwd() + "\n")
        self.stop_time = 0
        self.omc = OMCSessionZMQ()
        print self.omc.sendExpression("getVersion()")
        self.print_err()
        print self.omc.sendExpression(
            "setCommandLineOptions(\"+g=PDEModelica --demoMode=true\")")
        self.print_err()
        print self.omc.sendExpression("loadModel(Modelica)")
        self.print_err()
        print self.omc.sendExpression("loadFile(\"" + path_file + "\")")
        self.print_err()
        #create empty init file for case no parameters will be changed:
        #init_file = open("./WorkingDir/init_file.txt", "w")
        init_file = open("init_file.txt", "w")
        init_file.write("\n")
        init_file.close()

    def print_err(self):
        if self.display_errors:
            print self.omc.sendExpression("getErrorString()")

    def set_stop_time(self, stop_time):
        self.stop_time = stop_time

    def set_parameters(self, param_dict):
        #init_file = open("./WorkingDir/init_file.txt", "w")
        init_file = open("init_file.txt", "w")
        for key in param_dict:
            init_file.write(key + "=" + str(param_dict[key]) + "\n")
        init_file.close()

    def simulate(self):
        #os.chdir("./WorkingDir/")
        simul_str = "simulate(" + self.name + ", stopTime=" + str(
            self.stop_time) + ", simflags = \"-overrideFile=init_file.txt\")"
        print self.omc.sendExpression(simul_str)
        self.print_err()
        #os.chdir("../")

    def get_var(self, var, t):
        valStr = "val(" + var + " , " + str(t) + ")"
        val = self.omc.sendExpression(valStr)
        self.print_err()
        return val

    def get_var_final(self, var):
        return self.get_var(var, self.stop_time)