""" compute_force_stats.py Compute per-channel ACTIVE (nonzero) statistics for FORCE only. Why: the original force_ch_std was computed over ALL pixels including the ~98% zero background, which dilutes std to a tiny value. Dividing by that tiny std inflates real contact forces and makes the VAE loss spike. This computes std over NONZERO pixels only -> the correct normalization scale. Contact is NOT recomputed (it uses contact_ch_max, which is unaffected by zeros). Output: writes/updates force_ch_active_mean / force_ch_active_std into a json. You can either merge these into your existing dataset_norm_params.json, or pass this new json to the dataloader (it reads force_ch_active_std if present). Usage: python compute_force_stats.py --root ./grasping python compute_force_stats.py --root ./grasping --out ./grasping/force_stats.json # merge into existing stats file: python compute_force_stats.py --root ./grasping --merge_into ./grasping/dataset_norm_params.json """ import argparse import json from pathlib import Path import numpy as np from tqdm import tqdm CH_NAMES = ["L_fx", "L_fy", "L_fz", "R_fx", "R_fy", "R_fz"] def main(): ap = argparse.ArgumentParser() ap.add_argument("--root", required=True) ap.add_argument("--out", default=None, help="output json (default: /force_stats.json)") ap.add_argument("--merge_into", default=None, help="if set, merge force_ch_active_* into this existing json") args = ap.parse_args() root = Path(args.root) episodes = [p for p in root.rglob("*") if p.is_dir() and (p / "masks.json").exists()] print(f"Found {len(episodes)} valid episodes") # per-channel accumulators over NONZERO pixels only f_sum = np.zeros(6); f_sq = np.zeros(6); f_cnt = np.zeros(6) f_absmax = np.zeros(6) f_min = np.full(6, np.inf); f_max = np.full(6, -np.inf) total_frames = 0 skipped = 0 for ep in tqdm(episodes, desc="episodes"): fdir = ep / "modalities" / "force" if not fdir.exists(): skipped += 1 continue for ff in sorted(fdir.glob("*.npy")): f = np.load(ff).astype(np.float64) # (6,H,W) if f.ndim != 3 or f.shape[0] != 6: continue total_frames += 1 for ch in range(6): v = f[ch][f[ch] != 0] # NONZERO only if v.size: f_sum[ch] += v.sum() f_sq[ch] += (v ** 2).sum() f_cnt[ch] += v.size f_absmax[ch] = max(f_absmax[ch], np.abs(v).max()) f_min[ch] = min(f_min[ch], v.min()) f_max[ch] = max(f_max[ch], v.max()) if total_frames == 0: raise RuntimeError("no force frames found") f_cnt_safe = np.maximum(f_cnt, 1) f_active_mean = f_sum / f_cnt_safe f_active_std = np.sqrt(np.maximum(f_sq / f_cnt_safe - f_active_mean ** 2, 1e-12)) f_min[~np.isfinite(f_min)] = 0.0 f_max[~np.isfinite(f_max)] = 0.0 force_stats = { "force_ch_active_mean": f_active_mean.tolist(), "force_ch_active_std": f_active_std.tolist(), "force_ch_abs_max": f_absmax.tolist(), "force_ch_min": f_min.tolist(), "force_ch_max": f_max.tolist(), "num_frames": int(total_frames), } # print summary print(f"\nframes used: {total_frames}") print(f"{'ch':6s} {'active_std':>11s} {'abs_max':>9s} {'max/std':>8s}") print("-" * 40) for i in range(6): ratio = f_absmax[i] / (f_active_std[i] + 1e-12) print(f"{CH_NAMES[i]:6s} {f_active_std[i]:11.5f} {f_absmax[i]:9.4f} {ratio:8.1f}") print("\n(if max/std > ~20, a clip after normalization is still recommended)") # write output if args.merge_into: with open(args.merge_into) as fp: existing = json.load(fp) existing.update(force_stats) with open(args.merge_into, "w") as fp: json.dump(existing, fp, indent=2) print(f"\nmerged force_ch_active_* into {args.merge_into}") else: out = args.out or str(root / "force_stats.json") with open(out, "w") as fp: json.dump(force_stats, fp, indent=2) print(f"\nwrote {out}") if __name__ == "__main__": main()