Пример #1
0
 def run(self):
     global omc
     del (omc)
     omc = OMCSessionZMQ()
     omc.sendExpression("setModelicaPath(\"" + omhome + "/lib/omlibrary\")")
     omc.sendExpression('cd("tmp")')
     return []
Пример #2
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()
 def run(self):
   global omc
   del(omc)
   omc = OMCSessionZMQ()
   omc.sendExpression("setModelicaPath(\""+omhome+"/lib/omlibrary\")")
   omc.sendExpression('cd("tmp")')
   return []
Пример #4
0
    def run_cdl_simulation(self, model, output_folder, ip_list, op_list,
                           sample_time):
        """function that runs the CDL simulation using OpenModelica; also converts the .mat output file to .csv

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

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

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

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

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

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

        return simulation_output
Пример #5
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)
Пример #6
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()
Пример #7
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
Пример #8
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)
Пример #9
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)
Пример #10
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))
Пример #11
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)
Пример #12
0
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
FExcitersWorkingDir = RepoDir + "/OpenModelica/WorkingDir/Fault/Exciters/"

libraryPath = RepoDir + "/OpenIPSL/OpenIPSL/package.mo"
libraryName = "OpenIPSL"

from OMPython import OMCSessionZMQ
omc = OMCSessionZMQ()
one = omc.sendExpression("getVersion()")
two = omc.sendExpression("cd()")
three = omc.sendExpression("loadModel(Modelica)")
four = omc.sendExpression(
    "loadFile(getInstallationDirectoryPath() + \"/share/doc/omc/testmodels/BouncingBall.mo\")"
)
five = omc.sendExpression("instantiateModel(BouncingBall)")

print(one)
print(two)
print(three)
print(four)
print(five)

## Stage 2
six = omc.sendExpression("getClassNames()")
single_thread = "-n=1"

# Try to make the processes a bit nicer...
os.environ["GC_MARKERS"] = "1"

print("Start OMC version")

if ompython_omhome != "":
    # Use a different OMC for running OMPython than for running the tests
    omhome = os.environ["OPENMODELICAHOME"]
    omc_version = subprocess.check_output(
        omc_cmd + ["--version"],
        stderr=subprocess.STDOUT).decode("ascii").strip()
    os.environ["OPENMODELICAHOME"] = ompython_omhome
    omc = OMCSessionZMQ()
    ompython_omc_version = omc.sendExpression('getVersion()')
    os.environ["OPENMODELICAHOME"] = omhome
else:
    omc = OMCSessionZMQ(docker=docker, dockerExtraArgs=dockerExtraArgs)
    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 html.escape("%.2f" % f)


if not docker:
    omc.sendExpression('setModelicaPath("%s")' % librariespath)
Пример #14
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()")
Пример #15
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
Пример #16
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
Пример #17
0
# 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")
print(omc_exe,omc_version,dygraphs)
Пример #18
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)
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
Пример #20
0
RepoDir = os.path.abspath(os.path.join(RepoDir, os.pardir))
print(RepoDir)

#OpenIPSL Location
OpenIPSL = RepoDir + "/OpenIPSL/"
OpenIPSLPackage = RepoDir + "/OpenIPSL/OpenIPSL/package.mo"
#Working Directory
FExcitersWorkingDir = RepoDir + "/WorkingDir/Fault/Exciters/"
print(FExcitersWorkingDir)


libraryPath = RepoDir + "/OpenIPSL/OpenIPSL/package.mo"
libraryName = "OpenIPSL"

omc = OMCSessionZMQ()
if omc.sendExpression('loadFile("%s")' % (libraryPath)):
	print("Load success: %s" % libraryName + "\n")
else:
	errorMessage = libraryName + " was not loaded! Check the library path:\n" + libraryPath
	print(errorMessage)
	raise Exception(errorMessage)

print('Test Start...')
exciterName = "ESAC1A"
print(f"Fault {exciterName} Simulation Start...")
one = omc.sendExpression(f"cd(\"{FExcitersWorkingDir}" + exciterName +"\")")
print(one)
two = omc.sendExpression(f"loadFile(\"{OpenIPSLPackage}\")")
print(two)
three = omc.sendExpression("instantiateModel(OpenIPSL)")
# print(three)
Пример #21
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
Пример #22
0
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
FPowerSystemStabilizersWorkingDir = RepoDir + "/WorkingDir/Fault/PowerSystemStabilizers/"
print(omc.sendExpression("getVersion()"))

#Creation of matrix with names, paths and variables
psss = {
    'names': ["PSS2A", "PSS2B"],
    'path': [
        "OpenIPSL.Examples.Controls.PSSE.PSS.PSS2A",
        "OpenIPSL.Examples.Controls.PSSE.PSS.PSS2B"
    ],
    'delta': ['gENROE.delta'],
    'pelec': ['gENROE.PELEC'],
    'pmech': ['gENROE.PMECH'],
    'speed': ['gENROE.SPEED'],
    'vothsg': ["pSS2A.VOTHSG", "pSS2B.VOTHSG"]
}
#Delete old results
Пример #23
0
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
FMachinesWorkingDir = RepoDir + "/WorkingDir/Fault/Machines/"
print(omc.sendExpression("getVersion()"))

#Creation of matrix with names, paths and variables
machines = {
    'names': ["GENROU", "GENSAL", "GENCLS", "GENROE", "GENSAE", "CSVGN1"],
    'path': [
        "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"
    ],
    'delta': [
        'gENROU.delta', 'gENSAL.delta', 'gENCLS2.delta', 'gENROE.delta',
        'gENSAE.delta', 'cSVGN1.delta'
Пример #24
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]
Пример #25
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"
    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:
      return [nodes.error(None, nodes.paragraph(text = "Unable to execute python code at %s:%d:" % (basename(self.src), self.srcline)), nodes.paragraph(text = str(e)))]
Пример #27
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
#This is intended to be used in the manuelnvro Dell using Dymola 2020.
print(omc.sendExpression("getVersion()"))
print("OpenModelica Simulation Start...")
#Set WorkigDir
omc.sendExpression(
    "cd(\"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/OpenModelica/\")"
)
#Loading Package
omc.sendExpression(
    "loadFile(\"/home/manuelnvro/dev/Gitted/OpenIPSL/OpenIPSL/package.mo\")")
#Package Instantiation
omc.sendExpression("instantiateModel(OpenIPSL)")
#OpenModelica Simulation
omc.sendExpression(
    "simulate(OpenIPSL.Examples.Controls.PSSE.ES.EXAC1, stopTime=10.0, numberOfIntervals=5000)"
)
print("Simulation OK")
sim = SimRes(
    "/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/OpenModelica/OpenIPSL.Examples.Controls.PSSE.ES.EXAC1_res.mat"
)
variables = [
    'Time', 'gENROE.delta', 'gENROE.PELEC', 'eXAC1_1.EFD', 'gENROE.SPEED',
    'GEN1.V', 'LOAD.V', 'GEN2.V', 'FAULT.V'
Пример #28
0
    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:
Пример #29
0
    #rand_meal_len = random.randint(590,650)
    #rand_meal_period = random.randint(2300,2450)

    # Start Multiple Simulations  
    exit_ctrl = False       # exit condiction, just in case break does not work
    fail_pump = False       # pump failing condiction

    # Start counting time to run n Simulation
    loop_time = time.time()

    while (not(fail_pump) and not(exit_ctrl)):  
        
        # Build Model 
        omc = OMCSessionZMQ()

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

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

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

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

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

        omc.sendExpression("loadFile(\"rag_meal.mo\")")
Пример #30
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)
#  runningTestsuiteFiles = True

# Hide errors for old-school running-testsuite flags...
omc.sendExpression("getErrorString()", parsed = False)

outputFormat="mat"
referenceVars=[]
referenceFile = conf.get("referenceFile") or ""
if referenceFile != "":
  try:
    compSignals = os.path.join(os.path.dirname(referenceFile),"comparisonSignals.txt")
    if os.path.exists(compSignals):
      referenceVars=[s.strip() for s in open(compSignals).readlines() if (s.strip() != "")] # s.strip().lower() != "time" and ??? I guess we should check time variable...
      print(referenceVars)
    else:
      referenceVars=omc_new.sendExpression('readSimulationResultVars("%s", readParameters=true, openmodelicaStyle=true)' % referenceFile)
    variableFilter="|".join([v.replace("[",".").replace("]",".").replace("(",".").replace(")",".").replace('"',".") for v in referenceVars])
    emit_protected="-emit_protected"
  except:
    referenceFile=""
if referenceFile=="":
  variableFilter=""
  outputFormat="empty"
  emit_protected=""
"""TODO:
compareVarsUri := "modelica://" + /*libraryString*/ "Buildings" + "/Resources/Scripts/OpenModelica/compareVars/#modelName#.mos";
(compareVarsFile,compareVarsFileMessages) := uriToFilename(compareVarsUri);

