Git Product home page Git Product logo

ompython's Introduction

OMPython

OMPython is a Python interface that uses ZeroMQ or CORBA (omniORB) to communicate with OpenModelica.

FMITest Test

Dependencies

Using ZeroMQ

  • Python 2.7 and 3.x supported
  • PyZMQ is required

Using omniORB

  • Currently, only Python 2.7 is supported
  • omniORB is required:
    • Windows: included in the OpenModelica installation
    • Linux: Install omniORB including Python 2 support (the omniidl command needs to be on the PATH). On Ubuntu, this is done by running sudo apt-get install omniorb python-omniorb omniidl omniidl-python

Installation

Installation using pip is recommended.

Linux

Install the latest OMPython master by running:

python -m pip install -U https://github.com/OpenModelica/OMPython/archive/master.zip

Windows

Install the version packed with your OpenModelica installation by running:

cd %OPENMODELICAHOME%\share\omc\scripts\PythonInterface
python -m pip install -U .

Local installation

To Install the latest version of the OMPython master branch only, previously cloned into <OMPythonPath>, run:

cd <OMPythonPath>
python -m pip install -U .

Usage

Running the following commands should get you started

import OMPython
help(OMPython)
from OMPython import OMCSessionZMQ
omc = OMCSessionZMQ()
omc.sendExpression("getVersion()")

or read the OMPython documentation online.

Bug Reports

Contact

ompython's People

Contributors

adeas31 avatar adrpo avatar alchemyst avatar alkhwarizmi avatar anheuermann avatar arinomo avatar arun3688 avatar dietmarw avatar grantstephens avatar hkiel avatar inigogastesi avatar j-emils avatar javiarrobas avatar jnettels avatar jsreid13 avatar jules-l-jimmy avatar kzscisoft avatar ne3x7 avatar openmodelica-hudson avatar sjoelund avatar tesshub avatar thorade avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ompython's Issues

Potential error in OMPython documentation OMCSession() vs. OMCSessionZMQ()

Hello!

I have found a potential error in the html documentation of OMPython:

In the online documentation online as first example

To get started, create an OMCSessionZMQ object:

from OMPython import OMCSessionZMQ
omc = OMCSessionZMQ()**

is given.

However, from reading the help() it should be

To get started, create an OMCSession object:

from OMPython import OMCSession
omc = OMCSession()

Unfortunately I did not find the source of the website in this github repos for correcting myself.

Best

Publish wheels to PyPI

Source distributions run setup.py. OMPython's setup.py does not install OMPythonIDL if importing omniidl and omniORB fails. This happens when one creates a new virtualenv and does pip install OMPython

Publishing a Wheel would avoid this issue. Try pip install --extra-index-url https://pypi.metamorphsoftware.com --log log.txt OMPython in a new virtualenv. The .whl is installed and OMPythonIDL is available.

