syCen commited on
Commit
99594eb
·
verified ·
1 Parent(s): 170a37f

Update build_longvideo_test.py

Browse files
Files changed (1) hide show
  1. build_longvideo_test.py +163 -254
build_longvideo_test.py CHANGED
@@ -1,46 +1,42 @@
1
  """
2
- build_longvideo_test.py
3
- Build a long-horizon test index for autoregressive rollout evaluation.
4
 
5
- Takes the existing test json (data_test_0730.json), picks N cases from it, and
6
- re-extends each one from 16 future frames to n_chunks*16 (default 80) by walking
7
- forward through the episode's metadata.json with the SAME action_stride.
8
 
9
- Everything -- action_delta math, pose extraction, path naming -- is copied from
10
- build_pipeline_data.py so the output is schema-identical to data.json, just with
11
- a longer n_future. ACWMDataset should load it unchanged.
 
 
12
 
13
  Chunk k of the rollout uses:
14
- obs = future frame [16k - 1] (k=0 -> the original obs frame)
15
- action_delta = action_delta[16k : 16k+16]
16
- so chunk k's observation is exactly the last frame chunk k-1 generated.
17
 
18
- Cases that cannot reach n_chunks are truncated to the largest whole number of
19
- chunks; selection prefers full-length cases.
20
 
21
  Usage:
22
- python build_longvideo_test.py \
23
- --source_root /net/.../physical_wm/grasping \
24
- --test_json /n/netscratch/.../data_test_0730.json \
25
- --out /n/netscratch/.../data_test_0823_longvideo.json \
26
- --n_cases 16 --n_chunks 5 --action_stride 3
27
  """
28
 
29
  import argparse
30
  import json
31
  import os
32
  import random
33
- from collections import defaultdict
34
- from pathlib import Path
35
 
36
  import numpy as np
37
  from scipy.spatial.transform import Rotation as R
38
- from tqdm import tqdm
39
 
40
 
41
- # --------------------------------------------------------------------------- #
42
- # verbatim from build_pipeline_data.py -- do not "improve" these
43
- # --------------------------------------------------------------------------- #
44
  def load_metadata(episode_dir, camera="camera2"):
45
  with open(os.path.join(episode_dir, "metadata.json")) as f:
46
  meta = json.load(f)
@@ -59,127 +55,54 @@ def get_pose(entry):
59
 
60
 
61
  def action_delta(entry_from, entry_to):
 
62
  t0, r0, _ = get_pose(entry_from)
63
  t1, r1, g1 = get_pose(entry_to)
64
  dt = t1 - t0
65
- R0 = R.from_euler("xyz", r0)
66
- R1 = R.from_euler("xyz", r1)
67
- drot = (R0.inv() * R1).as_euler("xyz")
68
  return np.array([dt[0], dt[1], dt[2], drot[0], drot[1], drot[2], g1],
69
  dtype=np.float64)
70
 
71
 
72
- def rpy_delta_norm(r0, r1):
73
- d = r1 - r0
74
- d = (d + np.pi) % (2 * np.pi) - np.pi
75
- return float(np.linalg.norm(d))
76
-
77
-
78
- def compute_valid_range(meta, trans_thresh, rot_thresh):
79
  n = len(meta)
80
  if n < 2:
81
  return None
82
- trans_d = np.zeros(n)
83
- rot_d = np.zeros(n)
84
  for i in range(1, n):
85
  t0, r0, _ = get_pose(meta[i - 1])
86
  t1, r1, _ = get_pose(meta[i])
87
- trans_d[i] = float(np.linalg.norm(t1 - t0))
88
- rot_d[i] = rpy_delta_norm(r0, r1)
89
- moving = (trans_d > trans_thresh) | (rot_d > rot_thresh)
90
  if not moving.any():
91
  return None
