diff --git a/README.md b/README.md index 295e8c7..7eccbe4 100644 --- a/README.md +++ b/README.md @@ -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, diff --git a/docs/changelog.md b/docs/changelog.md index 9ea5b61..315e524 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -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) diff --git a/docs/llms.txt b/docs/llms.txt new file mode 100644 index 0000000..5e9f3a0 --- /dev/null +++ b/docs/llms.txt @@ -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=`, 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/) diff --git a/docs/notebooks.md b/docs/notebooks.md new file mode 100644 index 0000000..4231f21 --- /dev/null +++ b/docs/notebooks.md @@ -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. diff --git a/docs_hooks/llms.py b/docs_hooks/llms.py new file mode 100644 index 0000000..0873e71 --- /dev/null +++ b/docs_hooks/llms.py @@ -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\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") diff --git a/examples/notebooks/getting_started.ipynb b/examples/notebooks/getting_started.ipynb new file mode 100644 index 0000000..5b21a9c --- /dev/null +++ b/examples/notebooks/getting_started.ipynb @@ -0,0 +1,189 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# PythonFMU3 in a notebook\n", + "\n", + "Write an FMI 3.0 model in a cell, check it, simulate it, explore its parameters and build the FMU, all without leaving the notebook.\n", + "\n", + "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/StephenSmith25/PythonFMU3/blob/master/examples/notebooks/getting_started.ipynb)" + ], + "id": "cell-0" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# In Google Colab (or a fresh environment), install PythonFMU3 first:\n", + "# %pip install -q \"pythonfmu3[notebook]\"\n", + "%load_ext pythonfmu3" + ], + "id": "cell-1" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Write a model\n", + "\n", + "A water tank: water flows in at `q_in` and drains through a valve, so the outflow grows with the square root of the level. The `%%fmu` cell saves the class as `tank.py`, checks it and shows the FMU block and its variables. The `pythonfmu3` import is added for you if the cell doesn't have one." + ], + "id": "cell-2" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%%fmu\n", + "import math\n", + "\n", + "\n", + "class Tank(Fmi3Slave):\n", + "\n", + " def __init__(self, **kwargs):\n", + " super().__init__(**kwargs)\n", + " self.author = \"PythonFMU3 notebook example\"\n", + " self.description = \"A tank draining through a valve\"\n", + "\n", + " self.time = 0.0\n", + " self.q_in = 0.05 # m3/s\n", + " self.area = 2.0 # m2\n", + " self.valve = 0.04 # m2.5/s, outflow = valve * sqrt(level)\n", + " self.level = 1.0 # m\n", + " self.q_out = self.valve * math.sqrt(self.level)\n", + "\n", + " self.register_units([Unit(name=\"m\", m=1), Unit(name=\"m2\", m=2), Unit(name=\"m3/s\", m=3, s=-1)])\n", + " self.register_variable(Float64(\"time\", causality=Fmi3Causality.independent,\n", + " variability=Fmi3Variability.continuous))\n", + " self.register_variable(Float64(\"q_in\", causality=Fmi3Causality.input, start=0.05, unit=\"m3/s\"))\n", + " self.register_variable(Float64(\"area\", causality=Fmi3Causality.parameter,\n", + " variability=Fmi3Variability.fixed, start=2.0, unit=\"m2\"))\n", + " self.register_variable(Float64(\"valve\", causality=Fmi3Causality.parameter,\n", + " variability=Fmi3Variability.tunable, start=0.04))\n", + " self.register_variable(Float64(\"level\", causality=Fmi3Causality.output, unit=\"m\"))\n", + " self.register_variable(Float64(\"q_out\", causality=Fmi3Causality.output, unit=\"m3/s\"))\n", + "\n", + " def do_step(self, current_time, step_size):\n", + " self.q_out = self.valve * math.sqrt(max(self.level, 0.0))\n", + " self.level = max(self.level + (self.q_in - self.q_out) / self.area * step_size, 0.0)\n", + " self.time = current_time + step_size\n", + " return True" + ], + "id": "cell-3" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Simulate\n", + "\n", + "`Tank` is now a model handle. `simulate()` runs the class directly and returns a pandas DataFrame indexed by time, so plotting and analysis work as usual." + ], + "id": "cell-4" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "res = Tank.simulate(stop_time=300, start_values={\"q_in\": 0.05})\n", + "res.plot(y=\"level\", ylabel=\"level [m]\", grid=True);" + ], + "id": "cell-5" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Explore a parameter\n", + "\n", + "Because results are DataFrames, a parameter study is a loop. The level settles where inflow equals outflow, at (q_in / valve)\u00b2." + ], + "id": "cell-6" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd\n", + "\n", + "sweep = pd.DataFrame({\n", + " f\"valve = {v}\": Tank.simulate(stop_time=1500, start_values={\"valve\": v})[\"level\"]\n", + " for v in (0.03, 0.04, 0.05, 0.07)\n", + "})\n", + "sweep.plot(ylabel=\"level [m]\", grid=True);" + ], + "id": "cell-7" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Build the FMU\n", + "\n", + "`build()` writes `Tank.fmu` and shows a summary of it: interfaces, platforms with binaries and variables. Any simulation tool that imports FMI 3.0 FMUs can use it." + ], + "id": "cell-8" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "fmu = Tank.build()\n", + "fmu" + ], + "id": "cell-9" + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To check the built FMU in an importer, simulate it with FMPy (`pip install fmpy`) or fmusim:\n", + "\n", + "```python\n", + "fmu.simulate(stop_time=300, start_values={\"q_in\": 0.05})\n", + "```\n", + "\n", + "## Inspect any FMU\n", + "\n", + "`FMU` works with any FMI 2.0 or 3.0 FMU, from any tool. It only reads the file." + ], + "id": "cell-10" + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from pythonfmu3.notebook import FMU\n", + "\n", + "FMU(\"Tank.fmu\")" + ], + "id": "cell-11" + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/mkdocs.yml b/mkdocs.yml index 2635469..0bf5952 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,4 +1,5 @@ site_name: pythonfmu3 +site_url: https://pythonfmu3.readthedocs.io/en/latest/ nav: - Home: index.md - Installation: install.md @@ -6,7 +7,10 @@ nav: - Model Exchange: usageMX.md - Dependencies: dependencies.md - Studio: studio.md + - Jupyter notebooks: notebooks.md - AI agents (MCP): mcp.md - Migrating from PythonFMU: migration.md - Changelog: changelog.md -theme: readthedocs \ No newline at end of file +theme: readthedocs +hooks: + - docs_hooks/llms.py diff --git a/pyproject.toml b/pyproject.toml index 7989b2d..1ff0587 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,8 @@ dependencies = [] tests = ["pytest", "fmpy"] # The MCP server for AI agents (`pythonfmu3 mcp`) mcp = ["mcp>=1.2; python_version >= '3.10'"] +# Jupyter support (%%fmu cell magic, results as DataFrames, plots) +notebook = ["pandas", "matplotlib"] [project.urls] Homepage = "https://github.com/StephenSmith25/PythonFMU3" diff --git a/pythonfmu3/__init__.py b/pythonfmu3/__init__.py index d5e7048..be78bd0 100644 --- a/pythonfmu3/__init__.py +++ b/pythonfmu3/__init__.py @@ -8,3 +8,9 @@ from .default_experiment import DefaultExperiment from .variable_types import Float64Type, EnumerationType from .unit import BaseUnit, Unit + + +def load_ipython_extension(ipython): + """``%load_ext pythonfmu3`` in Jupyter: adds the ``%%fmu`` cell magic (see pythonfmu3.notebook).""" + from .notebook import load_ipython_extension as load + load(ipython) diff --git a/pythonfmu3/notebook.py b/pythonfmu3/notebook.py new file mode 100644 index 0000000..975d86c --- /dev/null +++ b/pythonfmu3/notebook.py @@ -0,0 +1,347 @@ +"""PythonFMU3 in Jupyter notebooks. + + %load_ext pythonfmu3 + + %%fmu + class Tank(Fmi3Slave): + ... + +The ``%%fmu`` cell magic saves the cell as a model file, checks it and shows the FMU +block, its variables and any problems. The cell's class name is then bound to a +:class:`Model`, so you can carry on with ``Tank.simulate(...)`` and ``Tank.build()``. + +Outside the magic, use ``Model("tank.py")`` for a model file and ``FMU("Tank.fmu")`` for +any FMU. Model code runs in a separate Python process each time, as in PythonFMU3 Studio, +so re-running a cell always uses the current code. + +Simulation results are pandas DataFrames (``pip install "pythonfmu3[notebook]"``). +""" +import ast +import html +import re +import shlex +from pathlib import Path +from typing import Any, Dict, List, Optional + +MARKER = "# Written by the %%fmu cell magic: edit the notebook cell, not this file." +_STYLE_BOX = "font-family:system-ui,-apple-system,'Segoe UI',sans-serif;font-size:13px;line-height:1.4" +_LINE = "rgba(127,127,127,.35)" +_ACCENT = "#2F5D8A" +_GOLD = "#E8B11C" + + +def _worker(request: Dict[str, Any], cwd: Path) -> Dict[str, Any]: + from .studio.server import run_worker + return run_worker(request, cwd) + + +def _e(value: Any) -> str: + return html.escape("" if value is None else str(value)) + + +def _raise(response: Dict[str, Any], what: str): + detail = response.get("traceback") or response.get("error") or "unknown error" + raise RuntimeError(f"{what} failed:\n{detail}") + + +def _frame(result: Dict[str, Any]): + try: + import pandas as pd + except ImportError as exc: + raise ImportError('Simulation results are pandas DataFrames: pip install "pythonfmu3[notebook]"') from exc + frame = pd.DataFrame(result["series"], index=pd.Index(result["time"], name="time")) + frame.attrs.update(simulator=result.get("simulator"), interface=result.get("interface"), + events=result.get("events", [])) + return frame + + +def _table(headers: List[str], rows: List[List[str]], max_rows: int = 200) -> str: + cell = f"padding:4px 10px;border-bottom:1px solid {_LINE};text-align:left;vertical-align:top" + head = "".join(f'{_e(h)}' for h in headers) + body = "".join("" + "".join(f'{c}' for c in row) + "" for row in rows[:max_rows]) + more = f'

… and {len(rows) - max_rows} more

' if len(rows) > max_rows else "" + return (f'
' + f"{head}{body}
{more}") + + +def _block(name: str, interfaces: List[str], inputs: List[str], outputs: List[str], params: List[str]) -> str: + def port(label, side): + dot = f'' + text = f"{_e(label)}" + return f'
' + \ + (text + dot if side == "flex-end" else dot + text) + "
" + chips = "".join(f'{_e(p)}' for p in params[:12]) + if len(params) > 12: + chips += f' +{len(params) - 12} more' + kinds = " · ".join({"cs": "Co-Simulation", "me": "Model Exchange"}.get(i, i) for i in interfaces) + return f""" +
+
{chips}
+
+
{''.join(port(i, 'flex-end') for i in inputs[:16])}
+
+
{_e(name)}
+
{_e(kinds)}
+
+
{''.join(port(o, 'flex-start') for o in outputs[:16])}
+
+
""" + + +class Model: + """A PythonFMU3 model file: check it, simulate it and build it from a notebook.""" + + def __init__(self, path): + self.path = Path(path).resolve() + if not self.path.is_file(): + raise FileNotFoundError(self.path) + self.analysis: Optional[Dict[str, Any]] = None + self.error: Optional[Dict[str, Any]] = None + + # --- checks ------------------------------------------------------------------------ + + def check(self) -> "Model": + """Load the model in a fresh process and run PythonFMU3 Studio's checks.""" + r = _worker({"command": "analyze", "path": str(self.path)}, self.path.parent) + self.analysis, self.error = (r["result"], None) if r.get("ok") else (None, r) + self._checked_mtime = self.path.stat().st_mtime_ns + return self + + def _ensure_checked(self): + """Check the model if it hasn't been checked, or if the file changed since.""" + if getattr(self, "_checked_mtime", None) != self.path.stat().st_mtime_ns: + self.check() + + @property + def ok(self) -> bool: + """True when the model loads and the checks found no errors.""" + self._ensure_checked() + return self.analysis is not None and not any(c["level"] == "error" for c in self.analysis["checks"]) + + @property + def problems(self) -> List[str]: + """Errors and warnings from the checks, as text.""" + self._ensure_checked() + if self.error: + return [f"error: {self.error.get('error')}"] + return [f"{c['level']}: {c['title']}: {c['detail']}" for c in self.analysis["checks"] if c["level"] != "ok"] + + @property + def variables(self) -> List[Dict[str, Any]]: + """The registered variables (name, type, causality, variability, unit, start, ...).""" + self._ensure_checked() + return list(self.analysis["variables"]) if self.analysis else [] + + # --- simulation and build ---------------------------------------------------------- + + def simulate(self, stop_time: float = 10.0, step_size: Optional[float] = None, + start_values: Optional[Dict[str, Any]] = None, interface: Optional[str] = None, + simulator: str = "python", outputs: Optional[List[str]] = None): + """Simulate the model and return a pandas DataFrame indexed by time. + + ``simulator="python"`` runs the class directly (quick); ``"fmpy"`` or ``"fmusim"`` + build the FMU and run it in that importer. ``interface`` is ``"cs"`` or ``"me"`` for + models with both. Events are in ``result.attrs["events"]``. + """ + if stop_time <= 0: + raise ValueError("stop_time must be positive") + step = step_size if step_size and step_size > 0 else stop_time / 500 + known = {v["name"] for v in self.variables} + unknown = sorted(set(start_values or {}) - known) + if self.analysis and unknown: + raise ValueError(f"Unknown variable(s) {', '.join(unknown)}; the model has {', '.join(sorted(known))}") + request = {"command": "simulate", "path": str(self.path), "simulator": simulator, "interface": interface, + "stopTime": stop_time, "stepSize": step, "startValues": start_values or {}} + if outputs: + request["outputs"] = list(outputs) + r = _worker(request, self.path.parent) + if not r.get("ok"): + _raise(r, "Simulation") + if r.get("stdout"): + print(r["stdout"], end="") + return _frame(r["result"]) + + def build(self, dest=None) -> "FMU": + """Build the FMU (into ``dest``, default the model's folder) and return it.""" + request = {"command": "build", "path": str(self.path)} + request["dest"] = str(Path(dest).resolve()) if dest else str(self.path.parent) + r = _worker(request, self.path.parent) + if not r.get("ok"): + _raise(r, "Building the FMU") + return FMU(r["result"]["fmu"]) + + # --- display ----------------------------------------------------------------------- + + def __repr__(self): + self._ensure_checked() + if self.error: + return f"" + a = self.analysis + state = "no problems" if not self.problems else f"{len(self.problems)} problem(s)" + return f"" + + def _repr_html_(self): + self._ensure_checked() + head = f'
' + if self.error: + tb = self.error.get("traceback") or self.error.get("error") + return (head + f'
{_e(self.path.name)} doesn\'t load
' + f'
{_e(tb)}
') + a = self.analysis + vs = a["variables"] + by = lambda *cs: [v["name"] + (f" [{v['unit']}]" if v["unit"] else "") for v in vs if v["causality"] in cs] + parts = [head, _block(a["className"], a["interfaces"], by("input"), by("output"), + [f"{v['name']} = {v['start'] if v['start'] is not None else v['value']}" + for v in vs if v["causality"] in ("parameter", "structuralParameter")])] + issues = [c for c in a["checks"] if c["level"] != "ok"] + if issues: + colour = {"error": "#c0392b", "warning": "#b7791f"} + parts.append("".join(f'
' + f'{_e(c["level"])}: {_e(c["title"])}: {_e(c["detail"])}
' for c in issues)) + else: + parts.append('
✓ No problems found
') + rows = [[_e(v["vr"]), f"{_e(v['name'])}", _e(v["type"]), _e(v["causality"]), + _e(v["variability"]), _e(v["unit"]), _e(v["start"]), _e(v["description"])] for v in vs] + parts.append(f'
Variables ({len(vs)})' + + _table(["vr", "name", "type", "causality", "variability", "unit", "start", "description"], rows) + + "
") + parts.append(f'
{_e(self.path)}
') + return "".join(parts) + + +class FMU: + """Any FMU file (FMI 2.0 or 3.0, from any tool): inspect it, validate it, simulate it.""" + + def __init__(self, path): + self.path = Path(path).resolve() + if not self.path.is_file(): + raise FileNotFoundError(self.path) + from .studio.worker import inspect_fmu # only reads the archive, runs nothing + self.info: Dict[str, Any] = inspect_fmu({"path": str(self.path)}) + + @property + def variables(self) -> List[Dict[str, Any]]: + return list(self.info["variables"]) + + def simulate(self, stop_time: float = 10.0, step_size: Optional[float] = None, + start_values: Optional[Dict[str, Any]] = None, interface: Optional[str] = None, + simulator: Optional[str] = None): + """Simulate with FMPy or fmusim (``simulator``; default: whichever is installed) and + return a pandas DataFrame indexed by time.""" + if stop_time <= 0: + raise ValueError("stop_time must be positive") + step = step_size if step_size and step_size > 0 else stop_time / 500 + r = _worker({"command": "simulate_fmu", "fmu": str(self.path), "simulator": simulator, "interface": interface, + "stopTime": stop_time, "stepSize": step, "startValues": start_values or {}}, self.path.parent) + if not r.get("ok"): + _raise(r, "Simulation") + return _frame(r["result"]) + + def validate(self) -> Dict[str, Any]: + """Validate with fmusim if installed, otherwise basic archive checks.""" + r = _worker({"command": "validate", "fmu": str(self.path)}, self.path.parent) + if not r.get("ok"): + _raise(r, "Validation") + return r["result"] + + def __repr__(self): + i = self.info + return (f"") + + def _repr_html_(self): + i = self.info + vs = i["variables"] + names = lambda c: [v["name"] + (f" [{v['unit']}]" if v.get("unit") else "") for v in vs if v["causality"] == c] + kinds = [{"CoSimulation": "cs", "ModelExchange": "me"}.get(k, k) for k in i["interfaces"]] + facts = [("File", f"{self.path.name} ({i['size'] / 1e6:.2f} MB)"), ("FMI version", i["fmiVersion"]), + ("Platforms", ", ".join(i["platforms"]) or "none (no binaries)"), + ("Generated by", i.get("generationTool")), ("Description", i.get("description"))] + rows = [[f"{_e(k)}", _e(v)] for k, v in facts if v] + params = [v["name"] + (f" = {v['start']}" if v.get("start") else "") for v in vs if v["causality"] == "parameter"] + parts = [f'
', _block(i["modelName"], kinds, names("input"), names("output"), params), + _table(["", ""], rows)] + for p in i["problems"]: + parts.append(f'
problem: {_e(p)}
') + vrows = [[_e(v["vr"]), f"{_e(v['name'])}", _e(v["type"]), _e(v["causality"]), + _e(v["variability"]), _e(v["unit"]), _e(v["start"])] for v in vs] + parts.append(f'
Variables ({len(vs)})' + + _table(["vr", "name", "type", "causality", "variability", "unit", "start"], vrows) + + "
") + return "".join(parts) + + +# --- the %%fmu cell magic ----------------------------------------------------------------- + +def _class_name(source: str) -> Optional[str]: + try: + tree = ast.parse(source) + except SyntaxError: + match = re.search(r"^class\s+(\w+)", source, re.MULTILINE) + return match.group(1) if match else None + names = [node.name for node in tree.body if isinstance(node, ast.ClassDef) + and any("Fmi3Slave" in ast.unparse(base) for base in node.bases)] + if not names: + names = [node.name for node in tree.body if isinstance(node, ast.ClassDef)] + return names[-1] if names else None + + +def _snake(name: str) -> str: + return re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).lower() + + +def fmu_cell(line: str, cell: str, namespace: Optional[Dict[str, Any]] = None) -> Model: + """Implementation of ``%%fmu [file.py] [--dir DIR] [--build] [--overwrite]``.""" + import argparse + + parser = argparse.ArgumentParser(prog="%%fmu", add_help=False) + parser.add_argument("file", nargs="?") + parser.add_argument("-d", "--dir", default=".") + parser.add_argument("-b", "--build", action="store_true") + parser.add_argument("--overwrite", action="store_true") + try: + args = parser.parse_args(shlex.split(line or "")) + except SystemExit: + raise ValueError("usage: %%fmu [file.py] [--dir DIR] [--build] [--overwrite]") from None + + class_name = _class_name(cell) + file_name = args.file or (f"{_snake(class_name)}.py" if class_name else None) + if not file_name: + raise ValueError("The cell has no model class; give a file name: %%fmu my_model.py") + if not file_name.endswith(".py"): + file_name += ".py" + path = (Path(args.dir) / file_name).resolve() + + # One header line, so line numbers in errors are the cell's line numbers plus one. + if re.search(r"^\s*(from|import)\s+pythonfmu3\b", cell, re.MULTILINE): + header = MARKER + else: + header = f"from pythonfmu3 import * {MARKER}" + source = f"{header}\n{cell.rstrip()}\n" + if path.exists() and not args.overwrite: + first = path.read_text(encoding="utf-8").split("\n", 1)[0] + if MARKER not in first: + raise FileExistsError(f"{path} exists and wasn't written by %%fmu; use --overwrite or another file name") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(source, encoding="utf-8") + + model = Model(path).check() + if namespace is not None and class_name: + namespace[class_name] = model + if args.build and model.ok: + try: + from IPython.display import display + except ImportError: # pragma: no cover - only used in IPython + display = print + display(model) + return model.build() + return model + + +def load_ipython_extension(ipython): + """Called by ``%load_ext pythonfmu3`` (or ``%load_ext pythonfmu3.notebook``).""" + def fmu(line, cell): + return fmu_cell(line, cell, ipython.user_ns) + fmu.__doc__ = fmu_cell.__doc__ + ipython.register_magic_function(fmu, magic_kind="cell", magic_name="fmu") diff --git a/pythonfmu3/studio/worker.py b/pythonfmu3/studio/worker.py index 93c81dc..b9279af 100644 --- a/pythonfmu3/studio/worker.py +++ b/pythonfmu3/studio/worker.py @@ -353,44 +353,68 @@ def find_fmusim() -> Optional[str]: return candidate if candidate and Path(candidate).exists() else None -def simulate_fmusim(req: Dict[str, Any]) -> Dict[str, Any]: +def _run_fmusim(fmu: str, req: Dict[str, Any], tmp: Path) -> Dict[str, Any]: fmusim = find_fmusim() if not fmusim: raise RuntimeError("fmusim was not found on PATH (or in PYTHONFMU3_FMUSIM)") - path = Path(req["path"]).resolve() - with tempfile.TemporaryDirectory(prefix="studio_") as tmp: - fmu = _build(path, Path(tmp))["fmu"] - out = Path(tmp) / "result.csv" - cmd = [fmusim, "simulate", fmu, "--stop-time", str(req["stopTime"]), - "--output-interval", str(req["stepSize"]), "--output-file", str(out)] - if req.get("interface"): - cmd += ["--interface-type", req["interface"]] - for name, value in (req.get("startValues") or {}).items(): - cmd += ["--start-value", f"{name}={value}"] - proc = subprocess.run(cmd, capture_output=True, text=True, timeout=300) - if proc.returncode != 0 or not out.exists(): - raise RuntimeError(f"fmusim failed:\n{proc.stdout}\n{proc.stderr}".strip()) - times, series = _read_csv(out) + out = Path(tmp) / "result.csv" + cmd = [fmusim, "simulate", str(fmu), "--stop-time", str(req["stopTime"]), + "--output-interval", str(req["stepSize"]), "--output-file", str(out)] + if req.get("interface"): + cmd += ["--interface-type", req["interface"]] + for name, value in (req.get("startValues") or {}).items(): + cmd += ["--start-value", f"{name}={value}"] + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=300) + if proc.returncode != 0 or not out.exists(): + raise RuntimeError(f"fmusim failed:\n{proc.stdout}\n{proc.stderr}".strip()) + times, series = _read_csv(out) return {"interface": req.get("interface"), "time": times, "series": series, "events": [], "simulator": "fmusim", "log": proc.stderr[-4000:]} -def simulate_fmpy(req: Dict[str, Any]) -> Dict[str, Any]: +def _run_fmpy(fmu: str, req: Dict[str, Any]) -> Dict[str, Any]: import fmpy - path = Path(req["path"]).resolve() - with tempfile.TemporaryDirectory(prefix="studio_") as tmp: - fmu = _build(path, Path(tmp))["fmu"] - result = fmpy.simulate_fmu( - fmu, stop_time=float(req["stopTime"]), output_interval=float(req["stepSize"]), - fmi_type={"cs": "CoSimulation", "me": "ModelExchange"}.get(req.get("interface"), None), - start_values=req.get("startValues") or {}, - ) + result = fmpy.simulate_fmu( + str(fmu), stop_time=float(req["stopTime"]), output_interval=float(req["stepSize"]), + fmi_type={"cs": "CoSimulation", "me": "ModelExchange"}.get(req.get("interface"), None), + start_values=req.get("startValues") or {}, + ) times = [float(t) for t in result["time"]] series = {name: [float(v) for v in result[name]] for name in result.dtype.names if name != "time"} return {"interface": req.get("interface"), "time": times, "series": series, "events": [], "simulator": "fmpy"} +def simulate_fmusim(req: Dict[str, Any]) -> Dict[str, Any]: + with tempfile.TemporaryDirectory(prefix="studio_") as tmp: + fmu = _build(Path(req["path"]).resolve(), Path(tmp))["fmu"] + return _run_fmusim(fmu, req, Path(tmp)) + + +def simulate_fmpy(req: Dict[str, Any]) -> Dict[str, Any]: + with tempfile.TemporaryDirectory(prefix="studio_") as tmp: + fmu = _build(Path(req["path"]).resolve(), Path(tmp))["fmu"] + return _run_fmpy(fmu, req) + + +def simulate_built(req: Dict[str, Any]) -> Dict[str, Any]: + """Simulate an existing .fmu with fmpy or fmusim (``req["simulator"]``, default: whichever is available).""" + import importlib.util + + fmu = Path(req["fmu"]).resolve() + simulator = req.get("simulator") + if simulator is None: + simulator = "fmpy" if importlib.util.find_spec("fmpy") else "fmusim" if find_fmusim() else None + if simulator is None: + raise RuntimeError("Simulating an FMU needs FMPy (pip install fmpy) or fmusim on PATH") + if simulator == "fmpy": + return _run_fmpy(str(fmu), req) + if simulator == "fmusim": + with tempfile.TemporaryDirectory(prefix="studio_") as tmp: + return _run_fmusim(str(fmu), req, Path(tmp)) + raise ValueError(f"Unknown simulator {simulator!r}: use 'fmpy' or 'fmusim'") + + def _read_csv(path: Path): import csv with open(path, newline="") as f: @@ -498,7 +522,8 @@ def inspect_fmu(req: Dict[str, Any]) -> Dict[str, Any]: } -COMMANDS = {"analyze": analyze, "simulate": simulate, "build": build, "validate": validate, "inspect": inspect_fmu} +COMMANDS = {"analyze": analyze, "simulate": simulate, "build": build, "validate": validate, "inspect": inspect_fmu, + "simulate_fmu": simulate_built} def main(): diff --git a/pythonfmu3/tests/test_llms_txt.py b/pythonfmu3/tests/test_llms_txt.py new file mode 100644 index 0000000..d53d850 --- /dev/null +++ b/pythonfmu3/tests/test_llms_txt.py @@ -0,0 +1,57 @@ +"""Checks for docs/llms.txt (the index for AI tools) and the llms-full.txt build hook.""" +import importlib.util +import re +from pathlib import Path + +import pytest + +from pythonfmu3.tests.test_docs import check_model, models_in + +ROOT = Path(__file__).resolve().parents[2] +LLMS = ROOT / "docs" / "llms.txt" +DOCS_URL = "https://pythonfmu3.readthedocs.io/en/latest/" + +pytestmark = pytest.mark.skipif(not LLMS.exists(), reason="needs a source checkout with docs/") + + +def nav_pages(): + text = (ROOT / "mkdocs.yml").read_text() + return re.findall(r"^\s+- [^:]+: (\S+\.md)$", text, re.MULTILINE) + + +def test_structure(): + text = LLMS.read_text() + assert text.startswith("# PythonFMU3\n\n> ") + assert "## Docs" in text and "## Optional" in text + + +def test_example_is_a_working_model(): + code = re.search(r"```python\n(.*?)```", LLMS.read_text(), re.DOTALL).group(1) + namespace = {"__name__": "__main__"} + exec(code, namespace) + (cls,) = models_in(namespace) + instance = check_model(cls) + instance.u = 3.0 + instance.do_step(0.0, 0.1) + assert instance.y == 6.0 + + +def test_doc_links_point_at_pages(): + pages = set(nav_pages()) + for url in re.findall(r"\((https://pythonfmu3\.readthedocs\.io/[^)]+)\)", LLMS.read_text()): + path = url[len(DOCS_URL):] + if path == "llms-full.txt": + continue + assert path.endswith("/") and f"{path[:-1]}.md" in pages, url + + +def test_llms_full_contains_every_page(tmp_path): + spec = importlib.util.spec_from_file_location("llms_hook", ROOT / "docs_hooks" / "llms.py") + hook = importlib.util.module_from_spec(spec) + spec.loader.exec_module(hook) + nav = [{page: page} for page in nav_pages()] + text = hook.build_llms_full(ROOT / "docs", nav, DOCS_URL) + for page in nav_pages(): + url = DOCS_URL if page == "index.md" else f"{DOCS_URL}{page[:-3]}/" + assert f"" in text + assert "class " in text and len(text) > 10000 diff --git a/pythonfmu3/tests/test_notebook.py b/pythonfmu3/tests/test_notebook.py new file mode 100644 index 0000000..a9a4d24 --- /dev/null +++ b/pythonfmu3/tests/test_notebook.py @@ -0,0 +1,156 @@ +"""Tests for the Jupyter support (pythonfmu3.notebook): the %%fmu magic, Model and FMU.""" +import json +import os +from pathlib import Path + +import pytest + +import pythonfmu3 +from pythonfmu3.builder import FmuBuilder +from pythonfmu3.notebook import FMU, MARKER, Model, fmu_cell + +NOTEBOOK = Path(__file__).resolve().parents[2] / "examples" / "notebooks" / "getting_started.ipynb" + +TANK = """class Tank(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.description = "A & more" + self.time = 0.0 + self.q_in = 0.2 + self.area = 2.0 + self.level = 1.0 + self.register_units([Unit(name="m", m=1)]) + 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("area", causality=Fmi3Causality.parameter, + variability=Fmi3Variability.tunable, start=2.0)) + self.register_variable(Float64("level", causality=Fmi3Causality.output, unit="m")) + + def do_step(self, current_time, step_size): + self.level += self.q_in / self.area * step_size + self.time = current_time + step_size + return True +""" + + +@pytest.fixture +def in_tmp(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + return tmp_path + + +def test_cell_magic_writes_checks_and_binds(in_tmp): + ns = {} + model = fmu_cell("", TANK, ns) + assert ns["Tank"] is model + assert model.ok and model.problems == [] + text = (in_tmp / "tank.py").read_text() + assert text.startswith("from pythonfmu3 import * " + MARKER + "\nclass Tank") + assert [v["name"] for v in model.variables] == ["time", "q_in", "area", "level"] + assert repr(model) == "" + + +def test_cell_magic_options_and_errors(in_tmp): + model = fmu_cell("models/my_tank.py", "from pythonfmu3 import *\n" + TANK, {}) + assert model.path == (in_tmp / "models" / "my_tank.py").resolve() + assert model.path.read_text().startswith(MARKER + "\nfrom pythonfmu3 import *") + + broken = fmu_cell("oops.py", "class Oops(Fmi3Slave)\n pass\n", {}) + assert not broken.ok + assert "line 2" in broken.problems[0] # cell line 1 + the header line + assert "SyntaxError" in broken._repr_html_() + + (in_tmp / "mine.py").write_text("x = 1\n") + with pytest.raises(FileExistsError): + fmu_cell("mine.py", TANK, {}) + assert fmu_cell("mine.py --overwrite", TANK, {}).ok + with pytest.raises(ValueError, match="no model class"): + fmu_cell("", "x = 1\n", {}) + + +def test_problems_are_reported(in_tmp): + model = fmu_cell("bad.py", "class Bad(Fmi3Slave):\n def __init__(self, **kw):\n super().__init__(**kw)\n" + " self.register_variable(Float64('u', causality=Fmi3Causality.input))\n", {}) + assert not model.ok + assert any("Independent variable" in p for p in model.problems) + assert "Independent variable" in model._repr_html_() + + +def test_html_is_escaped(in_tmp): + html = fmu_cell("", TANK, {})._repr_html_() + assert "q_in" in html and "area = 2.0" in html and "level [m]" in html + assert "" not in html + + +def test_simulate_returns_a_dataframe(in_tmp): + pd = pytest.importorskip("pandas") + model = fmu_cell("", TANK, {}) + res = model.simulate(stop_time=10, start_values={"q_in": 0.4}) + assert isinstance(res, pd.DataFrame) and res.index.name == "time" + assert list(res.columns) == ["level"] and len(res) == 501 + assert res["level"].iloc[-1] == pytest.approx(3.0) + assert res.attrs["simulator"] == "python" + with pytest.raises(ValueError, match="Unknown variable"): + model.simulate(stop_time=1, start_values={"nope": 1}) + + +def test_model_exchange_events(in_tmp): + pytest.importorskip("pandas") + from pythonfmu3.studio.server import TEMPLATES + model = fmu_cell("", (TEMPLATES / "bouncing_ball.py").read_text(), {}) + res = model.simulate(stop_time=3) + assert res.attrs["interface"] == "me" and len(res.attrs["events"]) > 3 + + +@pytest.mark.skipif(not FmuBuilder.has_binary(), reason="needs the compiled wrapper") +def test_build_and_inspect(in_tmp): + fmu = fmu_cell("", TANK, {}).build() + assert isinstance(fmu, FMU) and fmu.path.name == "Tank.fmu" + assert fmu.info["platforms"] and fmu.info["interfaces"] == ["CoSimulation"] + assert "Tank.fmu" in repr(fmu) and "q_in" in fmu._repr_html_() + assert fmu.validate()["passed"] + assert repr(FMU(fmu.path)) == repr(fmu) + + +def test_ipython_extension_registers_the_magic(in_tmp): + class Shell: + user_ns = {} + registered = None + + def register_magic_function(self, func, magic_kind, magic_name): + self.registered = (func, magic_kind, magic_name) + + shell = Shell() + pythonfmu3.load_ipython_extension(shell) + func, kind, name = shell.registered + assert (kind, name) == ("cell", "fmu") + model = func("", TANK) + assert shell.user_ns["Tank"] is model + + +@pytest.mark.skipif(not NOTEBOOK.exists(), reason="needs a source checkout") +def test_example_notebook_runs(in_tmp): + """Run the example notebook's code cells, emulating the two IPython magics it uses.""" + pytest.importorskip("pandas") + pytest.importorskip("matplotlib") + os.environ.setdefault("MPLBACKEND", "Agg") + ns = {"__name__": "__main__"} + for cell in json.loads(NOTEBOOK.read_text())["cells"]: + if cell["cell_type"] != "code": + continue + source = "".join(cell["source"]) + if source.startswith("%%fmu"): + line, body = source.split("\n", 1) + fmu_cell(line[len("%%fmu"):].strip(), body, ns) + continue + lines = [ln for ln in source.splitlines() if not ln.startswith("%load_ext")] + if "Tank.build()" in source and not FmuBuilder.has_binary(): + continue + if "FMU(" in source and not (in_tmp / "Tank.fmu").exists(): + continue + exec(compile("\n".join(lines), "cell", "exec"), ns) + final = ns["sweep"].iloc[-1] + for column, value in final.items(): + valve = float(column.split("=")[1]) + assert value == pytest.approx((0.05 / valve) ** 2, rel=0.05)