Universal wheels (as in #91) would be preferred, but this is not strictly necessary.

pep8

Mostly whitespace changes, but it might increase readability to follow pep8
https://www.python.org/dev/peps/pep-0008/

To clean the code atuomatically, run

autopep8 --in-place --recursive --max-line-length=999 OMPython

Use --max-line-length=999 to keep line breaks as they are
or do not specify any --max-line-length at all to use the pep8 default
https://www.python.org/dev/peps/pep-0008/#maximum-line-length

pylint uses --max-line-length=100,
github seems to be show diffs with 120 or less characters
https://stackoverflow.com/questions/22207920/what-is-githubs-character-limit-or-line-length-for-viewing-files-on-github

Use autopep8 --agressive to change more than just whitespace.

Error loading Modelica example models using ModelicaSystem library

I have been trying to test loading the example models using ModelicaSystem library on Jupyter python notebook. OM version V.1.13.1 with python 3.6. My code:

mod = ModelicaSystem("C:/OpenModelica1.13.164bit/lib/omlibrary/Modelica 3.2.2/package.mo","Modelica.Mechanics.MultiBody.Examples.Elementary.DoublePendulum")

But I have been getting the following error:


2019-01-31 09:19:54,838 - OMPython - INFO - OMC Server is up and running at file:///C:/Users/GPR7RNG/AppData/Local/Temp/openmodelica.port.edfc6a9457114e3094c10e273e546a5a pid=10232

Notification: Automatically loaded package Complex 3.2.2 due to uses annotation.
Notification: Automatically loaded package ModelicaServices 3.2.2 due to uses annotation.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-d9f6539ecb72> in <module>
----> 1 mod = ModelicaSystem(path+"/package.mo","Modelica.Mechanics.MultiBody.Examples.Elementary.DoublePendulum")

~\Documents\git\agv_simulations\scripts\Python\venv_py3\lib\site-packages\OMPython\__init__.py in __init__(self, fileName, modelName, lmodel, useCorba)
    711             if (self.fileName_):  # execution from different path
    712                 os.chdir(self.currDir)
--> 713                 self.__loadingModel(self.fileName, self.modelName, self.lmodel)
    714             else:
    715                 print("Error: File does not exist!!!")

~\Documents\git\agv_simulations\scripts\Python\venv_py3\lib\site-packages\OMPython\__init__.py in __loadingModel(self, fName, mName, lmodel)
    774         self.__getOutputNames()  # initialize oNamesList
    775         self.__getContinuousValues()  # initialize cValuesList
--> 776         self.__getParameterValues()  # initialize pValuesList
    777         self.__getInputValues()  # initialize input value list
    778         self.__getOutputValues()  # initialize oValuesList

~\Documents\git\agv_simulations\scripts\Python\venv_py3\lib\site-packages\OMPython\__init__.py in __getParameterValues(self, paraName)
   1115                             self.pValuesList.append(str_)
   1116                         else:
-> 1117                             self.pValuesList.append(float(str_))
   1118             return self.pValuesList
   1119         else:

ValueError: could not convert string to float: 'box'

That is the same with some other example models that I tried to load.

Edit: Found that this error comes when a parameter has a value other than type None, Boolean and numeric (Integer/float), e.g. String

OMPython using getParameterValue with sendExpression in a python script

I tried every command listed in the scripting API, everyone works except for getParameterValue:

when I type omc.sendExpression("setParameterValue(MyModel, param1, 2)") it replies: OK
(I already loaded the MyModel model first using loadModel with sendExpression)

when I type omc.sendExpression("getParameterValue(MyModel, param1)") it should reply "2" but instead it gives me a huge error:

File "", line 1, in
File "/home/user/.local/lib/python2.7/site-packages/OMPython/init.py", line 484, in sendExpression
answer = OMTypedParser.parseString(result)
File "/home/user/.local/lib/python2.7/site-packages/OMPython/OMTypedParser.py", line 109, in parseString
return omcGrammar.parseString(string)[0]
File "/home/user/.local/lib/python2.7/site-packages/pyparsing.py", line 1632, in parseString
raise exc
pyparsing.ParseException: Expected {quoted string, starting with " ending with " | Combine:({["-"] {"0" | W:(1234...,0123...)} [{"." W:(0123...)}] [{W:(eE) W:(0123...,0123...)}]}) | Forward: ... | Group:({Suppress:("{") [Forward: ... [, Forward: ...]...] Suppress:("}")}) | Group:({Suppress:("(") [Forward: ... [, Forward: ...]...] Suppress:(")")}) | {Suppress:("SOME") Suppress:("(") Forward: ... Suppress:(")")} | "true" | "false" | {"NONE" Suppress:("(") Suppress:(")")} | Combine:(Forward: ...)} (at char 1), (line:2, col:1)

Am I doing something wrong or is my installation corrupted? Because any other command from the scripting API works just fine.

Thank you.

Using "fixed-step" solver with ModelicaSystem library

Hello

I was wondering if there is any method to set fixed-step solver through ModelicaSystem library. I am trying to use this library along with Scipy.optimize to perform parameter fitting for my model. But everytime the model simulates with a different parameter value, it gives different number of outputs for a model. Is there any way to regularize this?

Add option to not generate log-files

I now have 3 million files like /tmp/openmodelica.hudson.objid.0c3f41ef40b543f48a84395c1d393d9c.log because OMPython doesn't clean log-files after it is done. I believe we should have more options:

  • Output log to file
  • Output log in memory to the OMPython object (a stream or a string?)
  • Skip outputting the log (to save memory)
  • Output log to stdout

Installing via pip causes error omnipy version error

Good Afternoon.

It seems that when the package is installed via pip on OSX an error occurs as PMPythonIDL sends version 3 and omnipy needs version 4.2.
The issue is resolved when installing OMPython using the command on the github README page.
I have replicated the issue on 3 computers running OSX.
Both github and pypi have version 2.0.2 for OMPython

ERROR - OMC Server is down. Please start it!

Hi,
I am recently trying to use OMPython; when I type:
omc = OMCSessionZMQ()
I receive the error:
2020-05-11 12:45:54,638 - OMPython - ERROR - OMC Server is down. Please start it! Log-file says:
'C:\Users\Ajode\OneDrive' is not recognized as an internal or external command,
operable program or batch file.

Traceback (most recent call last):

File "", line 1, in
omc = OMCSessionZMQ()

File "C:\Users\Ajode\anaconda3\lib\site-packages\OMPython_init_.py", line 545, in init
self._connect_to_omc(timeout)

File "C:\Users\Ajode\anaconda3\lib\site-packages\OMPython_init_.py", line 568, in _connect_to_omc
raise Exception("OMC Server is down. Could not open file %s" % self._port_file)

Exception: OMC Server is down. Could not open file C:/Users/AJODE~1/AppData/Local/Temp/openmodelica.port.2d8c47fd8f894f80b8527460d863bd54

Would you please help me with it?

pylint

As mentioned by @dietmarw in #1 you should run a code analysis with pylint or some other tool.
If you happen to use Spyder as your editor, this can be done (for the currently active file) by just pressing F8.
At least the errors should be fixed (or looked at), some of them are due to Py2 vs Py3, some of them are due to omniORB not being installed on my Windows machine, but some are real errors that need a fix.

spyder_codeanalysis

unable to install OMPython using pip

I am trying to install OMPython in Ubuntu using the command

pip install git+git://github.com/OpenModelica/OMPython.git

I am getting the error message as:

Downloading/unpacking git+git://github.com/OpenModelica/OMPython.git
Cloning git://github.com/OpenModelica/OMPython.git to /tmp/pip-nUtv8Z-build
fatal: unable to connect to github.com:
github.com[0: 192.30.252.131]: errno=Connection timed out

Complete output from command /usr/bin/git clone -q git://github.com/OpenModelica/OMPython.git /tmp/pip-nUtv8Z-build:


Cleaning up...
Command /usr/bin/git clone -q git://github.com/OpenModelica/OMPython.git /tmp/pip-nUtv8Z-build failed with error code 128 in None
Storing debug log for failure in /tmp/tmpiA5yom

Please help me solve this issue

Thank you

unable to import OMCSessionZMQ

I've tried to run a simple test on Spyder but it doesn't work:

from OMPython import OMCSessionZMQ
I got the error: ImportError: cannot import name 'OMCSessionZMQ'

For information, I've installed OMPython with the command below in the enviroment of Anaconda (py35):

cd %OPENMODELICAHOME%\share\omc\scripts\PythonInterface
python -m pip install .

And my OM version is 1.11.0.

Thanks a lot for your help!

Unable to load files containing annotation

I am using OpenModelica version v1.13.1, jupyter python notebook and OMPython. I have developed a package in OMEditor as follows:

package NewPackage
  model firstPackageModel
  input Real val;
  equation

  end firstPackageModel;

  model WheelVelocity
  
  parameter Real R = 0.1 "Radius of the wheel";
  parameter Real L = 0.35 "Distance between center of the wheels";
  
  input Real V;
  input Real w;
  
  Real w_l;
  Real w_r;
  
  equation
    
    V = R*(w_r+w_l)/2;
    w = R*(w_r-w_l)/L;

  end WheelVelocity;
  annotation(
    uses(Modelica(version = "3.2.2")));
end NewPackage;

I am trying to load this model in a python file using ModelicaSystem class of OMPython library. I have checked the current working directory of my python notebook to be the same as that of this package. When I run:
mod = ModelicaSystem("NewPackage.mo","NewPackage.WheelVelocity")
I get following error:

2019-01-30 14:22:51,136 - OMPython - INFO - OMC Server is up and running at file:///C:/Users/MyPC/AppData/Local/Temp/openmodelica.port.df50f7eccef8467b8bc5dc35b17aae04 pid=15672 
loadFile Error: Notification: Automatically loaded package Modelica 3.2.2 due to uses annotation.
Notification: Automatically loaded package Complex 3.2.2 due to uses annotation.
Notification: Automatically loaded package ModelicaServices 3.2.2 due to uses annotation.

But in the above model code, if I comment the annotation part, then there is no issue. I am unable to understand what seems to be the problem.

Make "ModelicaSystem" aware of "uses" annotation

When filing #63 I thought rather than having to rely on manually specifying the used libraries in the ModelicaSystem call like:

mod=ModelicaSystem("BouncingBall.mo","BouncingBall","Modelica")

OMPython should be clever enough to interpret the uses annotation inside the loaded model library.

OMCSessionZMQ() can't start OMCServer

Good evening.
I'm trying to run OMPython on a MacBook with OS Catalina 10.15.
When launching constructing an object with OMCSessionZMQ() an exception is raised:

`800 - OMPython - ERROR - OMC Server is down. Please start it! Log-file says:

/bin/sh: /opt/openmodelica/bin/omc/bin/omc: Not a directory

Traceback (most recent call last):

File "", line 1, in

File "/Users/gambister/anaconda3/lib/python3.7/site-packages/OMPython/init.py", line 541, in init

self._connect_to_omc(timeout)

File "/Users/gambister/anaconda3/lib/python3.7/site-packages/OMPython/init.py", line 564, in _connect_to_omc

raise Exception("OMC Server is down. Could not open file %s" % self._port_file)

Exception: OMC Server is down. Could not open file /var/folders/xm/rt0rgw3j2lv39dvytv9_kfvh0000gn/T/openmodelica.gambister.port.1a536a9443d941b0a180a144ca63e656`

It seems that the system is unable to run the server.

I occur into the same problem on my linux machine after having explicitly set the environment variable OPENMODELICAHOME as the path to the omc executable (i.e. using the command "export OPENMODELICAHOME=/usr/bin/omc"), so I am suspecting that I have some troubles in the environement variable setup.

On the Mac Book, I was obliged to manually set the environment variable OPENMODELICAHOME since the "spawn" function was not able to reach the openmodelica installation ( referring to code line 115 of init.py file path_to_omc = spawn.find_executable("omc") ).

Thanks in advance

Cannot init OMPython - Server port file mismatch

When testing with omc = OMCSessionZMQ() I get the following error:

2019-06-05 17:17:03,438 - OMPython - ERROR - OMC Server is down. Please start it! Log-file says:
Created ZeroMQ Server.
Dumped server port in file: /tmp/openmodelica.nobody.port.520e1d1cf66e42edab1847382e320d83
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/conda/lib/python3.7/site-packages/OMPython/__init__.py", line 541, in __init__
    self._connect_to_omc(timeout)
  File "/opt/conda/lib/python3.7/site-packages/OMPython/__init__.py", line 564, in _connect_to_omc
    raise Exception("OMC Server is down. Could not open file %s" % self._port_file)
Exception: OMC Server is down. Could not open file /tmp/openmodelica.jovyan.port.520e1d1cf66e42edab1847382e320d83

You'll notice the mismatch between the created file/tmp/openmodelica.nobody.port.520e1d1cf66e42edab1847382e320d83 and what OMPython is looking for /tmp/openmodelica.jovyan.port.520e1d1cf66e42edab1847382e320d83.

If I ls -lh /tmp it shows

-rw-r--r-- 1 jovyan users  113 Jun  5 17:27 openmodelica.jovyan.port.520e1d1cf66e42edab1847382e320d83.log
-rw-r--r-- 1 jovyan users   21 Jun  5 17:27 openmodelica.nobody.port.520e1d1cf66e42edab1847382e320d83

cat /tmp/openmodelica.nobody.port.520e1d1cf66e42edab1847382e320d83

Created ZeroMQ Server.
Dumped server port in file: /tmp/openmodelica.nobody.port.520e1d1cf66e42edab1847382e320d83$

cat /tmp/openmodelica.nobody.port.520e1d1cf66e42edab1847382e320d83

tcp://127.0.0.1:46505

ps ax | grep omc

   11 ?        Ss     0:00 /bin/sh -c /usr/bin/omc --interactive=zmq +z=520e1d1cf66e42edab1847382e320d83
   12 ?        Sl     0:00 /usr/bin/omc --interactive=zmq +z=520e1d1cf66e42edab1847382e320d83
   24 pts/0    S+     0:00 grep omc

Please assist. I believe the source of the issue is that the subprocess is ran as nobody instead of the current user, but it is not clear to me what is causing that.

Move all generated files to a temporary directory

Running examples in OMPython will place all generated files in the current directory.
This is not very nice and clutters up the workspace. OMPython should generate all files in some temporary directory instead.

OMParser is non-reentrant

Because of the shared variables result, inner_sets, next_set_list, next_set in OMParser, the routines are non-reentrant. This may cause problems when trying to use the routines concurrently or in other code.

ModelicaSystem object creates new OMCSession

Hi all,

The documentation implies that when creating a new ModelicaSystem object it uses the previously created OMCSession.

image

However, when calling ModelicaSystem it automatically creates a new OMCSession. Is this as intended? I need to setCommandLineOptions before creating the ModelicaSystem object. This could be done by creating an empty ModelicaSystem() and then sendExpression("..."), but then buildModel() gives

AttributeError: 'ModelicaSystem' object has no attribute 'modelName'

'utf-8' codec can't decode byte

Trying to load a model with Modelica.Blocks.Sources.CombiTimeTable component in Jupyter Python Notebook. OM Version 1.13.1, python 3.6.6 using ModelicaSystem class object from OMPython library. Getting following error:


'utf-8' codec can't decode byte 0xe4 in position 1000: invalid continuation byte
None

Apparently, this error is coming only with all "Table" components from the Modelica.Blocks package.

OMPython - ERROR - OMC Server is down

Hi - I am updating the Docker image from the jupyter-openmodelica project. I can open a notebook with the OpenModelica kernel but then it crashes with the above error message. The thread #1 seems to go into some of the issues.

Here is the Docker file

# Get a minimal notebook from the public Docker jupyter images
FROM jupyter/minimal-notebook
# Switch to root to install new components
USER root
# Update index
RUN apt-get update
# Install minimal OpenModelica Components from the nightly build
RUN for deb in deb deb-src; do echo "$deb http://build.openmodelica.org/apt xenial nightly"; done | sudo tee /etc/apt/sources.list.d/openmodelica.list
RUN wget -q http://build.openmodelica.org/apt/openmodelica.asc -O- | sudo apt-key add -
RUN apt-key fingerprint
RUN apt-get update
RUN apt-get install -y openmodelica
# Switch back to jupyter notebook default user to install the OpenModelica kernel
USER $NB_UID
# Install OMPython and jupyter-openmodelica kernel
RUN pip install -U git+git://github.com/OpenModelica/OMPython.git
RUN pip install -U git+git://github.com/OpenModelica/jupyter-openmodelica.git

I build and run this using the following commands (where jupyter-openmodelica/ is the directory containing the Dockerfile)

docker build -t openmodelica jupyter-openmodelica/
docker run -p 8888:8888 openmodelica

Here is the output when I open the notebook from the jupyter-openmodelica project :

2018-03-08 17:27:20,256 - OMPython - ERROR - OMC Server is down. Please start it! Log-file says:
Created ZeroMQ Server.
Dumped server port in file: /tmp/openmodelica.nobody.port.cd065c756553460fb78c4bb0d3fb8771    Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
  File "/opt/conda/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
  File "/opt/conda/lib/python3.6/site-packages/openmodelica_kernel/__main__.py", line 43, in <module>
IPKernelApp.launch_instance(kernel_class=OpenModelicaKernel)
  File "/opt/conda/lib/python3.6/site-packages/traitlets/config/application.py", line 657, in launch_instance
app.initialize(argv)
  File "<decorator-gen-123>", line 2, in initialize
  File "/opt/conda/lib/python3.6/site-packages/traitlets/config/application.py", line 87, in catch_config_error
return method(app, *args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 465, in initialize
self.init_kernel()
  File "/opt/conda/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 376, in init_kernel
user_ns=self.user_ns,
  File "/opt/conda/lib/python3.6/site-packages/traitlets/config/configurable.py", line 412, in instance
inst = cls(*args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/openmodelica_kernel/kernel.py", line 125, in __init__
self.omc=OMCSessionZMQ()
  File "/opt/conda/lib/python3.6/site-packages/OMPython/__init__.py", line 502, in __init__
self._connect_to_omc(timeout)
  File "/opt/conda/lib/python3.6/site-packages/OMPython/__init__.py", line 528, in _connect_to_omc
raise Exception
Exception

I hope there is some bandwidth on your part to look into this. Once the Dockerfile is working I will contribute it to the jupyter- openmodelica project.

ZMQ fails for ask(parsed=False)

>>> o=OMPython.OMCSessionZMQ()
>>> o.ask("a:=1:5", parsed=False)
2017-11-14 15:42:10,115 - OMPython - ERROR - OMC failed: a:=1:5, None, parsed=False
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/zmq/sugar/attrsettr.py", line 39, in __getattr__
    opt = getattr(constants, upper_key)
AttributeError: module 'zmq.sugar.constants' has no attribute 'SENDEXPRESSION'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/OMPython/__init__.py", line 216, in ask
    raise e
  File "/usr/local/lib/python3.5/dist-packages/OMPython/__init__.py", line 213, in ask
    res = self._omc.sendExpression(expression)
  File "/usr/local/lib/python3.5/dist-packages/zmq/sugar/attrsettr.py", line 42, in __getattr__
    self.__class__.__name__, upper_key)
AttributeError: Socket has no such option: SENDEXPRESSION
>>> o.ask("a:=1:5", parsed=True)
{'SET1': {'Set1': [1, 2, 3, 4, 5]}}
>>> o.sendExpression("a:=1:5", parsed=True)
(1, 2, 3, 4, 5)
>>> o.sendExpression("a:=1:5", parsed=False)
'{1,2,3,4,5}\n'
>>> o=OMPython.OMCSession()
>>> o.ask("a:=1:5", parsed=True)
{'SET1': {'Set1': [1, 2, 3, 4, 5]}}
>>> o.ask("a:=1:5", parsed=False)
'{1,2,3,4,5}\n'
>>> o.sendExpression("a:=1:5", parsed=False)
'{1,2,3,4,5}\n'
>>> o.sendExpression("a:=1:5", parsed=True)
(1, 2, 3, 4, 5)

Unable to access Open Modelica from Scilab

I am using 'OpenModelica v1.16.0-dev-371-geb234c072 (64-bit)', 'Python 2.7.18' and 'Scilab-5.5.2'. I want to access Open Modelica from Scilab and to do so I am using Python as a bridge. I am using PIMS toolbox of Scilab to connect with Python and from there using OMPython to work with OpenModelica.

But whenever I try to access an OMCSessionZMQ() from Scilab using Python. I get the following error ->

OMPython - ERROR - OMC Server is down. Please start it! Log-file says:
Created ZeroMQ Server.
Dumped server port in file: C:\Users\USER~1\AppData\Local\Temp\/openmodelica.port.69f1318e05e04a1eac6f7296ee05ebbb
OMC did not exit after being sent the quit() command; killing the process with pid=9980
!--error 999
Method invocation: An error occurred: Unable to invoke the method: OMCSessionZMQ
Python interpreter threw an exception:
Traceback:
File C:\Python27\lib\site-packages\OMPython_init
.py, line 559, in init
File C:\Python27\lib\site-packages\OMPython_init_.py, line 582, in connect_to_omc
exceptions.Exception: OMC Server is down. Could not open file c:/users/user~1/appdata/local/temp/sci_tmp_8420
/openmodelica.port.69f1318e05e04a1eac6f7296ee05ebbb_

Whereas if I try to do the same thing from the command line directly by running "cmd" command. Then it is working fine and giving the following result ->

OMPython - INFO - OMC Server is up and running at file:///c:/users/user~1/appdata/local/temp/openmodelica.port.4b6d2d21a95d499194d5bfb4fd58392a pid=2012

I tried executing the same thing by starting command line from Python in Scilab, but that also doesn't work out.

Please help. Kindly also let me know if there are other methods to connect Scilab with OpenModelica.

getParameters/__getXXXs fails when called single multicharacter argument

Dear OMPython maintainers,

Using OMPython 3.1.2 and OpenModelica 1.13.2, I think there is a bug when calling getParameters (and the underlying function __getXXXs, so that other getX functions may be affected) with a single parameter name which has several characters. Here is an example with the test model dcmotor:

from OMPython import OMCSessionZMQ

omc = OMCSessionZMQ()
model_path=omc.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels/"

from OMPython import ModelicaSystem
mod=ModelicaSystem(model_path + "dcmotor.mo","dcmotor")

when calling mod.getParameters('load.J'), one gets the error message 'l' is not in list, meaning that the 'load.J' string is wrongly interpreted like ['l', 'o', 'a' ...].

I believe the issue comes from iteration in the elements of names in the case elif len(names)==1 in __getXXXs. Maybe the goal was to get many one-letter params at once? Anyway, this breaks the function.

A solution could be remove the special case elif len(names)==1 and expand elif len(names) > 1: into else (implicitely >=1).

Final thought: I believe the two lines except ValueError as e: print(e) shoud be removed since they complicate debugging.

How to modify a component's value within a redeclare statement via OMPython?

Hello there!
To be clear, this is a question, not an issue. So please delete if this is inappropriate.

I asked this question on stackoverflow, with a complete working example and more explanation:
https://stackoverflow.com/questions/62168453

But the gist is: I would like to be able to replace the "sensitivity" in the example below via OMPython. Using omc.sendExpression() with setComponentModifierValue() allows me to edit component.value, but not anything within a redeclare statement.

  model System "A system with a component"
    Component component(value = 200, redeclare SpecialSensor sensor(sensitivity = 10)) "Modified component";
  end System;

I would be grateful for any advice.

setSimulationOptions startTime and stopTime values are sometimes ignored

I'm trying to do a restart simulation based on the bouncing ball, i.e. I want to end the initial run early, grab the final values of height and velocity and use those as inputs to a continuation run. It works apart from being able to consistently set the start time and end time of the continuation run.

I use setSimulationOptions 3 times. The first to set the start and end times of the initial run, e.g. startTime = 0, stopTime = 2.
The second define the continuation run, e.g.
startTime = 2, stopTime = 7.
I then do a third run that runs all the way through for comparison, e.g.
startTime = 0, stopTime = 7.

What happens is that the options are sometimes set and other times not. It is apparently random.

Linux download instructions breaks for Docker slim-jessie debian distribution

Within the instructions for downloading OpenModelica for Linux there is the command:

for deb in deb deb-src; do echo "$deb http://build.openmodelica.org/apt `lsb_release -cs` nightly"; done | sudo tee /etc/apt/sources.list.d/openmodelica.list

However within the Docker image for python:3.5.5-slim-jessie there is no lsb_release command in order to save space, so this command fails. There is an alternative command that can be used to achieve the same goal but works on all Linux versions, even very slim ones, I just added extra conversions to make sure only the first word of the name is retrieved and that it is converted to lowercase to match the way your file system stores it:

awk -F"[)(]+" '/VERSION=/ {print $2}' /etc/os-release | awk '{print $1}' | awk '{ print tolower($0) }'

Enhancements required for multi-simulation scenarios

Using getXXXX() method from ModelicaSystem class loads the results and parameter values from the resultant MAT file with the default name "model_name_res.mat". But if the same model has to be simulated multiple times by changing certain parameters, the resulting MAT file gets overwritten for each simulation iteration and comparing the results with the previous simulations is not possible. Therefore I would like to suggest following two enhancements in the existing OMPython library and in particular ModelicaSystem class:

  1. Allow the user to provide a name or suffix for the generated resultant MAT file
  2. Allow the user to define the path to the MAT file from which they want to read the results or parameters using getXXXX()/getXXXX(S) method.

Also added the same as a ticket on trac as: https://trac.openmodelica.org/OpenModelica/ticket/5378

typeCheck on python3 - type long does not exist

the function typeCheck defined at line 55 of init.py of OMParser uses the type long in the list
types. This type does not exist any more in python 3 and thus I get an error when I try to instantiate
an object of ModelicaSystem. I had to remove long from the list and now it works.

Loading .mo from other Modelica libraries

Hello,

I am trying to load this type of modelica library https://github.com/UdK-VPT/BuildingSystems/blob/master/BuildingSystems/Applications/PhotovoltaicSystems/PhotovoltaicSystem.mo and I am having the next error


2018-04-25 18:29:03,435 - OMPython - INFO - OMC Server is up and running at file:////tmp/openmodelica.proto.port.1b96d47d2ac3433887c3324306650d06

loadFile Error: Error: Failed to insert class PhotovoltaicSystem within BuildingSystems.Applications.PhotovoltaicSystems;

 the available classes were:

I have not classes inside this .mo file.
mod=ModelicaSystem(".../BuildingSystems-modelica/BuildingSystems/Applications/PhotovoltaicSystems/PhotovoltaicSystem.mo", "PhotovoltaicSystem", "Modelica")

How could I load this type of modelica file with OMPython?

Thanks!

I also have another question. I am interested to know if it is possible to modify/update variables in real time. I want to take for example the battery load and take this variable inside a control logic, then put some actions against the battery within a reinforcement learning algorithm inside python. Is it possible to do with Modelica?

Install OMPython offline

Hello All,
is there anyway to install OMPython offline?

Unfortunately my company firewall doesn't permit to download using python -m pip install -U .

This is the error I get:

Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x00000000049BBD30>: Failed to establish a new connection: [Errno 10061] No connection could be made because the target machine actively refused it',)': /simple/future/

I do appreciate your help.

Thanks.

ModelicaSystem does not return from call

Running the bouncingBall script on a Docker container with Debian and OMModelica installed appears to set up the OMC server but the ModelicaSystem call isn't returned:

omc = OMCSessionZMQ()
2019-10-02 14:56:49,581 - OMPython - INFO - OMC Server is up and running at file:////tmp/openmodelica.darren.port.b1050fd2bee2410895097c0fdfd303a7 pid=294
mod = ModelicaSystem("BouncingBall.mo", "BouncingBall", ["Modelica"])
2019-10-02 14:57:03,275 - OMPython - INFO - OMC Server is up and running at file:////tmp/openmodelica.darren.port.9edb9d062daf471dbefac6523603800c pid=315

But there is no return to the prompt. Ctrl-C gives the following traceback:

^CTraceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python3.7/dist-packages/OMPython/init.py", line 688, in init
self.__loadingModel()
File "/usr/local/lib/python3.7/dist-packages/OMPython/init.py", line 738, in __loadingModel
self.buildModel()
File "/usr/local/lib/python3.7/dist-packages/OMPython/init.py", line 742, in buildModel
buildModelResult = self.requestApi("buildModel", self.modelName)
File "/usr/local/lib/python3.7/dist-packages/OMPython/init.py", line 765, in requestApi
res = self.getconn.sendExpression(exp)
File "/usr/local/lib/python3.7/dist-packages/OMPython/init.py", line 612, in sendExpression
result = self._omc.recv_string()
File "/usr/local/lib/python3.7/dist-packages/zmq/sugar/socket.py", line 592, in recv_string
msg = self.recv(flags=flags)
File "zmq/backend/cython/socket.pyx", line 791, in zmq.backend.cython.socket.Socket.recv
File "zmq/backend/cython/socket.pyx", line 827, in zmq.backend.cython.socket.Socket.recv
File "zmq/backend/cython/socket.pyx", line 186, in zmq.backend.cython.socket._recv_copy
File "zmq/backend/cython/checkrc.pxd", line 12, in zmq.backend.cython.checkrc._check_rc
KeyboardInterrupt

Thanks

'new' vs 'old' frontend code generation

Dear all,

When trying to run a modelica model with OMPython, I get the same error messages as I would in OpenModelica with "old frontend for code generation" enabled. Unfortunately I only got this model to work in OpenModelica with this option disables, i.e. in the new frontend.

Is there a workaround to this in OMPython? Or should I debug the model in OpenModelica using the old frontend?

Many thanks for the help!

Cheers,
/Glenn

Python 3 support?

It seems OmniORB is the holdup keeping Python support to version 2. As I was digging around, I found that apparently the dev version/upcoming version offer Python 3 support, judging from some commit messages since 07/2014 and even some parts of the current version support Py3, so I thought I'd leave that here.

Third argument of "ModelicaSystem" not documented

When trying to use the ModelicaSystem
function as documented in the User's Guide it simply does not tell you what the quite central third argument should look like.

It took a lot of searching and going through the code to finally figure that it expects the to be used library name as a string.

E.g.,

mod=ModelicaSystem("BouncingBall.mo","BouncingBall","Modelica")

Also I'm not sure how to specify the dependency from several libraries.

Error during linearization

Hello,

Infos:
System: Archlinux
OMCompiler v1.13.2 AND v1.14.0-dev.257+g5daaf9ba0
OMPython: 3.1.2 (with pip installed)

if I want to linearize a model, I get the following error message:

~/.local/lib/python3.7/site-packages/OMPython/__init__.py in __getMatrix(self, xParameter, sizeParameter)
   1789         xElemNames.sort(key=len)
   1790         sortedX = xElemNames
-> 1791         size_ = int(self.getParameters(sizeParameter))
   1792         matX = []
   1793         matX = [[] for i in range(size_)]

TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

I use the Infos from here: https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/ompython.html#usage-of-linearization-methods:

from OMPython import OMCSessionZMQ 
omc = OMCSessionZMQ() 
model_path=omc.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels/" 
from OMPython import ModelicaSystem
mod=ModelicaSystem(model_path + "VanDerPol.mo", "VanDerPol")
mod.linearize()

with "VanDerPol", "BouncingBall" and an own small electric example with one real input and one real output.

what is my fault in linearizing the model?

Thanks for your help.

How to detect failed simulation?

I have a Modelica model (can't share that sadly). Using OMEdit, using certain parameter values the simulation (rightly so) fails to finish, and the OMEdit output console gives an error Simulation process failed. Exited with code -11.

Now, I am using OMPython to automate simulations of that model, and certain parameter combinations lead to simulations (correctly) failing. However, I could not find a way to detect, using OMPython, that the simulation fails!
Using the same parameters that correctly and visibly fail with OMEdit above, when doing model.simulate() followed by model.sendExpression('getErrorString()'), I only get an empty string back. In fact, in the (powershell) console I only see warnings and info-level messages, but no errors. However, a last info message says model terminate | Integrator failed. | Simulations terminated at time 167.512, which indicates a failed simulation to me.
Why is this info-level, though, and not error-level?
How can I detect that a simulation did not finish succesfully?

Spaces in path break subprocess.Popen() call to start omc_process

I have been using OMPython for a while on Windows 10. Now I had to set up a new laptop and suddenly this issue appears when trying to create any OMCSessionZMQ():

Exception: OMC Server is down. Could not open file C:/Users/NETTEL~1/AppData/Local/Temp/openmodelica.port.50aacfadefae421daeaba5261014af07

2020-01-23 16:19:22,756 - OMPython - ERROR - OMC Server is down. Please start it! Log-file says:
Der Befehl "C:\Program" ist entweder falsch geschrieben oder konnte nicht gefunden werden.

The log-file error is german for

the command  "C:\Program" is written incorrectly or was not found

After a little digging I found the cause in _start_omc_process(self):
In the line

self._omc_process = subprocess.Popen(self._omc_command, shell=True, stdout=self._omc_log_file, stderr=self._omc_log_file, env=my_env)

the argument

self._omc_command 

equals

C:\Program Files\OpenModelica1.14.1-64bit\bin\omc --interactive=zmq +z=8be605dda16044d8b1e8fedeba4dc045

Calling subprocess.Popen() with a space in C:\Program Files causes it to interpret it as two separate commands.
The solution is to call subprocess.Popen() not with a single string, but with the command given as a list:

['C:\\Program Files\\OpenModelica1.14.1-64bit\\bin\\omc', '--interactive=zmq', '+z=2667427e41304278b5f4a0144e9dd32f']

The fix is simple enough, and I will link a pull request shortly. I just cannot imagine how this code ever worked on a Windows machine, in the first place... :-)

Loading dependencies in ModelicaSystem

I'm trying to load a custom package and model using ModelicaSystem. E.g. I have files in my current directory:

TestPackage/package.mo
TestPackage/BouncingBall.mo

And so in python I do:

from OMPython import ModelicaSystem
mod = ModelicaSystem(
    "TestPackage/BouncingBall.mo",
    "TestPackage.BouncingBall",
    ["Modelica", "TestPackage/package.mo"],
)

When I run this, I get an error:

$ python run_model.py 
2020-02-27 14:08:05,317 - OMPython - INFO - OMC Server is up and running at file:////tmp/openmodelica.pscherpelz.port.98675bd6718747a0a04dcb3a5fe45caf pid=39793
loadFile Error: Error: Failed to insert class BouncingBall within TestPackage;

 the available classes were:

But I noticed that in OMPython/__init__.py, dependencies (lines 745-757) are actually loaded after the main model. If I put those dependencies at the top of the __loadingModel() function, everything loads normally.

Is there a reason dependencies are loaded after the main file? Is there something else I'm missing about setup? Thanks!

using ZeroMQ messaging instead of CORBA/omniORB?

Hi,

(This is more an open question rather than an issue.)

I was wondering if, in the mid term, there was the idea to replace the communication channel between the OMC and Python. I find the present choice (CORBA/omniORB) to be slightly complicated (*). To be clear, I have zero knowledge of these messaging systems. Only, I know people at IPython were very happy with ZMQ (which they started using when they split the kernel and the front end to make the Notebook interface). Also, Googling for "Corba ZMQ", I just found a link to a 2011 study by people from CERN. Of course the use case is different, but I just read through the paper and the story is they were looking for a replacement for their existing CORBA infrastructure. ZMQ appeared their best options (many criterions: simplicity, features...).

Now this is just an empty idea since I don't plan to start working on this, but maybe it is a useful suggestion?

best,
Pierre

(*)I mean simple practical issues: no pip install, no conda install. For Anaconda, I've found a third party built package at https://anaconda.org/mutirri/omniorb but after installation, I still get an ImportError: No module named omniORB...

OMPython Installation Error

Hello,
I am trying to install OMPython in Python 3.5 (Anaconda3) on a Windows 10 laptop.

I have already built omniORB 4.2.1 from source using VS2015 and have installed OpenModelica1.9.4-dev. The OPENMODELICAHOME environment variable is set to C:\OpenModelica1.9.4-dev.

I keep getting:

error: package directory 'OMPythonIDL' does not exist

(but it does in the OpenModelica directory). I even added the full path to OMPythonIDL to my path but I still get the same error.

One thing I am unsure of is the omniORBpy package - I see there is something available on sourceforge for. Do I need this package before installing OMPython?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.