import numpy as np import pytest from domain_rand import (B0, DT, J0, TARGET, Params, cost, evaluate, failed, nominal, sample_params, simulate, tune) @pytest.fixture(scope="module") def gains() -> dict[str, tuple[float, float]]: kp_n, kd_n, _ = tune(nominal()) kp_r, kd_r, _ = tune(sample_params(np.random.default_rng(0), spread=0.6, n=64)) return {"nominal": (kp_n, kd_n), "randomised": (kp_r, kd_r)} def test_exact_discretisation_matches_fine_euler() -> None: kp, kd = 3.0, 0.3 err = simulate(kp, kd, Params(np.array([J0]), np.array([B0]), np.array([0])))[0] # Reference: semi-implicit Euler with 1000 substeps per control period, no delay. th = w = 0.0 h = DT / 1000 ref = [] for _ in range(err.size): u = np.clip(kp * (TARGET - th) - kd * w, -1.0, 1.0) for _ in range(1000): w += h * (u - B0 * w) / J0 th += h * w ref.append(TARGET - th) assert np.max(np.abs(err - np.array(ref))) < 1e-4 def test_delay_holds_commands_back() -> None: p = Params(np.full(3, J0), np.full(3, B0), np.array([0, 1, 2])) err = simulate(5.0, 0.3, p) # With delay d the joint has not moved after d periods. assert err[0, 0] < TARGET assert err[1, 0] == TARGET and err[1, 1] < TARGET assert err[2, 1] == TARGET and err[2, 2] < TARGET def test_sample_params_ranges() -> None: p = sample_params(np.random.default_rng(5), spread=0.5, n=2000) assert np.all((p.j >= 0.5 * J0) & (p.j <= 1.5 * J0)) assert np.all((p.b >= 0.5 * B0) & (p.b <= 1.5 * B0)) assert set(np.unique(p.delay)) == {1, 2} with pytest.raises(ValueError): sample_params(np.random.default_rng(0), spread=1.0, n=1) def test_nominal_gains_win_on_the_nominal_plant(gains) -> None: c_nom, _ = evaluate(*gains["nominal"], spread=0.0) c_rand, _ = evaluate(*gains["randomised"], spread=0.0) assert c_nom < c_rand @pytest.mark.parametrize("spread", [0.4, 0.6]) def test_randomised_gains_are_more_robust(gains, spread: float) -> None: c_nom, f_nom = evaluate(*gains["nominal"], spread=spread) c_rand, f_rand = evaluate(*gains["randomised"], spread=spread) assert c_rand < c_nom assert f_rand < 0.02 and f_nom > 0.2 def test_cost_and_failure_definitions() -> None: t = np.arange(150) * DT good = TARGET * np.exp(-t / 0.1)[None, :] # smooth approach, no overshoot ringing = TARGET * (np.exp(-t / 0.3) * np.cos(20 * t))[None, :] assert not failed(good)[0] and failed(ringing)[0] assert cost(good)[0] < cost(ringing)[0]