Metadata-Version: 2.4
Name: pythonfmu3
Version: 1.3.0
Summary: A lightweight framework that enables the packaging of Python 3 code as FMI 3.0 co-simulation and model exchange FMUs.
Author: Stephen Smith
License-Expression: MIT
Project-URL: Homepage, https://github.com/StephenSmith25/PythonFMU3
Project-URL: Documentation, https://pythonfmu3.readthedocs.io/
Project-URL: Issues, https://github.com/StephenSmith25/PythonFMU3/issues
Keywords: FMI,FMI3,FMU,co-simulation,model exchange,simulation
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: End Users/Desktop
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Natural Language :: English
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: tests
Requires-Dist: pytest; extra == "tests"
Requires-Dist: fmpy; extra == "tests"
Provides-Extra: mcp
Requires-Dist: mcp>=1.2; python_version >= "3.10" and extra == "mcp"
Provides-Extra: notebook
Requires-Dist: pandas; extra == "notebook"
Requires-Dist: matplotlib; extra == "notebook"
Dynamic: license-file

# PythonFMU3

> Turn a Python class into an FMI 3.0 FMU that Simulink, OMSimulator, FMPy, `fmusim` and
> other simulation tools can import.

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![CI](https://github.com/StephenSmith25/PythonFMU3/workflows/CI/badge.svg)](https://github.com/StephenSmith25/PythonFMU3/actions?query=workflow%3ACI)
[![PyPI](https://img.shields.io/pypi/v/pythonfmu3)](https://pypi.org/project/pythonfmu3/)
[![Downloads](https://static.pepy.tech/badge/pythonfmu3)](https://pepy.tech/projects/pythonfmu3)
[![conda-forge](https://img.shields.io/conda/vn/conda-forge/pythonfmu3)](https://anaconda.org/conda-forge/pythonfmu3)
[![Read the Docs](https://readthedocs.org/projects/pythonfmu3/badge/?version=latest)](https://pythonfmu3.readthedocs.io/)
[![Listed on fmi-standard.org](https://img.shields.io/badge/FMI_tools-fmi--standard.org-2F5D8A)](https://fmi-standard.org/tools/)

**Try it in your browser, no install:** [PythonFMU3 Studio on the web](https://stephensmith25.github.io/pythonfmu3-app/)
lets you write a model, simulate it and download the FMU. It has an AI assistant that
writes and tests models for you, and you can share a model as a link.

### Highlights

- **Listed on the [FMI tools page](https://fmi-standard.org/tools/)** at fmi-standard.org.
- **Runs in any FMI 3.0 importer:** Python-based tools such as FMPy, and native tools such
  as Simulink, OMSimulator and `fmusim`.
- **Co-Simulation and Model Exchange**, with events, arrays, structural parameters, units,
  enumerations and FMU state.
- **[PythonFMU3 Studio](docs/studio.md):** `pythonfmu3 studio` opens a local app to write,
  check, simulate, build and inspect FMUs, with live plots and model templates. There is
  also a [web version](https://stephensmith25.github.io/pythonfmu3-app/).
- **[Jupyter notebooks](docs/notebooks.md):** write a model in a cell with `%%fmu`,
  simulate it into a pandas DataFrame, build the FMU.
- **[AI agents](docs/mcp.md):** `pythonfmu3 mcp` lets Claude, GitHub Copilot and Cursor
  write, check, simulate and build FMUs. The docs also publish
  [`llms.txt`](https://pythonfmu3.readthedocs.io/en/latest/llms.txt) so AI assistants
  get the API right.
- **[Examples](examples/README.md)** tested in FMPy and `fmusim`, including
  [1D pipe flow for conjugate heat transfer](examples/pipe_cht/).
- **Coming from PythonFMU (FMI 2.0)?** See the [migration guide](docs/migration.md).

See the [documentation](https://pythonfmu3.readthedocs.io/) for the full feature list and
current limitations, and the [changelog](docs/changelog.md) 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:

```bash
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](docs/install.md#running-fmus-outside-python-linux-and-macos)
for the full lookup order.

### PythonFMU3 Studio

`pythonfmu3 studio` opens a local web app to write, check, simulate, build and inspect
FMUs, with live plots, a model-description preview, an FMU inspector and templates. It
needs no extra dependencies. See the [Studio docs](docs/studio.md).

![PythonFMU3 Studio](docs/assets/studio-simulate.png)

### Jupyter notebooks

Write a model in a notebook cell with `%%fmu`, check it, simulate it into a pandas
DataFrame and build the FMU:

```ipython
%load_ext pythonfmu3
# %%fmu cell with your class, then:
res = Tank.simulate(stop_time=100)
fmu = Tank.build()
```

See [Jupyter notebooks](docs/notebooks.md) and the
[example notebook](examples/notebooks/getting_started.ipynb), which also runs in Google Colab.

### AI agents (MCP)

`pythonfmu3 mcp` lets AI agents (Claude, GitHub Copilot in VS Code, Cursor, ...) write,
check, simulate and build FMUs for you:

```bash
pip install "pythonfmu3[mcp]"
claude mcp add pythonfmu3 -- pythonfmu3 mcp ~/fmu-models
```

Then ask, for example: "Make me a bouncing ball FMU and simulate it for 5 s." See
[AI agents (MCP)](docs/mcp.md).

### How do I build an FMU from python code?

1. Install `pythonfmu3` package:

```bash
pip install pythonfmu3
```

2. Create a class extending `Fmi3Slave` (see below for an example).
   Keep a single FMU class per script.
3. 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.
PythonFMU3 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 the `pythonfmu3` package: `pip install pythonfmu3`
2. Create a class extending `Fmi3Slave` (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 the `pythonfmu3` 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

```python

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

```python

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
```

### Credits

PythonFMU3 is a fork of [PythonFMU](https://github.com/NTNU-IHB/PythonFMU), which
supports FMI 2.0, extended to FMI 3.0. Many thanks to the PythonFMU authors for the
foundation this project is built on.
