"""Numerical metrics over (observed, predicted) trajectory pairs. Responsibility: compute scalar fit quality (R-squared), per-variable residuals, and lightweight diagnostic statistics. Does no parsing, no simulation, no English-text generation. """ from __future__ import annotations from collections.abc import Iterable import numpy as np from pydantic import BaseModel, ConfigDict, Field class ResidualSummary(BaseModel): """Diagnostic statistics derived from per-variable residuals. Consumed exclusively by :mod:`physix.verifier.mismatch` to render the English residual summary surfaced to the agent. """ model_config = ConfigDict(frozen=True) per_variable_max_abs_residual: dict[str, float] = Field(default_factory=dict) per_variable_t_of_max_residual: dict[str, float] = Field(default_factory=dict) per_variable_late_residual_mean: dict[str, float] = Field(default_factory=dict) overall_r2: float = 0.0 def compute_match( observed: dict[str, np.ndarray], predicted: dict[str, np.ndarray], state_variables: Iterable[str], ) -> float: """Compute the per-step R-squared used as the primary reward signal. Returns the **average** of per-variable R-squared values, clipped to ``[0, 1]``. This intentionally rewards models that get *some* variables right even if others diverge. """ r2s = [ _r_squared(observed[var], predicted[var]) for var in state_variables if var in observed and var in predicted ] if not r2s: return 0.0 avg = float(np.mean(r2s)) return _clip01(avg) def residual_summary( timestamps: np.ndarray, observed: dict[str, np.ndarray], predicted: dict[str, np.ndarray], state_variables: Iterable[str], ) -> ResidualSummary: """Build a structured residual summary used downstream by mismatch.py.""" per_max: dict[str, float] = {} per_t_max: dict[str, float] = {} per_late_mean: dict[str, float] = {} r2_values: list[float] = [] for var in state_variables: if var not in observed or var not in predicted: continue obs = observed[var] pred = predicted[var] residual = pred - obs r2_values.append(_r_squared(obs, pred)) i_max = int(np.argmax(np.abs(residual))) per_max[var] = float(np.abs(residual[i_max])) per_t_max[var] = float(timestamps[i_max]) # Mean residual magnitude over the last 25% of the trajectory; this # is the signal the mismatch summariser uses to detect drift / # plateau-mismatch. late_start = int(0.75 * len(timestamps)) per_late_mean[var] = float(np.mean(np.abs(residual[late_start:]))) overall = float(np.mean(r2_values)) if r2_values else 0.0 return ResidualSummary( per_variable_max_abs_residual=per_max, per_variable_t_of_max_residual=per_t_max, per_variable_late_residual_mean=per_late_mean, overall_r2=_clip01(overall), ) def _r_squared(observed: np.ndarray, predicted: np.ndarray) -> float: """Coefficient of determination with a zero floor. Returns 0.0 when the observed series is constant (degenerate). Returns 0.0 when the model is worse than the observed mean. """ if observed.shape != predicted.shape: return 0.0 obs_mean = float(np.mean(observed)) ss_res = float(np.sum((observed - predicted) ** 2)) ss_tot = float(np.sum((observed - obs_mean) ** 2)) if ss_tot <= 0.0: return 0.0 return _clip01(1.0 - ss_res / ss_tot) def _clip01(value: float) -> float: if value < 0.0: return 0.0 if value > 1.0: return 1.0 return value