Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,21 @@ 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,
Expand Down
7 changes: 7 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@
Cursor and other MCP clients can write, check, simulate and build FMUs, using the same
checks and simulators as the Studio. Install with `pip install "pythonfmu3[mcp]"`
(Python 3.10+). See [AI agents (MCP)](mcp.md).
- **Jupyter support** (`%load_ext pythonfmu3`): the `%%fmu` cell magic saves, checks and
displays a model; `simulate()` returns pandas DataFrames; `build()` builds the FMU; and
`pythonfmu3.notebook.FMU` inspects and simulates any FMU. Install with
`pip install "pythonfmu3[notebook]"`. See [Jupyter notebooks](notebooks.md) and
`examples/notebooks/getting_started.ipynb`.
- `llms.txt` and `llms-full.txt` on the documentation site, so AI assistants can learn the
PythonFMU3 API and its rules.

## 1.1.0 (2026-11-14)

Expand Down
82 changes: 82 additions & 0 deletions docs/llms.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# PythonFMU3

> PythonFMU3 packages a Python class as an FMI 3.0 FMU (Functional Mock-up Unit) that
> simulation tools such as FMPy, OMSimulator, fmusim and Simulink can import. It supports
> Co-Simulation and Model Exchange, Float64, Int32, Int64, UInt64, Boolean, String and
> Enumeration variables, NumPy arrays and structural parameters. Install with
> `pip install pythonfmu3`; build an FMU with `pythonfmu3 build -f model.py`.

A minimal Co-Simulation model:

```python
from pythonfmu3 import Fmi3Causality, Fmi3Slave, Fmi3Variability, Float64


class Gain(Fmi3Slave):

def __init__(self, **kwargs):
super().__init__(**kwargs)
self.author = "Jane Doe"
self.description = "Multiplies the input by a gain"

self.time = 0.0
self.u = 0.0
self.k = 2.0
self.y = 0.0

self.register_variable(Float64("time", causality=Fmi3Causality.independent,
variability=Fmi3Variability.continuous))
self.register_variable(Float64("u", causality=Fmi3Causality.input, start=0.0))
self.register_variable(Float64("k", causality=Fmi3Causality.parameter,
variability=Fmi3Variability.tunable, start=2.0))
self.register_variable(Float64("y", causality=Fmi3Causality.output))

def do_step(self, current_time, step_size):
self.y = self.k * self.u
self.time = current_time + step_size
return True
```

Rules that are easy to get wrong:

- Subclass `Fmi3Slave` for Co-Simulation, or `Fmi3SlaveBase` plus `ModelExchange` for Model
Exchange (add `CoSimulation` as well to support both). One model class per file.
- Always register a Float64 `time` variable (causality `independent`, variability
`continuous`) and keep `self.time` up to date.
- Create each attribute (`self.u = 0.0`) before `register_variable`, otherwise no setter is
created and importers can't set inputs or parameters.
- Only Float64 variables can be `continuous`. Int32, Boolean and the other types use
`discrete`, or `fixed`/`tunable` for parameters.
- Set `author`, `description`, `license`, `version` and `copyright` in `__init__`
(`self.author = ...`); class-level values are ignored.
- Variable names map to attributes; leading underscores are stripped, so don't start names
with `_`.
- Units: `register_units([Unit(name="m/s", m=1, s=-1)])`, then `unit="m/s"`.
- Model Exchange: register each state and its derivative (`derivative=<value reference of
the state>`, counting from 0 in registration order) and implement
`get_continuous_state_derivatives()`.
- The machine that runs the FMU needs Python with a shared library and the packages the
model imports. Pack a `requirements.txt` into the FMU
(`pythonfmu3 build -f model.py requirements.txt`) and install it on the target with
`pythonfmu3 deploy`.

## Docs

