"""Structured, physically valid hand-only excitation data for flow-matching dynamics (schema 3.0.0-structured). Every environment runs one seeded program (shadow_dynamics/structured_excitation.py) at one speed regime. Programs are pre-checked with FK for visual-link penetration and redrawn if they overlap. The hand settles from the neutral pose to the program's first target (minimum jerk, excluded from the record), then runs T control steps. Every recorded state is labelled by shadow_dynamics.validity (visual-link penetration + PhysX self-contact + numerical checks); an episode is cut at its first invalid state and dropped if fewer than --min-steps remain. Saved in model-facing units: deg, deg/s. Output directory (never overwritten): shard_XXX.h5 (<= --shard-size episodes each), episodes.jsonl, rejections.jsonl, manifest.json, physics_parameters.json, geometry.npz, poses.json, source/. """ import argparse, hashlib, json, os, shutil, sys, time, traceback from pathlib import Path ROOT = Path(__file__).resolve().parents[1]; sys.path.insert(0, str(ROOT)) from shadow_dynamics.resources import restrict_simulator_gpu PHYSICAL_GPU = restrict_simulator_gpu() from omni.isaac.lab.app import AppLauncher parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", required=True) parser.add_argument("--poses", default="shadow_dynamics/data/shadow_pose_library.json") parser.add_argument("--viz-model", default="artifacts/viz_hand_model") parser.add_argument("--num-envs", type=int, default=128) parser.add_argument("--speeds-deg", nargs="+", type=float, default=[1, 5, 10, 20, 30]) parser.add_argument("--episodes-per-speed", nargs="+", type=int, required=True, help="one value for all speeds, or one per speed") parser.add_argument("--schedule", choices=["uniform", "shares"], default="shares", help="uniform: equal count per family (pilot); shares: group shares 30/20/25/15/10") parser.add_argument("--hold-mode", choices=["library", "balanced"], default="library", help="balanced: idle fingers hold random mixed (mostly bent) postures") parser.add_argument("--family-shares", nargs="*", default=None, help="name=fraction pairs; overrides --schedule (fractions renormalized)") parser.add_argument("--split", choices=["seed", "ood"], default="seed", help="seed: seed %% 10 (8 val, 9 test, else train); ood: every episode is OOD test") parser.add_argument("--seconds", type=float, default=20.0) parser.add_argument("--settle-seconds", type=float, default=2.0) parser.add_argument("--hold-seconds", type=float, default=0.5) parser.add_argument("--seed", type=int, required=True, help="first episode seed; episode k uses seed + k") parser.add_argument("--min-steps", type=int, default=40, help="drop episodes whose valid prefix is shorter (2 s)") parser.add_argument("--precheck-mm", type=float, default=1.0, help="max visual penetration allowed on the commanded path") parser.add_argument("--hull-contact-mm", type=float, default=0.5) parser.add_argument("--hull-invalid-mm", type=float, default=3.0) parser.add_argument("--hull-palm-invalid-mm", type=float, default=8.0, help="finger-palm pairs: the palm hull over-covers its concave front (a fully curled index reads ~5 mm with 1-2.6 mm PhysX clearance); gross-overlap guard only, the palm's PhysX boxes stop real pass-through") parser.add_argument("--physx-penetration-mm", type=float, default=2.0) parser.add_argument("--max-redraws", type=int, default=40) parser.add_argument("--shard-size", type=int, default=1024) AppLauncher.add_app_launcher_args(parser) args = parser.parse_args(); args.physics_hz = 120; args.control_hz = 20; args.mode = "free" app = AppLauncher(args, multi_gpu=False).app import h5py import numpy as np import torch from shadow_dynamics.env import ResearchShadowEnv, make_cfg from shadow_dynamics.hand_geometry import HandGeometry, TorchFK from shadow_dynamics import structured_excitation as sx from shadow_dynamics.validity import ValidityMonitor, CLASS_NAMES, INVALID_PENETRATION, INVALID_NUMERICAL HZ = 20 UNITS = {"position_unit": "deg", "velocity_unit": "deg/s", "action_unit": "deg", "effort_unit": "N*m (revolute)", "force_unit": "N", "penetration_unit": "mm", "time_unit": "s", "control_dt_s": 1.0 / HZ, "control_hz": HZ, "physics_hz": 120} def physics_parameters(env): v = env.hand.root_physx_view; out = {"joint_names": env.hand.joint_names, "body_names": env.hand.body_names, "units": { "mass": "kg", "inertia": "kg*m^2 (body frame, row-major 3x3)", "com": "m + quat wxyz (body frame)", "stiffness": "N*m/rad", "damping": "N*m*s/rad", "limits": "rad", "max_force": "N*m", "armature": "kg*m^2", "friction": "dimensionless", "tendon_stiffness": "N/m (PhysX fixed-tendon units)"}} for name, fn in [("mass", "get_masses"), ("inertia", "get_inertias"), ("com", "get_coms"), ("stiffness", "get_dof_stiffnesses"), ("damping", "get_dof_dampings"), ("limits", "get_dof_limits"), ("max_force", "get_dof_max_forces"), ("max_velocity", "get_dof_max_velocities"), ("armature", "get_dof_armatures"), ("friction", "get_dof_friction_coefficients"), ("tendon_stiffness", "get_fixed_tendon_stiffnesses"), ("tendon_damping", "get_fixed_tendon_dampings"), ("tendon_limit_stiffness", "get_fixed_tendon_limit_stiffnesses"), ("tendon_limits", "get_fixed_tendon_limits"), ("tendon_rest_length", "get_fixed_tendon_rest_lengths"), ("tendon_offset", "get_fixed_tendon_offsets")]: try: out[name] = np.asarray(getattr(v, fn)()[0].cpu() if hasattr(getattr(v, fn)(), "cpu") else getattr(v, fn)()[0]).tolist() except Exception as e: out[name] = f"unavailable: {type(e).__name__}" try: out["fixed_tendon_names"] = list(env.hand.fixed_tendon_names) except Exception: pass out["actuated_indices"] = env.active; out["passive_indices"] = env.passive out["actuator_model"] = "Isaac Lab ImplicitActuator (PhysX joint drive, position target), gains above; hand link gravity disabled" return out class ShardWriter: def __init__(self, out, manifest, shard_size): self.out = out; self.manifest = manifest; self.size = shard_size; self.file = None; self.n = 0; self.shard = -1; self.index = [] def _open(self): if self.file is not None: self._close() self.shard += 1; path = self.out / f"shard_{self.shard:03d}.h5.partial"; self.file = h5py.File(path, "w") self.file.attrs["schema_version"] = sx.SCHEMA; self.file.attrs["manifest_json"] = json.dumps(self.manifest) for k, v in UNITS.items(): self.file.attrs[k] = v def _close(self): self.file.attrs["complete"] = True; name = self.file.filename; self.file.close(); os.replace(name, name[:-len(".partial")]); self.file = None def write(self, data, meta): if self.file is None or self.n % self.size == 0: self._open() eid = f"episode_{self.n:06d}"; g = self.file.create_group(eid); g.attrs["metadata_json"] = json.dumps(meta) for k, v in data.items(): g.create_dataset(k, data=v, compression="gzip", compression_opts=1, shuffle=True) self.n += 1; entry = dict(episode_id=eid, shard=f"shard_{self.shard:03d}.h5", **{k: v for k, v in meta.items() if k not in ("program", "reference_deg")}) self.index.append(entry) with (self.out / "episodes.jsonl").open("a") as f: f.write(json.dumps(entry) + "\n") return entry def close(self): if self.file is not None: self._close() def main(): assert sorted(os.sched_getaffinity(0)) == __import__("shadow_dynamics.resources", fromlist=["budget_cpus"]).budget_cpus() torch.set_num_threads(1) out = Path(args.output); out.mkdir(parents=True, exist_ok=False) per = args.episodes_per_speed * len(args.speeds_deg) if len(args.episodes_per_speed) == 1 else args.episodes_per_speed assert len(per) == len(args.speeds_deg) if args.split == "seed": assert not set(args.speeds_deg) & set(sx.OOD_SPEEDS_DEG), "OOD speeds must use --split ood" else: assert set(args.speeds_deg) <= set(sx.OOD_SPEEDS_DEG) if args.family_shares: fs = {k: float(v) for k, v in (x.split("=") for x in args.family_shares)}; assert set(fs) <= set(sx.FAMILIES), fs; tot = sum(fs.values()); plan = [] for sp, n in zip(args.speeds_deg, per): fams = [f for f, w in fs.items() for _ in range(int(round(n * w / tot)))]; fams = (fams + list(fs) * n)[:n]; plan += [(sp, f) for f in fams] plan = [plan[i] for i in np.random.default_rng(args.seed).permutation(len(plan))] else: plan = sx.schedule({sp: n for sp, n in zip(args.speeds_deg, per)}, args.speeds_deg, np.random.default_rng(args.seed), mode=args.schedule) lib = json.loads(Path(args.poses).read_text()); shutil.copy2(args.poses, out / "poses.json") cfg = make_cfg(args); cfg.object_cfg.spawn.rigid_props.kinematic_enabled = True env = ResearchShadowEnv(cfg); writer = None try: env.configure_research("free"); N = env.num_envs; dev = env.device low, high = np.rad2deg(env.low.cpu().numpy()).astype(np.float64), np.rad2deg(env.high.cpu().numpy()).astype(np.float64) assert [a.replace("robot0_", "") for a in env.action_names] == lib["action_names"] spec = sx.Spec(env.action_names, low, high, lib["poses_deg"]); gen = sx.Generator(spec, args.seconds, HZ, hold_mode=args.hold_mode); T = gen.T geo = HandGeometry.from_viz_model(args.viz_model); geo.save(out / "geometry.npz"); fk = TorchFK(args.viz_model, dev) assert fk.joint_names == env.hand.joint_names checker = sx.ProgramChecker(geo, fk, env.hand.joint_names, env.action_names, args.precheck_mm / 1000, dev) thresholds = dict(touch_separation_m=0.0, touch_force_n=1e-3, limit_excess_rad=0.5, velocity_rad_s=200.0, hull_invalid_m=args.hull_invalid_mm / 1000, hull_palm_invalid_m=args.hull_palm_invalid_mm / 1000, physx_penetration_m=args.physx_penetration_mm / 1000, hull_contact_m=args.hull_contact_mm / 1000) mon = ValidityMonitor(env, geo, thresholds) (out / "physics_parameters.json").write_text(json.dumps(physics_parameters(env), indent=1)) mapping = dict(joint_names=env.hand.joint_names, action_names=env.action_names, active_indices=env.active, passive_indices=env.passive, joint_limits_deg=np.rad2deg(env.hand.data.soft_joint_pos_limits[0].cpu().numpy()).tolist(), action_limits_deg=np.stack([low, high], 1).tolist(), body_names=env.hand.body_names, finger_channels=sx.FINGER_CHANNELS, wrist_channels=sx.WRIST) manifest = dict(run_id=out.name, schema_version=sx.SCHEMA, units=UNITS, mapping=mapping, arguments=vars(args), control_hz=HZ, physics_hz=120, episode_steps=T, hold_mode=args.hold_mode, family_shares=args.family_shares, speeds_deg_s=args.speeds_deg, episodes_per_speed=per, schedule=args.schedule, split_mode=args.split, split_rule="seed % 10 == 8 validation, == 9 test, else train" if args.split == "seed" else "all episodes: ood_speed_", families=sx.FAMILIES, family_groups=sx.GROUPS, group_shares=sx.GROUP_SHARES, validity_thresholds=thresholds, precheck_mm=args.precheck_mm, validity_classes=CLASS_NAMES, passive_model_precheck="J0 = clip(1.13 J1, 0, 90) deg", action_semantics="action_applied[t] is the joint-position target applied between state t and t+1 (after slew limit = speed regime, and joint limits); action_commanded[t] is the program's request before slew limiting", state_semantics="T+1 states, T actions; settle (min-jerk from neutral, excluded) + hold precede state 0; initial_target_deg = applied target during the hold", effort_semantics="hand.data.applied_torque: implicit-actuator torque estimate stiffness*(target-q) - damping*qdot, clipped to effort limits", contact_semantics="PhysX self-contact between hand links (touching: separation <= 0 or force > 1e-3 N); visual-link penetration from k-DOP hulls of the visual meshes", model_id="isaaclab-1.2-stock-shadow-hand, self-collision on, hand gravity off", physical_gpu=PHYSICAL_GPU, cpu_affinity=sorted(os.sched_getaffinity(0))) (out / "manifest.json").write_text(json.dumps(manifest, indent=1)) src = out / "source"; src.mkdir() for p in [Path(__file__), ROOT / "shadow_dynamics/structured_excitation.py", ROOT / "shadow_dynamics/validity.py", ROOT / "shadow_dynamics/hand_geometry.py", ROOT / "shadow_dynamics/env.py"]: shutil.copy2(p, src / p.name) writer = ShardWriter(out, manifest, args.shard_size) started = time.monotonic(); steps_done = 0; counts = {"written": 0, "dropped": 0, "precheck_redraws": 0, "precheck_failed": 0} n_settle, n_hold = int(args.settle_seconds * HZ), int(args.hold_seconds * HZ) for b0 in range(0, len(plan), N): batch = plan[b0:b0 + N]; seeds = [args.seed + b0 + i for i in range(len(batch))]; n = len(batch) progs, infos, rngs = [None] * n, [None] * n, [np.random.default_rng(s) for s in seeds]; redraws = [0] * n; pending = list(range(n)) while pending: # generate, check the start, scale toward the start where contact is near, check the applied path; redraw failures cands = {i: gen.generate(rngs[i], batch[i][1], batch[i][0]) for i in pending} raw = np.stack([c[0] for c in cands.values()]); start_ok = checker.max_penetration(raw[:, 0]) <= checker.threshold fixed, lam = checker.repair(raw) for k, (i, c) in enumerate(cands.items()): c[1]["repair_mean_scale"] = round(float(lam[k].mean()), 4); c[1]["repair_scaled_fraction"] = round(float((lam[k] < 0.999).mean()), 4) cands[i] = (fixed[k], c[1]) paths = np.stack([sx.applied_path(c[0], c[0][0], batch[i][0], low, high) for i, c in cands.items()]) settle = np.stack([sx.min_jerk(np.linspace(0, 1, 9))[:, None] * c[0][0][None] for c in cands.values()]) worst = np.maximum(checker.check_paths(paths), checker.check_paths(settle)); worst[~start_ok] = np.inf nxt = [] for (i, c), w in zip(cands.items(), worst): if w <= checker.threshold or redraws[i] >= args.max_redraws: progs[i], infos[i] = c; infos[i]["precheck_max_penetration_mm"] = round(float(w) * 1000, 3); infos[i]["precheck_passed"] = bool(w <= checker.threshold) if w > checker.threshold: counts["precheck_failed"] += 1 else: redraws[i] += 1; nxt.append(i) pending = nxt counts["precheck_redraws"] += sum(redraws) req = np.zeros((T, N, 20)); req[:, :n] = np.stack([p.astype(np.float64) for p in progs], 1) if n < N: req[:, n:] = 0.0 start = req[0].copy() env.reset_physical() for k in range(n_settle): # settle from neutral to the first target, then hold (excluded from the record) tgt = sx.min_jerk((k + 1) / n_settle) * start; env.advance(torch.as_tensor(np.deg2rad(tgt), dtype=torch.float32, device=dev)) for k in range(n_hold): env.advance(torch.as_tensor(np.deg2rad(start), dtype=torch.float32, device=dev)) prev = start.copy(); slews = np.array([batch[i][0] for i in range(n)] + [1.0] * (N - n)) rec = {k: [] for k in ("q", "qdot", "effort", "fingertip_force", "validity", "hull_penetration_mm", "hull_finger_penetration_mm", "hull_palm_penetration_mm", "hull_worst_pair", "physx_min_separation_mm", "touching_pairs", "link_contact", "finger_contact", "joint_limit_flags")} pair_hist = torch.zeros(N, mon.L, mon.L, device=dev) def snap(): d = env.hand.data; m = mon.measure(); pair_hist.add_(m.pop("touching_matrix").float()) rec["q"].append(torch.rad2deg(d.joint_pos).cpu().numpy()); rec["qdot"].append(torch.rad2deg(d.joint_vel).cpu().numpy()) rec["effort"].append(d.applied_torque.cpu().numpy()) rec["fingertip_force"].append(torch.stack([env.scene[f].data.net_forces_w[:, 0] for f in ("th", "ff", "mf", "rf", "lf")], 1).cpu().numpy()) for k, v in m.items(): rec[k].append(v.cpu().numpy()) snap(); applied, commanded = [], [] for t in range(T): prev = np.clip(prev + np.clip(req[t] - prev, -slews[:, None] / HZ, slews[:, None] / HZ), low, high) env.advance(torch.as_tensor(np.deg2rad(prev), dtype=torch.float32, device=dev)) applied.append(np.rad2deg(env.last_target.cpu().numpy().astype(np.float64))); commanded.append(req[t].copy()); snap() steps_done += T * n R = {k: np.stack(v, 1) for k, v in rec.items()}; A = np.stack(applied, 1); C = np.stack(commanded, 1) pair_frac = (pair_hist / (T + 1)).cpu().numpy() for i in range(n): sp, fam = batch[i]; s = seeds[i]; cls = R["validity"][i] bad = np.where(cls >= INVALID_PENETRATION)[0]; cut = int(bad[0]) if len(bad) else T + 1 # number of states kept n_act = cut - 1 reason = "time_limit" if not len(bad) else ("invalid_penetration" if cls[bad[0]] == INVALID_PENETRATION else "invalid_numerical") split = sx.split_for_seed(s) if args.split == "seed" else f"ood_speed_{int(sp)}" info = infos[i] if n_act < args.min_steps: counts["dropped"] += 1 with (out / "rejections.jsonl").open("a") as f: f.write(json.dumps(dict(seed=s, family=fam, speed_deg_s=sp, reason=reason, first_invalid_step=int(bad[0]) if len(bad) else None, hull_mm_at_invalid=float(R["hull_penetration_mm"][i][bad[0]]) if len(bad) else None, worst_pair=list(geo.pairs[int(R["hull_worst_pair"][i][bad[0]])]) if len(bad) else None, precheck_mm=info["precheck_max_penetration_mm"])) + "\n") continue if len(bad): with (out / "rejections.jsonl").open("a") as f: f.write(json.dumps(dict(seed=s, family=fam, speed_deg_s=sp, reason=reason + "_truncated", first_invalid_step=int(bad[0]), kept_steps=n_act, hull_mm_at_invalid=float(R["hull_penetration_mm"][i][bad[0]]), worst_pair=list(geo.pairs[int(R["hull_worst_pair"][i][bad[0]])]))) + "\n") data = {k: R[k][i][:cut].astype(np.float32 if R[k].dtype.kind == "f" else R[k].dtype) for k in R} data["action_applied"] = A[i][:n_act].astype(np.float32); data["action_commanded"] = C[i][:n_act].astype(np.float32) data["time"] = (np.arange(cut) / HZ).astype(np.float64) qd = data["qdot"]; pas = env.passive cnt = np.bincount(cls[:cut], minlength=4) top_pairs = sorted([(float(pair_frac[i, a, b]), mon.body_names[a], mon.body_names[b]) for a in range(mon.L) for b in range(a + 1, mon.L) if pair_frac[i, a, b] > 0], reverse=True)[:8] meta = dict(seed=s, split=split, motion_family=fam, family_group=sx.FAMILY_GROUP[fam], active_fingers=info.get("active_fingers"), speed_deg_s=float(sp), control_hz=HZ, physics_hz=120, valid=True, steps=n_act, termination_reason="time_limit" if not len(bad) else reason + "_truncated", initial_target_deg=np.round(start[i], 5).tolist(), validity_counts={CLASS_NAMES[k]: int(cnt[k]) for k in range(4)}, contact_fraction=round(float((cls[:cut] == 1).mean()), 4), max_hull_penetration_mm=round(float(data["hull_penetration_mm"].max()), 3), min_physx_separation_mm=round(float(data["physx_min_separation_mm"].min()), 3), touching_link_pairs=top_pairs, max_abs_qdot_deg_s=round(float(np.abs(qd).max()), 2), max_abs_passive_qdot_deg_s=round(float(np.abs(qd[:, pas]).max()), 2), passive_spike_steps_over_40rad_s=int((np.abs(qd[:, pas]) > np.rad2deg(40)).any(1).sum()), precheck_redraws=redraws[i], precheck_max_penetration_mm=info["precheck_max_penetration_mm"], run_id=out.name, env_index=i, program={k: v for k, v in info.items() if k not in ("precheck_max_penetration_mm", "precheck_passed")}) writer.write(data, meta); counts["written"] += 1 el = time.monotonic() - started print(f"BATCH {b0 // N + 1}/{(len(plan) + N - 1) // N} episodes {counts['written']} dropped {counts['dropped']} redraws {counts['precheck_redraws']} " f"precheck_failed {counts['precheck_failed']} elapsed {el:.0f}s env_steps_per_s {steps_done / el:.0f}", flush=True) writer.close() summary = dict(counts, elapsed_s=time.monotonic() - started, env_steps_per_s=steps_done / (time.monotonic() - started), shards=writer.shard + 1) summary["sha256"] = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(out.glob("shard_*.h5"))} (out / "collection_summary.json").write_text(json.dumps(summary, indent=1)) print("COLLECTION_COMPLETE " + json.dumps({k: v for k, v in summary.items() if k != "sha256"}), flush=True) finally: if writer and writer.file is not None: writer.file.close() env.close() try: main() except Exception: traceback.print_exc(); sys.stdout.flush(); sys.stderr.flush(); os._exit(1) finally: app.close()