"""calib_logic.py: the arithmetic of idea card 01 (ideas/IDEA-01-CALIBRATION-ONLY.md, revised kill test), no torch and no MuJoCo, so the Mac can test it. calib_check.py (box, GPU) runs the arms and calls these functions. - scaled_command: the wrapper's rule. ONLY the right-knee entry of the command entering the simulator is multiplied by the arm's scale, then clipped to [-1, 1]; the planner's and policy's action is never touched (a new array is returned: the upstream DMControlWrapper passes the SAME array to both control steps of a decision, so an in-place change would scale twice). - estimate_gain: K-est's least-squares slope through the origin of f_t (qfrc_inverse at the dof of hinge right_knee, nothing subtracted) on the applied knee command u_t, on the steps that survive the sample cuts. - comparators and outcome: Df_bar, N and T from the saved Gate A reading; the ORDERED outcome per arm. """ import json import math import os import numpy as np KNEE = "right_knee" # the hinge and its motor actuator in dm_control walker.xml HEALTHY_KNEE_GEAR = 50.0 # walker.xml knee gear (the known healthy model) CHANGED_KNEE_SCALE = 0.5 # the bridge change: gear 50 to 25 COMMAND_LIMIT = 1.0 # actuator ctrlrange [-1, 1] ORACLE_SCALE = 2.0 # K2 EST_CONTROL_STEPS = 200 # K-est: the first 200 control steps of walking MIN_ABS_COMMAND = 0.05 # K-est: steps with |u_t| < 0.05 are excluded # AGENT-DECISION: "the knee near its joint limits" is not given a number in the card. A step is cut when the knee angle # lies within 0.1 rad (about 6 degrees) of either end of its range, or when the simulator holds an active limit row for # the knee. Both are sample cuts only (qfrc_inverse already excludes constraint force). LIMIT_MARGIN_RAD = 0.1 GATE_A_SEEDS = (2, 3, 4) RUN_TASK = "walker-run" RETENTION_TASKS = ("walker-stand", "walker-walk-backwards") # Episodes per arm on the paired bank 1000 + i: 10 running (the outcome) and 5 each of standing and walking backwards # (reported only), the bridge's A-block counts, so every arm block is episode for episode the saved A block's bank # (operator decision 2026-10-12: 5, not 10, retention episodes). EPISODES_BY_TASK = {RUN_TASK: 10, "walker-stand": 5, "walker-walk-backwards": 5} ARMS = ("N-check", "K2", "K-est") N_CHECK_TOLERANCE = 1e-3 # per-episode return agreement with the saved A block (it reproduced exactly # across processes on seeds 2, 3 and 4) SUFFICES, PARTIAL, FAILS = "CALIBRATION SUFFICES", "CALIBRATION PARTIAL", "CALIBRATION FAILS" def write_once(path, obj): """Writes JSON to a file that must not exist yet (mode 'x'): results are never overwritten.""" with open(path, "x") as f: json.dump(obj, f, indent=1, default=str) def claim_out_dir(out_dir): """Creates out_dir, or accepts it only when it exists and is empty.""" os.makedirs(out_dir, exist_ok=True) left = sorted(os.listdir(out_dir)) if left: raise SystemExit(f"refusing non-empty out_dir {out_dir} (holds {left[:5]}): results are never overwritten") def scaled_command(action, knee_index, scale): """Returns (command for the simulator, clipped). Only entry knee_index is scaled and then clipped to [-1, 1]; clipped is True when the clip changed the scaled value (|scale u| > 1). The input array is not modified.""" if not (isinstance(scale, (int, float)) and math.isfinite(scale) and scale > 0): raise ValueError(f"scale must be a positive finite number, got {scale!r}") command = np.array(action, copy=True) raw = float(command[knee_index]) * float(scale) clipped_value = min(COMMAND_LIMIT, max(-COMMAND_LIMIT, raw)) command[knee_index] = clipped_value return command, abs(raw) > COMMAND_LIMIT def clip_fraction(flags): """Share of control steps whose scaled knee command hit the clip.""" flags = list(flags) if not flags: raise ValueError("no control steps recorded") return sum(bool(x) for x in flags) / len(flags) def near_limit(angle, lower, upper, margin=LIMIT_MARGIN_RAD): """True when the joint angle lies within margin of either end of its range [lower, upper].""" if not lower < upper: raise ValueError(f"joint range must have lower < upper, got [{lower}, {upper}]") return bool(angle < lower + margin or angle > upper - margin) def sample_mask(u, right_leg_contact, knee_near_limit, min_abs_u=MIN_ABS_COMMAND): """The steps K-est may use, and how many each cut removed (a step can fall under several cuts).""" u = np.asarray(u, dtype=np.float64) contact = np.asarray(right_leg_contact, dtype=bool) limit = np.asarray(knee_near_limit, dtype=bool) if not (u.shape == contact.shape == limit.shape) or u.ndim != 1: raise ValueError(f"u, contact and limit flags must be equal-length vectors, got {u.shape}, {contact.shape}, {limit.shape}") small = np.abs(u) < min_abs_u keep = ~(small | contact | limit) return keep, {"steps": int(u.size), "small_command": int(small.sum()), "right_leg_contact": int(contact.sum()), "knee_near_limit": int(limit.sum()), "used": int(keep.sum())} def estimate_gain(u, f, keep): """g_hat = sum(u f) / sum(u^2) over the kept steps (least squares through the origin); the residual sd uses n - 1 degrees of freedom (one fitted parameter). Raises when fewer than two steps survive or the inputs are not finite.""" u = np.asarray(u, dtype=np.float64) f = np.asarray(f, dtype=np.float64) keep = np.asarray(keep, dtype=bool) if not (u.shape == f.shape == keep.shape) or u.ndim != 1: raise ValueError(f"u, f and keep must be equal-length vectors, got {u.shape}, {f.shape}, {keep.shape}") uk, fk = u[keep], f[keep] if uk.size < 2: raise ValueError(f"K-est needs at least two usable steps, got {uk.size}") if not (np.all(np.isfinite(uk)) and np.all(np.isfinite(fk))): raise ValueError("non-finite command or force among the kept steps") g_hat = float(np.dot(uk, fk) / np.dot(uk, uk)) residual = fk - g_hat * uk return {"g_hat": g_hat, "residual_sd": float(np.sqrt(np.dot(residual, residual) / (uk.size - 1))), "steps_used": int(uk.size)} def k_est_scale(g_hat, healthy_gear=HEALTHY_KNEE_GEAR): """scale = healthy gear / g_hat. A non-positive or non-finite g_hat cannot define a gain.""" if not (math.isfinite(g_hat) and g_hat > 0): raise ValueError(f"g_hat must be positive and finite to define a scale, got {g_hat!r}") return healthy_gear / g_hat def comparators(gate_a): """Df_bar, N and T from the saved Gate A reading (results/bridge/gate_a_reading_2026-10-11.json). Refuses a file whose seeds are not 2, 3, 4, whose A blocks or T differ between seeds, or whose record checks did not pass.""" seeds = {int(s["seed"]): s for s in gate_a["seeds"]} if tuple(sorted(seeds)) != GATE_A_SEEDS: raise ValueError(f"expected Gate A seeds {GATE_A_SEEDS}, got {sorted(seeds)}") if not all(s.get("all_checks_pass") for s in seeds.values()): raise ValueError("a Gate A seed failed its record checks") running_after = {k: float(s["arms"]["Df"]["running_after"]) for k, s in sorted(seeds.items())} running_a = {float(s["arms"]["Df"]["running_A"]) for s in seeds.values()} ts = {float(s["T"]) for s in seeds.values()} if len(running_a) != 1 or len(ts) != 1: raise ValueError(f"A block or T differs between seeds: A {sorted(running_a)}, T {sorted(ts)}") return {"Df_bar": float(np.mean(list(running_after.values()))), "Df_running_after_by_seed": running_after, "N": running_a.pop(), "T": ts.pop()} def outcome(arm_mean, df_bar, n, t): """The card's rule, IN ORDER: SUFFICES if mean >= Df_bar - T; else PARTIAL if mean > N + T; else FAILS.""" for name, x in (("arm_mean", arm_mean), ("df_bar", df_bar), ("n", n), ("t", t)): if not (isinstance(x, (int, float)) and math.isfinite(x)): raise ValueError(f"{name} must be finite, got {x!r}") if arm_mean >= df_bar - t: return SUFFICES if arm_mean > n + t: return PARTIAL return FAILS def progress_total(k_est_estimable=True): """Dashboard progress lines: one per episode per arm plus the estimation line; K-est's arm is absent when g_hat could not be estimated.""" per_arm = sum(EPISODES_BY_TASK.values()) return per_arm * (len(ARMS) if k_est_estimable else len(ARMS) - 1) + 1 def n_check(episodes, saved_episodes, tolerance=N_CHECK_TOLERANCE): """An arm block against the saved A block, episode by episode on the same bank (same count required). At scale 1 it must reproduce; at other scales the differences are reported.""" if len(episodes) != len(saved_episodes) or not saved_episodes: raise ValueError(f"need {len(saved_episodes)} episodes to compare episode by episode, got {len(episodes)}") diffs = [abs(float(a) - float(b)) for a, b in zip(episodes, saved_episodes)] return {"compared": len(diffs), "max_abs_diff": max(diffs), "tolerance": tolerance, "reproduces": max(diffs) <= tolerance} def split_episodes(flags_by_step, episode_starts): """Cuts one stream of per-control-step flags into episodes at the recorded reset positions.""" starts = list(episode_starts) + [len(flags_by_step)] if not episode_starts or starts[0] != 0 or any(b < a for a, b in zip(starts, starts[1:])): raise ValueError(f"episode starts must begin at 0 and increase, got {episode_starts}") return [list(flags_by_step[a:b]) for a, b in zip(starts, starts[1:])]