- [Installation](https://pythonfmu3.readthedocs.io/en/latest/install/): installing, the native library, running FMUs outside Python
- [Co-Simulation](https://pythonfmu3.readthedocs.io/en/latest/usage/): writing and building a Co-Simulation FMU
- [Model Exchange](https://pythonfmu3.readthedocs.io/en/latest/usageMX/): states, derivatives and events
- [Dependencies](https://pythonfmu3.readthedocs.io/en/latest/dependencies/): FMUs that use third-party packages
- [Studio](https://pythonfmu3.readthedocs.io/en/latest/studio/): `pythonfmu3 studio`, a local web app to edit, check, simulate and inspect models
- [Jupyter notebooks](https://pythonfmu3.readthedocs.io/en/latest/notebooks/): the `%%fmu` cell magic, simulations as pandas DataFrames, building and inspecting FMUs
- [AI agents (MCP)](https://pythonfmu3.readthedocs.io/en/latest/mcp/): `pythonfmu3 mcp`, an MCP server for Claude, GitHub Copilot and Cursor
- [All docs in one file](https://pythonfmu3.readthedocs.io/en/latest/llms-full.txt): every page above, as Markdown

## Examples

- [Examples folder](https://github.com/StephenSmith25/PythonFMU3/tree/HEAD/examples): Co-Simulation, Model Exchange, arrays, enumerations, events, and 1D pipe flow for conjugate heat transfer with a structural parameter
- [Web app](https://stephensmith25.github.io/pythonfmu3-app/): try PythonFMU3 in the browser

## Optional

- [Migrating from PythonFMU](https://pythonfmu3.readthedocs.io/en/latest/migration/): moving FMI 2.0 PythonFMU models to PythonFMU3
- [Changelog](https://pythonfmu3.readthedocs.io/en/latest/changelog/)
118 changes: 118 additions & 0 deletions docs/notebooks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# Jupyter notebooks

Write a model in a notebook cell, check it, simulate it, run parameter studies and build
the FMU without leaving Jupyter. It works in JupyterLab, the classic notebook, VS Code and
Google Colab.

[Open the example notebook in Colab](https://colab.research.google.com/github/StephenSmith25/PythonFMU3/blob/master/examples/notebooks/getting_started.ipynb)

## Install

```bash
pip install "pythonfmu3[notebook]"
```

This adds pandas and Matplotlib, for results and plots.

## Write a model in a cell

Load the extension once per notebook, then start a cell with `%%fmu`:

```ipython
%load_ext pythonfmu3
```

```ipython
%%fmu
class Tank(Fmi3Slave):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.time = 0.0
self.q_in = 0.2
self.level = 1.0
self.register_variable(Float64("time", causality=Fmi3Causality.independent,
variability=Fmi3Variability.continuous))
self.register_variable(Float64("q_in", causality=Fmi3Causality.input, start=0.2))
self.register_variable(Float64("level", causality=Fmi3Causality.output))

def do_step(self, current_time, step_size):
self.level += self.q_in * step_size
self.time = current_time + step_size
return True
```

Running the cell:

- saves it as a model file, `tank.py` (named after the class), in the notebook's folder.
The `pythonfmu3` import is added if the cell doesn't have one;
- loads the model in a separate Python process and runs the same checks as
[PythonFMU3 Studio](studio.md);
- shows the FMU block (inputs, outputs and parameters), any problems, and a table of the
variables;
- binds the class name, `Tank`, to a model handle you use in the next cells.

Options: `%%fmu my_tank.py` chooses the file name, `--dir models` the folder, `--build`
also builds the FMU, and `--overwrite` replaces a file that wasn't written by `%%fmu`.
Files written by `%%fmu` start with a comment saying so; edit the cell, not the file.

## Simulate

```ipython
res = Tank.simulate(stop_time=100, start_values={"q_in": 0.4})
res.plot(y="level")
```

`simulate()` returns a pandas DataFrame indexed by time, with a column per output and
local variable (array elements as `name[1]`, `name[2]`, ...), so analysis and plotting work
as usual. Events are in `res.attrs["events"]`.

| Argument | Meaning |
| --- | --- |
| `stop_time` | End time (default 10) |
| `step_size` | Output interval (default `stop_time / 500`) |
| `start_values` | Values for parameters and inputs, e.g. `{"q_in": 0.4}`; unknown names are an error |
| `interface` | `"cs"` or `"me"`, for models that support both |
| `simulator` | `"python"` (default) runs the class directly; `"fmpy"` or `"fmusim"` build the FMU and run it in that importer |
| `outputs` | Only record these variables |

A parameter study is a loop:

```ipython
import pandas as pd

sweep = pd.DataFrame({f"q_in = {q}": Tank.simulate(stop_time=100, start_values={"q_in": q})["level"]
for q in (0.1, 0.2, 0.4)})
sweep.plot()
```

`Tank.ok`, `Tank.problems` and `Tank.variables` give the check results in code.

## Build the FMU

```ipython
fmu = Tank.build() # writes Tank.fmu next to tank.py; Tank.build("out") for another folder
fmu # shows the FMU: interfaces, platforms, variables
fmu.simulate(stop_time=100) # runs the FMU itself, in FMPy or fmusim
fmu.validate() # fmusim validation if installed, otherwise archive checks
```

## Models in files, and any FMU

`Model` works with any model file, and `FMU` with any FMI 2.0 or 3.0 FMU from any tool:

```ipython
from pythonfmu3.notebook import FMU, Model

Model("controller.py") # checks and shows it, like %%fmu
FMU("supplier_model.fmu") # inspects it; the FMU is only read
```

## Notes

- Each check and simulation runs in a fresh Python process, so re-running a cell always
uses the current code, and an error in a model can't crash the notebook.
- Error line numbers refer to the saved file, which has one extra line at the top (the
`%%fmu` comment, and the import if one was added).
- Building FMUs needs PythonFMU3's native library for your platform, as for any FMU
build. The PyPI packages include it for Windows and Linux x86_64, so Colab works out of
the box.
35 changes: 35 additions & 0 deletions docs_hooks/llms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""MkDocs hook: write llms-full.txt, every page in the nav as one Markdown file for AI tools.

docs/llms.txt (the index) is copied to the site like any other file.
"""
from pathlib import Path


def _pages(nav):
for item in nav or []:
if isinstance(item, dict):
for title, value in item.items():
if isinstance(value, str):
yield title, value
else:
yield from _pages(value)
elif isinstance(item, str):
yield None, item


def build_llms_full(docs_dir, nav, site_url=""):
docs_dir = Path(docs_dir)
parts = ["# PythonFMU3 documentation\n\n"
"All pages of the PythonFMU3 docs in one file. The index is llms.txt.\n"]
for title, page in _pages(nav):
source = docs_dir / page
if not source.is_file() or source.suffix != ".md":
continue
url = site_url.rstrip("/") + "/" + ("" if page == "index.md" else page[:-3] + "/") if site_url else page
parts.append(f"\n\n---\n\n<!-- {title or page}: {url} -->\n\n{source.read_text(encoding='utf-8').strip()}\n")
return "".join(parts)


def on_post_build(config, **kwargs):
text = build_llms_full(config["docs_dir"], config["nav"], config.get("site_url") or "")
Path(config["site_dir"], "llms-full.txt").write_text(text, encoding="utf-8")
Loading
Loading