Skip to main content

OpenModelica compiler (omc) interface for Python

Project description

OpenModelicaCompilerForPython License: OSMC-PL lint.yml Pytest

OpenModelica compiler (omc) interface for Python

Change log

See CHANGELOG.md

Installation

$ python3 -m pip install OpenModelicaCompiler

omc4py is acutual package name.

import omc4py

Prerequisites

Follow the link

Platform Link
Windows https://openmodelica.org/download/download-windows/
Linux https://openmodelica.org/download/download-linux/
Mac https://openmodelica.org/download/download-mac/

And ensure omc command installed.

$ omc --version
OpenModelica 1.22.3

For Windows, it will work if omc.exe exists in the default installation.

"C:\Program Files\OpenModelica1.22.3-64bit\bin\omc.exe" --version
OpenModelica v1.22.3 (64-bit)

Usage

Open session

omc4py.open_session() returns session object which interfaces to omc.

from omc4py import open_session

with open_session() as session:
    print(session.getVersion())

If omc4py.open_session cannot find omc, a valid omc command or executable path can be specified.

from omc4py import open_session

with open_session(
    "C:/Program Files/OpenModelica1.22.3-64bit/bin/omc.exe"
) as session:
    print(session.getVersion())

Call OpenModelica Scripting API via session

The OpenModelica Scripting API is available from the methods of session object.

See UserGuide for OpenModelica Scripting API

OpenModelica classes and Python classes are converted to each other. For example, the following OpenModelica function can be used from the following Python methods.

// Modelica declaration

// Returns the version of the Modelica compiler.
function getVersion
  input TypeName cl = $Code(OpenModelica);
  output String version;
end getVersion;
# Python interface
from typing import Union
from omc4py import TypeName

class Session:
    def getVersion(self, cl: Union[TypeName, str, None] = None) -> str:
        """
        Returns the version of the Modelica compiler.
        """
        ...

Class conversion between OpenModelica and Python

OpenModelica input (argument) output (return) description
Real float float
Integer int int
Boolean x; bool bool
String x; str str
TypeName omc4py.TypeName | str omc4py.TypeName
VariableName omc4py.VariableName | str omc4py.VariableName
VariableNames Sequence[omc4py.VariableName | str] list[omc4py.VariableName | str]
type T = enumeration(a, b, c); T | Literal["a", "b", "c"] T
record T ... T T T is dataclass
T[:] Sequence[T] list[T]
T[:,:] Sequence[Sequence[T]] list[list[T]]
T x = ${default}; x: T | None = None N/A
function f returns Multiple outputs N/A class F(NamedTuple): ... returned NamedTuple name is the capitalized name of the function

Exception handling

class diagram of omc4py.exception

  • OMCNotification, OMCWarning, OMCError are raised from omc
  • OMCRuntimeError is raised from omc4py python implementation (not from omc)

We are not sure about whole OpenModelica's exception handling policy. Through omc4py project, We found that there are 4 situation for expection caused by function calls.

omc behavior

  1. Function returns "\n" instead of valid value (no exception info)
  2. Function returns formatted error messages (contains sourceInfo, level, kind, message) instead of valid value
  3. Function returns unformatted error message (typically, startswith "* Error") instead of valid value
  4. Function returns valid value and set exception messages internally

omc4py behavior

  1. function returns None instead of valid result (no exception will be sent)
  2. function send OMCNotification or OMCWarning, or raise OMCError
  3. function raise OMCRuntimeError with the message returned by the omc
  4. function returns valid value. You can check exceptions explicitly by session.__check__()

Normally, 4th case seems to be notification or warning. If you want to be sure to check for exceptions, call session.__check__() before exit doubtful context.

from omc4py import open_session

def doubtful_task(session):
    # session.doubtful_API1(...)
    # session.doubtful_API2(...)
    # session.doubtful_API3(...)
    session.__check__()

with open_session() as session:
    doubtful_task(session)

Asyncio feature

The session class has a counterpart asynchronous session class. If asyncio=True is specified in open_session, an asynchronous session object can be opened.

from omc4py import open_session

with open_session(asyncio=True) as session:
    await session.getVersion()

session object and asynchronous session object can be cross-referenced by the synchronous and asynchrnous attributes.

diagram

from omc4py import open_session

with open_session() as session:
    # This session is synchronous
    # Synchronous calling
    session.getVersion()

    # Get asynchronous session by attribute
    async_session = session.asynchronous

    # Asynchronous calling
    await async_session.getVersion()
from omc4py import open_session

with open_session(asyncio=True) as async_session:
    # This session is asynchronous
    # Asynchronous calling
    await async_session.getVersion()

    # Get synchronous session by attribute
    session = async_session.synchronous

    # Synchronous calling
    session.getVersion()

Tips

Multiple session

It is also possible to open multiple sessions with different versions of omc at the same time by explicitly specifying omc.

from omc4py import open_session

with \
    open_session(
        "C:/Program Files/OpenModelica1.22.3-64bit/bin/omc.exe"
    ) as session_1_22, \
    open_session(
        "C:/Program Files/OpenModelica1.21.0-64bit/bin/omc.exe"
    ) as session_1_21:

    print("v1.22.3:", session_1_22.getVersion())
    print("v1.21.0:", session_1_21.getVersion())

