diff --git a/pythonfmu3/mcp_server.py b/pythonfmu3/mcp_server.py index 5f2ae57..ee38026 100644 --- a/pythonfmu3/mcp_server.py +++ b/pythonfmu3/mcp_server.py @@ -153,12 +153,27 @@ def var(v): def _summarize_simulation(res: Dict[str, Any]) -> Dict[str, Any]: + """Summarise a result: scalars get initial/final/min/max and 11 samples over time; arrays + (series named x[1], x[2], ...) get their final profile along the elements, and the overall + min/max. Scalars come first so they are never crowded out by long arrays.""" t = res["time"] n = len(t) idx = sorted({round(i * (n - 1) / 10) for i in range(11)}) + + def finite(ys): + return [y for y in ys if isinstance(y, (int, float)) and y == y and abs(y) != float("inf")] + + scalars, arrays = {}, {} + for name, ys in res["series"].items(): + base, _, rest = name.partition("[") + if rest: + arrays.setdefault(base, []).append(ys) + else: + scalars[name] = ys + variables = {} - for name, ys in list(res["series"].items())[:30]: - nums = [y for y in ys if isinstance(y, (int, float)) and y == y and abs(y) != float("inf")] + for name, ys in list(scalars.items())[:30]: + nums = finite(ys) if not nums: variables[name] = {"note": "not numeric or not finite", "final": ys[-1] if ys else None} continue @@ -166,6 +181,18 @@ def _summarize_simulation(res: Dict[str, Any]) -> Dict[str, Any]: "samples": [ys[i] for i in idx]} if len(nums) < len(ys): variables[name]["non_finite"] = len(ys) - len(nums) + + for name, columns in list(arrays.items())[:10]: + 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: + entry["final"] = final + else: # long arrays: 24 evenly spaced elements + picks = sorted({round(i * (len(final) - 1) / 23) for i in range(24)}) + entry["final_sampled"] = {f"[{i + 1}]": final[i] for i in picks} + variables[name] = entry + return {"ok": True, "simulator": res.get("simulator"), "interface": res.get("interface"), "points": n, "end_time": t[-1] if t else None, "sample_times": [t[i] for i in idx], "events": len(res.get("events", [])), "first_events": res.get("events", [])[:5], @@ -298,7 +325,8 @@ def simulate(path: str, stop_time: float = 10.0, step_size: Optional[float] = No if stop_time / step > 200_000: raise ValueError("Too many output points: increase step_size") r = _worker({"command": "simulate", "path": str(p), "simulator": simulator, "interface": interface, - "stopTime": stop_time, "stepSize": step, "startValues": start_values or {}}, p.parent) + "stopTime": stop_time, "stepSize": step, "startValues": start_values or {}, + "maxArrayElements": 1000, "strictStartValues": True}, p.parent) if not r.get("ok"): return _failure(r) res = r["result"] diff --git a/pythonfmu3/studio/worker.py b/pythonfmu3/studio/worker.py index b9279af..4711a3c 100644 --- a/pythonfmu3/studio/worker.py +++ b/pythonfmu3/studio/worker.py @@ -193,12 +193,17 @@ def analyze(req: Dict[str, Any]) -> Dict[str, Any]: # --- simulate ---------------------------------------------------------------------------- -def _set_start_values(instance, values: Dict[str, Any]): +def _set_start_values(instance, values: Dict[str, Any], strict: bool = False): by_name = {v.name: v for v in instance.vars.values()} for name, value in (values or {}).items(): var = by_name.get(name) if var is None or var.setter is None: - continue + if not strict: # the Studio may still hold values for a renamed variable + continue + if var is None: + raise ValueError(f"Unknown variable {name!r} in the start values; the model has " + f"{', '.join(sorted(by_name))}") + raise ValueError(f"{name!r} can't be set: only inputs and parameters with a setter can") kind = type(var).__name__ if kind in ("Int32", "Int64", "UInt64", "Enumeration"): value = int(float(value)) @@ -221,11 +226,16 @@ def _recorded(instance, names: Optional[List[str]]): return keep +# How many elements of each array variable are recorded. The Studio plots up to 16; the MCP +# server asks for more, so the whole profile (e.g. every pipe segment) is in the results. +_MAX_ARRAY_ELEMENTS = 16 + + def _sample(series, recorded): for var in recorded: value = jsonable(var.getter()) if isinstance(value, list): - for i, item in enumerate(value[:16]): + for i, item in enumerate(value[:_MAX_ARRAY_ELEMENTS]): series.setdefault(f"{var.name}[{i + 1}]", []).append(_num(item)) else: series.setdefault(var.name, []).append(_num(value)) @@ -234,6 +244,8 @@ def _sample(series, recorded): def _num(value): if isinstance(value, bool): return 1.0 if value else 0.0 + if isinstance(value, str) and value.strip().lower() in ("true", "false"): # fmusim Booleans + return 1.0 if value.strip().lower() == "true" else 0.0 try: return float(value) except (TypeError, ValueError): @@ -247,9 +259,11 @@ def simulate_python(req: Dict[str, Any]) -> Dict[str, Any]: interface = req.get("interface") or interfaces_of(instance)[0] start, stop = float(req.get("startTime", 0.0)), float(req["stopTime"]) step = float(req["stepSize"]) - _set_start_values(instance, req.get("startValues")) + _set_start_values(instance, req.get("startValues"), bool(req.get("strictStartValues"))) instance.enter_initialization_mode() instance.exit_initialization_mode() + global _MAX_ARRAY_ELEMENTS + _MAX_ARRAY_ELEMENTS = int(req.get("maxArrayElements", 16)) recorded = _recorded(instance, req.get("outputs")) times, series, events = [start], {}, [] _sample(series, recorded) @@ -354,6 +368,8 @@ def find_fmusim() -> Optional[str]: def _run_fmusim(fmu: str, req: Dict[str, Any], tmp: Path) -> Dict[str, Any]: + global _MAX_ARRAY_ELEMENTS + _MAX_ARRAY_ELEMENTS = int(req.get("maxArrayElements", 16)) fmusim = find_fmusim() if not fmusim: raise RuntimeError("fmusim was not found on PATH (or in PYTHONFMU3_FMUSIM)") @@ -363,6 +379,8 @@ def _run_fmusim(fmu: str, req: Dict[str, Any], tmp: Path) -> Dict[str, Any]: if req.get("interface"): cmd += ["--interface-type", req["interface"]] for name, value in (req.get("startValues") or {}).items(): + if isinstance(value, (list, tuple)): # arrays: fmusim takes space-separated values + value = " ".join(str(v) for v in value) 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(): @@ -416,17 +434,22 @@ def simulate_built(req: Dict[str, Any]) -> Dict[str, Any]: def _read_csv(path: Path): + """Read a result CSV. fmusim writes an array variable as one column of space-separated + values; those are expanded into name[1], name[2], ... like the Python preview does.""" import csv with open(path, newline="") as f: - rows = list(csv.reader(f)) + rows = [row for row in csv.reader(f) if row] header = [h.strip().strip('"') for h in rows[0]] - times, series = [], {h: [] for h in header[1:]} + times, series = [], {} for row in rows[1:]: - if not row: - continue times.append(float(row[0])) for h, cell in zip(header[1:], row[1:]): - series[h].append(_num(cell.split(" ")[0]) if cell else None) + parts = cell.split() + if len(parts) > 1: + for i, part in enumerate(parts[:_MAX_ARRAY_ELEMENTS]): + series.setdefault(f"{h}[{i + 1}]", []).append(_num(part)) + else: + series.setdefault(h, []).append(_num(parts[0]) if parts else None) return times, series diff --git a/pythonfmu3/tests/test_mcp_server.py b/pythonfmu3/tests/test_mcp_server.py index d765203..784e316 100644 --- a/pythonfmu3/tests/test_mcp_server.py +++ b/pythonfmu3/tests/test_mcp_server.py @@ -144,3 +144,53 @@ async def steps(session, call): err, sim = await call("simulate", path="bouncing_ball.py", stop_time=3.0, variables=["ball.derv"]) assert not err and set(sim["variables"]) == {"ball.derv"} run_session(workspace, steps) + + +ARRAYS = """import numpy as np +from pythonfmu3 import Dimension, Fmi3Causality, Fmi3Slave, Fmi3Variability, Float64 + + +class Profile(Fmi3Slave): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.time = 0.0 + self.gain = 1.0 + self.T = np.arange(40, 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("total", causality=Fmi3Causality.output)) + + def do_step(self, current_time, step_size): + self.T = self.gain * np.arange(40, dtype=float) + self.total = float(self.T.sum()) + self.time = current_time + step_size + return True +""" + + +def test_array_outputs_and_start_values(tmp_path): + pytest.importorskip("numpy") + workspace = tmp_path / "ws" + workspace.mkdir() + + async def steps(session, call): + err, model = await call("write_model", path="profile.py", content=ARRAYS) + assert not err and model["problems"] == [] + 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))) + # 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) + header = (workspace / sim["csv"]).read_text().split("\n", 1)[0] + assert "T[40]" 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"] + run_session(workspace, steps) diff --git a/pythonfmu3/tests/test_studio.py b/pythonfmu3/tests/test_studio.py index 3ee2022..495b92d 100644 --- a/pythonfmu3/tests/test_studio.py +++ b/pythonfmu3/tests/test_studio.py @@ -147,3 +147,24 @@ def test_static_page_is_served(app): status, body = call(httpd, "/", token=False) assert status == 200 and b"PythonFMU3 Studio" in body assert call(httpd, "/../server.py", token=False)[0] == 404 + + +def test_read_csv_expands_fmusim_arrays_and_booleans(tmp_path): + from pythonfmu3.studio import worker as w + csv_file = tmp_path / "r.csv" + csv_file.write_text("time,T,on,x\n0,1 2 3,true,0.5\n1,4 5 6,false,1.5\n") + w._MAX_ARRAY_ELEMENTS = 16 + times, series = w._read_csv(csv_file) + assert times == [0.0, 1.0] + assert series["T[3]"] == [3.0, 6.0] and "T" not in series + assert series["on"] == [1.0, 0.0] and series["x"] == [0.5, 1.5] + + +def test_strict_start_values(): + from pythonfmu3.studio import worker as w + path = TEMPLATES / "pid_controller.py" + lenient = w.simulate_python({"path": str(path), "stopTime": 0.1, "stepSize": 0.05, "startValues": {"nope": 1}}) + assert lenient["time"] + with pytest.raises(ValueError, match="Unknown variable 'nope'"): + w.simulate_python({"path": str(path), "stopTime": 0.1, "stepSize": 0.05, "startValues": {"nope": 1}, + "strictStartValues": True})