syCen commited on
Commit
07f7ccb
·
verified ·
1 Parent(s): 5cdd76e

Create compute_physical_stats.py

Browse files
Files changed (1) hide show
  1. compute_physical_stats.py +123 -0
compute_physical_stats.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ compute_dataset_stats.py
4
+ Dataset-wide normalization stats for the contact / force modalities. Run AFTER
5
+ generate_modalities.py (needs modalities/{contact,force}/*.npy).
6
+
7
+ Replaces the old compute_force_stats.py + compute_dataset_stats() pair.
8
+
9
+ contact -> contact_ch_max (per finger, 2) nonneg magnitude field:
10
+ normalize by max only.
11
+ force -> force_ch_active_std (per channel, 6) signed, heavy-tailed,
12
+ ~98% zero background:
13
+ std over NONZERO pixels
14
+ only (all-pixel std is
15
+ diluted toward 0 and
16
+ blows up real contacts).
17
+
18
+ Output: <root>/dataset_norm_params.json (or --out)
19
+
20
+ Usage:
21
+ python compute_dataset_stats.py --root ./grasping
22
+ python compute_dataset_stats.py --root ./grasping --out ./grasping/dataset_norm_params.json
23
+ """
24
+ import argparse
25
+ import json
26
+ from pathlib import Path
27
+
28
+ import numpy as np
29
+ from tqdm import tqdm
30
+
31
+
32
+ FORCE_CH = ["L_fx", "L_fy", "L_fz", "R_fx", "R_fy", "R_fz"]
33
+
34
+
35
+ def main():
36
+ ap = argparse.ArgumentParser()
37
+ ap.add_argument("--root", required=True)
38
+ ap.add_argument("--out", default=None,
39
+ help="output json (default: <root>/dataset_norm_params.json)")
40
+ args = ap.parse_args()
41
+
42
+ root = Path(args.root)
43
+ episodes = [p for p in root.rglob("*")
44
+ if p.is_dir() and (p / "modalities" / "force").exists()]
45
+ print(f"Found {len(episodes)} episodes with modalities")
46
+
47
+ # contact: per-finger max only (values are >= 0)
48
+ contact_ch_max = np.zeros(2)
49
+
50
+ # force: per-channel accumulators over NONZERO pixels only
51
+ f_sum = np.zeros(6); f_sq = np.zeros(6); f_cnt = np.zeros(6)
52
+ f_absmax = np.zeros(6)
53
+ f_min = np.full(6, np.inf); f_max = np.full(6, -np.inf)
54
+
55
+ n_frames = 0
56
+ n_bad = 0
57
+ for ep in tqdm(episodes, desc="episodes"):
58
+ cdir = ep / "modalities" / "contact"
59
+ fdir = ep / "modalities" / "force"
60
+ for ff in sorted(fdir.glob("*.npy")):
61
+ f = np.load(ff).astype(np.float64) # (6,H,W)
62
+ if f.ndim != 3 or f.shape[0] != 6:
63
+ n_bad += 1
64
+ continue
65
+ flat = f.reshape(6, -1)
66
+ for ch in range(6):
67
+ v = flat[ch][flat[ch] != 0] # nonzero only
68
+ if v.size:
69
+ f_sum[ch] += v.sum()
70
+ f_sq[ch] += (v ** 2).sum()
71
+ f_cnt[ch] += v.size
72
+ f_absmax[ch] = max(f_absmax[ch], float(np.abs(v).max()))
73
+ f_min[ch] = min(f_min[ch], float(v.min()))
74
+ f_max[ch] = max(f_max[ch], float(v.max()))
75
+
76
+ cf = cdir / ff.name
77
+ if cf.exists():
78
+ c = np.load(cf).astype(np.float64) # (2,H,W)
79
+ if c.ndim == 3 and c.shape[0] == 2:
80
+ contact_ch_max = np.maximum(
81
+ contact_ch_max, c.reshape(2, -1).max(1))
82
+ n_frames += 1
83
+
84
+ if n_frames == 0:
85
+ raise RuntimeError("no modality frames found under --root")
86
+
87
+ f_cnt_safe = np.maximum(f_cnt, 1)
88
+ f_active_mean = f_sum / f_cnt_safe
89
+ f_active_std = np.sqrt(np.maximum(f_sq / f_cnt_safe - f_active_mean ** 2, 1e-12))
90
+ f_min[~np.isfinite(f_min)] = 0.0
91
+ f_max[~np.isfinite(f_max)] = 0.0
92
+
93
+ stats = {
94
+ "num_episodes": len(episodes),
95
+ "num_frames": int(n_frames),
96
+ # contact (2): normalize by per-finger max
97
+ "contact_ch_max": contact_ch_max.tolist(),
98
+ # force (6): normalize by per-channel nonzero std
99
+ "force_ch_active_mean": f_active_mean.tolist(),
100
+ "force_ch_active_std": f_active_std.tolist(),
101
+ "force_ch_abs_max": f_absmax.tolist(),
102
+ "force_ch_min": f_min.tolist(),
103
+ "force_ch_max": f_max.tolist(),
104
+ }
105
+
106
+ # heavy-tail check: if abs_max >> std, clip after normalizing
107
+ print(f"\nframes: {n_frames} (bad-shape skipped: {n_bad})")
108
+ print(f"contact_ch_max: {contact_ch_max.tolist()}")
109
+ print(f"{'ch':6s} {'active_std':>11s} {'abs_max':>9s} {'max/std':>8s}")
110
+ print("-" * 40)
111
+ for i in range(6):
112
+ ratio = f_absmax[i] / (f_active_std[i] + 1e-12)
113
+ print(f"{FORCE_CH[i]:6s} {f_active_std[i]:11.5f} {f_absmax[i]:9.4f} {ratio:8.1f}")
114
+ print("(max/std > ~20 -> clip after normalization, e.g. force_clip=6)")
115
+
116
+ out = args.out or str(root / "dataset_norm_params.json")
117
+ with open(out, "w") as fp:
118
+ json.dump(stats, fp, indent=2)
119
+ print(f"\nwrote {out}")
120
+
121
+
122
+ if __name__ == "__main__":
123
+ main()