omc4py as interactive shell

As shown above, it is recommended to ensure that session is closed by calling omc4py.open_session() via with-statement.

However, sometimes you want to use session interactively, like OMShell. omc4py closes all unclosed sessions when exiting the python interpreter.

>>> from omc4py import open_session
>>> session = open_session()
>>> session.loadString("""
... package A
...     package B
...             package C
...             end C;
...     end B;
... end A;
... """)
True
>>> list(session.getClassNames("A", recursive=True))
[TypeName('A'), TypeName('A.B'), TypeName('A.B.C')]
>>>
>>>
>>> exit()  # session will be closed internally

Besides, session object has __close__ method to explicitly close session.

>>> from omc4py import open_session
>>> session = open_session()
>>> session.__close__()
>>>
>>> exit()

About session API

Documentation in OpenModelica build server shows exhaustive information about OpenModelica.Scripting. You will find sub-packages not explained user guide.

  • OpenModelica.Scripting.Internal.*
  • OpenModelica.Scripting.Experimental.*

They are available from absolute reference

# Example for "timerTick" and "timerTock"
# in "OpenModelica.Scripting.Internal.Time"
from omc4py import open_session
from time import sleep

timer_index: int = 1

with open_session() as session:
    session.OpenModelica.Scripting.Internal.Time.timerTick(timer_index)

    sleep(0.1)

    # show elapsed time from last timerTick
    print(session.OpenModelica.Scripting.Internal.Time.timerTock(timer_index))

Let me introduce typical API functions!

loadModel

Load library and returns True if success. You can specify versions by second argument

import omc4py

with omc4py.open_session() as session:
    assert(session.loadModel("Modelica"))  # load MSL
import omc4py

with omc4py.open_session() as session:
    assert(session.loadModel("Modelica", ["4.0.0"]))  # load MSL 4.0.0

getClassNames

Returns array of class names in the given class

import omc4py

with omc4py.open_session() as session:
    assert(session.loadModel("Modelica"))
    for className in session.getClassNames("Modelica"):
        print(className)

By default, getClassNames() only returns "sub" classes. If you want to know all classes belongs to the class set recursive=True.

import omc4py

with omc4py.open_session() as session:
    assert(session.loadModel("Modelica"))
    for className in session.getClassNames("Modelica", recursive=True):
        print(className)  # many class names will be printed

getComponents

Returns array of component (variable, parameter, constant, ...etc) profiles

import omc4py

with omc4py.open_session() as session:
    assert(session.loadModel("Modelica", ["4.0.0"]))
    for component in session.getComponents("Modelica.Constants"):
        print(
            f"{component.className.last_identifier!s:<20}"
            f"{component.name!s:<15}"
            f"{component.comment!r}"
        )

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

openmodelicacompiler-0.3.3.tar.gz (498.6 kB view details)

Uploaded Source

Built Distribution

openmodelicacompiler-0.3.3-py3-none-any.whl (571.9 kB view details)

Uploaded Python 3

File details

Details for the file openmodelicacompiler-0.3.3.tar.gz.

File metadata

  • Download URL: openmodelicacompiler-0.3.3.tar.gz
  • Upload date:
  • Size: 498.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 colorama/0.4.4 importlib-metadata/4.6.4 keyring/23.5.0 pkginfo/1.8.2 readme-renderer/34.0 requests-toolbelt/0.9.1 requests/2.25.1 rfc3986/1.5.0 tqdm/4.57.0 urllib3/1.26.5 CPython/3.10.12

File hashes

Hashes for openmodelicacompiler-0.3.3.tar.gz
Algorithm Hash digest
SHA256 d88457f1b40cbdc10ca95e09cc113a9fdb7b6e4729580688f578fc2454752c1c
MD5 0cb705390115977aaa3d3f832363d62a
BLAKE2b-256 3d5026bd3060e1751dd11ef21237112e1eeabb3a676275b7afd1cd00623a509b

See more details on using hashes here.

File details

Details for the file openmodelicacompiler-0.3.3-py3-none-any.whl.

File metadata

  • Download URL: openmodelicacompiler-0.3.3-py3-none-any.whl
  • Upload date:
  • Size: 571.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 colorama/0.4.4 importlib-metadata/4.6.4 keyring/23.5.0 pkginfo/1.8.2 readme-renderer/34.0 requests-toolbelt/0.9.1 requests/2.25.1 rfc3986/1.5.0 tqdm/4.57.0 urllib3/1.26.5 CPython/3.10.12

File hashes

Hashes for openmodelicacompiler-0.3.3-py3-none-any.whl
Algorithm Hash digest
SHA256 09075877ba68ee06708d2bc210c80800154f6fb58139fe4fb6c8466f261393a0
MD5 21a6b8b85dc1188ba0a625d95ae5f160
BLAKE2b-256 24bccb1f498984f4c18b4da9e63be5e764c94d8b7c66ffe63436a78835812014

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page