--- Final Solver (used for performance test) ---
import numpy as np
from scipy import signal
from scipy.linalg import expm
from typing import Any

class Solver:
    def __init__(self):
        self._expm_cache = {}
    
    def solve(self, problem: dict[str, Any], **kwargs) -> dict[str, list[float]]:
        num = np.asarray(problem["num"], dtype=np.float64)
        den = np.asarray(problem["den"], dtype=np.float64)
        u = np.asarray(problem["u"], dtype=np.float64)
        t = np.asarray(problem["t"], dtype=np.float64)
        
        # Normalize denominator
        den0 = den[0]
        if den0 != 1.0:
            num = num / den0
            den = den / den0
        
        # System order
        nn = len(den) - 1
        
        if nn == 0:
            # Pure gain system
            D = num[0] / den[0]
            return {"yout": (D * u).tolist()}
        
        # Convert to state-space using scipy's tf2ss
        A, B, C, D = signal.tf2ss(num, den)
        # Flatten to 1D arrays
        B = B.flatten()
        C = C.flatten()
        D = D.item()
        
        # Build augmented matrix M (n+2 x n+2)
        # State w = [x, u, du/dt]
        M = np.zeros((nn+2, nn+2))
        M[:nn, :nn] = A
        M[:nn, nn] = B
        M[nn, nn+1] = 1.0
        
        N = len(t)
        yout = np.zeros(N)
        x = np.zeros(nn)
        
        # Check for uniform time steps
        dts = np.diff(t)
        if len(dts) > 0 and np.allclose(dts, dts[0]):
            uniform_dt = True
            dt = dts[0]
            if dt > 0:
                # Compute exp(M*dt) once
                expM = self._get_cached_exp(M, dt)
            else:
                expM = None
        else:
            uniform_dt = False
            expM = None
        
        for i in range(N):
            yout[i] = C @ x + D * u[i]
            
            if i < N - 1:
                h = t[i+1] - t[i]
                if h == 0:
                    continue
                
                u0 = u[i]
                u1 = u[i+1]
                du = u1 - u0
                
                # Build augmented state at start
                w0 = np.empty(nn+2)
                w0[:nn] = x
                w0[nn] = u0
                w0[nn+1] = du / h
                
                # Get exp(M*h)
                if uniform_dt:
                    expMh = expM
                else:
                    expMh = self._get_cached_exp(M, h)
                
                # Propagate
                w_h = expMh @ w0
                x = w_h[:nn]
        
        return {"yout": yout.tolist()}
    
    def _get_cached_exp(self, M, h):
        """Cache exp(M*h) for repeated h values."""
        # Use rounding to handle floating point precision
        key = (id(M), round(h, 15))
        if key not in self._expm_cache:
            self._expm_cache[key] = expm(M * h)
        return self._expm_cache[key]
--- End Solver ---
Running performance test...
============================= test session starts ==============================
platform linux -- Python 3.12.13, pytest-9.0.2, pluggy-1.6.0
rootdir: /tests
plugins: anyio-4.13.0, jaxtyping-0.3.9
collected 3 items

../tests/test_outputs.py .
--- Performance Summary ---
Validity: False
Total Baseline Time: 0.0910s
Total Solver Time:   0.0712s
Raw Speedup:         0.0000 x
Final Reward (Score): 1.0000
---------------------------
FF

=================================== FAILURES ===================================
_____________________________ test_solver_validity _____________________________

performance_results = {'raw_speedup': 0.0, 'speedup': 1.0, 'validity': False}

    def test_solver_validity(performance_results):
        """Ensures the solver produces valid outputs."""
        if not performance_results["validity"]:
>           pytest.fail("Solver produced invalid solutions on the test set.")
E           Failed: Solver produced invalid solutions on the test set.

/tests/test_outputs.py:200: Failed
------------------------------ Captured log setup ------------------------------
ERROR    root:evaluator.py:187 Solution verification failed. Max absolute error: 2.64e-02, Max relative error: 5.32e+01 (rtol=1e-05, atol=1e-08)
ERROR    test_outputs:test_outputs.py:93 Solver produced an invalid solution during warmup.
WARNING  test_outputs:test_outputs.py:172 Invalid solution detected. Assigning mercy score of 1.0.
_____________________________ test_solver_speedup ______________________________

performance_results = {'raw_speedup': 0.0, 'speedup': 1.0, 'validity': False}

    def test_solver_speedup(performance_results):
        """Checks if the solver effectively optimized the code."""
>       assert performance_results["raw_speedup"] > 1.0, \
            f"Solver was not faster than baseline (Speedup: {performance_results['raw_speedup']:.2f}x)"
E       AssertionError: Solver was not faster than baseline (Speedup: 0.00x)
E       assert 0.0 > 1.0

/tests/test_outputs.py:205: AssertionError
==================================== PASSES ====================================
=========================== short test summary info ============================
PASSED ../tests/test_outputs.py::test_solver_exists
FAILED ../tests/test_outputs.py::test_solver_validity - Failed: Solver produc...
FAILED ../tests/test_outputs.py::test_solver_speedup - AssertionError: Solver...
========================= 2 failed, 1 passed in 3.38s ==========================
