def run(self):
   global omc
   del(omc)
   omc = OMCSession()
   omc.sendExpression("setModelicaPath(\""+omhome+"/lib/omlibrary\")")
   omc.sendExpression('cd("tmp")')
   return []
Exemple #2
0
 def __init__(self, rootPath):
     '''
     Constructor starts omc and loads MSL
     '''
     self.rootPath = rootPath
     self.omc = OMCSession()
     os.chdir(self.rootPath)
     self.omc.sendExpression("loadModel(Modelica)")
Exemple #3
0
    def __init__(self, modelName, modelFileName, config):

        SimulatorBase.Model.__init__(self, modelName, modelFileName, config)
        self.modelType = 'Modelica model in OpenModelica'
        self._omc = OMCSession()
        self.onlyResultFile = False
        self.integrationSettings.resultFileExtension = 'mat'

        self._availableIntegrationAlgorithms = ['Dassl', 'Euler', 'Rungekutta', 'Dopri5']
        self.integrationSettings.algorithmName = self._availableIntegrationAlgorithms[0]

        self._IntegrationAlgorithmHasFixedStepSize = [False, True, True, False]
        self._IntegrationAlgorithmCanProvideStepSizeResults = [False, True, True, False]

        self.compileModel()

        if self.resFile != '""':
            self._initialResult = loadResultFileInit(os.path.join(os.getcwd(), self.name + "_init.xml"))
        else:
            print "The selected model could not be instantiated, check for any dependencies that the model might have"
            return

        # SocketServer setup to visualize the simulation progress bar
        HOST, PORT = "localhost", 0
        self.server = SocketServer.TCPServer((HOST, PORT), ThreadedTCPRequestHandler)
        self.ip, self.port = self.server.server_address
        self.server_port = self.port

        self.server_thread = threading.Thread(target=self.server.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.setDaemon(True)
        self.server_thread.start()
 def __init__(self, parent= None, configResources= None, configSimulation= None):
     QtGui.QDialog.__init__(self, parent)
     self.setupUi(self)
     self.__simsource= configResources
     self.__simconfig= configSimulation
     self.load_configuration()
     self.btnModelBrowser.clicked.connect(self.browse_models)
     self.btnLibraryBrowser.clicked.connect(self.browse_libraries)
     self.cbxModelList.activated['QString'].connect(self.set_models)
     self.progressBar.setRange(0,1)
     #
     self.btnRunSimulation.setIcon(QIcon('./res/img/Play.ico'))
     self.btnRunSimulation.setIconSize(QSize(48,48))
     self.btnRunSimulation.clicked.connect(self.onStartSimulation)
     self.btnPlot.setIcon(QIcon('./res/img/Presentation.ico'))
     self.btnPlot.setIconSize(QSize(48,48))
     self.btnPlot.clicked.connect(self.browse_simulation)
     #debug
     self.__omcSession= OMCSession()
     if self.__simconfig.compiler== 'dymola':
         self.__simulationTask = TaskThreadDY(self, self.__simsource, self.__simconfig, self.__results)
     elif self.__simconfig.compiler== 'jmodelica':
         pass
     elif self.__simconfig.compiler== 'openmodelica':
         self.__simulationTask = TaskThreadOMC(self, self.__simsource, self.__simconfig, self.__omcSession, self.__results)
     self.__simulationTask.taskFinished.connect(self.onFinishSimulation)
 def __init__(self, sources= None, experiment= None, results= None):
     ''' Loading simulations resources. Parameters related to models to be simulated and libraries'''
     self.__sources= sources
     ''' Loading configuration values for the simulator solver '''
     self.__experiment= experiment
     self.__results= results
     self.__omcSession= OMCSession()
Exemple #6
0
 def __init__(self, rootPath):
     '''
     Constructor starts omc and loads MSL
     '''
     self.rootPath = rootPath
     self.omc = OMCSession()
     os.chdir(self.rootPath)
     self.omc.sendExpression("loadModel(Modelica)")
    def __init__(self, modelName, modelFileName, config):

        Plugins.Simulator.SimulatorBase.Model.__init__(self, modelName,
                                                       modelFileName,
                                                       'OpenModelica', config)
        self._omc = OMCSession()
        self.onlyResultFile = False
        self.integrationSettings.resultFileExtension = 'mat'

        self._availableIntegrationAlgorithms = [
            'Dassl', 'Euler', 'Rungekutta', 'Dopri5'
        ]
        self.integrationSettings.algorithmName = self._availableIntegrationAlgorithms[
            0]

        self._IntegrationAlgorithmHasFixedStepSize = [False, True, True, False]
        self._IntegrationAlgorithmCanProvideStepSizeResults = [
            False, True, True, False
        ]

        self.compileModel()

        if self.resFile != '""':
            self._initialResult = loadResultFileInit(
                os.path.join(os.getcwd(), self.name + "_init.xml"))
        else:
            print "The selected model could not be instantiated, check for any dependencies that the model might have"
            return

        # SocketServer setup to visualize the simulation progress bar
        HOST, PORT = "localhost", 0
        self.server = SocketServer.TCPServer((HOST, PORT),
                                             ThreadedTCPRequestHandler)
        self.ip, self.port = self.server.server_address
        self.server_port = self.port

        self.server_thread = threading.Thread(target=self.server.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.setDaemon(True)
        self.server_thread.start()
Exemple #8
0
    def Select_Model(self):
        OMPython = OMCSession()
        command= CommandOMC()
        OMPython.execute(command.loadModelica())
        OMPython.execute(command.loadFile(self.mfile))
        #print self.mfile
        #print command.set_ModelName(self.mfile)
        self._MN=OMPython.execute(command.getClassNames(self.mfile))
        self.filetouse=self.mfile.replace('.mo', '.')
        print self._MN['SET1']['Set1']
        fle= open('dict1.properties','w')
        for x in range(len(self._MN['SET1']['Set1'])):
            self.lis.append(self.filetouse+self._MN['SET1']['Set1'][x])
            fle.writelines(str(self.filetouse+self._MN['SET1']['Set1'][x]+'\n'))
        #_______________________________________________________
#         self.tt=command.set_ModelName(self.mfile)+'.'+self._MN['SET1']['Set1'][0]
#         #print self.tt
#         self.success=OMPython.execute(command.getClassNames(self.tt))
#         self.success['SET2']['Set1']
#         fle= open('dict1.properties','w')
#         for x in range(len(self.success['SET1']['Set1'])):
#             for y in range(len(self.success['SET2']['Set1'])):
#                 self.lis.append(self.mfile+self.success['SET1']['Set1'][x]+'.'+self.success['SET2']['Set1'][y])
#                 fle.writelines(str(self.mfile+self.success['SET1']['Set1'][x]+'.'+self.success['SET2']['Set1'][y]+'\n'))
        #____________________________________________________
        self.comboBox_5.clear()
        self.comboBox_5.addItems(self.lis)
            
        #print self.lis
        
        """
 def run(self):
     global omc
     del (omc)
     omc = OMCSession()
     omc.sendExpression("setModelicaPath(\"" + omhome + "/lib/omlibrary\")")
     omc.sendExpression('cd("tmp")')
     return []
Exemple #10
0
def createsession():
    ## Create a new omc session for the users and allot a seperate working directory for the session ##
    #print 'creating omc session'
    session['msg'] = []
    session['mat'] = []
    sid = request.form['sid']
    session['tmpdir'] = tempfile.mkdtemp()
    #print session['tmpdir']
    os.chdir(session['tmpdir'])
    sess = OMCSession()
    sessionobj[sid] = sess
    #print sessionobj
    #sys.stdout.flush()
    return "success"
Exemple #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 = OMCSession()
        os.chdir(self.rootPath)
        self.omc.sendExpression("loadModel(Modelica)")

    def loadLib(self, libPath):
        # Attempt to load the library
        if self.omc.sendExpression('loadFile("%s")' %
                                   (self.rootPath + libPath)):
            print "%s is successfully loaded." % libPath
        else:
            raise Exception(
                "%s was not loaded! Check the library path.") % libPath

    def runCheck(self, libName, libPath):
        # Load library
        self.loadLib(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:
                    # print passMsg
                    nPassed += 1
                else:
                    failMsg = self.omc.sendExpression("getErrorString()")
                    print failMsg
                    nFailed += 1
        # Print a check summary
        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 (nFailed == 0)
Exemple #12
0
 def Simulation(self):
     
     """ starting a new session """
     OMPython = OMCSession()
     command= CommandOMC()
     OMPython.execute(command.loadModelica())
     OMPython.execute(command.loadFile(self.mfile))
     print self.mfile
     print command.set_ModelName(self.mfile)
     self._MN=OMPython.execute(command.getClassNames(self.mfile))
     print self._MN['SET1']['Set1']
     self.tt=command.set_ModelName(self.mfile)+'.'+self._MN['SET1']['Set1'][0]
     print self.tt
     self.success=OMPython.execute(command.getClassNames(self.tt))
     print self.success['SET2']['Set1']
Exemple #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 = OMCSession()
        os.chdir(self.rootPath)
        self.omc.sendExpression("loadModel(Modelica)")


    def loadLib(self, libPath):
        # Attempt to load the library
        if self.omc.sendExpression('loadFile("%s")' % (self.rootPath + libPath)):
            print "%s is successfully loaded." % libPath
        else:
            raise Exception("%s was not loaded! Check the library path.")  % libPath

    def runCheck(self, libName, libPath):
        # Load library
        self.loadLib(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:
                    # print passMsg
                    nPassed += 1
                else:
                    failMsg = self.omc.sendExpression("getErrorString()")
                    print failMsg
                    nFailed += 1
        # Print a check summary
        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 (nFailed == 0)
class EngineOMC(object):
    
    def __init__(self, sources= None, experiment= None, results= None):
        ''' Loading simulations resources. Parameters related to models to be simulated and libraries'''
        self.__sources= sources
        ''' Loading configuration values for the simulator solver '''
        self.__experiment= experiment
        self.__results= results
        self.__omcSession= OMCSession()
#         ''' Loading output variables of the model, their values will be stored in h5 and plotted '''
#         self.outputs= outvar.OutVariableStream(sys.argv[3])
        
    @property
    def omcSession(self):
        return self.__omcSession
    @omcSession.setter
    def omcSession(self, valor):
        self.__omcSession= valor
        
    def simulate(self):
        objCOMC= CommandOMC()
        '''Load Modelica library'''
        self.__omcSession.execute("loadModel(Modelica)")
        command= objCOMC.loadFile(self.__sources.libraryFile)
        print '1) Command', command
        self.__omcSession.execute(command)
        '''loading the model we want to simulate'''
        command= objCOMC.loadFile(self.__sources.modelFile)
        print '2) Command', command
        # here, show the list of parameters we can modify, (variability= parameter)
        print self.__sources.modelName 
        success= self.__omcSession.execute(command)
        result= None
        if (success):
            #command= objCOMC.simulate(self.moModel, self.simOptions, 'vf1=0.1,pm1=0.001')
            command= objCOMC.simulate(self.__experiment.modelName, self.__experiment, False)
            print '3) Command', command
            result= self.__omcSession.execute(command)
            print '4) Result', result
        # TODO: Handle when simulation fails, no result file
#         inMemoryResultFile= OMPython.get(result, 'SimulationResults.resultFile')
#         print '5) Result file ', inMemoryResultFile
#         resultfile= objCOMC.saveResult(inMemoryResultFile, self.outPath)
            print '5) Simulation Results', result['SimulationResults']
            self.__results= result['SimulationResults']
            print '6) Result file', self.__results['resultFile']
        else:
            print ("Failed to load resources!")
Exemple #15
0
class EngineOMC(ModelicaEngine):
    
    def __init__(self, resources= None, settings= None):
        super(EngineOMC, self).__init__(resources, settings)
        self._omcSession= OMCSession()
        self._simulationResult= None
        
    @property
    def omcSession(self):
        return self._omcSession
        
    @property
    def simulationResult(self):
        return self._simulationResult
        
    def simulate(self):
        objCOMC= CommandOMC()
        '''Load Modelica library'''
        self._omcSession.execute("loadModel(Modelica)")
        command= objCOMC.loadFile(self._resources.libraryFile)
        print '1) Command', command
        self._omcSession.execute(command)
        '''loading the model we want to simulate'''
        command= objCOMC.loadFile(self._resources.modelFile)
        print '2) Command', command
        # here, show the list of parameters we can modify, (variability= parameter)
        print self._resources.modelName 
        success= self._omcSession.execute(command)
        if (success):
            #command= objCOMC.simulate(self.moModel, self.simOptions, 'vf1=0.1,pm1=0.001')
            command= objCOMC.simulate(self._configuration.modelName, self._configuration, False)
            print '3) Command', command
            omc_result= self._omcSession.execute(command)
            print '4) Result', omc_result
        # TODO: Handle when simulation fails, no result file
#         inMemoryResultFile= OMPython.get(result, 'SimulationResults.resultFile')
#         print '5) Result file ', inMemoryResultFile
#         resultfile= objCOMC.saveResult(inMemoryResultFile, self.outPath)
            print '5) Simulation Results', omc_result['SimulationResults']
            self._simulationResult= omc_result['SimulationResults']
            print '6) Result file', self._simulationResult['resultFile']
        else:
            print ("Failed to load resources!")

    def linearize(self):
        pass
Exemple #16
0
 def __init__(self, resources= None, settings= None):
     super(EngineOMC, self).__init__(resources, settings)
     self._omcSession= OMCSession()
     self._simulationResult= None
# Apply Copyright in all .mo files of the library

import sys
import os
from OMPython import OMCSession

# Start OMC session and load MSL

omc = OMCSession()
omc.sendExpression("loadModel(Modelica)")

# Load OpenIPSL and get all models
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\OpenIPSL\package.mo")')
omc.sendExpression(
    'loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\_Tutorial\Tutorial\package.mo")'
)
omc.sendExpression(
    'loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\AKD\package.mo")')
omc.sendExpression(
    'loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\IEEE9\package.mo")'
)
omc.sendExpression(
    'loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\IEEE14\package.mo")'
)
omc.sendExpression(
    'loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\KundurSMIB\package.mo")'
)
omc.sendExpression(
    'loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\N44\package.mo")')
omc.sendExpression(
    'loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\PSAT_Systems\package.mo")'
class Model(Plugins.Simulator.SimulatorBase.Model):
    def __init__(self, modelName, modelFileName, config):

        Plugins.Simulator.SimulatorBase.Model.__init__(self, modelName,
                                                       modelFileName,
                                                       'OpenModelica', config)
        self._omc = OMCSession()
        self.onlyResultFile = False
        self.integrationSettings.resultFileExtension = 'mat'

        self._availableIntegrationAlgorithms = [
            'Dassl', 'Euler', 'Rungekutta', 'Dopri5'
        ]
        self.integrationSettings.algorithmName = self._availableIntegrationAlgorithms[
            0]

        self._IntegrationAlgorithmHasFixedStepSize = [False, True, True, False]
        self._IntegrationAlgorithmCanProvideStepSizeResults = [
            False, True, True, False
        ]

        self.compileModel()

        if self.resFile != '""':
            self._initialResult = loadResultFileInit(
                os.path.join(os.getcwd(), self.name + "_init.xml"))
        else:
            print "The selected model could not be instantiated, check for any dependencies that the model might have"
            return

        # SocketServer setup to visualize the simulation progress bar
        HOST, PORT = "localhost", 0
        self.server = SocketServer.TCPServer((HOST, PORT),
                                             ThreadedTCPRequestHandler)
        self.ip, self.port = self.server.server_address
        self.server_port = self.port

        self.server_thread = threading.Thread(target=self.server.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.setDaemon(True)
        self.server_thread.start()

    def compileModel(self):
        """
        This function is needed to load the data into the VariablesBrowser
        before simulating the model with parameters.
        """
        if len(self.fileName) == 1:
            if self.fileName[0] <> "":
                # Load the Modelica Standard library only if there is a uses-annotation on the model (done automagically)
                if not (os.path.isfile(self.fileName[0]) and self._omc.
                        sendExpression("loadFile(\"" + self.fileName[0].encode(
                            sys.getfilesystemencoding()) + "\")")):
                    print self._omc.sendExpression("getErrorString()")
                    raise FileDoesNotExist("compileModel failed, file '" +
                                           self.fileName[0] +
                                           "' does not exist")
            else:
                pack = str(self.name.split(".", 1)[0])
                if not self._omc.sendExpression("loadModel(" + pack + ")"):
                    print self._omc.sendExpression("getErrorString()")
                    raise FileDoesNotExist("compileModel failed, package " +
                                           pack + " does not exist")

            # set the working directory in OMC
            pwd = os.path.abspath('.').replace('\\', '/')
            workdir = self._omc.sendExpression("cd(\"" + pwd + "\")")
            # simulate the model
            simResult = self._omc.sendExpression(
                str("buildModel(" + self.name + ")"))
            if simResult[0] == "":
                raise BuildModelFail(
                    self._omc.sendExpression("getErrorString()"))
            # call getErrorString() to get complete error.
            print self._omc.sendExpression("getErrorString()"),
            # read the result file
            self.resFile = os.path.join(workdir, self.name + "_res.mat")

    def getReachedSimulationTime(self):
        '''
        Read the current simulation time during a simulation
        from the Model.exe file generated during loadFile()
        '''
        t = ((simulationProgressData * self.integrationSettings.stopTime) /
             100.0)
        return t

    def simulate(self):
        def precheck_for_set_sim_options():
            s = self.integrationSettings
            settings = s.__dict__

            # prepare the simulation options string for OpenModelica
            set_sim_options = [
                'startTime', 'stopTime', 'errorToleranceTol',
                'resultFileFormat', 'fixedStepSize', 'algorithmName'
            ]
            om_sim_options = [
                'startTime', 'stopTime', 'tolerance', 'outputFormat',
                'fixedStepSize', 'method'
            ]
            simulate_options = []
            for k, v in settings.iteritems():
                if k in set_sim_options:
                    i = set_sim_options.index(k)
                    if v != None and v != "":
                        if k == "algorithmName":
                            v = str(v).lower()
                        simulate_options += [om_sim_options[i] + "=" + str(v)]
            return ",".join(simulate_options)

        def precheck_for_model():
            self.sim_opts = precheck_for_set_sim_options()

        def readStatistics():
            '''
            Read statistics from the LOG_STATS.txt file
            '''
            work_dir = os.getcwd()
            result_exe = os.path.join(
                work_dir, self.name +
                (".exe" if os.name == "nt" else
                 "")) + " -lv LOG_STATS" + " -r=\"" + os.path.abspath(
                     self.integrationSettings.resultFileName) + "\""
            if self.sim_opts <> "":
                result_exe += " -override=" + self.sim_opts
            result_exe += " -port=%d" % self.server_port

            with open('LOG_STATS.txt', 'w') as output_f:
                p = subprocess.Popen(result_exe, stdout=output_f, shell=True)

            import time
            attempts = 0
            while True:
                if not os.path.isfile('LOG_STATS.txt'):
                    time.sleep(0.15)
                    attempts += 1
                    if attempts == 10:
                        return
                else:
                    statistics = open('LOG_STATS.txt', 'r')
                    break

            nTimeEvents = 0
            nStateEvents = 0
            currentGridPoints = 0
            currentTime = self.integrationSettings.startTime

            if statistics != None:
                fact = [line.strip() for line in statistics]
                for i in fact:
                    if "State Events" in i:
                        nStateEvents = int(i.split(':', 1)[1])
                    if "Sample Events" in i:
                        nTimeEvents = int(i.split(':', 1)[1])
                    if "simulation time" in i:
                        currentTime = float(i.split(':', 1)[1])
                statistics.close()

            currentTime = self.integrationSettings.stopTime
            # Wait for the process to finish; otherwise we cannot read the result-file
            p.wait()

            self.integrationStatistics.nTimeEvents = nTimeEvents
            self.integrationStatistics.nStateEvents = nStateEvents
            self.integrationStatistics.nGridPoints = currentGridPoints
            self.integrationStatistics.reachedTime = currentTime

        precheck_for_model()
        readStatistics()
        if not os.path.isfile(self.integrationSettings.resultFileName):
            raise FileDoesNotExist(self.integrationSettings.resultFileName)

    def setVariableTree(self):
        if self.resFile == '""':
            return
        for v in self._initialResult:
            value = None
            if v['variability'] == 'fixed' or v['valueEdit']:
                value = v['value']
            else:
                value = None

            variableAttribute = ''
            if v['description'] != '':
                variableAttribute += 'Description:' + chr(
                    9) + v['description'] + '\n'
            variableAttribute += 'Causality:' + chr(9) + v['causality'] + '\n'
            variableAttribute += 'Variability:' + chr(
                9) + v['variability'] + '\n'
            variableAttribute += 'Type:' + chr(9) + v['type']

            self.variableTree.variable[v['name'].replace(
                '[', '.[')] = Plugins.Simulator.SimulatorBase.TreeVariable(
                    self.structureVariableName(v['name'].replace('[', '.[')),
                    value, v['valueEdit'], v['unit'], v['variability'],
                    variableAttribute)

    def getAvailableIntegrationAlgorithms(self):
        return self._availableIntegrationAlgorithms

    def getIntegrationAlgorithmHasFixedStepSize(self, algorithmName):
        return self._IntegrationAlgorithmHasFixedStepSize[
            self._availableIntegrationAlgorithms.index(algorithmName)]

    def getIntegrationAlgorithmCanProvideStepSizeResults(self, algorithmName):
        return self._IntegrationAlgorithmCanProvideStepSizeResults[
            self._availableIntegrationAlgorithms.index(algorithmName)]
# Apply Copyright in all .mo files of the library

import sys
import os
from OMPython import OMCSession

# Start OMC session and load MSL

omc = OMCSession()
omc.sendExpression("loadModel(Modelica)")

# Load OpenIPSL and get all models
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\OpenIPSL\package.mo")')
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\_Tutorial\Tutorial\package.mo")')
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\AKD\package.mo")')
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\IEEE9\package.mo")')
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\IEEE14\package.mo")')
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\KundurSMIB\package.mo")')
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\N44\package.mo")')
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\PSAT_Systems\package.mo")')
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\SevenBus\package.mo")')
omc.sendExpression('loadFile("C:\dev\OSS\OpenIPSL_Repo\Application Examples\TwoAreas\package.mo")')

list_models = omc.sendExpression('getClassNames(OpenIPSL,recursive=true)')
list_models_1 = omc.sendExpression('getClassNames(Tutorial,recursive=true)')
list_models_2 = omc.sendExpression('getClassNames(AKD,recursive=true)')
list_models_3 = omc.sendExpression('getClassNames(IEEE9,recursive=true)')
list_models_4 = omc.sendExpression('getClassNames(IEEE14,recursive=true)')
list_models_5 = omc.sendExpression('getClassNames(KundurSMIB,recursive=true)')
list_models_6 = omc.sendExpression('getClassNames(N44,recursive=true)')
list_models_7 = omc.sendExpression('getClassNames(PSAT_Systems,recursive=true)')
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 = OMCSession()
    ompython_omc_version = omc.sendExpression('getVersion()')
    os.environ["OPENMODELICAHOME"] = omhome
else:
    omc = OMCSession()
    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)
import traceback
from os.path import basename
from StringIO import StringIO
import subprocess

from sphinx.util.compat 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 OMCSession

omc = OMCSession()
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, e:
 def __init__(self, **kwargs):
     Kernel.__init__(self, **kwargs)
     self.omc = OMCSession()
     self.matfile = None
        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 = OMCSession()
if ompython_omhome != "":
    os.environ["OPENMODELICAHOME"] = ompython_omhome
    omc_new = OMCSession()
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"]
Exemple #24
0
import sys
from OMPython import OMCSession

# List of the test examples that will be checked

omc = OMCSession()
omc.sendExpression("loadModel(Modelica)")
omc.sendExpression('loadFile("/OpenIPSL/OpenIPSL/package.mo")')
omc.sendExpression("getClassNames()")
'''
test_list = ["OpenIPSL.Examples.Machines.PSSE.GENSAL",
             "OpenIPSL.Examples.Machines.PSSE.GENSAE",
             "OpenIPSL.Examples.Machines.PSSE.GENROE",
             "OpenIPSL.Examples.Machines.PSSE.GENROU"]
'''


# Get the list of all test cases in class DevelopmentExamples
test_list = omc.sendExpression('getClassNames(OpenIPSL,recursive=true)')
nFailed = 0
nPassed = 0

for test in test_list:
    if omc.sendExpression("isModel(%s)" % (test)):
        passMsg = omc.sendExpression("checkModel(%s)" % (test))
        failMsg = omc.sendExpression("getErrorString()")
        if "completed successfully." in passMsg:
# print passMsg
            nPassed += 1
        else:
            print failMsg
def createOmcSession():
    return OMCSession(
        docker=docker, dockerExtraArgs=dockerExtraArgs,
        timeout=5) if corbaStyle else OMCSessionZMQ(
            docker=docker, dockerExtraArgs=dockerExtraArgs, timeout=5)
$\frac{dx}{dt} = ax$.

"""
code='''model Simple
    Real x(start=1);
    parameter Real a=1;
equation
    der(x)=a*x;
end Simple;''' # модель мовою Modelica 
with open('Simple.mo', 'w') as f: f.write(code) # створити файл моделі
import os, sys
sys.path.insert(0, r"e:\OpenModelica\share\omc\scripts\PythonInterface") # шлях до модулів
from OMPython import OMCSession, ModelicaSystem

# перший спосіб - використання OMCSession:
omc = OMCSession()
omc.sendExpression('loadFile("Simple.mo")')
omc.sendExpression('setParameterValue(Simple, a, 2)')
omc.sendExpression('simulate(Simple)')
omc.sendExpression('plot(x)')
print omc.sendExpression('val(x , 1.0)') # результат x(time=1.0)

# або більш зручний спосіб:
mod=ModelicaSystem("Simple.mo","Simple")
print mod.getParameters()
mod.setParameters(a=2)
mod.setSimulationOptions(stopTime=2.0)
mod.simulate()
print mod.getSolutions('time','x') # результати як масиви

# або компілювати модель і симулювати без OMPython:
Exemple #27
0
class Model(SimulatorBase.Model):

    def __init__(self, modelName, modelFileName, config):

        SimulatorBase.Model.__init__(self, modelName, modelFileName, config)
        self.modelType = 'Modelica model in OpenModelica'
        self._omc = OMCSession()
        self.onlyResultFile = False
        self.integrationSettings.resultFileExtension = 'mat'

        self._availableIntegrationAlgorithms = ['Dassl', 'Euler', 'Rungekutta', 'Dopri5']
        self.integrationSettings.algorithmName = self._availableIntegrationAlgorithms[0]

        self._IntegrationAlgorithmHasFixedStepSize = [False, True, True, False]
        self._IntegrationAlgorithmCanProvideStepSizeResults = [False, True, True, False]

        self.compileModel()

        if self.resFile != '""':
            self._initialResult = loadResultFileInit(os.path.join(os.getcwd(), self.name + "_init.xml"))
        else:
            print "The selected model could not be instantiated, check for any dependencies that the model might have"
            return

        # SocketServer setup to visualize the simulation progress bar
        HOST, PORT = "localhost", 0
        self.server = SocketServer.TCPServer((HOST, PORT), ThreadedTCPRequestHandler)
        self.ip, self.port = self.server.server_address
        self.server_port = self.port

        self.server_thread = threading.Thread(target=self.server.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.setDaemon(True)
        self.server_thread.start()

    def compileModel(self):
        """
        This function is needed to load the data into the VariablesBrowser
        before simulating the model with parameters.
        """
        if len(self.fileName) == 1:
          if self.fileName[0] <> "":
            # Load the Modelica Standard library only if there is a uses-annotation on the model (done automagically)
            if not (os.path.isfile(self.fileName[0]) and self._omc.sendExpression("loadFile(\"" + self.fileName[0].encode(sys.getfilesystemencoding()) + "\")")):
                print self._omc.sendExpression("getErrorString()")
                raise FileDoesNotExist("compileModel failed, file '" + self.fileName[0] + "' does not exist")
          else:
            pack = str(self.name.split(".",1)[0])
            if not self._omc.sendExpression("loadModel(" + pack + ")"):
              print self._omc.sendExpression("getErrorString()")
              raise FileDoesNotExist("compileModel failed, package " + pack + " does not exist")

          # set the working directory in OMC
          pwd = os.path.abspath('.').replace('\\', '/')
          workdir = self._omc.sendExpression("cd(\"" + pwd + "\")")
          # simulate the model
          simResult = self._omc.sendExpression(str("buildModel(" + self.name + ")"))
          if simResult[0] == "":
            raise BuildModelFail(self._omc.sendExpression("getErrorString()"))
          # call getErrorString() to get complete error.
          print self._omc.sendExpression("getErrorString()"),
          # read the result file
          self.resFile = os.path.join(workdir,self.name + "_res.mat")

    def getReachedSimulationTime(self):
        '''
        Read the current simulation time during a simulation
        from the Model.exe file generated during loadFile()
        '''
        t = ((simulationProgressData * self.integrationSettings.stopTime) / 100.0)
        return t

    def simulate(self):

        def precheck_for_set_sim_options():
            s = self.integrationSettings
            settings = s.__dict__

            # prepare the simulation options string for OpenModelica
            set_sim_options = ['startTime', 'stopTime', 'errorToleranceTol', 'resultFileFormat', 'fixedStepSize', 'algorithmName']
            om_sim_options = ['startTime', 'stopTime', 'tolerance', 'outputFormat', 'fixedStepSize', 'method']
            simulate_options = []
            for k, v in settings.iteritems():
                if k in set_sim_options:
                    i = set_sim_options.index(k)
                    if v != None and v != "":
                        if k == "algorithmName":
                            v = str(v).lower()
                        simulate_options += [om_sim_options[i] + "=" + str(v)]
            return ",".join(simulate_options)

        def precheck_for_model():
            self.sim_opts = precheck_for_set_sim_options()

        def readStatistics():
            '''
            Read statistics from the LOG_STATS.txt file
            '''
            work_dir = os.getcwd()
            result_exe = os.path.join(work_dir, self.name + (".exe" if os.name == "nt" else "")) + " -lv LOG_STATS" + " -r=\"" + os.path.abspath(self.integrationSettings.resultFileName) + "\""
            if self.sim_opts <> "":
              result_exe += " -override=" + self.sim_opts
            result_exe += " -port=%d" % self.server_port

            with open('LOG_STATS.txt', 'w') as output_f:
                p = subprocess.Popen(result_exe,
                    stdout=output_f, shell=True)

            import time
            attempts = 0
            while True:
                if not os.path.isfile('LOG_STATS.txt'):
                    time.sleep(0.15)
                    attempts += 1
                    if attempts == 10:
                        return
                else:
                    statistics = open('LOG_STATS.txt', 'r')
                    break

            nTimeEvents = 0
            nStateEvents = 0
            currentGridPoints = 0
            currentTime = self.integrationSettings.startTime

            if statistics != None:
                fact = [line.strip() for line in statistics]
                for i in fact:
                    if "State Events" in i:
                        nStateEvents = int(i.split(':', 1)[1])
                    if "Sample Events" in i:
                        nTimeEvents = int(i.split(':', 1)[1])
                    if "simulation time" in i:
                        currentTime = float(i.split(':', 1)[1])
                statistics.close()

            currentTime = self.integrationSettings.stopTime
            # Wait for the process to finish; otherwise we cannot read the result-file
            p.wait()

            self.integrationStatistics.nTimeEvents = nTimeEvents
            self.integrationStatistics.nStateEvents = nStateEvents
            self.integrationStatistics.nGridPoints = currentGridPoints
            self.integrationStatistics.reachedTime = currentTime

        precheck_for_model()
        readStatistics()
        if not os.path.isfile(self.integrationSettings.resultFileName):
          raise FileDoesNotExist(self.integrationSettings.resultFileName)

    def setVariableTree(self):
        if self.resFile == '""':
            return
        for v in self._initialResult:
            value = None
            if v['variability'] == 'fixed' or v['valueEdit']:
              value = v['value']
            else:
              value = None

            variableAttribute = ''
            if v['description'] != '' :
                variableAttribute += 'Description:' + chr(9) + v['description'] + '\n'
            variableAttribute += 'Causality:' + chr(9) + v['causality'] + '\n'
            variableAttribute += 'Variability:' + chr(9) + v['variability'] + '\n'
            variableAttribute += 'Type:' + chr(9) + v['type']

            self.variableTree.variable[v['name'].replace('[', '.[')] = SimulatorBase.TreeVariable(self.structureVariableName(v['name'].replace('[', '.[')), value, v['valueEdit'], v['unit'], v['variability'], variableAttribute)

    def getAvailableIntegrationAlgorithms(self):
        return self._availableIntegrationAlgorithms

    def getIntegrationAlgorithmHasFixedStepSize(self, algorithmName):
        return self._IntegrationAlgorithmHasFixedStepSize[self._availableIntegrationAlgorithms.index(algorithmName)]

    def getIntegrationAlgorithmCanProvideStepSizeResults(self, algorithmName):
        return self._IntegrationAlgorithmCanProvideStepSizeResults[self._availableIntegrationAlgorithms.index(algorithmName)]
import traceback
from os.path import basename
from StringIO import StringIO
import subprocess

from sphinx.util.compat 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 OMCSession

omc = OMCSession()
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())]
class OpenModelicaKernel(Kernel):
    implementation = 'openmodelica_kernel'
    implementation_version = '1.0'
    language = 'openmodelica'
    language_version = '1.0'
    language_info = {
        'name': "openmodelica",
        'version': "1.0",
        'mimetype': 'text/modelica',
    }
    banner = "openmodelicakernel - for evaluating modelica codes in jupyter notebook"

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

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

        z1 = 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 == True):
            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)

            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:
                    pass

            except:
                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:
            pass
