OMPython

repository·master·Indexed 41 days ago

https://github.com/openmodelica/ompython

A Python API interface for OpenModelica version 4.1.0 that enables programmatic control of the OpenModelica Compiler (OMC) using ZeroMQ. It provides tools for session management via OMCSessionLocal, model execution configuration with ModelExecutionConfig, and Design of Experiments (DoE) orchestration through the ModelicaSystemDoE class.

Tokens
18.2K
Snippets
61
Records
85
Agent score
99%

What's inside OMPython

  1. OMPython dependencies and requirements

    master

    Ensure your environment meets the following requirements:

    Python Versions:

    • Python >= 3.10
    • Python >= 3.12 is required if you want to use OMPath functionality (which provides a pathlib.Path compatible abstraction layer for file system access via OMC).

    Required Packages:

    • numpy
    • psutil
    • pyparsing
    • pyzmq
  2. How the 'override' argument works

    master

    In ModelExecutionConfig, the 'override' argument is used to change Modelica variables without recompiling the model.

    When you call arg_set('override', {'var_name': value}), the library converts the dictionary into a comma-separated string of key=value pairs formatted for the model executable's command line.

    Value Conversion Rules:

    • Booleans: Converted to true or false (lowercase).
    • Numbers: Converted to their string representation.
    • Strings: Stripped of whitespace. If a string can be evaluated as a number or boolean via ast.literal_eval, it is converted to that type before being formatted.
    • None: If a key in the override dictionary is set to None, that specific override is removed.
  3. Initialize an OMCSession via ZMQ

    master

    The OMCSessionABC class is the base for all ZMQ-based OMC sessions. It manages the connection to the OMC process, handles the ZeroMQ socket lifecycle, and manages a log file for the session.

    Subclasses include:

    • OMCSessionLocal: For a local OMC process.
    • OMCSessionDocker: To run OMC inside a new Docker container.
    • OMCSessionDockerContainer: To connect to an existing Docker container.
    • OMCSessionPort: To connect to an existing OMC server via a specific port.
    • OMCSessionWSL: For Windows Subsystem for Linux environments.

    When an OMCSession is initialized, it creates a unique random string for the instance and sets up a temporary log file to capture OMC output.

  4. Understand the OMSessionABC abstraction

    master

    The OMSessionABC is the base class for defining an OpenModelica (OMC) session. It provides a structured way to interact with OMC, whether via a ZMQ backend (for remote/containerized execution like Docker or WSL) or a dummy implementation for local model execution.

    Key responsibilities of a session implementation include:

    • Managing communication timeouts.
    • Handling command prefixes for remote environments.
    • Providing path management via OMPathABC.
    • Executing expressions via sendExpression.
    • Managing working directories and temporary directories.
  5. How OMPathRunner implementations work

    master

    OMPython uses different OMPathRunner classes to handle file system operations depending on the environment. These classes inherit from OMPathRunnerABC and provide methods like is_file(), is_dir(), read_text(), write_text(), mkdir(), and unlink().

    Runner Types

    1. OMPathRunnerLocal: Uses standard Python pathlib.Path logic. It is efficient but may not provide correct Windows path representations; for Windows, convert via pathlib.Path(ompath_obj.as_posix()).
    2. OMPathRunnerBash: Designed for environments like WSL or Docker. It executes commands via bash -c (e.g., using test, cat, mkdir -p, rm) to interact with the file system. This ensures compatibility with POSIX-style commands even if the host environment is different.
  6. Manage paths with OMPathABC

    master
    The OMPathABC class is a specialized path object designed to work with an OMSessionABC. Unlike standard pathlib.Path objects, OMPathABC instances are aware of the session they belong to, allowing them to perform file operations (like read_text, write_text, mkdir, unlink) even when the files reside in a remote environment (e.g., inside a Docker container or WSL) accessed via the session.
  7. How OMCSessionCmd caching works

    master

    The OMCSessionCmd class implements a simple caching mechanism to avoid redundant network/process calls to the OMC.

    Conditions for caching:

    1. The OMCSessionCmd must be initialized with readonly=True.
    2. The query must not be getErrorString.
    3. The exact same expression and parsing configuration must be requested.

    This is useful when performing heavy introspection on a large Modelica library where the same class properties are queried multiple times.

  8. How nested sets and subsets are parsed

    master

    The OMParser module uses a hierarchical approach to parse nested Modelica sets using braces {} and double braces {{}}.

    • Single Braces {}: Handled by make_sets and get_inner_sets. These represent standard sets or collections of values.
    • Double Braces {{}}: Handled by get_inner_sets and make_subset_sets. These represent nested structures (subsets) within a main set.

    When parsing, the module maintains a result dictionary that organizes data into a hierarchy of SET names, Subset names, and Set names (e.g., result['SET1']['Subset1']['Set1']). This allows the parser to represent complex, multi-level Modelica data structures in a way that preserves their nesting logic.

  9. Start an OpenModelica session with OMCSessionLocal

    master

    To interact with a local OpenModelica Compiler (OMC) instance, instantiate OMCSessionLocal. This object allows you to send expressions and commands to the compiler via the sendExpression method.

    import OMPython
    omc = OMPython.OMCSessionLocal()
    omc.sendExpression("getVersion()")