import numpy as np import pytest from sysid import fit_step, initial_guess, simulate_step, step_position J_TRUE, B_TRUE, U = 0.01, 0.10, 0.05 def test_noise_free_fit_is_exact() -> None: t, theta = simulate_step(J_TRUE, B_TRUE, U, dt=0.01, n=100, noise_std=0.0, rng=np.random.default_rng(0), counts_per_rev=None) fit = fit_step(t, theta, U) assert fit.b == pytest.approx(B_TRUE, rel=1e-8) assert fit.j == pytest.approx(J_TRUE, rel=1e-6) @pytest.mark.parametrize("seed", range(5)) def test_noisy_fit_recovers_parameters(seed: int) -> None: t, theta = simulate_step(J_TRUE, B_TRUE, U, dt=0.01, n=100, noise_std=0.003, rng=np.random.default_rng(seed)) fit = fit_step(t, theta, U) assert fit.b == pytest.approx(B_TRUE, rel=0.02) assert fit.j == pytest.approx(J_TRUE, rel=0.08) assert fit.residual_rms < 0.005 def test_initial_guess_from_tail_is_close() -> None: t = np.arange(100) * 0.01 k, tau = initial_guess(t, step_position(t, U / B_TRUE, J_TRUE / B_TRUE)) # The tail has decayed to exp(-5), so the linear fit is already within a few percent. assert k == pytest.approx(U / B_TRUE, rel=0.02) assert tau == pytest.approx(J_TRUE / B_TRUE, rel=0.05) def test_more_data_shrinks_uncertainty() -> None: rng = np.random.default_rng(3) short = fit_step(*simulate_step(J_TRUE, B_TRUE, U, 0.01, 100, 0.003, rng), U) long = fit_step(*simulate_step(J_TRUE, B_TRUE, U, 0.01, 400, 0.003, rng), U) assert 0.0 < long.b_std < short.b_std