Exemple #30
0
class UI_Simulation(QtGui.QDialog, form_gui):
    '''
    classdocs
    TODO: list of components and variables of the model 
    '''
    __engine= None 
    __results= None
    
    def __init__(self, parent= None, configResources= None, configSimulation= None):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.__simsource= configResources
        self.__simconfig= configSimulation
        self.load_configuration()
        self.btnModelBrowser.clicked.connect(self.browse_models)
        self.btnLibraryBrowser.clicked.connect(self.browse_libraries)
        self.cbxModelList.activated['QString'].connect(self.set_models)
        self.progressBar.setRange(0,1)
        #
        self.btnRunSimulation.setIcon(QIcon('./res/img/Play.ico'))
        self.btnRunSimulation.setIconSize(QSize(48,48))
        self.btnRunSimulation.clicked.connect(self.onStartSimulation)
        self.btnPlot.setIcon(QIcon('./res/img/Presentation.ico'))
        self.btnPlot.setIconSize(QSize(48,48))
        self.btnPlot.clicked.connect(self.browse_simulation)
        #debug
        self.__omcSession= OMCSession()
        if self.__simconfig.compiler== 'dymola':
            self.__simulationTask = TaskThreadDY(self, self.__simsource, self.__simconfig, self.__results)
        elif self.__simconfig.compiler== 'jmodelica':
            pass
        elif self.__simconfig.compiler== 'openmodelica':
            self.__simulationTask = TaskThreadOMC(self, self.__simsource, self.__simconfig, self.__omcSession, self.__results)
        self.__simulationTask.taskFinished.connect(self.onFinishSimulation)
    
    ### save/load configuration
    def load_configuration(self):
        if self.__simconfig!= None:
            self.txtCompiler.setText(self.__simconfig.compiler)
            self.txtStartTime.setText(self.__simconfig.startTime)
            self.txtStopTime.setText(self.__simconfig.stopTime)
            if self.__simconfig.numberOfIntervals!= '-1':
                self.txtInterval.setText(self.__simconfig.numberOfIntervals)
            else:
                self.txtInterval.setText(self.__simconfig.fixStepSize)
            self.txtTolerance.setText(self.__simconfig.tolerance)
            self.txtSolver.setText(self.__simconfig.method)
            
    def browse_models(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self, 'Open Model file', 
                                                     directory= self.__simsource.modelFolder+'/', 
                                                     filter='Modelica Models (*.mo)')
        self.txtModelFile.setText(fileName)
        self.__simsource.modelFile= str(fileName)
        self.__simsource.modelName= str(fileName)
        self.cbxModelList.clear()
        command= CommandOMC()
        success= self.__omcSession.execute(command.loadFile(self.__simsource.modelFile))
        if (success):
            modelNames= self.__omcSession.execute(command.getClassNames(self.__simsource.modelName))