92
- first = int(np.argmax(moving))
93
- last = n - 1 - int(np.argmax(moving[::-1]))
94
- return first, last
95
-
96
-
97
- def contact_nonblack(path):
98
- return bool(np.any(np.load(path) != 0))
99
-
100
-
101
- # --------------------------------------------------------------------------- #
102
- def reachable_chunks(meta, obs_pos, last_pos, action_stride, chunk_len, n_chunks):
103
- """How many whole 16-frame chunks fit starting at obs_pos."""
104
- for k in range(n_chunks, 0, -1):
105
- if obs_pos + k * chunk_len * action_stride <= last_pos:
106
- return k
107
- return 0
108
-
109
-
110
- def build_long_clip(ep_dir, source_root, meta, obs_pos, n_future,
111
- action_stride, chunk_len):
112
- """Schema-identical to build_pipeline_data.py's clip, with n_future frames."""
113
- future_pos = [obs_pos + (i + 1) * action_stride for i in range(n_future)]
114
-
115
- obs_entry = meta[obs_pos]
116
- obs_frame_idx = obs_entry["frame_idx"]
117
- future_frame_idxs = [meta[p]["frame_idx"] for p in future_pos]
118
-
119
- obs_image_path = obs_entry.get(
120
- "image_path", f"images/frame_{obs_frame_idx:06d}.png")
121
- future_image_paths = [
122
- meta[p].get("image_path", f"images/frame_{meta[p]['frame_idx']:06d}.png")
123
- for p in future_pos
124
- ]
125
- contact_paths = [os.path.join("modalities/contact", f"{fi:06d}.npy")
126
- for fi in future_frame_idxs]
127
- force_paths = [os.path.join("modalities/force", f"{fi:06d}.npy")
128
- for fi in future_frame_idxs]
129
-
130
- for p in contact_paths + force_paths:
131
- if not os.path.exists(os.path.join(ep_dir, p)):
132
- return None, f"missing {p}"
133
-
134
- # action[i] = pos[s+i*stride] -> pos[s+(i+1)*stride]
135
- action = np.stack([
136
- action_delta(meta[obs_pos + i * action_stride],
137
- meta[obs_pos + (i + 1) * action_stride])
138
- for i in range(n_future)
139
- ])
140
-
141
- n_nonblack = sum(contact_nonblack(os.path.join(ep_dir, cp))
142
- for cp in contact_paths)
143
-
144
- t, r, g = get_pose(obs_entry)
145
-
146
- # per-chunk contact activity: tells you which chunks actually have contact,
147
- # so a flat force curve in chunk 0 is not mistaken for model collapse
148
- n_chunks = n_future // chunk_len
149
- chunk_active = []
150
- for k in range(n_chunks):
151
- sub = contact_paths[k * chunk_len:(k + 1) * chunk_len]
152
- chunk_active.append(
153
- sum(contact_nonblack(os.path.join(ep_dir, cp)) for cp in sub) / chunk_len)
154
-
155
- clip = {
156
- "episode": os.path.relpath(ep_dir, source_root),
157
- "obs_frame_idx": obs_frame_idx,
158
- "future_frame_idxs": future_frame_idxs,
159
- "obs_image_path": obs_image_path,
160
- "future_image_paths": future_image_paths,
161
- "contact_paths": contact_paths,
162
- "force_paths": force_paths,
163
- "obs_pose": [t[0], t[1], t[2], r[0], r[1], r[2], g],
164
- "action_delta": action.tolist(),
165
- "activate_frac": n_nonblack / n_future,
166
- "n_contact_frames": n_nonblack,
167
- # rollout bookkeeping
168
- "n_chunks": n_chunks,
169
- "chunk_len": chunk_len,
170
- "chunk_activate_frac": chunk_active,
171
- }
172
- return clip, None
173
 
174
 
175
- # --------------------------------------------------------------------------- #
176
  def main():
177
  ap = argparse.ArgumentParser()
178
- ap.add_argument("--source_root", required=True)
179
- ap.add_argument("--test_json", required=True,
180
- help="existing short test json; supplies episode + obs_frame_idx")
 
 
181
  ap.add_argument("--out", required=True)
182
- ap.add_argument("--n_cases", type=int, default=16)
183
  ap.add_argument("--n_chunks", type=int, default=5)
184
  ap.add_argument("--chunk_len", type=int, default=16)
185
  ap.add_argument("--action_stride", type=int, default=3)
@@ -187,148 +110,134 @@ def main():
187
  ap.add_argument("--trans_thresh", type=float, default=1.0)
188
  ap.add_argument("--rot_thresh", type=float, default=0.01)
189
  ap.add_argument("--seed", type=int, default=0)
