Skip to main content

PythonFMU3

A lightweight framework that enables the packaging of Python 3 code as FMUs (following FMI version 3.0).

License: MIT contributions welcome

CI PyPI Read the Docs

This project is a fork of the original PythonFMU repository available at https://github.com/NTNU-IHB/PythonFMU, which was used as the basis for adding support for FMI 3.0. While we have made efforts to expand the functionality of this project, it currently has some limitations and does not support all the features of FMI 3.0. We would like to acknowledge and give credit to the original PythonFMU project for their contributions to this work.

Support:

Both the Model Exchange and Co-simulation interfaces are supported, with Float64, Int32, Int64, UInt64, Boolean, String and Enumeration variables (plus NumPy arrays of the numeric types). See the documentation for the full list of supported features and current limitations, and the examples folder for more models.

See the changelog for what changed in each release.

Where can I run the FMU?

In any FMI 3.0 importer: Python-based tools such as FMPy, and native tools such as OMSimulator, fmusim or Simulink.

The machine running the simulation needs Python 3 with a shared Python library, plus the packages your model imports (see pythonfmu3 deploy below). Inside a Python-based importer the FMU uses that interpreter. Otherwise, on Linux and macOS the FMU finds and loads libpython itself; if it picks the wrong one, or none, point it at the right library:

export PYTHONFMU_PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.12.so.1.0

On Windows, python3.dll must be on the PATH. See Running FMUs outside Python for the full lookup order.

How do I build an FMU from python code?

  1. Install pythonfmu3 package:
pip install pythonfmu3
  1. Create a new class extending the Fmi3Slave class declared in the pythonfmu3.fmi3slave module (see below for an example). Keep a single FMU class per script.
  2. Run pythonfmu3 build to create the fmu.
usage: pythonfmu3 build [-h] -f SCRIPT_FILE [-d DEST] [--doc DOCUMENTATION_FOLDER] [--terminals TERMINALS]
                        [--no-external-tool] [--only-one-per-process] [--handle-state] [--serialize-state]
                        [--no-variable-step] [--needs-completed-step]
                        [Project files ...]

Build an FMU from a Python script.

positional arguments:
  Project files         Additional project files required by the Python script.

options:
  -h, --help            show this help message and exit
  -f SCRIPT_FILE, --file SCRIPT_FILE
                        Path to the Python script.
  -d DEST, --dest DEST  Where to save the FMU.
  --doc DOCUMENTATION_FOLDER
                        Documentation folder to include in the FMU.
  --terminals TERMINALS
                        Terminals file (terminalsAndIcons.xml) to include in the FMU.
  --no-external-tool    If given, needsExecutionTool=false
  --only-one-per-process
                        If given, canBeInstantiatedOnlyOncePerProcess=true
  --handle-state        If given, canGetAndSetFMUState=true
  --serialize-state     If given, canSerializeFMUState=true
  --no-variable-step    If given, canHandleVariableCommunicationStepSize=false
  --needs-completed-step
                        If given, needsCompletedIntegratorStep=true

How do I build an FMU from python code with third-party dependencies?

Often, Python scripts depends on non-builtin libraries like numpy, scipy, etc. PythonFMU does not package a full environment within the FMU. However, you can package a requirements.txt or environment.yml file within your FMU following these steps:

  1. Install pythonfmu package: pip install pythonfmu3
  2. Create a new class extending the Fmi3Slave class declared in the pythonfmu3.fmi3slave module (see the examples below).
  3. Create a requirements.txt file (to use pip manager) and/or a environment.yml file (to use conda manager) that defines your dependencies.
  4. Run pythonfmu3 build -f myscript.py requirements.txt to create the fmu including the dependencies file.

And using pythonfmu3 deploy, end users will be able to update their local Python environment. The steps to achieve that:

  1. Install pythonfmu package: pip install pythonfmu3
  2. Be sure to be in the Python environment to be updated. Then execute pythonfmu3 deploy -f my.fmu
usage: pythonfmu3 deploy [-h] -f FMU [-e ENVIRONMENT] [{pip,conda}]

Deploy a Python FMU. The command will look in the `resources` folder for one of the following files:
`requirements.txt` or `environment.yml`. If you specify a environment file but no package manager, `conda` will be selected for `.yaml` and `.yml` otherwise `pip` will be used. The tool assume the Python environment in which the FMU should be executed is the current one.

positional arguments:
  {pip,conda}           Python packages manager

optional arguments:
  -h, --help            show this help message and exit
  -f FMU, --file FMU    Path to the Python FMU.
  -e ENVIRONMENT, --env ENVIRONMENT
                        Requirements or environment file.

Cosimulation Example:

Write the script

