diff --git a/docs/changelog.md b/docs/changelog.md index add1d6d..c641321 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -1,6 +1,17 @@ # Changelog -## 1.3.0 (unreleased) +## Unreleased + +### Fixed +- Several FMUs in one Python process (FMPy, or a Python co-simulation script) now each + run their own model script. Each FMU's script is loaded under a module name unique to + that FMU, so two FMUs whose scripts share a name (two different `model.py`), or a + script named like a module the process had already imported, no longer pick up the + wrong code. Native importers were not affected. +- MCP server: array outputs of up to 60 elements, such as a 30-segment pipe profile, are + shown in full in simulation summaries; longer arrays as 30 samples. + +## 1.3.0 (2026-11-18) ### Added - **Jupyter support** (`%load_ext pythonfmu3`): the `%%fmu` cell magic saves, checks and @@ -20,6 +31,13 @@ - CI tests every supported Python version (3.11 to 3.15) on Linux, and the oldest and newest on Windows and macOS. +### Fixed +- MCP simulations record whole array outputs and summarise single-value outputs first, + so long arrays no longer hide outputs such as an outlet temperature. +- Simulating in fmusim: array start values are passed in the format fmusim accepts, and + fmusim's array and Boolean results are read correctly. +- MCP simulations report a misspelt start value instead of silently ignoring it. + ## 1.2.0 (2026-11-16) ### Added diff --git a/pythonfmu3/mcp_server.py b/pythonfmu3/mcp_server.py index ee38026..4b28a47 100644 --- a/pythonfmu3/mcp_server.py +++ b/pythonfmu3/mcp_server.py @@ -186,10 +186,10 @@ def finite(ys): final = [col[-1] for col in columns] nums = finite([y for col in columns for y in col]) entry = {"elements": len(columns), "min": min(nums) if nums else None, "max": max(nums) if nums else None} - if len(final) <= 24: + if len(final) <= 60: entry["final"] = final - else: # long arrays: 24 evenly spaced elements - picks = sorted({round(i * (len(final) - 1) / 23) for i in range(24)}) + else: # long arrays: 30 evenly spaced elements + picks = sorted({round(i * (len(final) - 1) / 29) for i in range(30)}) entry["final_sampled"] = {f"[{i + 1}]": final[i] for i in picks} variables[name] = entry diff --git a/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp b/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp index b7179e2..d2c8609 100644 --- a/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp +++ b/pythonfmu3/pythonfmu-export/src/pythonfmu/PySlaveInstance.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -21,6 +22,57 @@ namespace pythonfmu namespace { +// Loads the model script from this FMU's resources folder under a module name unique to +// that folder. Importing it by its plain name would reuse any module of the same name +// already loaded in the process: another FMU's "model.py" when several FMUs share one +// Python importer (FMPy, a Python co-simulation script), or an unrelated module. Instances +// of the same FMU (same resources folder) share the module. +PyObject* loadModelModule(const std::string& resources, const std::string& moduleName) +{ + const std::string path = resources + "/" + moduleName + ".py"; + std::ostringstream unique; + unique << "pythonfmu3_fmu_" << std::hex << std::hash{}(resources) << "_" << moduleName; + const std::string uniqueName = unique.str(); + + PyObject* modules = PyImport_GetModuleDict(); // borrowed + if (PyObject* existing = PyDict_GetItemString(modules, uniqueName.c_str())) { // borrowed + Py_INCREF(existing); + return existing; + } + + PyObject* util = PyImport_ImportModule("importlib.util"); + if (!util) return nullptr; + PyObject* spec = PyObject_CallMethod(util, "spec_from_file_location", "ss", uniqueName.c_str(), path.c_str()); + PyObject* module = spec ? PyObject_CallMethod(util, "module_from_spec", "O", spec) : nullptr; + Py_DECREF(util); + if (!module) { + Py_XDECREF(spec); + return nullptr; + } + // Registered before running it, as a normal import does (dataclasses, pickling and + // relative lookups need sys.modules[__name__]); removed again if running it fails. + if (PyDict_SetItemString(modules, uniqueName.c_str(), module) != 0) { + Py_DECREF(module); + Py_DECREF(spec); + return nullptr; + } + PyObject* loader = PyObject_GetAttrString(spec, "loader"); + PyObject* result = loader ? PyObject_CallMethod(loader, "exec_module", "O", module) : nullptr; + Py_XDECREF(loader); + Py_DECREF(spec); + if (!result) { + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); // keep the model's error for the log + PyDict_DelItemString(modules, uniqueName.c_str()); + PyErr_Clear(); + PyErr_Restore(type, value, traceback); + Py_DECREF(module); + return nullptr; + } + Py_DECREF(result); + return module; +} + // Holds the GIL for the lifetime of the object. Releasing in the destructor guarantees // the GIL is given back on every exit path, including C++ exceptions. class GilGuard @@ -220,8 +272,8 @@ PySlaveInstance::PySlaveInstance(std::string instanceName, std::string resources const auto info = readSlaveModuleInfo(resources_ + "/slavemodule.txt"); const std::string& moduleName = info.first; - PyRef module(PyImport_ImportModule(moduleName.c_str())); - if (!module) handle_py_exception("[ctor] PyImport_ImportModule(" + moduleName + ")"); + PyRef module(loadModelModule(resources_, moduleName)); + if (!module) handle_py_exception("[ctor] loading " + moduleName + ".py"); std::string className = info.second; if (className.empty()) { diff --git a/pythonfmu3/tests/test_mcp_server.py b/pythonfmu3/tests/test_mcp_server.py index 784e316..39dc6b9 100644 --- a/pythonfmu3/tests/test_mcp_server.py +++ b/pythonfmu3/tests/test_mcp_server.py @@ -155,17 +155,17 @@ def __init__(self, **kwargs): super().__init__(**kwargs) self.time = 0.0 self.gain = 1.0 - self.T = np.arange(40, dtype=float) + self.T = np.arange(100, dtype=float) self.total = 0.0 self.register_variable(Float64("time", causality=Fmi3Causality.independent, variability=Fmi3Variability.continuous)) self.register_variable(Float64("gain", causality=Fmi3Causality.parameter, variability=Fmi3Variability.tunable, start=1.0)) - self.register_variable(Float64("T", causality=Fmi3Causality.output, dimensions=[Dimension(start="40")])) + self.register_variable(Float64("T", causality=Fmi3Causality.output, dimensions=[Dimension(start="100")])) self.register_variable(Float64("total", causality=Fmi3Causality.output)) def do_step(self, current_time, step_size): - self.T = self.gain * np.arange(40, dtype=float) + self.T = self.gain * np.arange(100, dtype=float) self.total = float(self.T.sum()) self.time = current_time + step_size return True @@ -183,13 +183,13 @@ async def steps(session, call): err, sim = await call("simulate", path="profile.py", stop_time=1.0, start_values={"gain": 2.0}) assert not err # scalars are summarised even when a long array comes first - assert sim["variables"]["total"]["final"] == pytest.approx(2.0 * sum(range(40))) + assert sim["variables"]["total"]["final"] == pytest.approx(2.0 * sum(range(100))) # the whole array is recorded and summarised as a profile profile = sim["variables"]["T"] - assert profile["elements"] == 40 - assert profile["final_sampled"]["[40]"] == pytest.approx(78.0) + assert profile["elements"] == 100 + assert profile["final_sampled"]["[100]"] == pytest.approx(198.0) header = (workspace / sim["csv"]).read_text().split("\n", 1)[0] - assert "T[40]" in header + assert "T[100]" in header # a misspelt start value is an error, not silently ignored err, msg = await call("simulate", path="profile.py", stop_time=1.0, start_values={"gian": 2.0}) assert msg["ok"] is False and "Unknown variable 'gian'" in msg["error"] diff --git a/pythonfmu3/tests/test_module_isolation.py b/pythonfmu3/tests/test_module_isolation.py new file mode 100644 index 0000000..d1de392 --- /dev/null +++ b/pythonfmu3/tests/test_module_isolation.py @@ -0,0 +1,85 @@ +"""Several FMUs in one Python process must each run their own model script, even when the +scripts share a module name (two different "model.py") or a module of that name is already +imported. This is the situation in FMPy or a Python co-simulation script.""" +import subprocess +import sys +import textwrap +import zipfile +from pathlib import Path + +import pytest + +from pythonfmu3.builder import FmuBuilder +from pythonfmu3.osutil import get_lib_extension, get_platform + +pytestmark = pytest.mark.skipif(not FmuBuilder.has_binary(), reason="needs the compiled wrapper") + +MODEL = """ +from pythonfmu3 import Fmi3Causality, Fmi3Slave, Fmi3Variability, Float64 + + +class {name}(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.time = 0.0 + self.y = 0.0 + self.register_variable(Float64("time", causality=Fmi3Causality.independent, + variability=Fmi3Variability.continuous)) + self.register_variable(Float64("y", causality=Fmi3Causality.output)) + + def do_step(self, current_time, step_size): + self.y = {value} + self.time = current_time + step_size + return True +""" + +HOST = r""" +import ctypes as C, sys, types +# An unrelated module already imported under the same name as the FMUs' scripts +sys.modules["model"] = types.ModuleType("model") + +CB = C.CFUNCTYPE(None, C.c_void_p, C.c_int, C.c_char_p, C.c_char_p) +log = CB(lambda e, s, c, m: print("LOG", m.decode(), file=sys.stderr)) + +def run(lib_path, resources, vr_y): + lib = C.CDLL(lib_path) + lib.fmi3InstantiateCoSimulation.restype = C.c_void_p + lib.fmi3InstantiateCoSimulation.argtypes = [C.c_char_p] * 3 + [C.c_bool] * 4 + [C.c_void_p, C.c_size_t, C.c_void_p, CB, C.c_void_p] + lib.fmi3EnterInitializationMode.argtypes = [C.c_void_p, C.c_bool, C.c_double, C.c_double, C.c_bool, C.c_double] + lib.fmi3ExitInitializationMode.argtypes = [C.c_void_p] + lib.fmi3DoStep.argtypes = [C.c_void_p, C.c_double, C.c_double, C.c_bool] + [C.POINTER(C.c_bool)] * 3 + [C.POINTER(C.c_double)] + lib.fmi3GetFloat64.argtypes = [C.c_void_p, C.POINTER(C.c_uint32), C.c_size_t, C.POINTER(C.c_double), C.c_size_t] + c = lib.fmi3InstantiateCoSimulation(b"i", b"", resources.encode(), False, True, False, False, None, 0, None, log, None) + assert c, "instantiation failed" + assert lib.fmi3EnterInitializationMode(c, False, 0, 0, False, 0) == 0 + assert lib.fmi3ExitInitializationMode(c) == 0 + b = [C.c_bool() for _ in range(3)]; last = C.c_double() + assert lib.fmi3DoStep(c, 0.0, 0.1, True, *[C.byref(x) for x in b], C.byref(last)) == 0 + out = (C.c_double * 1)() + assert lib.fmi3GetFloat64(c, (C.c_uint32 * 1)(vr_y), 1, out, 1) == 0 + return out[0] + +args = sys.argv[1:] +print([run(args[i], args[i + 1], 1) for i in range(0, len(args), 2)]) +""" + + +def build(tmp_path, folder, name, value): + src = tmp_path / folder + src.mkdir() + (src / "model.py").write_text(MODEL.format(name=name, value=value)) + fmu = FmuBuilder.build_FMU(src / "model.py", dest=tmp_path / f"{folder}_out") + extracted = tmp_path / f"{folder}_fmu" + with zipfile.ZipFile(fmu) as z: + z.extractall(extracted) + lib = extracted / "binaries" / get_platform() / f"{name}.{get_lib_extension()}" + return [str(lib), str(extracted / "resources")] + + +def test_fmus_with_the_same_module_name_run_their_own_code(tmp_path): + first = build(tmp_path, "a", "FirstModel", 1.0) + second = build(tmp_path, "b", "SecondModel", 2.0) + proc = subprocess.run([sys.executable, "-c", HOST, *first, *second, *first], + capture_output=True, text=True, timeout=120) + assert proc.returncode == 0, proc.stderr[-3000:] + assert proc.stdout.strip() == "[1.0, 2.0, 1.0]"