"""Shared engine types: parameter schemas, results and errors.""" from __future__ import annotations import math from collections.abc import Iterable, Sequence from dataclasses import asdict, dataclass, field class SpecError(ValueError): """The spec asks for something the engine cannot or will not compute.""" class EngineError(RuntimeError): """The engine failed numerically on a valid spec.""" @dataclass(frozen=True) class Param: name: str unit: str min: float max: float default: float | None required: bool = False description: str = "" @dataclass class Result: sim: str op: str params: dict values: dict series: dict = field(default_factory=dict) notes: list[str] = field(default_factory=list) def to_dict(self) -> dict: return asdict(self) def prompt_dict(self) -> dict: return {"values": self.values, "notes": self.notes} def _number(name: str, value) -> float: if isinstance(value, bool) or not isinstance(value, (int, float)): raise SpecError(f"parameter '{name}' must be a number, got {value!r}") value = float(value) if not math.isfinite(value): raise SpecError(f"parameter '{name}' must be finite, got {value}") return value def validate_params(schema: Sequence[Param], given: dict, exclusive: Iterable[tuple[str, ...]] = ()) -> dict: """Check `given` against `schema`; return params in schema order with defaults filled in.""" names = {p.name for p in schema} for key in given: if key not in names: raise SpecError(f"unknown parameter '{key}' (expected one of: {', '.join(p.name for p in schema)})") for group in exclusive: present = [k for k in group if k in given] if len(present) > 1: raise SpecError("give only one of " + ", ".join(f"'{k}'" for k in group)) out = {} for p in schema: if p.name in given: v = _number(p.name, given[p.name]) if not p.min <= v <= p.max: raise SpecError(f"{p.name}={v:g} is out of range [{p.min:g}, {p.max:g}] {p.unit}") out[p.name] = v elif p.required: raise SpecError(f"parameter '{p.name}' is required") elif p.default is not None: out[p.name] = float(p.default) return out def finite(values: dict) -> dict: for k, v in values.items(): if isinstance(v, float) and not math.isfinite(v): raise EngineError(f"non-finite result for {k}") return values def series(x, y, x_label: str, y_label: str) -> dict: return {"x": [float(v) for v in x], "y": [float(v) for v in y], "x_label": x_label, "y_label": y_label}