if regularFileExists(compareVarsFile) then
  runScript(compareVarsFile);
  vars := compareVars;
Пример #32
0
def convertPackage(p):
    errorsInDiff = []
    with open(p) as f:
        data = json.load(f)
    uses = data.get('uses', {})
    libnameOnFile = os.path.basename(os.path.dirname(p))
    libname = libnameOnFile.split(" ")[0]
    shutil.copytree(
        os.path.dirname(p),
        "converted-libraries/.openmodelica/libraries/%s" % libnameOnFile)
    for root, dir, files in os.walk(
            "converted-libraries/.openmodelica/libraries/%s" % libnameOnFile):
        for file in files:
            if file.endswith(".mo"):
                try:
                    with open(os.path.join(root, file)) as fin:
                        fin.read()
                except UnicodeDecodeError:
                    with open(os.path.join(root, file),
                              encoding="ISO-8859-1") as fin:
                        latin1Data = fin.read()
                    with open(os.path.join(root, file), "w",
                              encoding="UTF-8") as fout:
                        fout.write(latin1Data)

    if libname in [
            "Modelica", "ModelicaServices", "Complex", "ModelicaTest",
            "ModelicaTestOverdetermined"
    ]:
        ver = libnameOnFile.split(" ")[1]
        if ver.startswith("1.") or ver.startswith("3."):
            return None
    if libname in ["TAeZoSysPro_testsuite"] and "Modelica" not in uses:
        uses['Modelica'] = '3.2.3'
        data['uses'] = uses
    if not uses.get('Modelica', '0.0.0') in convertFromVersion:
        return None
    if libname in [
            "Modelica", "ModelicaServices", "Complex", "ModelicaTest",
            "ModelicaTestOverdetermined"
    ]:
        return None
    print("Start working on %s" % libnameOnFile)
    omc = OMCSessionZMQ()
    libnameOnFileFullPath = "converted-libraries/.openmodelica/libraries/%s/package.mo" % libnameOnFile
    omcAssert(omc, 'loadFile("%s", uses=false)' % libnameOnFileFullPath)
    errString = omc.sendExpression("getErrorString()")
    if errString:
        print(errString)
    loadedFilePath = omc.sendExpression("getSourceFile(%s)" % libname)
    if libnameOnFileFullPath not in loadedFilePath:
        raise Exception("Expected to have loaded %s but got %s" %
                        (libnameOnFileFullPath, loadedFilePath))
    gcProfStatsBeforeConversion = omc.sendExpression("GC_get_prof_stats()")
    timeBeforeConvert = time.time()
    omcAssert(omc,
              'runConversionScript(%s, "%s")' % (libname, conversionScript))
    print("runConversionScript(%s, %s) OK" % (libnameOnFile, conversionScript))
    uses = data["uses"]
    for (n, v) in data["uses"].items():
        if n in ["Modelica", "ModelicaServices", "Complex"]:
            omcAssert(
                omc,
                'addClassAnnotation(%s, annotate=$annotation(uses(%s(version="4.0.0"))))'
                % (libname, n))
            data["uses"][n] = "4.0.0"
    names = omc.sendExpression('getClassNames(%s, sort=true, recursive=true)' %
                               libname)
    names = list(names)
    names.reverse()
    fileMapping = {}
    for n in names:
        f = omc.sendExpression('getSourceFile(%s)' % n)
        fileMapping[f] = n
    statsByFile = []
    nFail = 0
    nDiff = 0
    gcProfStatsBefore = omc.sendExpression("GC_get_prof_stats()")
    timeAfterConvert = time.time()
    timeForConversion = timeAfterConvert - timeBeforeConvert
    for (newFile, newClass) in fileMapping.items():
        oldFile = os.path.join(
            libdir,
            newFile.split("converted-libraries/.openmodelica/libraries/")[1])
        assert (newFile != oldFile)
        before = omc.sendExpression('before := readFile("%s")' % newFile)
        after = omc.sendExpression('after := listFile(%s)' % newClass)
        if (not before) or (not after):
            raise Exception("%s %s (%s). %s. before: %s after: %s" %
                            (oldFile, newFile, newClass,
                             omc.sendExpression('getErrorString()'),
                             str(type(before)), str(type(after))))
        omc.sendExpression("getErrorString()")
        start = time.time()
        if libname in []:  # If we have libraries where the diff algorithm fails in the future
            res = omc.sendExpression('res := after')  # Skip the diff
        else:
            try:
                res = omc.sendExpression(
                    'res := diffModelicaFileListings(before, after, OpenModelica.Scripting.DiffFormat.plain, failOnSemanticsChange=true)'
                )
            except pyparsing.ParseException as e:
                errStr = omc.sendExpression(
                    'diffModelicaFileListings(before, after, OpenModelica.Scripting.DiffFormat.plain, failOnSemanticsChange=true)',
                    parsed=False)
                if errStr.strip():
                    print(errStr)
                res = None
                omc.sendExpression(omc, 'res := ""')
        end = time.time()
        isFail = False
        if not res:
            omc.sendExpression('writeFile("%s", after)' % newFile)
            if allowErrorsInDiff:
                errorsInDiff += [newFile]
                omc.sendExpression('writeFile("%s.before",before)' % newFile)
                omc.sendExpression('writeFile("%s.after",after)' % newFile)
                res = after
                nFail += 1
                isFail = True
            else:
                errStr = omc.sendExpression("getErrorString()")
                if errStr:
                    print(errStr)
                raise Exception(
                    '--allowErrorsInDiff is not active:\necho(false);before:=readFile("%s");\nafter:=readFile("%s");echo(true);\ndiffModelicaFileListings(before, after, OpenModelica.Scripting.DiffFormat.plain, failOnSemanticsChange=true);\ngetErrorString();'
                    % (oldFile, newFile))
        else:
            omcAssert(omc, 'writeFile("%s", res)' % (newFile))
        isDiff = before != res
        if before != res:
            nDiff += 1
        statsByFile += [{
            "time": end - start,
            "size": len(before),
            "isDiff": isDiff,
            "fail": isFail
        }]
    path = "converted-libraries/.openmodelica/libraries/%s/openmodelica.metadata.json" % libnameOnFile
    with open(path, "w") as f:
        gcProfStats = omc.sendExpression("GC_get_prof_stats()")
        data["uses"] = dict(uses)
        data[
            "extraInfo"] = "Conversion script %s was applied" % conversionScript
        json.dump(data, f)
    if createDiff:
        diffOutputFile = "converted-libraries/.openmodelica/libraries/%s.diff" % libnameOnFile
        print("Creating %s" % diffOutputFile)
        with open(diffOutputFile, "wb") as diffOut:
            diffOutput = subprocess.call([
                "diff", "-ur",
                os.path.dirname(p),
                "converted-libraries/.openmodelica/libraries/%s" %
                libnameOnFile
            ],
                                         stdout=diffOut)
    del omc
    return {
        "errorsInDiff": errorsInDiff,
        "path": path,
        "timeForConversion": timeForConversion,
        "statsByFile": statsByFile,
        "gcProfStatsBeforeConversion": gcProfStatsBeforeConversion,
        "gcProfStatsBefore": gcProfStatsBefore,
        "gcProfStats": gcProfStats
    }