#             print modelNames
#             print modelNames['SET1']['Set1'][0]
    #         fle= open('dict1.properties','w')
            for x in range(len(modelNames['SET1']['Set1'])):
    #             self.modellist.append(modelNames['SET1']['Set1'][x])
    #             fle.writelines(str(modelNames['SET1']['Set1'][x]+'\n'))
                # add modellist to combobox
                self.cbxModelList.addItem(modelNames['SET1']['Set1'][x])
        else:
            print 'Something unexpected happened!'
     
    def set_models(self, text):
        self.__simconfig.modelName= str(text)
        
    def browse_libraries(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self, 'Open Library file', 
                                                     directory= self.__simsource.libraryFolder+'/', 
                                                     filter='Modelica Models (*.mo)')
        self.txtLibraryFile.setText(fileName)
        self.__simsource.libraryFile= str(fileName)
        
    def browse_simulation(self):
#         simmodel = SimRes('./SevenBus.Network_res.mat')
        #debug
        ''' TODO change debug object, use simulation results '''
        simmodel = SimRes('./res/dy/Two_Areas_PSSE_AVR_Noise_dassl_dsin.mat')
#         simmodel.browse()
        simbrowser = UI_Plot_MEE(self, simmodel)
        simbrowser.show() 
    
    def onStartSimulation(self):
        self.progressBar.setRange(0,0)
        self.__simulationTask.start()
            
    def onFinishSimulation(self):
        # Stop the pulsation
        self.progressBar.setRange(0,100)
    
    def closeEvent(self, event):
        self.__omcSession.sendExpression('quit()')
        self.__omcSession= None
        event.accept() # let the window close