How can I call an OpenModelica model in Python with OMPython?

最后都变了- 提交于 2019-12-04 21:18:07

问题


I have an OpenModelica model made with OMEdit. In order to get a concrete example I designed the following:

Now I would like to run the model in Python. I can do this by using OMPython. After importing OMPython and loading the files I use the following command to run the simulation:

result = OMPython.execute("simulate(myGain, numberOfIntervals=2, outputFormat=\"mat\")")

The simulation now runs and the results are written to a file.

Now I would like to run the same model but with an different parameter for the constant block.

How can I do this?

Since the parameter is compiled into the model it should not be possible to change it. So what I need is a model like that:

Is it possible to call the model from Python and set the variable "a" to a specific value?

With the command OMPython.execute("simulate(...)") I can specify some environment variables like "numberOfIntervals" or "outputFormat" but not more.


回答1:


You can send more flags to the simulate command. For example simflags to override parameters. See https://openmodelica.org/index.php/forum/topic?id=1011 for some details.

You can also use the buildModel(...) command followed by system("./ModelName -overrideFile ...") to avoid re-translation and re-compilation or with some minor scripting parallel parameter sweeps. If you use Linux or OSX it should be easy to call OMPython to create the executable and then call it yourself. On Windows you need to setup some environment variables for it to work as expected.




回答2:


I believe you are looking for the setParameterValue command. You can read about it here: https://openmodelica.org/download/OMC_API-HowTo.pdf

Basically you would add a line similar to OMPython.execute("setParameterValue(myGain, a, 20)") to your python script before the line where you run the simulation, so long as a is a parameter in your model.




回答3:


  • Create one new folder in windows

  • In this folder put/create 2 new files file1.py and file2.bat

  • The file1.py content is:


import os
import sys
sys.path.insert(0, "C:\OpenModelica1.11.0-32bit\share\omc\scripts\PythonInterface")
from OMPython import OMCSession
sys.path.insert(0, "C:\OpenModelica1.11.0-32bit\lib\python")
os.environ['USER'] = 'stefanache'
omc = OMCSession()
omc.sendExpression("loadModel(Modelica)")
omc.sendExpression("loadFile(getInstallationDirectoryPath() + \"/share/doc/omc/testmodels/BouncingBall.mo\")")
omc.sendExpression("instantiateModel(BouncingBall)")
omc.sendExpression("simulate(BouncingBall)")
omc.sendExpression("plot(h)")`
  • the file2.bat content is:

@echo off
python file1.py
pause
  • then click on file2.bat... and please be patient!

The plotted result window will appear.



来源:https://stackoverflow.com/questions/20966511/how-can-i-call-an-openmodelica-model-in-python-with-ompython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!