Пример #33
0
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"
SMIBPartialDestinationPath = RepoDir + "/OpenIPSL/OpenIPSL/Examples/"
SMIBPartialDestination = RepoDir + "/OpenIPSL/OpenIPSL/Examples/SMIBpartial.mo"
print(omc.sendExpression("getVersion()"))

#Adding Auxiliary Files
try:
    print('Deleting Auxiliary Models')
    os.chdir(SMIBPartialDestinationPath)
    os.remove("SMIBpartial.mo")
except:
    print('Error Deleting Auxiliar Models...')
try:
    print('Adding Auxiliary models...')
    os.system('cp ' + SMIBPartialSource + ' ' + SMIBPartialDestination)
except:
    print('Error Adding Auxiliary Models...\n')
print("Load Variation Open Modelica Machines Simulation Start...\n")
Пример #34
0
import os
from OMPython import OMCSessionZMQ
from OMPython import ModelicaSystem
os.chdir("output")
omc = OMCSessionZMQ()
model_path=omc.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels/"
mod=ModelicaSystem(model_path + "BouncingBall.mo","BouncingBall",["Modelica"])
#mod.buildModel()
print(mod.getQuantities())
print(mod.simulate()) # (simflags="stopTime=3.0")
mod.setLinearizationOptions(["stopTime=2.0"])
print(mod.linearize())
#outp = mod.linearize() # mod.getOutputs()
#print(outp)
# cmds = [
#   'loadFile(getInstallationDirectoryPath() + "/share/doc/omc/testmodels/BouncingBall.mo")',
#   "simulate(BouncingBall, stopTime=3.0)",
#   "plot(h)"
#   ]
# for cmd in cmds:
#   answer = omc.sendExpression(cmd)
#   print("\n{}:\n{}".format(cmd, answer))