"""Audit structural and data-dependent ranks without commanding hardware. The synthetic poses are mathematical probes, not executable robot poses. This audits the existing 84-column rigid-body/rotor/friction/bias model; it does not establish identifiability of added history or calibration states. """ from __future__ import annotations import argparse import hashlib import json from pathlib import Path import numpy as np import identification_core as core import ti5_dyn_model as dynamics ROOT = Path(__file__).resolve().parents[2] PARAMETER_NAMES = [ f"link{joint}_{name}" for joint in range(1, 7) for name in ("mass", "hx", "hy", "hz", "Ixx", "Ixy", "Ixz", "Iyy", "Iyz", "Izz") ] + [ f"joint{joint}_{name}" for name in ("rotor_inertia", "viscous", "coulomb", "bias") for joint in range(1, 7) ] def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1 << 20), b""): digest.update(chunk) return digest.hexdigest() def spectrum(matrix: np.ndarray, structural_tol: float, effective_tol: float) -> dict: """Column normalization prevents SI units alone from setting the rank.""" if matrix.ndim != 2 or not len(matrix) or not np.isfinite(matrix).all(): raise ValueError("expected a finite nonempty two-dimensional design") column_norm = np.linalg.norm(matrix, axis=0) active = column_norm > max(float(column_norm.max()) * 1e-10, 1e-12) scale = np.where(active, column_norm, 1.0) normalized = matrix / scale normalized[:, ~active] = 0.0 singular_values = np.linalg.svd(normalized, compute_uv=False) result = { "rows": len(matrix), "columns": matrix.shape[1], "active_columns": int(active.sum()), "column_rms_in_native_parameter_units": ( column_norm / np.sqrt(len(matrix)) ).tolist(), "singular_values_column_normalized": singular_values.tolist(), } for label, tolerance in (("structural", structural_tol), ("effective", effective_tol)): retained = singular_values > singular_values[0] * tolerance rank = int(retained.sum()) result[f"{label}_relative_tolerance"] = tolerance result[f"{label}_rank"] = rank result[f"{label}_nullity"] = matrix.shape[1] - rank result[f"{label}_condition_retained"] = ( float(singular_values[0] / singular_values[retained][-1]) if rank else None ) return result def kinematics_summary(q: np.ndarray, dq: np.ndarray, ddq: np.ndarray) -> dict: return { "q_min_rad": q.min(axis=0).tolist(), "q_max_rad": q.max(axis=0).tolist(), "dq_abs_p50_p95_max_rad_s": np.quantile(np.abs(dq), [0.5, 0.95, 1], axis=0).tolist(), "ddq_abs_p50_p95_max_rad_s2": np.quantile( np.abs(ddq), [0.5, 0.95, 1], axis=0 ).tolist(), } def run(args: argparse.Namespace) -> dict: rng = np.random.default_rng(args.seed) q = rng.uniform(-2.5, 2.5, (args.synthetic_samples, 6)) dq = rng.uniform(-1.0, 1.0, q.shape) ddq = rng.uniform(-2.0, 2.0, q.shape) dynamic = core.design(q, dq, ddq).reshape(-1, 84) static = core.design(q, np.zeros_like(dq), np.zeros_like(ddq)).reshape(-1, 84) gravity_columns = [10 * joint + column for joint in range(6) for column in range(4)] def audit(matrix: np.ndarray) -> dict: return spectrum(matrix, args.structural_tol, args.effective_tol) synthetic = { "seed": args.seed, "generator": "numpy.random.default_rng / PCG64", "sample_count": args.synthetic_samples, "ranges": {"q_rad": [-2.5, 2.5], "dq_rad_s": [-1.0, 1.0], "ddq_rad_s2": [-2.0, 2.0]}, "collision_checked": False, "purpose": "numerical structural rank probe only; do not execute these poses", "dynamic_84": audit(dynamic), "rigid_body_60": audit(dynamic[:, :60]), "gravity_24": audit(static[:, gravity_columns]), "static_with_bias_84": audit(static), } # Identify individual rotor columns already spanned by the rigid-body model. u, singular_values, _ = np.linalg.svd(dynamic[:, :60], full_matrices=False) rigid_basis = u[:, singular_values > singular_values[0] * args.structural_tol] synthetic["rotor_column_fraction_outside_rigid_span"] = [ float(np.linalg.norm(column - rigid_basis @ (rigid_basis.T @ column)) / np.linalg.norm(column)) for column in dynamic[:, 60:66].T ] samples_path = args.samples.resolve() with np.load(samples_path, allow_pickle=False) as archive: a = archive["A"] valid = archive["valid"].astype(bool) training = archive["training"].astype(bool) & valid heldout = archive["heldout"].astype(bool) & valid episode = archive["episode"] actual_q, actual_dq, actual_ddq = [archive[key] for key in ("q", "dq", "ddq")] if a.ndim != 3 or a.shape[1:] != (6, 84) or valid.shape != a.shape[:2]: raise ValueError("unsupported archived design dimensions") if np.any(training & heldout): raise ValueError("training and heldout masks overlap") archive_results = {} for label, mask in (("training", training), ("heldout", heldout), ("all_valid", valid)): selected_frames = np.any(mask, axis=1) archive_results[label] = { "selection": f"archived {label} joint-row mask intersected with valid; no resampling", "joint_observations": mask.sum(axis=0).tolist(), "frame_count": int(selected_frames.sum()), "episode_ids": np.unique(episode[selected_frames]).tolist(), "kinematics": kinematics_summary( actual_q[selected_frames], actual_dq[selected_frames], actual_ddq[selected_frames] ), "dynamic_84": audit(a[mask]), "rigid_body_60": audit(a[mask, :60]), } legacy_path = ROOT / "docs/ti5_identified_dynamics_20261015.json" legacy = json.loads(legacy_path.read_text())["identifiability"] return { "schema": "ti5_identifiability_audit_v1", "model": "60 rigid-body + 6 rotor inertia + 6 viscous + 6 Coulomb + 6 bias", "parameter_names": PARAMETER_NAMES, "implementation_sha256": { path.name: sha256(path) for path in (Path(__file__), Path(core.__file__), Path(dynamics.__file__)) }, "numpy_version": np.__version__, "synthetic": synthetic, "archive_path": str(samples_path), "archive_sha256": sha256(samples_path), "archive": archive_results, "legacy_report": { "path": str(legacy_path), "sha256": sha256(legacy_path), "rank": legacy["rank"], "relative_svd_tolerance": legacy["relative_svd_tolerance"], "condition_kept": legacy["condition_kept"], }, "interpretation": [ "Random full-state rank is a numerical estimate of the model's structural rank, not a formal symbolic proof.", "Column normalization measures dependencies but hides absolute excitation amplitude; inspect column RMS and velocity/acceleration coverage too.", "Structural nullspace cannot be eliminated by collecting more poses within this model.", "Rank alone does not establish parameter precision or validate torque scaling, geometry, friction, or residual assumptions.", "Heldout rank is a kinematic diagnostic only; heldout torque is neither read nor fitted.", "This script does not estimate statistical parameter confidence intervals.", ], } def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--samples", type=Path, default=ROOT / "motion_records/highrate_20261015_1630/analysis/regression_samples.npz") parser.add_argument("--out", type=Path, default=ROOT / "motion_records/reassessment_20261016/identifiability.json") parser.add_argument("--docs-copy", type=Path) parser.add_argument("--seed", type=int, default=161016) parser.add_argument("--synthetic-samples", type=int, default=500) parser.add_argument("--structural-tol", type=float, default=1e-10) parser.add_argument("--effective-tol", type=float, default=1e-3) args = parser.parse_args() if args.synthetic_samples < 100 or not 0 < args.structural_tol < args.effective_tol < 1: parser.error("need at least 100 synthetic samples and 0 < structural_tol < effective_tol < 1") result = run(args) text = json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False) + "\n" for destination in (args.out, args.docs_copy): if destination is not None: destination.parent.mkdir(parents=True, exist_ok=True) destination.write_text(text) print(json.dumps({ "out": str(args.out), "synthetic_ranks": { name: result["synthetic"][name]["structural_rank"] for name in ("dynamic_84", "rigid_body_60", "gravity_24", "static_with_bias_84") }, "archive_ranks": { name: { key: group["dynamic_84"][key] for key in ("rows", "structural_rank", "effective_rank", "effective_condition_retained") } for name, group in result["archive"].items() }, }, indent=2)) if __name__ == "__main__": main()