"""python3 -m unittest test_calib_logic (Mac, no torch, no MuJoCo)""" import json import os import tempfile import unittest import numpy as np import calib_logic as CL KNEE = 1 # walker actuator order: right_hip, right_knee, right_ankle, left_... HERE = os.path.dirname(os.path.abspath(__file__)) GATE_A = os.path.join(HERE, "..", "..", "results", "bridge", "gate_a_reading_2026-10-11.json") def gate_a(after=(517.0879547119141, 563.5872436523438, 562.4611083984375), a=334.19755859375, t=36.75360868129278, seeds=(2, 3, 4), checks=True): return {"seeds": [{"seed": s, "T": t, "all_checks_pass": checks, "arms": {"Df": {"running_A": a, "running_after": x}}} for s, x in zip(seeds, after)]} class ScaledCommand(unittest.TestCase): def test_scales_only_the_knee_entry(self): u = np.array([0.1, 0.3, -0.2, 0.4, -0.5, 0.6], dtype=np.float32) c, clipped = CL.scaled_command(u, KNEE, 2.0) self.assertAlmostEqual(float(c[KNEE]), 0.6, places=6) np.testing.assert_array_equal(np.delete(c, KNEE), np.delete(u, KNEE)) self.assertFalse(clipped) def test_clips_to_the_actuator_range_and_flags_it(self): c, clipped = CL.scaled_command(np.array([0, 0.7, 0, 0, 0, 0], dtype=np.float32), KNEE, 2.0) self.assertEqual(float(c[KNEE]), 1.0) self.assertTrue(clipped) c, clipped = CL.scaled_command(np.array([0, -0.9, 0, 0, 0, 0], dtype=np.float32), KNEE, 2.0) self.assertEqual(float(c[KNEE]), -1.0) self.assertTrue(clipped) def test_a_command_exactly_at_the_limit_is_not_counted_as_clipped(self): _, clipped = CL.scaled_command(np.array([0, 0.5, 0, 0, 0, 0], dtype=np.float32), KNEE, 2.0) self.assertFalse(clipped) def test_scale_one_is_the_identity_bit_for_bit(self): u = np.array([-1.0, 1.0, 0.123456789, -0.987654321, 0.0, 0.5], dtype=np.float32) c, clipped = CL.scaled_command(u, KNEE, 1.0) self.assertEqual(c.dtype, u.dtype) np.testing.assert_array_equal(c, u) self.assertFalse(clipped) def test_the_policy_action_is_never_modified(self): """Upstream passes the same array to both control steps of a decision; in-place scaling would apply twice.""" u = np.array([0, 0.3, 0, 0, 0, 0], dtype=np.float32) first, _ = CL.scaled_command(u, KNEE, 2.0) second, _ = CL.scaled_command(u, KNEE, 2.0) self.assertAlmostEqual(float(u[KNEE]), 0.3, places=6) np.testing.assert_array_equal(first, second) def test_non_positive_or_non_finite_scale_is_an_error(self): for s in (0.0, -2.0, float("nan"), float("inf")): with self.assertRaises(ValueError): CL.scaled_command(np.zeros(6), KNEE, s) class ClipFraction(unittest.TestCase): def test_share_of_clipped_steps(self): self.assertEqual(CL.clip_fraction([True, False, False, True]), 0.5) def test_no_steps_is_an_error(self): with self.assertRaises(ValueError): CL.clip_fraction([]) def test_split_episodes_at_resets(self): self.assertEqual(CL.split_episodes([1, 0, 0, 1, 1], [0, 2]), [[1, 0], [0, 1, 1]]) def test_split_rejects_a_stream_not_starting_with_a_reset(self): with self.assertRaises(ValueError): CL.split_episodes([1, 0], [1]) with self.assertRaises(ValueError): CL.split_episodes([1, 0], []) class Estimator(unittest.TestCase): def test_recovers_the_true_gear_from_noiseless_forces(self): u = np.linspace(-1, 1, 200) keep, _ = CL.sample_mask(u, np.zeros(200, bool), np.zeros(200, bool)) r = CL.estimate_gain(u, 25.0 * u, keep) self.assertAlmostEqual(r["g_hat"], 25.0, places=9) self.assertAlmostEqual(r["residual_sd"], 0.0, places=9) self.assertEqual(r["steps_used"], int(keep.sum())) self.assertAlmostEqual(CL.k_est_scale(r["g_hat"]), 2.0, places=9) def test_least_squares_through_the_origin_with_noise(self): rng = np.random.default_rng(0) u = rng.uniform(-1, 1, 200) f = 25.0 * u + rng.normal(0, 1.0, 200) keep = np.ones(200, bool) r = CL.estimate_gain(u, f, keep) self.assertAlmostEqual(r["g_hat"], float(np.dot(u, f) / np.dot(u, u)), places=12) self.assertLess(abs(r["g_hat"] - 25.0), 0.5) self.assertAlmostEqual(r["residual_sd"], 1.0, delta=0.15) def test_cut_steps_do_not_enter_the_fit(self): u = np.array([0.5, 0.5, 0.5, 0.01, 0.5]) f = np.array([12.5, 12.5, 999.0, 999.0, 999.0]) # step 2 contact, step 3 small, step 4 near limit keep, cuts = CL.sample_mask(u, [False, False, True, False, False], [False, False, False, False, True]) self.assertEqual(keep.tolist(), [True, True, False, False, False]) self.assertEqual(cuts, {"steps": 5, "small_command": 1, "right_leg_contact": 1, "knee_near_limit": 1, "used": 2}) self.assertAlmostEqual(CL.estimate_gain(u, f, keep)["g_hat"], 25.0) def test_small_command_threshold_is_strict(self): keep, _ = CL.sample_mask([0.05, -0.05, 0.0499], [False] * 3, [False] * 3) self.assertEqual(keep.tolist(), [True, True, False]) def test_fewer_than_two_usable_steps_is_an_error(self): with self.assertRaises(ValueError): CL.estimate_gain([0.5, 0.5], [1.0, 1.0], [True, False]) def test_non_finite_force_among_kept_steps_is_an_error(self): with self.assertRaises(ValueError): CL.estimate_gain([0.5, 0.5], [1.0, float("nan")], [True, True]) def test_mismatched_lengths_are_an_error(self): with self.assertRaises(ValueError): CL.sample_mask([0.5, 0.5], [False], [False, False]) def test_scale_needs_a_positive_gain(self): for g in (0.0, -25.0, float("nan")): with self.assertRaises(ValueError): CL.k_est_scale(g) def test_near_limit(self): lo, hi = -2.618, 0.0 # walker knee range, -150 to 0 degrees self.assertTrue(CL.near_limit(-0.05, lo, hi)) self.assertTrue(CL.near_limit(-2.6, lo, hi)) self.assertFalse(CL.near_limit(-1.0, lo, hi)) with self.assertRaises(ValueError): CL.near_limit(0.0, 1.0, -1.0) class Outcome(unittest.TestCase): C = dict(df_bar=547.7, n=334.2, t=36.75) def test_suffices_at_and_above_df_bar_minus_t(self): self.assertEqual(CL.outcome(547.7 - 36.75, **self.C), CL.SUFFICES) self.assertEqual(CL.outcome(600.0, **self.C), CL.SUFFICES) def test_partial_between(self): self.assertEqual(CL.outcome(510.9, **self.C), CL.PARTIAL) self.assertEqual(CL.outcome(334.2 + 36.76, **self.C), CL.PARTIAL) def test_fails_at_or_below_n_plus_t_including_worse_than_n(self): self.assertEqual(CL.outcome(334.2 + 36.75, **self.C), CL.FAILS) self.assertEqual(CL.outcome(200.0, **self.C), CL.FAILS) def test_order_wins_when_ranges_overlap(self): """Df_bar - T below N + T: the first rule decides.""" self.assertEqual(CL.outcome(350.0, df_bar=380.0, n=334.2, t=36.75), CL.SUFFICES) def test_non_finite_inputs_are_an_error(self): with self.assertRaises(ValueError): CL.outcome(float("nan"), **self.C) class Comparators(unittest.TestCase): def test_values_from_a_gate_a_shaped_record(self): c = CL.comparators(gate_a()) self.assertAlmostEqual(c["Df_bar"], 547.7121, places=3) self.assertAlmostEqual(c["N"], 334.19755859375) self.assertAlmostEqual(c["T"], 36.75360868129278) self.assertEqual(sorted(c["Df_running_after_by_seed"]), [2, 3, 4]) @unittest.skipUnless(os.path.exists(GATE_A), "saved Gate A reading not present") def test_the_saved_gate_a_reading(self): with open(GATE_A) as f: c = CL.comparators(json.load(f)) self.assertAlmostEqual(c["Df_bar"], 547.7, delta=0.05) self.assertAlmostEqual(c["N"], 334.2, delta=0.05) self.assertAlmostEqual(c["T"], 36.75361, places=5) def test_refuses_other_seeds_failed_checks_or_unequal_a_blocks(self): with self.assertRaises(ValueError): CL.comparators(gate_a(seeds=(1, 2, 3))) with self.assertRaises(ValueError): CL.comparators(gate_a(checks=False)) g = gate_a() g["seeds"][1]["arms"]["Df"]["running_A"] = 334.0 with self.assertRaises(ValueError): CL.comparators(g) class NCheckAndFiles(unittest.TestCase): def test_identical_episodes_reproduce(self): r = CL.n_check([1.0, 2.0, 3.0], [1.0, 2.0, 3.0]) self.assertTrue(r["reproduces"]) self.assertEqual(r["max_abs_diff"], 0.0) def test_counts_must_match_the_saved_block(self): with self.assertRaises(ValueError): CL.n_check([1.0, 2.0, 3.0, 4.0], [1.0, 2.0]) self.assertEqual(CL.n_check([1.0, 2.0], [1.0, 2.0])["compared"], 2) def test_episode_counts_are_the_bridge_a_block_counts(self): self.assertEqual(CL.EPISODES_BY_TASK, {"walker-run": 10, "walker-stand": 5, "walker-walk-backwards": 5}) def test_progress_total(self): self.assertEqual(CL.progress_total(True), 61) self.assertEqual(CL.progress_total(False), 41) def test_a_difference_beyond_tolerance_fails(self): self.assertFalse(CL.n_check([1.0, 2.01], [1.0, 2.0])["reproduces"]) def test_too_few_episodes_is_an_error(self): with self.assertRaises(ValueError): CL.n_check([1.0], [1.0, 2.0]) def test_write_once_refuses_an_existing_file(self): with tempfile.TemporaryDirectory() as d: p = os.path.join(d, "x.json") CL.write_once(p, {"a": 1}) with self.assertRaises(FileExistsError): CL.write_once(p, {"a": 2}) with open(p) as f: self.assertEqual(json.load(f), {"a": 1}) def test_claim_out_dir_refuses_a_non_empty_dir(self): with tempfile.TemporaryDirectory() as d: CL.claim_out_dir(os.path.join(d, "new")) open(os.path.join(d, "new", "keep"), "w").close() with self.assertRaises(SystemExit): CL.claim_out_dir(os.path.join(d, "new")) if __name__ == "__main__": unittest.main()