190
- ap.add_argument("--one_per_episode", action="store_true", default=True,
191
- help="at most one rollout per episode (default on) so the "
192
- "cases are not near-duplicates of each other")
193
- ap.add_argument("--allow_repeat_episode", dest="one_per_episode",
194
- action="store_false")
195
- ap.add_argument("--use_full_range", action="store_true",
196
- help="allow rolling past the moving segment into the static "
197
- "tail; default stops at the valid range's last frame")
198
  args = ap.parse_args()
199
 
200
  rng = random.Random(args.seed)
201
- source_root = str(Path(args.source_root))
202
-
203
- with open(args.test_json) as f:
204
- test = json.load(f)
205
- src_clips = test["clips"] if isinstance(test, dict) else test
206
- print(f"loaded {len(src_clips)} clips from {args.test_json}")
207
-
208
- # unique (episode, obs_frame_idx) start points, grouped by episode
209
- by_ep = defaultdict(set)
210
- for c in src_clips:
211
- by_ep[c["episode"]].add(c["obs_frame_idx"])
212
- print(f"{len(by_ep)} distinct episodes")
213
-
214
- n_future = args.n_chunks * args.chunk_len
215
- span = n_future * args.action_stride
216
- print(f"target: {n_future} future frames, span={span} raw frames "
217
- f"(stride={args.action_stride})")
218
-
219
- # ---- evaluate every candidate start point ----
220
- candidates = [] # (n_reachable, episode, obs_pos, meta, ep_dir)
221
- meta_cache = {}
222
- for ep, obs_idxs in tqdm(sorted(by_ep.items()), desc="scanning episodes"):
223
- ep_dir = os.path.join(source_root, ep)
224
- if ep not in meta_cache:
225
- try:
226
- meta_cache[ep] = load_metadata(ep_dir, args.camera)
227
- except Exception as e:
228
- print(f" [skip] {ep}: {e}")
229
- meta_cache[ep] = None
230
- meta = meta_cache[ep]
231
- if not meta:
232
- continue
233
 
 
234
  vr = compute_valid_range(meta, args.trans_thresh, args.rot_thresh)
235
  if vr is None:
 
236
  continue
237
  first, last = vr
238
- if args.use_full_range:
239
- last = len(meta) - 1
240
-
241
- fi2pos = {m["frame_idx"]: i for i, m in enumerate(meta)}
242
- for fi in sorted(obs_idxs):
243
- pos = fi2pos.get(fi)
244
- if pos is None:
245
- continue
246
- k = reachable_chunks(meta, pos, last, args.action_stride,
247
- args.chunk_len, args.n_chunks)
248
- if k > 0:
249
- candidates.append((k, ep, pos, fi))
250
-
251
- if not candidates:
252
- raise RuntimeError("no start point can reach even one chunk")
253
-
254
- hist = defaultdict(int)
255
- for k, *_ in candidates:
256
- hist[k] += 1
257
- print("\nreachable-chunk histogram over all candidate starts:")
258
- for k in sorted(hist, reverse=True):
259
- print(f" {k} chunks: {hist[k]}")
260
-
261
- # ---- select: prefer full-length, then shorter; one per episode ----
262
- rng.shuffle(candidates)
263
- candidates.sort(key=lambda x: -x[0]) # stable: full-length first
264
-
265
- selected, used_eps = [], set()
266
- for k, ep, pos, fi in candidates:
267
- if len(selected) >= args.n_cases:
268
- break
269
- if args.one_per_episode and ep in used_eps:
270
  continue
271
- selected.append((k, ep, pos, fi))
272
- used_eps.add(ep)
273
-
274
- if len(selected) < args.n_cases and args.one_per_episode:
275
- print(f"\nonly {len(selected)} cases with one-per-episode; "
276
- f"filling the rest by allowing repeats")
277
- for k, ep, pos, fi in candidates:
278
- if len(selected) >= args.n_cases:
 
 
 
279
  break
280
- if (k, ep, pos, fi) in selected:
281
- continue
282
- selected.append((k, ep, pos, fi))
283
-
284
- print(f"\nselected {len(selected)} cases:")
285
- for k, ep, pos, fi in selected:
286
- print(f" {k} chunks frame={fi:6d} {ep}")
287
-
288
- # ---- build ----
289
- out_clips = []
290
- for k, ep, pos, fi in tqdm(selected, desc="building"):
291
- meta = meta_cache[ep]
292
- clip, err = build_long_clip(
293
- os.path.join(source_root, ep), source_root, meta, pos,
294
- k * args.chunk_len, args.action_stride, args.chunk_len)
295
- if clip is None:
296
- print(f" [drop] {ep} frame {fi}: {err}")
297
  continue
