File size: 10,184 Bytes
b6f2e18 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | """
Descriptive statistics for the Isaac Lab "stack" dataset.
The repo's calc_stat_analysis.py / plot_action_curves.py are RoboTwin-specific (they
read joint_action/vector and endpose/*) and do not run on this data. This is the
equivalent for the stack format.
Distinct from calc_stat_stack.py: that produces the min/max the model normalizes with.
This describes the data -- distributions, episode structure, how much of it is the robot
sitting still, and whether the held-out split actually looks like the training split.
Reads only the small action/state arrays, never images.
Usage:
python -m utils.analyze_stack_dataset \
--dataset_dir /work/amin-a/srlwam/data/stack/sim/v0 \
--split_file ./splits/stack_sim_v0_split.json \
--out_json ./reports/stack_sim_v0_stats.json \
--out_png ./reports/stack_sim_v0_stats.png
"""
import argparse
import json
import sys
import time
from collections import defaultdict
from pathlib import Path
import h5py
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from dataloader.isaac_stack_dataset import ( # noqa: E402
load_or_create_split, canonicalize_quaternion, DEFAULT_STATE_KEYS)
ACTION_LABELS = ["dx", "dy", "dz", "drx", "dry", "drz", "grip"]
ACTION_UNITS = ["m", "m", "m", "rad", "rad", "rad", "cmd"]
def collect(episodes, idx, action_key, state_keys, canon, quat_key):
by_file = defaultdict(list)
for i in idx:
by_file[episodes[i]["hdf5_path"]].append(episodes[i]["demo_name"])
actions, states, lengths = [], [], []
for path, demos in sorted(by_file.items()):
with h5py.File(path, "r") as f:
for dn in demos:
g = f["data"][dn]
a = np.asarray(g[action_key][:], dtype=np.float64)
actions.append(a)
lengths.append(a.shape[0])
parts = []
for k in state_keys:
v = np.asarray(g["obs"][k][:], dtype=np.float64)
if v.ndim == 1:
v = v[:, None]
if canon and k == quat_key and v.shape[1] == 4:
v = canonicalize_quaternion(v)
parts.append(v)
states.append(np.concatenate(parts, axis=1))
return actions, states, np.array(lengths)
def describe(actions, states, lengths, stationary_eps):
A = np.concatenate(actions, axis=0)
S = np.concatenate(states, axis=0)
# "Stationary" = the pose delta (first 6 dims) is below eps. The LiLa-WAM pipeline
# strips these segments for RoboTwin (utils/clean_dataset_stationary.py); worth
# knowing how much of this dataset is the arm barely moving.
motion = np.abs(A[:, :6]).max(axis=1)
stationary = {f"frac_below_{e:g}": float((motion < e).mean()) for e in stationary_eps}
def per_dim(X, labels=None):
return [{
"name": (labels[i] if labels else f"d{i}"),
"min": float(X[:, i].min()), "max": float(X[:, i].max()),
"mean": float(X[:, i].mean()), "std": float(X[:, i].std()),
"p1": float(np.percentile(X[:, i], 1)), "p99": float(np.percentile(X[:, i], 99)),
} for i in range(X.shape[1])]
return {
"num_demos": int(len(lengths)),
"num_frames": int(A.shape[0]),
"episode_length": {
"min": int(lengths.min()), "max": int(lengths.max()),
"mean": float(lengths.mean()), "std": float(lengths.std()),
"median": float(np.median(lengths)),
},
"action": {
"dim": int(A.shape[1]),
"per_dim": per_dim(A, ACTION_LABELS if A.shape[1] == 7 else None),
"gripper_open_frac": float((A[:, 6] > 0).mean()) if A.shape[1] == 7 else None,
"motion_magnitude": {
"mean": float(motion.mean()), "median": float(np.median(motion)),
"p95": float(np.percentile(motion, 95)),
},
"stationary": stationary,
},
"state": {"dim": int(S.shape[1]), "per_dim": per_dim(S)},
}, A, S, motion
def plot(train, val, out_png):
try:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
except ImportError:
print("matplotlib missing; skipping figure")
return None
(tr_stats, A_tr, S_tr, mot_tr), (va_stats, A_va, _, mot_va) = train, val
fig, axes = plt.subplots(3, 4, figsize=(19, 11))
axes[0][0].hist(tr_stats["_lengths"], bins=40, color="#4C78A8", alpha=.85, label="train", density=True)
axes[0][0].hist(va_stats["_lengths"], bins=40, color="#F58518", alpha=.55, label="val", density=True)
axes[0][0].set_title("episode length (frames)"); axes[0][0].legend(fontsize=8)
for i in range(7):
ax = axes[(i + 1) // 4][(i + 1) % 4]
lo = min(np.percentile(A_tr[:, i], .1), np.percentile(A_va[:, i], .1))
hi = max(np.percentile(A_tr[:, i], 99.9), np.percentile(A_va[:, i], 99.9))
rng = (lo, hi) if hi > lo else None
ax.hist(A_tr[:, i], bins=80, range=rng, color="#4C78A8", alpha=.85, density=True, label="train")
ax.hist(A_va[:, i], bins=80, range=rng, color="#F58518", alpha=.55, density=True, label="val")
ax.set_title(f"action[{i}] {ACTION_LABELS[i]} ({ACTION_UNITS[i]})", fontsize=10)
ax.set_yscale("log")
if i == 0:
ax.legend(fontsize=8)
ax = axes[2][0]
ax.hist(mot_tr, bins=100, color="#4C78A8", alpha=.85, density=True, label="train")
ax.hist(mot_va, bins=100, color="#F58518", alpha=.55, density=True, label="val")
ax.set_yscale("log"); ax.set_title("max |pose delta| per frame"); ax.legend(fontsize=8)
ax = axes[2][1]
for j, lbl in enumerate(["eef_x", "eef_y", "eef_z"]):
ax.hist(S_tr[:, j], bins=60, alpha=.6, density=True, label=lbl)
ax.set_title("eef position (m)"); ax.legend(fontsize=8)
ax = axes[2][2]
for j, lbl in zip(range(3, 7), ["qw", "qx", "qy", "qz"]):
ax.hist(S_tr[:, j], bins=60, alpha=.6, density=True, label=lbl)
ax.set_title("eef quaternion (canonicalized)"); ax.legend(fontsize=8)
ax = axes[2][3]
phase = np.concatenate([np.linspace(0, 1, n) for n in tr_stats["_lengths"]])
mag = mot_tr
bins = np.linspace(0, 1, 41)
which = np.digitize(phase, bins) - 1
prof = [mag[which == b].mean() if (which == b).any() else np.nan for b in range(40)]
ax.plot(bins[:-1], prof, color="#4C78A8")
ax.set_title("motion vs normalized episode time"); ax.set_xlabel("phase")
for row in axes:
for a in row:
a.tick_params(labelsize=7)
fig.suptitle("srlwam stack/sim/v0 — dataset statistics (train vs held-out val)", fontsize=13)
fig.tight_layout()
Path(out_png).parent.mkdir(parents=True, exist_ok=True)
fig.savefig(out_png, dpi=115, bbox_inches="tight")
return out_png
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dataset_dir", required=True)
ap.add_argument("--split_file", default="./splits/stack_sim_v0_split.json")
ap.add_argument("--out_json", default="./reports/stack_sim_v0_stats.json")
ap.add_argument("--out_png", default="./reports/stack_sim_v0_stats.png")
ap.add_argument("--val_ratio", type=float, default=0.1)
ap.add_argument("--split_seed", type=int, default=42)
ap.add_argument("--action_key", default="actions")
ap.add_argument("--state_keys", nargs="+", default=list(DEFAULT_STATE_KEYS))
ap.add_argument("--no_canonicalize_quat", action="store_true")
ap.add_argument("--quat_state_key", default="eef_quat")
ap.add_argument("--stationary_eps", nargs="+", type=float, default=[1e-4, 1e-3, 5e-3])
args = ap.parse_args()
split = load_or_create_split(args.dataset_dir, args.split_file,
args.val_ratio, args.split_seed)
eps = split["episodes"]
canon = not args.no_canonicalize_quat
out, packed = {}, {}
t0 = time.time()
for name in ("train", "val"):
acts, sts, lens = collect(eps, split[name], args.action_key, args.state_keys,
canon, args.quat_state_key)
stats, A, S, motion = describe(acts, sts, lens, args.stationary_eps)
stats["_lengths"] = lens
out[name] = stats
packed[name] = (stats, A, S, motion)
print(f" {name}: {stats['num_demos']} demos, {stats['num_frames']} frames "
f"({time.time() - t0:.0f}s)")
png = plot(packed["train"], packed["val"], args.out_png)
serializable = {k: {kk: vv for kk, vv in v.items() if not kk.startswith("_")}
for k, v in out.items()}
serializable["meta"] = {
"dataset_dir": args.dataset_dir, "split_file": args.split_file,
"canonicalize_quat": canon, "action_key": args.action_key,
"state_keys": list(args.state_keys),
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
}
Path(args.out_json).parent.mkdir(parents=True, exist_ok=True)
with open(args.out_json, "w") as f:
json.dump(serializable, f, indent=2)
print(f"\nWrote {args.out_json}" + (f" and {png}" if png else ""))
# Train/val comparability -- a split that is not representative makes val misleading.
print("\ntrain vs val (should be close):")
tr, va = out["train"], out["val"]
print(f" {'metric':<28}{'train':>12}{'val':>12}{'rel diff':>11}")
rows = [("episode length mean", tr["episode_length"]["mean"], va["episode_length"]["mean"]),
("gripper open fraction", tr["action"]["gripper_open_frac"], va["action"]["gripper_open_frac"]),
("motion magnitude mean", tr["action"]["motion_magnitude"]["mean"],
va["action"]["motion_magnitude"]["mean"])]
for lbl, a, b in rows:
rel = abs(a - b) / max(abs(a), 1e-12)
print(f" {lbl:<28}{a:>12.4f}{b:>12.4f}{rel:>10.2%}")
for i in range(min(7, tr["action"]["dim"])):
a, b = tr["action"]["per_dim"][i], va["action"]["per_dim"][i]
rel = abs(a["std"] - b["std"]) / max(abs(a["std"]), 1e-12)
print(f" std {a['name']:<24}{a['std']:>12.5f}{b['std']:>12.5f}{rel:>10.2%}")
if __name__ == "__main__":
main()
|