diff --git a/README.md b/README.md index 7eccbe4..7805464 100644 --- a/README.md +++ b/README.md @@ -1,29 +1,43 @@ # PythonFMU3 -> A lightweight framework that enables the packaging of Python 3 code as FMUs (following FMI version 3.0). +> 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) -[![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/StephenSmith25/PythonFMU3/issues) - [![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/) - -**Try it in your browser, no install:** [PythonFMU3 Studio](https://stephensmith25.github.io/pythonfmu3-app/) -lets you write a model, simulate it and download the FMU, all in the browser. To run it on -your computer instead, use `pythonfmu3 studio` (see [the Studio docs](docs/studio.md)). - - -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](https://pythonfmu3.readthedocs.io/) for the full list of -supported features and current limitations, and the `examples` folder for more models. - -See the [changelog](docs/changelog.md) for what changed in each release. +[![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? @@ -87,7 +101,7 @@ Then ask, for example: "Make me a bouncing ball FMU and simulate it for 5 s." Se pip install pythonfmu3 ``` -2. Create a new class extending the `Fmi3Slave` class declared in the `pythonfmu3.fmi3slave` module (see below for an example). +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. @@ -124,17 +138,17 @@ options: ### 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. +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 _pythonfmu_ package: `pip install pythonfmu3` -2. Create a new class extending the `Fmi3Slave` class declared in the `pythonfmu3.fmi3slave` module (see the examples below). +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 _pythonfmu_ package: `pip install pythonfmu3` +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` ``` @@ -255,3 +269,9 @@ registration order starting at 0 (here `time` = 0, `x0` = 1, `x1` = 2). ``` 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. diff --git a/docs/dependencies.md b/docs/dependencies.md index 8837ebb..edb144c 100644 --- a/docs/dependencies.md +++ b/docs/dependencies.md @@ -1,43 +1,55 @@ -## FMU Dependencies +# 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: +PythonFMU3 doesn't package a Python environment inside the FMU. The FMU runs in a +Python installation on the machine that simulates it, so that Python needs the packages +your model imports (NumPy, SciPy, a machine-learning library, ...). -1. Install _pythonfmu3_ package: `pip install pythonfmu3` -2. Create a new class extending the `Fmi3Slave` class declared in the `pythonfmu3.fmi3slave` module (see the [Co-simulation examples](usage.md)). -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. +## Shipping your requirements with the FMU -And using `pythonfmu3 deploy`, end users will be able to update their local Python environment. The steps to achieve that: - -1. Install _pythonfmu3_ package: `pip install pythonfmu3` -2. Be sure to be in the Python environment to be updated. Then execute `pythonfmu3 deploy -f my.fmu` +**1. List the packages** in a `requirements.txt` (for pip) or an `environment.yml` (for +conda): +```text +numpy>=1.24 +scipy ``` -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. +**2. Pass the file to `pythonfmu3 build`** after the script. It is packed into the FMU's +`resources/` folder: + +```bash +pythonfmu3 build -f my_model.py requirements.txt +``` -positional arguments: - {pip,conda} Python packages manager +**3. On the machine that runs the FMU,** activate the Python environment the FMU will use +(see below) and install the packages from the FMU: -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. +```bash +pythonfmu3 deploy -f MyModel.fmu ``` -### Which Python environment does the FMU use? +`deploy` finds `requirements.txt` or `environment.yml` in the FMU and installs it with pip +or conda. Choose the tool explicitly with `pythonfmu3 deploy -f MyModel.fmu pip` (or +`conda`), or name a different file inside the FMU with `-e`. + +The machine running the FMU needs PythonFMU3 installed only if you use `deploy`: the FMU +itself carries its own copy of the `pythonfmu3` package. -- **Python-based importer** (e.g. FMPy): the interpreter running the importer, with its - packages. Run `pythonfmu3 deploy` in that same environment. -- **Native importer on Linux/macOS** (OMSimulator, `fmusim`, Simulink, ...): the Python +## Which Python environment does the FMU use? + +- **Python-based importer** (FMPy, for example): the interpreter running the importer, + with its packages. Run `pythonfmu3 deploy` in that same environment. +- **Native importer on Linux or macOS** (OMSimulator, `fmusim`, Simulink, ...): the Python whose `libpython` the FMU loads (see [Running FMUs outside Python](install.md#running-fmus-outside-python-linux-and-macos)). That is a base installation, not a virtual environment: packages installed only in a - venv are not found unless you add its `site-packages` folder to `PYTHONPATH`, e.g. + venv aren't found unless you add its `site-packages` folder to `PYTHONPATH`, for example `export PYTHONPATH=/path/to/venv/lib/python3.12/site-packages`. -- **Windows**: the Python providing the `python3.dll` found on the `PATH`. +- **Windows:** the Python that provides the `python3.dll` found on the `PATH`. + +## Keeping dependencies light + +Every package a model imports has to be installed wherever the FMU runs, so the fewer the +better. The standard library and NumPy cover most models. For a trained machine-learning +model, consider exporting its weights and evaluating them with NumPy, rather than +requiring the full framework on every machine that runs the FMU. diff --git a/docs/index.md b/docs/index.md index 9fab301..36cb86d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -11,155 +11,162 @@ ## Overview -PythonFMU3 bridges the gap between Python's rich ecosystem and the Functional Mock-up Interface (FMI) 3.0 standard, enabling seamless integration of Python models into multi-domain simulation environments. Whether you're developing control systems, signal processing algorithms, or complex system models, PythonFMU3 makes it easy to package your Python code as industry-standard FMUs. +PythonFMU3 turns a Python class into an FMI 3.0 FMU (Functional Mock-up Unit): a +standard package that simulation tools such as Simulink, OMSimulator, FMPy and +`fmusim` can import and run alongside their own models. Write the model in Python, with +any packages you like, and PythonFMU3 builds the FMU around it. -### Key Features +Typical uses: -- **🔄 Dual FMU Support**: Create both Co-simulation and Model Exchange FMUs -- **🐍 Pure Python**: Write your models in familiar Python syntax -- **📦 Easy Packaging**: Simple CLI tool to build FMUs from Python scripts -- **🔧 Variable Types**: Float64, Int32, Int64, UInt64, Boolean, String and Enumeration, plus NumPy arrays of the numeric types -- **⚡ Native FMU binaries**: a C++ FMI 3.0 implementation that runs your Python code in an embedded interpreter -- **🌐 Cross-Platform**: prebuilt for Windows (x86_64) and Linux (x86_64); macOS and ARM build from source -- **📊 NumPy Integration**: Native support for array operations and scientific computing -- **🎛️ Parameter Management**: Configurable parameters with units and constraints -- **🔍 Debugging Support**: Built-in logging and error handling +- **Controllers and logic:** PID loops, state machines, supervisory control. +- **Models that are easier to write in Python:** data-driven or machine-learning models, + models that call scientific libraries, quick prototypes of physics. +- **Signal processing and test inputs:** filters, signal generators, data playback. -### Use Cases +## Quick start -**Control Systems** -- PID controllers, state machines, and adaptive control algorithms -- Integration with Simulink, OpenModelica, or other simulation tools - -**Signal Processing** -- Digital filters, signal generators, and data analysis algorithms -- Real-time processing in co-simulation environments - -**Machine Learning** -- Deploy trained models as FMUs for system-level simulation -- Integration of AI/ML components in engineering workflows - -**System Modeling** -- Battery models, thermal systems, and multi-physics simulations -- Rapid prototyping of mathematical models - -## Quick Start - -### Installation ```bash pip install pythonfmu3 ``` -### Create Your First FMU +**1. Write the model** in a file, `my_model.py`: -**1. Write a Python model:** ```python -from pythonfmu3 import Fmi3Slave, Fmi3Causality, Float64 +from pythonfmu3 import Fmi3Causality, Fmi3Slave, Fmi3Variability, Float64 + class MyModel(Fmi3Slave): + def __init__(self, **kwargs): super().__init__(**kwargs) - - # Create the attributes first: register_variable only adds a setter - # (needed for inputs and parameters) for attributes that already exist + self.description = "Doubles its input" + + # 1. Create every attribute first... + self.time = 0.0 self.input = 0.0 self.output = 0.0 - # Register variables + # 2. ...then register it as an FMU variable (the name is the attribute name) + self.register_variable(Float64("time", causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous)) self.register_variable(Float64("input", causality=Fmi3Causality.input, start=0.0)) self.register_variable(Float64("output", causality=Fmi3Causality.output)) - + def do_step(self, current_time, step_size): - # Your model logic here + # Called by the importer to advance the model from current_time by step_size self.output = 2.0 * self.input + self.time = current_time + step_size return True ``` +Two rules catch most first-time problems: + +- **Register a `time` variable** (causality `independent`) and keep `self.time` up to + date. FMI 3.0 expects every FMU to declare its independent variable. +- **Create each attribute before registering it.** `register_variable` only creates a + setter for attributes that already exist, and without a setter the importer can't set + your inputs and parameters. + **2. Build the FMU:** + ```bash -pythonfmu3 build -f my_model.py +pythonfmu3 build -f my_model.py # writes MyModel.fmu ``` -**3. Use in simulation:** +**3. Simulate it** in any FMI 3.0 importer, for example FMPy: + ```python import fmpy -result = fmpy.simulate_fmu('MyModel.fmu', stop_time=10.0) +result = fmpy.simulate_fmu("MyModel.fmu", stop_time=10.0, start_values={"input": 1.5}) ``` -The FMU also runs in native FMI 3.0 importers such as OMSimulator, `fmusim` or Simulink. -The simulating machine needs Python 3 with a shared Python library and your model's -packages; see [Running FMUs outside Python](install.md#running-fmus-outside-python-linux-and-macos). - -## Architecture - -An FMU built by PythonFMU3 contains your script, a copy of the `pythonfmu3` package and a -native library implementing the FMI 3.0 C API: - -- **C++ wrapper**: implements the FMI functions and forwards each call to your Python - class (`do_step`, the variable getters and setters, ...) -- **Python interpreter**: the host's interpreter when the importer is itself Python (e.g. - FMPy), otherwise one started inside the simulation process. Your model's packages must - be installed in that Python; see [Dependencies](dependencies.md) -- **Python loader (Linux/macOS)**: the FMU's library has no link-time dependency on - Python, and loads `libpython` on first instantiation when the host has none, so native - (non-Python) importers can load the FMU - -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. - -## What's Supported - -### FMI 3.0 Features -- ✅ **Co-simulation FMUs** with `do_step()` method -- ✅ **Model Exchange FMUs** with derivative functions -- ✅ **Variable types**: Float64, Int32, Int64, UInt64, Boolean, String, Enumeration -- ✅ **Array variables** (NumPy) of the numeric and Boolean types, with fixed sizes or - sizes given by a structural parameter -- ✅ **Parameters** with fixed, tunable, and constant variability -- ✅ **Units** for physical quantities -- ✅ **Initial values** and causality declarations -- ✅ **Event indicators** and discrete state updates (Model Exchange) -- ✅ **Getting, setting and serializing FMU state** (opt-in with `--handle-state` and - `--serialize-state`; see the limitations below) -- ✅ **Logging**, with Python exceptions reported with their traceback - -### Advanced Capabilities -- ✅ **NumPy integration** for scientific computing -- ✅ **Custom getters/setters** for complex variable access -- ✅ **Nested variables** with structured naming -- ✅ **Resource management** for external files and dependencies -- ✅ **Runs in any FMI 3.0 importer**: Python-based (FMPy) and native (OMSimulator, - `fmusim`, Simulink, ...) -- ✅ **Memory-efficient** variable handling +The machine that runs the FMU needs Python 3 with a shared Python library, plus the +packages your model imports; see +[Running FMUs outside Python](install.md#running-fmus-outside-python-linux-and-macos) and +[Dependencies](dependencies.md). + +Prefer not to install anything yet? [Try PythonFMU3 in your browser](https://stephensmith25.github.io/pythonfmu3-app/): +the web version has the editor and simulator, an AI assistant that writes and tests models, +and shareable links. + +## How it works + +An FMU built by PythonFMU3 is a zip file containing: + +- **your script** and a copy of the `pythonfmu3` package, in `resources/`; +- **`modelDescription.xml`**, generated from the variables you registered; +- **a native library** for each platform, implementing the FMI 3.0 C API. It starts (or + reuses) a Python interpreter and forwards every FMI call to your class: `fmi3DoStep` + calls `do_step`, `fmi3GetFloat64` reads your attributes, and so on. + +When the importer is itself Python (FMPy, for example), the FMU uses that interpreter. +Otherwise (Simulink, OMSimulator, `fmusim`, ...) the FMU loads a Python installation +itself; on Linux and macOS it looks for `libpython` in several places, and you can point it +at a specific one with `PYTHONFMU_PYTHON_LIBRARY`. + +PythonFMU3 is listed on the [FMI tools page](https://fmi-standard.org/tools/). + +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. Moving a PythonFMU +model across? See [Migrating from PythonFMU](migration.md). + +## What's supported + +**Interfaces:** Co-Simulation (you implement `do_step`) and Model Exchange (you provide +derivatives and the importer's solver integrates them), or both in one FMU. + +**Variables:** + +- Float64, Int32, Int64, UInt64, Boolean, String and Enumeration; +- NumPy arrays of the numeric and Boolean types, with fixed sizes or sizes set by a + structural parameter; +- every causality (parameter, calculated parameter, structural parameter, input, output, + local, independent) and variability; units; start values and `initial`; custom getters + and setters; structured names such as `ball.h`. + +**Behaviour:** + +- events in Model Exchange: event indicators and discrete-state updates; +- step results in Co-Simulation (`Fmi3StepResult`: discard a step, ask to terminate); +- getting, setting and serializing FMU state, opt-in with the `--handle-state` and + `--serialize-state` build options; +- logging to the importer, with Python exceptions reported with their traceback; +- extra files (data, trained models, `requirements.txt`) packed into the FMU. + +**Tools around it:** [PythonFMU3 Studio](studio.md) (a local app, plus a +[web version](https://stephensmith25.github.io/pythonfmu3-app/) with an AI assistant), +[Jupyter notebooks](notebooks.md), and an [MCP server for AI agents](mcp.md). ### Limitations -- ⚠️ **Variable types** Float32, Int8, Int16, UInt8, UInt16, UInt32, Binary and Clock are not - supported, nor are String arrays -- ⚠️ **Scheduled Execution** is not supported, and Co-simulation ignores Event Mode and - early return -- ⚠️ **Directional and adjoint derivatives** are not available -- ⚠️ **Array sizes** are fixed once the FMU is instantiated: changing a structural - parameter in Configuration Mode does not resize arrays -- ⚠️ **FMU state** only covers registered variables, and serialization uses JSON (no NumPy - arrays). Override `_get_fmu_state`/`_set_fmu_state` if your model has other internal state -- ⚠️ **Prebuilt binaries** exist for Windows x86_64 and Linux x86_64 only; on macOS and ARM, - build the wrapper from source (see [Installation](install.md)) - -## Examples and Documentation - -Explore comprehensive examples and documentation: - -- **[Co-simulation Examples](usage.md)**: PID controller, units, arrays, step results -- **[Model Exchange Examples](usageMX.md)**: Van der Pol oscillator, bouncing ball with events -- **[PythonFMU3 Studio](studio.md)**: the `pythonfmu3 studio` web app for editing, simulating and inspecting FMUs -- **[Installation Guide](install.md)**: installing, building from source, and running FMUs - outside Python -- **[Dependencies](dependencies.md)**: third-party packages and which Python an FMU uses -- **[Changelog](changelog.md)** - -## Community and Support - -- 🐛 **Bug Reports**: [GitHub Issues](https://github.com/StephenSmith25/PythonFMU3/issues) -- 💡 **Feature Requests**: [GitHub Issues](https://github.com/StephenSmith25/PythonFMU3/issues) -- 📖 **Documentation**: [Read the Docs](https://pythonfmu3.readthedocs.io/) -- 📦 **PyPI Package**: [pythonfmu3](https://pypi.org/project/pythonfmu3/) + +- **Variable types:** Float32, Int8, Int16, UInt8, UInt16, UInt32, Binary and Clock aren't + supported, nor are String arrays. +- **Co-Simulation:** Event Mode and early return aren't supported yet, nor is Scheduled + Execution. +- **Directional and adjoint derivatives** aren't available. +- **Arrays sized by a structural parameter** aren't resized automatically when the + parameter changes in Configuration Mode. Make the parameter a property whose setter + reallocates the arrays, as in the + [pipe CHT example](https://github.com/StephenSmith25/PythonFMU3/tree/HEAD/examples/pipe_cht). +- **FMU state** covers registered variables only, and serialization uses JSON (no NumPy + arrays). Override `_get_fmu_state` and `_set_fmu_state` if your model has other + internal state. +- **Prebuilt binaries** are included for Windows x86_64 and Linux x86_64. On macOS and ARM + Linux, build the native library from source (see [Installation](install.md)). +- **Python is needed on the machine that runs the FMU.** + +## Where next + +- [Installation](install.md): installing, building from source, and running FMUs outside Python +- [Co-Simulation](usage.md): variables explained, the FMU lifecycle, a PID controller, arrays, building +- [Model Exchange](usageMX.md): states, derivatives and events +- [Dependencies](dependencies.md): third-party packages, and which Python an FMU uses +- [Studio](studio.md), [Jupyter notebooks](notebooks.md) and [AI agents (MCP)](mcp.md) +- [Examples](https://github.com/StephenSmith25/PythonFMU3/tree/HEAD/examples), and the tools each was tested with +- [Changelog](changelog.md) + +## Community and support + +- Bugs and feature requests: [GitHub Issues](https://github.com/StephenSmith25/PythonFMU3/issues) +- Package: [pythonfmu3 on PyPI](https://pypi.org/project/pythonfmu3/) diff --git a/docs/install.md b/docs/install.md index e539a76..8b448a1 100644 --- a/docs/install.md +++ b/docs/install.md @@ -1,39 +1,45 @@ -# Install +# Installation -The package can be installed using pip: +## Which install do you need? -```bash -pip install pythonfmu3 -``` +| Your computer | Install | +| --- | --- | +| Windows x86_64, Linux x86_64 | `pip install pythonfmu3`. Ready to build FMUs. | +| macOS (Apple Silicon or Intel), ARM Linux | `pip install pythonfmu3`, then build the native library once (below). Until you do, everything except building runnable FMUs works: built FMUs contain no binaries. | +| Developing PythonFMU3 itself | Install from source (below). | -Alternatively, the project can installed from source. First clone the repo, -```bash -git clone https://github.com/StephenSmith25/PythonFMU3.git -``` +PythonFMU3 needs Python 3.9 or later. Optional extras add the +[Jupyter support](notebooks.md) (`pip install "pythonfmu3[notebook]"`) and the +[MCP server for AI agents](mcp.md) (`pip install "pythonfmu3[mcp]"`, Python 3.10+). + +Check the installation with `pythonfmu3 --version`. -Next build the C++ wrapper. You need CMake (3.10 or later), a C++17 compiler and the -Python development headers (e.g. `python3-dev` on Debian/Ubuntu). The library is written -to `pythonfmu3/resources/binaries//`. +## Installing from source, or building the native library + +Every FMU contains a small native library that implements the FMI 3.0 C API and runs your +Python code. The PyPI packages include it for Windows x86_64 and Linux x86_64; on other +platforms, build it with CMake (3.10 or later), a C++17 compiler and the Python +development headers (`python3-dev` on Debian/Ubuntu; included with Homebrew and +python.org Python on macOS): ```bash +git clone https://github.com/StephenSmith25/PythonFMU3.git cd PythonFMU3 cmake -S pythonfmu3/pythonfmu-export -B build -DCMAKE_BUILD_TYPE=Release cmake --build build --config Release +pip install -e . # or: pip install . ``` -On Windows, add `-A x64` to the first command for a 64-bit build. Prebuilt libraries in the -PyPI package cover Windows x86_64 and Linux x86_64; on macOS (Intel or Apple Silicon) and -ARM Linux, install from source this way. -Next the python project may be installed with either, +On Windows, add `-A x64` to the first `cmake` command for a 64-bit build. The library is +written to `pythonfmu3/resources/binaries//`, for example `aarch64-darwin` on +Apple Silicon, and every FMU you build from then on includes it. -```bash -pip install -e . -``` -or, +If `pip install -e .` fails with "editable mode currently requires a setuptools-based +build", your pip is too old: run `python -m pip install --upgrade pip` first. -```bash -pip install . -``` +To check that an FMU has binaries, list its `binaries/` folder (`unzip -l MyModel.fmu`), +or open it in [PythonFMU3 Studio](studio.md)'s Inspector, which lists the platforms it +has binaries for. ## Running FMUs outside Python (Linux and macOS) diff --git a/docs/studio.md b/docs/studio.md index d0f07bc..b9add48 100644 --- a/docs/studio.md +++ b/docs/studio.md @@ -7,7 +7,8 @@ your computer. > **Try it without installing anything:** the > [web version](https://stephensmith25.github.io/pythonfmu3-app/) runs in your browser > using [Pyodide](https://pyodide.org). It has the editor, the Python preview, building -> and downloading FMUs, the Inspector and the templates. It can't run fmusim or FMPy, or +> and downloading FMUs, the Inspector and the templates, plus an AI assistant (with your +> own Anthropic API key) and shareable links to models. It can't run fmusim or FMPy, or > models that import packages Pyodide doesn't have, and it keeps your files in the browser > rather than in a folder. Source: > [StephenSmith25/pythonfmu3-app](https://github.com/StephenSmith25/pythonfmu3-app). diff --git a/docs/usage.md b/docs/usage.md index ea42ecc..86be384 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -1,50 +1,98 @@ -# Co-simulation Examples +# Co-Simulation -Co-simulation FMUs are self-contained simulation units that manage their own time stepping and internal solver. Unlike Model Exchange FMUs, Co-simulation FMUs encapsulate both the model equations and the numerical methods used to solve them. The master algorithm coordinates multiple FMUs by calling their `do_step()` method and exchanging input/output values. +A Co-Simulation FMU advances itself: the importer (the simulation tool that loads the +FMU) sets the inputs, asks the FMU to step forward with `do_step`, reads the outputs, and +exchanges them with the other models in the simulation. How the FMU gets from one +communication point to the next is up to you, which makes Co-Simulation the natural +choice for controllers, logic, and models with their own solver. -## Key Concepts +In Model Exchange, by contrast, the FMU only provides derivatives and the importer's +solver integrates them; see [Model Exchange](usageMX.md). -### Co-simulation vs Model Exchange -- **Co-simulation**: FMU manages its own time stepping with `do_step()` method -- **Model Exchange**: External solver manages time stepping and calls derivative functions +## Writing a model -### FMU Lifecycle -The typical Co-simulation FMU lifecycle follows this sequence: -1. **Instantiation**: Create FMU instance with `fmi3InstantiateCoSimulation()` -2. **Initialization**: Set parameters and inputs with `fmi3EnterInitializationMode()` -3. **Simulation**: Repeatedly call `fmi3DoStep()` to advance time -4. **Termination**: Clean up with `fmi3Terminate()` and `fmi3FreeInstance()` +Subclass `Fmi3Slave` and, in `__init__`, create your attributes and register the ones the +importer should see as variables. Then implement `do_step`: -### Required Methods -For Co-simulation FMUs, you must implement: -- `__init__()`: create the attributes, then register them as variables -- `do_step(current_time, step_size)`: advance the simulation by one step. Return `True` - (success), `False` (the step is discarded) or an `Fmi3StepResult` (see below) -- Optional: `enter_initialization_mode()`, `exit_initialization_mode()`, `terminate()` +- `do_step(current_time, step_size)` advances the model from `current_time` to + `current_time + step_size`. Return `True` for success, `False` to discard the step (the + importer may retry with a smaller step), or an `Fmi3StepResult` (see + [Step results](#step-results)). +- Update `self.time` at the end of the step. Create each attribute **before** registering it: `register_variable` only creates a -setter for attributes that already exist, and without a setter the importer cannot set -inputs or parameters. Alternatively pass `getter=` and `setter=` explicitly. +setter for attributes that already exist, and without a setter the importer can't set +inputs or parameters. If a value lives somewhere else, pass `getter=` and `setter=` +functions instead. -## Key Implementation Details +Set `self.author`, `self.description`, `self.license`, `self.version` and +`self.copyright` in `__init__`; they go into the model description. Keep one model class +per script. -### Variable Registration -Co-simulation FMUs support various variable types and causalities: +### What the importer calls, and what runs in your class + +| Importer calls | PythonFMU3 runs | Use it to | +| --- | --- | --- | +| `fmi3InstantiateCoSimulation` | `__init__(**kwargs)` | create attributes and register variables. `self.resources` is the FMU's resources folder, for data files | +| `fmi3Set...` / `fmi3Get...` | the variables' setters and getters (your attributes) | | +| `fmi3EnterInitializationMode` | `enter_initialization_mode()` | optional | +| `fmi3ExitInitializationMode` | `exit_initialization_mode()` | optional: compute values that depend on the parameters the importer set | +| `fmi3DoStep` | `do_step(current_time, step_size)` | advance the model | +| `fmi3Terminate` | `terminate()` | optional: close files, write results | + +Parameters are set before `fmi3ExitInitializationMode`, so anything derived from them +(array sizes, precomputed constants, initial outputs) belongs in +`exit_initialization_mode`, not in `__init__`, which runs before the importer has set +anything. + +## Variables explained + +Every variable has a type (`Float64`, `Int32`, `Int64`, `UInt64`, `Boolean`, `String`, +`Enumeration`), a **causality** (who sets it) and a **variability** (when it can change). + +| Causality | Meaning | Typical variability | +| --- | --- | --- | +| `input` | Set by the importer before each step, typically from another model's output | `continuous` (Float64) or `discrete` | +| `output` | Computed by your model, read by the importer | `continuous` (Float64) or `discrete` | +| `parameter` | A value the user sets before the simulation | `fixed` or `tunable` | +| `calculatedParameter` | Computed from parameters, constant during the simulation | `fixed` or `tunable` | +| `structuralParameter` | Changes the model's structure, such as array sizes; set in Configuration Mode | `fixed` or `tunable` | +| `local` | Internal, but visible to the importer for plotting and debugging | any | +| `independent` | Time. Exactly one, a `Float64` with variability `continuous` | `continuous` | + +| Variability | Can change | +| --- | --- | +| `constant` | Never | +| `fixed` | Only before the simulation starts (until `exit_initialization_mode`) | +| `tunable` | Between steps, when the importer sets it; typically used for parameters | +| `discrete` | Only at steps or events. The default for Int32, Boolean, String and the other non-Float64 types | +| `continuous` | At any time. Only `Float64` variables can be continuous | + +Give inputs and parameters a `start` value: it is the value importers show and use +until they set their own. `initial` (`exact`, `approx` or `calculated`) says how a start +value is used; the defaults suit most models, and you only need it for Model Exchange +states (`initial=Fmi3Initial.exact`). ```python -# Input variables (set by master algorithm) -self.register_variable(Float64("input_signal", causality=Fmi3Causality.input, start=0.0)) +# An input, set by the importer before each step +self.register_variable(Float64("u", causality=Fmi3Causality.input, start=0.0)) -# Output variables (read by master algorithm) -self.register_variable(Float64("output_signal", causality=Fmi3Causality.output)) +# An output, computed by the model +self.register_variable(Float64("y", causality=Fmi3Causality.output)) -# Parameters (configurable, usually fixed during simulation) +# A parameter the user can change between steps self.register_variable(Float64("gain", causality=Fmi3Causality.parameter, - variability=Fmi3Variability.tunable, start=1.0)) + variability=Fmi3Variability.tunable, start=1.0)) + +# An integer mode switch: non-Float64 types are discrete (or fixed/tunable as parameters) +self.register_variable(Int32("mode", causality=Fmi3Causality.parameter, + variability=Fmi3Variability.fixed, start=0)) ``` +## Examples + ### PID Controller Example ```python from pythonfmu3 import Fmi3Causality, Fmi3Slave, Fmi3Variability, Float64 @@ -58,6 +106,8 @@ class PIDController(Fmi3Slave): self.author = "PythonFMU3 Team" self.description = "PID Controller" + self.time = 0.0 + # Inputs self.setpoint = 0.0 self.measurement = 0.0 @@ -76,6 +126,7 @@ class PIDController(Fmi3Slave): self.first_step = True # Register variables + self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) self.register_variable(Float64("setpoint", causality=Fmi3Causality.input, start=0.0)) self.register_variable(Float64("measurement", causality=Fmi3Causality.input, start=0.0)) self.register_variable(Float64("output", causality=Fmi3Causality.output)) @@ -107,6 +158,7 @@ class PIDController(Fmi3Slave): # Store error for next iteration self.previous_error = error + self.time = current_time + step_size return True ``` @@ -172,8 +224,15 @@ class LinearTransform(Fmi3Slave): return True ``` -Array sizes are taken from the dimensions when the FMU is instantiated. Changing a -structural parameter such as `m` in Configuration Mode does not resize the arrays. +Arrays are NumPy arrays of the declared size. A dimension is either a fixed size +(`Dimension(start="2")`) or the value reference of a structural parameter +(`Dimension(valueReference="1")`, here `m`), which tells importers where the size comes +from. + +PythonFMU3 doesn't resize your arrays when an importer changes a structural parameter in +Configuration Mode: make the parameter a Python property whose setter reallocates them. +The [1D pipe flow example](https://github.com/StephenSmith25/PythonFMU3/tree/HEAD/examples/pipe_cht) +does this for its number of segments `N`. ### Step results @@ -204,23 +263,38 @@ importer's logger. If `category` is omitted it is derived from the status importer enables debug logging. Exceptions raised in your code are reported with their Python traceback and make the call fail with `fmi3Fatal`. -### Create the FMU +## Building the FMU ```bash -pythonfmu3 build -f pythonslave.py myproject +pythonfmu3 build -f pid_controller.py # writes PIDController.fmu here +pythonfmu3 build -f pid_controller.py -d build # ...into build/ +pythonfmu3 build -f model.py lookup_table.csv data/ # with extra files and folders ``` -In this example a python class named `PythonSlave` that extends `Fmi3Slave` is declared in a file named `pythonslave.py` -(keep a single FMU class per script), -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. +The FMU is named after the class. Extra files and folders listed after the script are +copied into the FMU's `resources/` folder next to your script, so the model can open them +relative to its own file, or through `self.resources`. Pass a `requirements.txt` the same +way to ship your dependencies (see [Dependencies](dependencies.md)). + +Build options set capability flags in the model description: + +| Option | Effect | +| --- | --- | +| `--handle-state` | Importers may save and restore the FMU's state (`canGetAndSetFMUState`) | +| `--serialize-state` | ...and serialize it to bytes (`canSerializeFMUState`) | +| `--no-variable-step` | The FMU only handles a constant step size (`canHandleVariableCommunicationStepSize=false`) | +| `--only-one-per-process` | Importers may create only one instance per process | +| `--no-external-tool` | Sets `needsExecutionTool=false` | +| `--doc FOLDER` | Include a documentation folder | +| `--terminals FILE` | Include a `terminalsAndIcons.xml` | +| `-d DIR` | Where to write the FMU (default: the current folder) | ## Integration and Testing ### Using FMPy for Testing ```python -# Example of co-simulation setup +# Simulate the FMU with FMPy import fmpy from fmpy import simulate_fmu import matplotlib.pyplot as plt diff --git a/docs/usageMX.md b/docs/usageMX.md index 1c20e19..665740f 100644 --- a/docs/usageMX.md +++ b/docs/usageMX.md @@ -1,6 +1,6 @@ # Model Exchange Examples -Model Exchange FMUs are used for continuous-time simulation where an external solver integrates the system of differential equations. The FMU provides the derivative function and state information, while the master algorithm handles time stepping and numerical integration. +Model Exchange FMUs are used for continuous-time simulation where an external solver integrates the system of differential equations. The FMU provides the derivative function and state information, while the importer's solver handles time stepping and numerical integration. ## Key Concepts