298
- out_clips.append(clip)
299
-
300
- config = dict(test.get("config", {})) if isinstance(test, dict) else {}
301
- config.update({
302
- "camera": args.camera,
303
- "action_stride": args.action_stride,
304
- "n_future": n_future,
305
- "chunk_len": args.chunk_len,
306
- "n_chunks": args.n_chunks,
307
- "trans_thresh": args.trans_thresh,
308
- "rot_thresh": args.rot_thresh,
309
- "action_dim_names": ["dx", "dy", "dz", "drx", "dry", "drz", "gripper_abs"],
310
- "obs_pose_names": ["x", "y", "z", "r1", "r2", "r3", "gripper"],
311
- "note": ("long-horizon rollout index. n_future is VARIABLE per clip "
312
- "(n_chunks*chunk_len); read clip['n_chunks']. chunk k uses "
313
- "obs = future frame [16k-1] and action_delta[16k:16k+16]."),
314
- "source_test_json": args.test_json,
315
- "seed": args.seed,
316
- })
317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  with open(args.out, "w") as f:
319
- json.dump({"config": config, "n_clips": len(out_clips),
320
- "clips": out_clips}, f)
321
-
322
- dist = defaultdict(int)
323
- for c in out_clips:
324
- dist[c["n_chunks"]] += 1
325
- print(f"\nwrote {args.out} ({len(out_clips)} clips)")
326
- print(" chunk-count distribution: " +
327
- ", ".join(f"{k}x{v}" for k, v in sorted(dist.items(), reverse=True)))
328
- print(" per-case contact activity by chunk:")
329
- for c in out_clips:
330
- s = " ".join(f"{v:.2f}" for v in c["chunk_activate_frac"])
331
- print(f" {c['episode'][-40:]:40s} frame={c['obs_frame_idx']:6d} [{s}]")
332
 
333
 
334
  if __name__ == "__main__":
 
1
  """
2
+ make_longvideo_test.py
3
+ Build a long-horizon rollout test json, schema-identical to data_test_0730.json.
4
 
5
+ Picks N random episodes from one task directory, takes ONE case per episode
6
+ starting at the beginning of its moving segment, and extends it to
7
+ n_chunks * 16 future frames at action_stride.
8
 
9
+ samples[i] has exactly the 5 keys the dataset expects:
10
+ episode, obs_frame_idx, observation_frame, frames, actions
11
+ `frames` and `actions` are n_chunks*16 long instead of 16. `actions` are RAW
12
+ deltas (mm / rad / absolute gripper) -- ACWMDataset normalizes them with
13
+ statistics.json, same as before.
14
 
15
  Chunk k of the rollout uses:
16
+ obs = frames[16k - 1] (k=0 -> observation_frame)
17
+ action = actions[16k : 16k+16]
 
18
 
19
+ Per-case chunk metadata goes in top-level "rollout_info" (parallel to samples),
20
+ so `samples` stays byte-compatible with what the dataset already reads.
21
 
22
  Usage:
23
+ python make_longvideo_test.py \
24
+ --task_dir /n/lab_storage/ydu_lab/sycen/data/physical_wm/grasping/grasping_videos/grasping_gello_flip_the_switch_box_open_to_the_left_100 \
25
+ --source_root /n/lab_storage/ydu_lab/sycen/data/physical_wm/grasping \
26
+ --out /n/netscratch/ydu_lab/Lab/sycen/data/data_test_0823_longvideo.json \
27
+ --n_episodes 15 --n_chunks 5
28
  """
29
 
30
  import argparse
31
  import json
32
  import os
33
  import random
 
 
34
 
35
  import numpy as np
36
  from scipy.spatial.transform import Rotation as R
 
37
 
38
 
39
+ # --- copied verbatim from build_pipeline_data.py ---------------------------- #
 
 
40
  def load_metadata(episode_dir, camera="camera2"):
41
  with open(os.path.join(episode_dir, "metadata.json")) as f:
42
  meta = json.load(f)
 
55
 
56
 