from pythonfmu3 import Fmi3Causality, Fmi3Slave, Boolean, Int32, Float64, String


class PythonSlave(Fmi3Slave):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.author = "John Doe"
        self.description = "A simple description"

        # Create attributes before registering them: register_variable only adds a setter
        # (needed for inputs and parameters) for attributes that already exist.
        self.time = 0.0
        self.intOut = 1
        self.realOut = 3.0
        self.booleanVariable = True
        self.stringVariable = "Hello World!"
        self.register_variable(Float64("time", causality=Fmi3Causality.independent))
        self.register_variable(Int32("intOut", causality=Fmi3Causality.output))
        self.register_variable(Float64("realOut", causality=Fmi3Causality.output))
        self.register_variable(Boolean("booleanVariable", causality=Fmi3Causality.local))
        self.register_variable(String("stringVariable", causality=Fmi3Causality.local))
        
        # Note:
        # it is also possible to explicitly define getters and setters as lambdas in case the variable is not backed by a Python field.
        # self.register_variable(Float64("myReal", causality=Fmi3Causality.output, getter=lambda: self.realOut, setter=lambda v: set_real_out(v))

    def do_step(self, current_time, step_size):
        return True

Create the FMU

pythonfmu3 build -f pythonslave.py myproject

In this example a python class named PythonSlave that extends Fmi3Slave is declared in a file named pythonslave.py, where myproject is an optional folder containing additional project files required by the python script. Project folders such as this will be recursively copied into the FMU. Multiple project files/folders may be added.

Model Exchange Example

To create a model exchange FMU you must inherit from Fmi3SlaveBase and one of (or both) mixin classes ModelExchange or CoSimulation.

Write the script

from pythonfmu3 import Fmi3Causality, Fmi3Initial, Fmi3SlaveBase, Fmi3Variability, Float64, ModelExchange
from typing import List


class PythonSlaveMX(Fmi3SlaveBase, ModelExchange):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.author = "John Doe"
        self.description = "A simple description"

        self.time = 0.0
        self.mu = 1.0
        self.x0 = 2
        self.x1 = 0
        self.derx0 = 0.0
        self.derx1 = 0.0

        self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous))
        self.register_variable(Float64("x0", causality=Fmi3Causality.output, start=2, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact))
        self.register_variable(Float64("x1", causality=Fmi3Causality.output, start=0, variability=Fmi3Variability.continuous, initial=Fmi3Initial.exact))
        self.register_variable(Float64("derx0", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=1))
        self.register_variable(Float64("derx1", causality=Fmi3Causality.local, variability=Fmi3Variability.continuous, derivative=2))
        self.register_variable(Float64("mu", causality=Fmi3Causality.parameter, variability=Fmi3Variability.fixed))


    def get_continuous_state_derivatives(self) -> List[float]:
        self.derx0 = self.x1
        self.derx1 = self.mu * ((1 - self.x0**2) * self.x1) - self.x0
        return [self.derx0, self.derx1]
        

Note: Model Exchange classes must define a self.time member. Derivative variables give the value reference of their state with derivative=; value references are assigned in registration order starting at 0 (here time = 0, x0 = 1, x1 = 2).

Create the FMU

pythonfmu3 build -f pythonslaveMX.py

Metadata

Release files for pythonfmu3 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pythonfmu3 1.0.0
File Size Uploaded Provenance Actions
pythonfmu3-1.0.0.tar.gz 408.4 kB Without provenance Details for pythonfmu3-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pythonfmu3 1.0.0
File Interpreter ABI Platform Actions
pythonfmu3-1.0.0-py3-none-any.whl Python 3 none any Details for pythonfmu3-1.0.0-py3-none-any.whl

Total release size: 832.9 kB

Release files / pythonfmu3-1.0.0.tar.gz

Download URL pythonfmu3-1.0.0.tar.gz
Size 408.4 kB
Tags Source
SHA-256 checksum
How to use checksums
1bffb4278ba259d4575ca1c93df71d1db4a386ac096647da3dae2b9d450172cd
BLAKE2b-256 checksum
How to use checksums
c0b085e16d63ab03ef1c5526e17f12adf4994615adec0aa1df82bbec01b3ca0e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Release files / pythonfmu3-1.0.0-py3-none-any.whl

Download URL pythonfmu3-1.0.0-py3-none-any.whl
Size 424.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7c66f42c621c81841b578a4135c416dd8adba2e7d6c8b40e25c1eca9a2b19f58
BLAKE2b-256 checksum
How to use checksums
39454a813bc8a23733f5007a626a1f93ce732e29d5a084e4846b8f3c3278fc66
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.15.2

Security for pythonfmu3 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page