chenhuaDr's picture
Upload code/ti5_arm_scripts/audit_hold_drift.py
303f0e8 verified
Raw History Blame Contribute Delete
15.4 kB
#!/usr/bin/env python3
"""Audit native holding-torque drift and pose coverage; never access hardware.
Reconstruct the previously defined kinematic holds without looking at torque
or prediction error. Report every eligible hold, including its transients.
The three named examples are retrospective illustrations, not a test set.
"""
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
from scipy.ndimage import label
def digest(path):
result = hashlib.sha256()
with Path(path).open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
result.update(block)
return result.hexdigest()
def load_arrays(path, keys):
with np.load(path, allow_pickle=False) as archive:
return {key: archive[key] for key in keys}
def linear_summary(t, values):
"""OLS time trend, with no measured-torque-dependent window selection."""
t = np.asarray(t, dtype=float)
values = np.asarray(values, dtype=float)
centered_t = t - t.mean()
centered_y = values - values.mean(axis=0)
slope = centered_t @ centered_y / (centered_t @ centered_t)
residual = centered_y - centered_t[:, None] * slope
total_ss = np.sum(centered_y**2, axis=0)
residual_ss = np.sum(residual**2, axis=0)
return {
"slope_nm_s": slope.tolist(),
"r_squared": [
float(1 - error / total) if total > 1e-16 else None
for error, total in zip(residual_ss, total_ss)
],
"residual_rms_nm": np.sqrt(np.mean(residual**2, axis=0)).tolist(),
}
def holding_windows(raw, processed):
"""Match the historical analyze_native_signals.py hold definition.
The source recording has no missing native cycles. Reject a discontinuous
quiet run explicitly instead of silently treating a gap as a stationary
interval if this tool is used on another recording.
"""
t = raw["t"]
quiet = (
processed["valid"].all(axis=1)
& (abs(processed["dq"]).max(axis=1) < 0.003)
& (abs(processed["ddq"]).max(axis=1) < 0.03)
)
labels, _ = label(quiet)
holds = []
for group in np.unique(labels[labels > 0]):
indices = np.flatnonzero(labels == group)
if len(indices) < 200:
continue
times = processed["t"][indices]
if np.any(np.diff(times) > 0.015):
raise ValueError("Quiet run crosses a processed timestamp gap")
start, end = times[0] + 0.5, times[-1] - 0.1
a, b = np.searchsorted(t, [start, end])
if b - a < 500 or not raw["valid"][a:b].all():
continue
if np.any(np.diff(t[a:b]) > 0.005):
raise ValueError("Quiet run crosses a native timestamp gap")
holds.append((int(group), int(a), int(b)))
return holds
def summarize_holds(raw, windows):
summaries = []
for index, (group, start, end) in enumerate(windows):
t = raw["t"][start:end]
torque = raw["torque_nm"][start:end].astype(float)
q = raw["position_rad"][start:end]
target = raw["target_position_rad"][start:end]
error = target - q
first, second = np.array_split(np.arange(len(t)), 2)
summaries.append({
"hold_index": index,
"quiet_component_id": group,
"native_frame_start": start,
"native_frame_end_exclusive": end,
"start_s": float(t[0]),
"end_s": float(t[-1]),
"duration_s": float(t[-1] - t[0]),
"native_frames": len(t),
"q_median_deg": np.degrees(np.median(q, axis=0)).tolist(),
"q_range_deg": np.degrees(np.ptp(q, axis=0)).tolist(),
"torque_median_nm": np.median(torque, axis=0).tolist(),
"torque_std_nm": torque.std(axis=0).tolist(),
"torque_first_half_mean_nm": torque[first].mean(axis=0).tolist(),
"torque_second_half_mean_nm": torque[second].mean(axis=0).tolist(),
"torque_second_minus_first_half_nm": (
torque[second].mean(axis=0) - torque[first].mean(axis=0)
).tolist(),
"q_second_minus_first_half_deg": np.degrees(
q[second].mean(axis=0) - q[first].mean(axis=0)
).tolist(),
"target_minus_actual_median_deg": np.degrees(
np.median(error, axis=0)
).tolist(),
"target_minus_actual_first_half_mean_deg": np.degrees(
error[first].mean(axis=0)
).tolist(),
"target_minus_actual_second_half_mean_deg": np.degrees(
error[second].mean(axis=0)
).tolist(),
"linear_torque_trend": linear_summary(t, torque),
})
return summaries
def repeated_poses(holds, tolerance_deg=0.3):
pairs = []
for i, first in enumerate(holds):
for second in holds[i + 1:]:
delta_q = np.array(second["q_median_deg"]) - first["q_median_deg"]
maximum = float(np.max(abs(delta_q)))
if maximum > tolerance_deg:
continue
pairs.append({
"hold_indices": [first["hold_index"], second["hold_index"]],
"max_pose_difference_deg": maximum,
"q_second_minus_first_deg": delta_q.tolist(),
"torque_second_minus_first_median_nm": (
np.array(second["torque_median_nm"])
- first["torque_median_nm"]
).tolist(),
"target_error_second_minus_first_deg": (
np.array(second["target_minus_actual_median_deg"])
- first["target_minus_actual_median_deg"]
).tolist(),
})
return pairs
def heldout_pose_coverage(samples, split):
holds = []
for hold_id in np.unique(samples["hold_id"][samples["static"].any(axis=1)]):
use = (samples["hold_id"] == hold_id) & samples["static"].any(axis=1)
groups = np.unique(samples["group"][use])
if len(groups) != 1:
raise ValueError("A static hold crosses motion groups")
holds.append({
"hold_id": int(hold_id),
"arrival_motion_group": int(groups[0]),
"sample_frames": int(use.sum()),
"q_median_rad": np.median(samples["q"][use], axis=0),
})
training = [h for h in holds if h["arrival_motion_group"] in split["training_episodes"]]
heldout = [h for h in holds if h["arrival_motion_group"] in split["heldout_episodes"]]
if not training or not heldout:
raise ValueError("Expected nonempty training and heldout static groups")
distances = []
for hold in heldout:
maximum_errors = np.array([
np.max(abs(np.degrees(hold["q_median_rad"] - train["q_median_rad"])))
for train in training
])
nearest = int(np.argmin(maximum_errors))
distances.append({
"heldout_hold_id": hold["hold_id"],
"heldout_arrival_motion_group": hold["arrival_motion_group"],
"heldout_sample_frames": hold["sample_frames"],
"nearest_training_hold_id": training[nearest]["hold_id"],
"nearest_training_motion_group": training[nearest]["arrival_motion_group"],
"max_axis_difference_deg": float(maximum_errors[nearest]),
})
values = np.array([row["max_axis_difference_deg"] for row in distances])
return {
"distance_definition": "max_j abs(q_heldout_j - q_training_j), using each hold median",
"training_holds": len(training),
"heldout_holds": len(heldout),
"nearest_training_distances": distances,
"nearest_distance_min_median_max_deg": [
float(values.min()), float(np.median(values)), float(values.max())
],
"heldout_holds_with_training_neighbor_within_0_3deg": int((values <= 0.3).sum()),
"interpretation": "Near-repeat heldout poses test history interpolation; they do not establish prediction at unseen poses.",
}
def plot_example(raw, window, hold_index, joint, prefix_seconds, destination):
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
_, start, end = window
t = raw["t"][start:end]
elapsed = t - t[0]
torque = raw["torque_nm"][start:end, joint].astype(float)
q = np.degrees(raw["position_rad"][start:end, joint])
error = np.degrees(
raw["target_position_rad"][start:end, joint]
- raw["position_rad"][start:end, joint]
)
prefix = elapsed < prefix_seconds
trend = linear_summary(elapsed[prefix], torque[prefix, None])
slope = trend["slope_nm_s"][0]
line = torque[prefix].mean() + slope * (elapsed[prefix] - elapsed[prefix].mean())
fig, axes = plt.subplots(3, 1, figsize=(9, 7), sharex=True, constrained_layout=True)
axes[0].plot(elapsed[::5], torque[::5], color="0.7", linewidth=0.5, label="Native torque (every 5th display point)")
blocks = np.arange(0, len(torque) - 49, 50)
axes[0].plot(
[elapsed[b:b + 50].mean() for b in blocks],
[torque[b:b + 50].mean() for b in blocks],
color="C0", linewidth=1.3, label="50-frame block mean (~50 ms)",
)
axes[0].plot(elapsed[prefix], line, color="C3", linestyle="--", label=f"First {prefix_seconds:g} s linear trend")
axes[0].set_ylabel("Motor torque [SDK Nm]")
axes[0].legend(fontsize=8)
r_squared = trend["r_squared"][0]
r_squared_label = f"{r_squared:.4f}" if r_squared is not None else "n/a"
axes[0].set_title(
f"Hold {hold_index}, J{joint + 1}: slope {slope:.4f} Nm/s, "
f"R²={r_squared_label}; source start {t[0]:.3f} s"
)
axes[1].plot(elapsed[::5], q[::5], color="C1", linewidth=0.9)
axes[1].set_ylabel("Actual joint angle [deg]")
axes[1].ticklabel_format(axis="y", style="plain", useOffset=False)
axes[2].plot(elapsed[::5], error[::5], color="C2", linewidth=0.9)
axes[2].set_ylabel("Target - actual [deg]")
axes[2].set_xlabel("Time since start of retained hold [s]")
for axis in axes:
axis.grid(alpha=0.25)
fig.savefig(destination, dpi=150)
plt.close(fig)
return {
"hold_index": hold_index,
"joint": joint + 1,
"prefix_seconds": prefix_seconds,
"prefix_native_frames": int(prefix.sum()),
"slope_nm_s": slope,
"r_squared": trend["r_squared"][0],
"prefix_target_minus_actual_median_deg": float(np.median(error[prefix])),
"prefix_actual_angle_range_deg": float(np.ptp(q[prefix])),
"plot": destination.name,
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--analysis", type=Path, required=True)
parser.add_argument("--outdir", type=Path, required=True)
args = parser.parse_args()
inputs = {
"native_arrays": args.analysis / "native_arrays.npz",
"preprocessed": args.analysis / "preprocessed.npz",
"history_samples": args.analysis / "history_samples.npz",
"split": args.analysis / "split.json",
"implementation": Path(__file__),
}
raw = load_arrays(inputs["native_arrays"], (
"t", "torque_nm", "position_rad", "target_position_rad", "valid",
))
processed = load_arrays(inputs["preprocessed"], ("t", "dq", "ddq", "valid"))
samples = load_arrays(inputs["history_samples"], ("hold_id", "static", "group", "q"))
split = json.loads(inputs["split"].read_text())
if np.any(np.diff(raw["t"]) <= 0) or np.any(np.diff(processed["t"]) <= 0):
raise ValueError("Nonmonotonic source timestamps")
for key in ("torque_nm", "position_rad", "target_position_rad"):
if not np.isfinite(raw[key][raw["valid"]]).all():
raise ValueError(f"Nonfinite valid source field: {key}")
windows = holding_windows(raw, processed)
holds = summarize_holds(raw, windows)
if not holds:
raise ValueError("No qualifying predefined holds")
pairs = repeated_poses(holds)
drift = abs(np.array([row["torque_second_minus_first_half_nm"] for row in holds]))
args.outdir.mkdir(parents=True, exist_ok=True)
# These indices document already observed examples. All windows above are
# audited irrespective of their drift, residual, or model prediction.
examples = []
for hold_index, joint, seconds in ((12, 2, 4.0), (17, 1, 2.0), (26, 1, 2.0)):
if hold_index < len(windows):
examples.append(plot_example(
raw, windows[hold_index], hold_index, joint, seconds,
args.outdir / f"hold_{hold_index}_j{joint + 1}_drift.png",
))
report = {
"schema": "ti5_hold_drift_audit_v1",
"inputs": {name: {"path": str(path), "sha256": digest(path)} for name, path in inputs.items()},
"units": {"torque": "configured SDK Nm, not independently calibrated", "angles": "degrees", "time": "seconds"},
"hold_definition": "All axes healthy, |dq|<0.003rad/s, |ddq|<0.03rad/s² for >=200 samples on the 100Hz grid; trim first 0.5s and last 0.1s; retain >=500 healthy native frames. This reproduces the pre-existing signals.json definition without reading torque to select holds.",
"comparison_definition": "Split every retained hold into equal frame-count halves. Report second-minus-first means. Trend is OLS on all native samples, with no outlier removal.",
"hold_count": len(holds),
"holds": holds,
"absolute_half_mean_torque_change_p50_p90_max_nm": np.quantile(drift, [0.5, 0.9, 1], axis=0).tolist(),
"repeat_pose_tolerance_deg": 0.3,
"repeat_pair_count": len(pairs),
"repeated_pose_hold_pairs": pairs,
"heldout_pose_coverage": heldout_pose_coverage(samples, split),
"retrospective_illustrations": examples,
"interpretation": [
"Some kinematically quiet holds exhibit highly linear torque ramps under nearly constant target-position error. This is consistent with feedback integral accumulation against friction, but drive internals are not directly observed.",
"A velocity-only state frozen at zero velocity cannot represent these ramps. Fixed 0.5s settling does not establish torque stationarity.",
"These observations do not identify an integral gain. No controller parameter or exponential relaxation time was fitted.",
"A simple decaying-exponential interpretation is not established: the observed early ramps are near-linear and sometimes followed by micro-motion. A sufficiently long exponential time constant can approximate a ramp over a short window, so these data alone do not mathematically exclude it.",
"Named examples were inspected previously and are diagnostic. The report includes all predefined holds and never selects or removes samples using model residuals.",
"Torque slopes are descriptive within autocorrelated time series. OLS R² is not an independent-sample statistical confidence level.",
],
}
output = args.outdir / "hold_drift.json"
output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n")
print(json.dumps({
"output": str(output), "holds": len(holds), "repeat_pairs": len(pairs),
"heldout_pose_coverage": report["heldout_pose_coverage"], "examples": examples,
}, indent=2, allow_nan=False))
if __name__ == "__main__":
main()