57
  def action_delta(entry_from, entry_to):
58
+ """[dx,dy,dz, drx,dry,drz, gripper_abs]; rot = SO(3) relative, euler xyz."""
59
  t0, r0, _ = get_pose(entry_from)
60
  t1, r1, g1 = get_pose(entry_to)
61
  dt = t1 - t0
62
+ drot = (R.from_euler("xyz", r0).inv() * R.from_euler("xyz", r1)).as_euler("xyz")
 
 
63
  return np.array([dt[0], dt[1], dt[2], drot[0], drot[1], drot[2], g1],
64
  dtype=np.float64)
65
 
66
 
67
+ def compute_valid_range(meta, trans_thresh=1.0, rot_thresh=0.01):
 
 
 
 
 
 
68
  n = len(meta)
69
  if n < 2:
70
  return None
71
+ moving = np.zeros(n, dtype=bool)
 
72
  for i in range(1, n):
73
  t0, r0, _ = get_pose(meta[i - 1])
74
  t1, r1, _ = get_pose(meta[i])
75
+ dr = (r1 - r0 + np.pi) % (2 * np.pi) - np.pi
76
+ moving[i] = (np.linalg.norm(t1 - t0) > trans_thresh
77
+ or np.linalg.norm(dr) > rot_thresh)
78
  if not moving.any():
79
  return None
