"""Generate a one-sentence English summary of where prediction disagrees with observation. Responsibility: convert a :class:`ResidualSummary` plus the two trajectories into a deterministic English string the agent can use as feedback. No LLM involved; this is templated text driven by simple rules over the numerical residuals. The output is the only place in the env where structured numerical state is translated into natural language for the agent. We invest in this carefully because a 1.5B model reasons better over short English sentences than over 100-row residual tables. """ from __future__ import annotations from collections.abc import Iterable import numpy as np from physix.verifier.metrics import ResidualSummary def summarize_mismatch( observed: dict[str, np.ndarray], predicted: dict[str, np.ndarray], state_variables: Iterable[str], timestamps: np.ndarray, summary: ResidualSummary, ) -> str: """Return a one-sentence English description of the residual. The sentence is built by: 1. Picking the variable with the **highest** late-window residual mean. 2. Inspecting whether the residual grows late in the trajectory (drift), early in the trajectory (initial-condition mismatch), oscillates around zero (phase / amplitude error), or stays uniformly small (good fit). 3. Producing one descriptor for the dominant pattern. Returns ``""`` if no residuals could be computed. """ if summary.overall_r2 >= 0.93: return "Predicted and observed trajectories agree closely." target = _pick_dominant_variable(summary, state_variables) if target is None: return "" obs = observed[target] pred = predicted[target] residual = pred - obs pattern = _classify_pattern(residual, timestamps) return _render_sentence(target, pattern, summary, timestamps) def _pick_dominant_variable( summary: ResidualSummary, state_variables: Iterable[str], ) -> str | None: """Pick the variable with the largest late-window residual mean.""" candidates: list[tuple[str, float]] = [] for var in state_variables: if var in summary.per_variable_late_residual_mean: candidates.append((var, summary.per_variable_late_residual_mean[var])) if not candidates: return None return max(candidates, key=lambda kv: kv[1])[0] def _classify_pattern(residual: np.ndarray, timestamps: np.ndarray) -> str: """Classify the dominant pattern of the residual into one of: - ``"diverges_late"``: residual magnitude grows monotonically. - ``"early_offset"``: large residual near t=0 then shrinks. - ``"phase_or_amplitude"``: residual oscillates around zero with non-trivial amplitude. - ``"uniform_small"``: residual is small everywhere. """ n = len(residual) if n == 0: return "uniform_small" early_window = residual[: max(1, n // 4)] late_window = residual[3 * n // 4 :] abs_residual = np.abs(residual) early_mag = float(np.mean(np.abs(early_window))) late_mag = float(np.mean(np.abs(late_window))) overall_mag = float(np.mean(abs_residual)) or 1e-9 # Sign-flip count: rough proxy for oscillation around zero. sign_flips = int(np.sum(np.diff(np.sign(residual)) != 0)) if late_mag > 2.0 * early_mag and late_mag > 0.05 * float(np.ptp(residual) + 1e-9): return "diverges_late" if early_mag > 2.0 * late_mag: return "early_offset" if sign_flips > n // 5 and overall_mag > 0.05 * float(np.ptp(residual) + 1e-9): return "phase_or_amplitude" return "uniform_small" def _render_sentence( variable: str, pattern: str, summary: ResidualSummary, timestamps: np.ndarray, ) -> str: """Render the chosen pattern into a single English sentence.""" t_max = summary.per_variable_t_of_max_residual.get(variable, 0.0) max_abs = summary.per_variable_max_abs_residual.get(variable, 0.0) if pattern == "diverges_late": return ( f"Predicted {variable!s} diverges from observed past t={t_max:.1f}s " f"(peak residual {max_abs:.2f}); the late-time behaviour is " "structurally wrong (consider a missing damping, drag, or " "saturation term)." ) if pattern == "early_offset": return ( f"Predicted {variable!s} is offset near t=0 (peak residual " f"{max_abs:.2f} at t={t_max:.1f}s); the dynamics align later, " "suggesting an initial-condition or constant-term mismatch." ) if pattern == "phase_or_amplitude": return ( f"Predicted {variable!s} oscillates around the observed but is " f"out of phase or amplitude (peak residual {max_abs:.2f}); " "consider tuning the natural frequency or adding light damping." ) return ( f"Predicted {variable!s} matches observed broadly but residual is " f"non-trivial (peak {max_abs:.2f} at t={t_max:.1f}s); fine-tune the " "parameters." )