#!/usr/bin/env python """Fit cloth parameter card (density, bending, air_damp) to ground-truth cloth trajectories, NeuIDO-style: differentiable-proxy fitting loop that re-simulates in Blender with candidate parameters and minimizes trajectory distance. This is the "with NeuIDO method" arm of the ablation. The "without" arm just uses fixed default parameters (no fitting). Method (mirror of NeuIDO's few-shot adaptation, Eq. 8, but with a classical optimizer instead of a learned latent): z_hat = argmin_z L_sim(R(z), u) where R(z) = Blender cloth rollout under parameter card z, and L measures per-frame vertex-cloud distance (chamfer) + bbox/COM matching vs the observed cloth positions u = dyn/Cloth.npz. Coordinate notes: * dyn/Cloth.npz pos is in world coordinates already (verified vs bbox of static table mesh), same as Blender world space after to_mesh(). * The truth cloth starts exactly at frame-0 pose in every rollout, so the fit identifies the card (density/bending/air) from the drop dynamics. Usage (H100, after unpack_world.py): python fit_params_neuido.py --world work/B_07/world --out work/B_07/fit \ --trials 24 --parallel 3 Output: /best_card.json, /trials.csv, /fit_log.txt """ import argparse import csv import itertools import json import os import subprocess import sys import tempfile from pathlib import Path import numpy as np BLENDER = os.path.expanduser("~/jiayin/blender/blender") SCRIPT = os.path.expanduser("~/jiayin/4dcodebench/resim/resim_cloth_blender.py") def chamfer(a, b, n=2000, seed=0): rng = np.random.default_rng(seed) ai = rng.choice(len(a), min(n, len(a)), replace=False) bi = rng.choice(len(b), min(n, len(b)), replace=False) A, B = a[ai].astype(np.float64), b[bi].astype(np.float64) d = ((A[:, None, :] - B[None, :, :]) ** 2).sum(-1) d1 = np.sqrt(d.min(1)) d2 = np.sqrt(((B[:, None, :] - A[None, :, :]) ** 2).sum(-1)).min(1) return 0.5 * (d1.mean() + d2.mean()) def rollout_loss(world_dir, traj_dir, gt, frame_stride=3, n_samples=1500): """Loss between a rollout's clothtraj.npz and gt (F,N,3).""" f = Path(traj_dir) / "clothtraj.npz" if not f.exists(): return None try: sim = np.load(f)["pos"].astype(np.float32) except Exception: return None if not np.isfinite(sim).all() or sim.shape != gt.shape: return None # NaN/instability guard: cloth flew away if np.abs(sim).max() > 50: return 10.0 frames = list(range(0, gt.shape[0], frame_stride)) if frames[-1] != gt.shape[0] - 1: frames.append(gt.shape[0] - 1) losses = [chamfer(sim[i], gt[i], n=n_samples, seed=i) for i in frames] return float(np.mean(losses)) def run_rollout(world_dir, out_dir, card, gpu, timeout=600): """Run one Blender cloth rollout with a parameter card. Returns bool. Fitting rollouts use --no_render: sim + trajectory export take ~4 min, rendering would add ~12 min for pixels we never look at during fitting. """ cmd = [ BLENDER, "--background", "--python", SCRIPT, "--", "--world", str(world_dir), "--out", str(out_dir), "--density", str(card["density"]), "--bending", str(card["bending"]), "--air_damp", str(card["air_damp"]), "--no_render", "--quality", "8", # faster solver for fitting ] logf = open(Path(out_dir) / "blender.log", "w") env = dict(os.environ, CUDA_VISIBLE_DEVICES=str(gpu)) try: subprocess.run(cmd, env=env, stdout=logf, stderr=subprocess.STDOUT, timeout=timeout, check=False) except subprocess.TimeoutExpired: logf.close() return False logf.close() return (Path(out_dir) / "clothtraj.npz").exists() def main(): ap = argparse.ArgumentParser() ap.add_argument("--world", required=True) ap.add_argument("--out", required=True) ap.add_argument("--trials", type=int, default=24) ap.add_argument("--parallel", type=int, default=3, help="concurrent rollouts") ap.add_argument("--gpus", default="4,5,6", help="GPUs to rotate for rollouts") ap.add_argument("--seed", type=int, default=7) ap.add_argument("--center", default=None, help="JSON file with a card; when given, sample locally " "around it (gaussian, --sigma) instead of global uniform") ap.add_argument("--sigma", default="0.15,0.4,0.3", help="gaussian std for density,bending,air_damp local sampling") args = ap.parse_args() world = Path(args.world).resolve() out = Path(args.out).resolve() out.mkdir(parents=True, exist_ok=True) gpus = [int(g) for g in args.gpus.split(",")] gt = np.load(world / "dyn" / "Cloth.npz")["pos"].astype(np.float32) F = gt.shape[0] rng = np.random.default_rng(args.seed) trials = [] if args.center: # local refinement (NeuIDO few-shot adaptation analogue): start from a # predicted card and explore its neighborhood c = json.loads(Path(args.center).read_text()) s_d, s_b, s_a = (float(x) for x in args.sigma.split(",")) for i in range(args.trials): if i == 0: trials.append({"density": c["density"], "bending": c["bending"], "air_damp": c["air_damp"], "tag": "center"}) else: trials.append({ "density": float(np.clip(rng.normal(c["density"], s_d), 0.03, 3.0)), "bending": float(np.clip(rng.normal(c["bending"], s_b), 0.0, 6.0)), "air_damp": float(np.clip(rng.normal(c["air_damp"], s_a), 0.1, 6.0)), "tag": f"loc{i}", }) else: # global search: first point = default card, rest uniform in the box dens_lo, dens_hi = 0.08, 1.6 bend_lo, bend_hi = 0.0, 4.0 air_lo, air_hi = 0.3, 4.0 trials.append({ "density": 0.35, "bending": 0.02, "air_damp": 1.0, "tag": "default" }) while len(trials) < args.trials: trials.append({ "density": float(rng.uniform(dens_lo, dens_hi)), "bending": float(rng.uniform(bend_lo, bend_hi)), "air_damp": float(rng.uniform(air_lo, air_hi)), "tag": f"rand{len(trials)}", }) log = open(out / "fit_log.txt", "a") rows = [] def work(item, gpu): tag = item["tag"] tdir = out / f"trial_{tag}" tdir.mkdir(exist_ok=True) ok = run_rollout(world, tdir, item, gpu) loss = None if ok: try: loss = rollout_loss(world, tdir, gt) except Exception as e: print(f"[fit] {tag} loss error: {e}", flush=True) loss = None row = dict(item, loss=loss) print(f"[fit] {tag} card={item} loss={loss}", flush=True) print(f"[fit] {tag} card={item} loss={loss}", file=log, flush=True) return row results = [] from concurrent.futures import ThreadPoolExecutor gpu_cycle = itertools.cycle(gpus) queue = list(trials) with ThreadPoolExecutor(max_workers=args.parallel) as ex: futs = [] for item in queue: gpu = next(gpu_cycle) futs.append(ex.submit(work, item, gpu)) for f in futs: results.append(f.result()) ok = [r for r in results if r["loss"] is not None] ok.sort(key=lambda r: r["loss"]) best = ok[0] print(f"[fit] BEST: {best}", flush=True) print(f"[fit] BEST: {best}", file=log, flush=True) with open(out / "trials.csv", "w", newline="") as f: w = csv.DictWriter(f, fieldnames=["tag", "density", "bending", "air_damp", "loss"]) w.writeheader() for r in sorted(results, key=lambda r: (r["loss"] is None, r["loss"] or 9e9)): w.writerow(r) best_card = { "density": best["density"], "bending": best["bending"], "air_damp": best["air_damp"], "tensile": 15.0, "compress": 15.0, "shear": 8.0, "method": "neuido_style_fit", "loss": best["loss"], } (out / "best_card.json").write_text(json.dumps(best_card, indent=1)) print(f"[fit] wrote {out/'best_card.json'}") if __name__ == "__main__": main()