80
+ return int(np.argmax(moving)), n - 1 - int(np.argmax(moving[::-1]))
81
+ # ---------------------------------------------------------------------------- #
82
+
83
+
84
+ def rel_image(episode_rel, entry):
85
+ """Full relative path with episode prefix, matching the test json."""
86
+ p = entry.get("image_path", f"images/frame_{entry['frame_idx']:06d}.png")
87
+ return os.path.join(episode_rel, p)
88
+
89
+
90
+ def contact_active(ep_dir, frame_idx):
91
+ p = os.path.join(ep_dir, "modalities", "contact", f"{frame_idx:06d}.npy")
92
+ if not os.path.exists(p):
93
+ return None
94
+ return bool(np.any(np.load(p) != 0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
 
 
97
  def main():
98
  ap = argparse.ArgumentParser()
99
+ ap.add_argument("--task_dir", required=True,
100
+ help="directory containing the episode folders (0000, 0001, ...)")
101
+ ap.add_argument("--source_root", required=True,
102
+ help="root that `episode` is relative to; must match the "
103
+ "--source_root you pass to inference")
104
  ap.add_argument("--out", required=True)
105
+ ap.add_argument("--n_episodes", type=int, default=15)
106
  ap.add_argument("--n_chunks", type=int, default=5)
107
  ap.add_argument("--chunk_len", type=int, default=16)
108
  ap.add_argument("--action_stride", type=int, default=3)
 
110
  ap.add_argument("--trans_thresh", type=float, default=1.0)
111
  ap.add_argument("--rot_thresh", type=float, default=0.01)
112
  ap.add_argument("--seed", type=int, default=0)
113
+ ap.add_argument("--start_offset", type=int, default=0,
114
+ help="frames to skip past the start of the moving segment; "
115
+ "raise it if the early chunks have no contact")
 
 
 
 
 
116
  args = ap.parse_args()
117
 
118
  rng = random.Random(args.seed)
119
+ task_dir = os.path.abspath(args.task_dir)
120
+ source_root = os.path.abspath(args.source_root)
121
+
122
+ ep_names = sorted(
123
+ d for d in os.listdir(task_dir)
124
+ if os.path.isdir(os.path.join(task_dir, d))
125
+ and os.path.exists(os.path.join(task_dir, d, "metadata.json"))
126
+ )
127
+ print(f"{len(ep_names)} episodes in {os.path.basename(task_dir)}")
128
+ rng.shuffle(ep_names)
129
+
130
+ samples, info = [], []
131
+ n_short = n_missing = 0
132
+
133
+ for name in ep_names:
134
+ if len(samples) >= args.n_episodes:
135
+ break
136
+ ep_dir = os.path.join(task_dir, name)
137
+ episode_rel = os.path.relpath(ep_dir, source_root)
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
+ meta = load_metadata(ep_dir, args.camera)
140
  vr = compute_valid_range(meta, args.trans_thresh, args.rot_thresh)
141
  if vr is None:
142
+ n_short += 1
143
  continue
144
  first, last = vr
145
+ s = min(first + args.start_offset, last)
146
+
147
+ # largest whole number of chunks that fits
148
+ k = 0
149
+ for cand in range(args.n_chunks, 0, -1):
150
+ if s + cand * args.chunk_len * args.action_stride <= last:
151
+ k = cand
152
+ break
153
+ if k == 0:
154
+ n_short += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  continue
156
+
157
+ n_future = k * args.chunk_len
158
+ fut_pos = [s + (i + 1) * args.action_stride for i in range(n_future)]
159
+
160
+ # every frame's png and modality npy must exist
161
+ ok = True
162
+ for p in fut_pos:
163
+ fi = meta[p]["frame_idx"]
164
+ if not os.path.exists(os.path.join(source_root,
165
+ rel_image(episode_rel, meta[p]))):
166
+ ok = False
167
  break
168
+ for mod in ("contact", "force"):
169
+ if not os.path.exists(os.path.join(
170
+ ep_dir, "modalities", mod, f"{fi:06d}.npy")):
171
+ ok = False
172
+ break
173
+ if not ok:
174
+ break
175
+ if not ok:
176
+ n_missing += 1
 
 
 
 
 
 
 
 
177
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
+ actions = np.stack([
180
+ action_delta(meta[s + i * args.action_stride],
181
+ meta[s + (i + 1) * args.action_stride])
182
+ for i in range(n_future)
183
+ ])
184
+
185
+ samples.append({
186
+ "episode": episode_rel,
187
+ "obs_frame_idx": meta[s]["frame_idx"],
188
+ "observation_frame": rel_image(episode_rel, meta[s]),
189
+ "frames": [rel_image(episode_rel, meta[p]) for p in fut_pos],
190
+ "actions": actions.tolist(),
191
+ })
192
+
193
+ # contact activity per chunk -- a flat force curve in a chunk with
194
+ # activate=0.00 is correct behaviour, not model collapse
195
+ act = []
196
+ for c in range(k):
197
+ sub = fut_pos[c * args.chunk_len:(c + 1) * args.chunk_len]
198
+ vals = [contact_active(ep_dir, meta[p]["frame_idx"]) for p in sub]
199
+ act.append(sum(bool(v) for v in vals) / len(vals))
200
+ info.append({
201
+ "episode": episode_rel,
202
+ "obs_frame_idx": meta[s]["frame_idx"],
203
+ "n_chunks": k,
204
+ "chunk_len": args.chunk_len,
205
+ "n_frames_total": len(meta),
206
+ "valid_range": [first, last],
207
+ "chunk_activate_frac": act,
208
+ })
209
+
210
+ out = {
211
+ "source": task_dir,
212
+ "config": {
213
+ "action_stride": args.action_stride,
214
+ "chunk_len": args.chunk_len,
215
+ "n_chunks_requested": args.n_chunks,
216
+ "camera": args.camera,
217
+ "source_root": source_root,
218
+ "seed": args.seed,
219
+ "note": ("long-horizon rollout index. `frames`/`actions` are "
220
+ "n_chunks*16 long. chunk k: obs = frames[16k-1] "
221
+ "(k=0 -> observation_frame), action = actions[16k:16k+16]. "
222
+ "actions are RAW deltas; normalize with statistics.json."),
223
+ },
224
+ "n_samples": len(samples),
225
+ "samples": samples,
226
+ "rollout_info": info,
227
+ }
228
  with open(args.out, "w") as f:
229
+ json.dump(out, f)
230
+
231
+ print(f"\nwrote {args.out} ({len(samples)} cases)")
232
+ if n_short:
233
+ print(f" {n_short} episodes too short / never moving")
234
+ if n_missing:
235
+ print(f" {n_missing} episodes dropped for missing png/npy")
236
+ print(f"\n{'episode':>6s} {'obs':>5s} {'len':>4s} ch contact fraction per chunk")
237
+ for it in info:
238
+ s = " ".join(f"{v:.2f}" for v in it["chunk_activate_frac"])
239
+ print(f"{it['episode'].split('/')[-1]:>6s} {it['obs_frame_idx']:5d} "
240
+ f"{it['n_frames_total']:4d} {it['n_chunks']} [{s}]")
 
241
 
242
 
243
  if __name__ == "__main__":