yxma commited on
Commit
bcd600f
·
verified ·
1 Parent(s): eb8765a

Add pipeline scripts (make_parquet_v2.py, make_analytical_plots.py, make_samples_100.py)

Browse files
scripts/make_analytical_plots.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Generate analytical plots for the dataset card:
3
+ - composition.png frames per subset, stacked by markered/markerless
4
+ - resolution_distribution.png 320x240 vs 640x480 per subset
5
+ - force_distribution.png FEATS f_z histogram + indenter shapes
6
+ - threedcal_coverage.png (x,y) probe-position heatmap
7
+ - rtm_digit_distribution.png digit-class counts
8
+ """
9
+
10
+ import glob
11
+ import os
12
+
13
+ import matplotlib
14
+ matplotlib.use("Agg")
15
+ import matplotlib.pyplot as plt
16
+ import numpy as np
17
+ import pyarrow.parquet as pq
18
+
19
+ BASE = "/media/yxma/Disk1/yuxiang/mini_data_parquet"
20
+ OUT = f"{BASE}/assets"
21
+
22
+ SUBSETS = ["fota_labeled", "fota_unlabeled", "threedcal", "feats",
23
+ "feelanyforce", "gelslam", "tactile_tracking", "real_tactile_mnist"]
24
+
25
+
26
+ def scan_subset(sub, columns):
27
+ paths = sorted(glob.glob(f"{BASE}/{sub}/*.parquet"))
28
+ out = {c: [] for c in columns}
29
+ for p in paths:
30
+ t = pq.read_table(p, columns=columns)
31
+ for c in columns:
32
+ out[c].extend(t.column(c).to_pylist())
33
+ return out
34
+
35
+
36
+ # 1. composition stacked bar
37
+ def plot_composition():
38
+ counts = {}
39
+ for sub in SUBSETS:
40
+ d = scan_subset(sub, ["markered"])
41
+ n_m = sum(1 for x in d["markered"] if x)
42
+ n_u = sum(1 for x in d["markered"] if not x)
43
+ counts[sub] = (n_m, n_u)
44
+
45
+ labels = SUBSETS
46
+ m = np.array([counts[s][0] for s in labels])
47
+ u = np.array([counts[s][1] for s in labels])
48
+ fig, ax = plt.subplots(figsize=(11, 4.5))
49
+ x = np.arange(len(labels))
50
+ ax.bar(x, u, label="markerless", color="#4c95d6")
51
+ ax.bar(x, m, bottom=u, label="markered", color="#d6794c")
52
+ for i, s in enumerate(labels):
53
+ total = counts[s][0] + counts[s][1]
54
+ ax.text(i, total + max(m+u)*0.005, f"{total:,}",
55
+ ha="center", va="bottom", fontsize=9)
56
+ ax.set_xticks(x)
57
+ ax.set_xticklabels(labels, rotation=20, ha="right")
58
+ ax.set_ylabel("Frames")
59
+ ax.set_title("gelsight-mini-pretrain · frames per subset (stacked by gel variant)")
60
+ ax.legend(loc="upper right", frameon=False)
61
+ ax.spines[["top","right"]].set_visible(False)
62
+ plt.tight_layout()
63
+ plt.savefig(f"{OUT}/composition.png", dpi=140)
64
+ plt.close()
65
+ print("wrote composition.png")
66
+
67
+
68
+ # 2. resolution distribution
69
+ def plot_resolution():
70
+ cols = {}
71
+ for sub in SUBSETS:
72
+ d = scan_subset(sub, ["height", "width"])
73
+ from collections import Counter
74
+ c = Counter(zip(d["width"], d["height"]))
75
+ cols[sub] = c
76
+
77
+ all_dims = sorted({k for sub in cols.values() for k in sub.keys()})
78
+ colors = {(640,480): "#4c95d6", (320,240): "#d6794c"}
79
+ fig, ax = plt.subplots(figsize=(11, 4.5))
80
+ x = np.arange(len(SUBSETS))
81
+ bottom = np.zeros(len(SUBSETS))
82
+ for d in all_dims:
83
+ vals = np.array([cols[s].get(d, 0) for s in SUBSETS])
84
+ ax.bar(x, vals, bottom=bottom,
85
+ color=colors.get(d, "#999999"),
86
+ label=f"{d[0]}×{d[1]} ({vals.sum():,})")
87
+ bottom += vals
88
+ ax.set_xticks(x)
89
+ ax.set_xticklabels(SUBSETS, rotation=20, ha="right")
90
+ ax.set_ylabel("Frames")
91
+ ax.set_title("Image resolution per subset (GelSight Mini native modes)")
92
+ ax.legend(loc="upper right", frameon=False)
93
+ ax.spines[["top","right"]].set_visible(False)
94
+ plt.tight_layout()
95
+ plt.savefig(f"{OUT}/resolution_distribution.png", dpi=140)
96
+ plt.close()
97
+ print("wrote resolution_distribution.png")
98
+
99
+
100
+ # 3. FEATS force distribution + indenter mix
101
+ def plot_feats_force():
102
+ d = scan_subset("feats", ["f_z", "f_x", "f_y", "indenter"])
103
+ fz = np.array([x for x in d["f_z"] if x is not None])
104
+ fig, axes = plt.subplots(1, 2, figsize=(11, 4))
105
+ axes[0].hist(fz, bins=60, color="#4c95d6", edgecolor="white")
106
+ axes[0].axvline(0, color="#444", linestyle="--", linewidth=1)
107
+ axes[0].set_xlabel("normal force f_z (N)")
108
+ axes[0].set_ylabel("Frames")
109
+ axes[0].set_title(f"FEATS normal force distribution (n={len(fz):,})")
110
+ axes[0].spines[["top","right"]].set_visible(False)
111
+ # indenter mix
112
+ from collections import Counter
113
+ c = Counter(x or "unknown" for x in d["indenter"])
114
+ items = sorted(c.items(), key=lambda kv: -kv[1])
115
+ keys = [k for k,_ in items]; vals = [v for _,v in items]
116
+ axes[1].barh(range(len(keys)), vals, color="#d6794c", edgecolor="white")
117
+ axes[1].set_yticks(range(len(keys)))
118
+ axes[1].set_yticklabels(keys)
119
+ axes[1].invert_yaxis()
120
+ axes[1].set_xlabel("Frames")
121
+ axes[1].set_title("FEATS indenter-shape mix")
122
+ axes[1].spines[["top","right"]].set_visible(False)
123
+ for i, v in enumerate(vals):
124
+ axes[1].text(v + max(vals)*0.005, i, f"{v:,}", va="center", fontsize=9)
125
+ plt.tight_layout()
126
+ plt.savefig(f"{OUT}/force_distribution.png", dpi=140)
127
+ plt.close()
128
+ print("wrote force_distribution.png")
129
+
130
+
131
+ # 4. 3DCal probe-position heatmap
132
+ def plot_threedcal_coverage():
133
+ d = scan_subset("threedcal", ["x_mm", "y_mm"])
134
+ x = np.array([v for v in d["x_mm"] if v is not None])
135
+ y = np.array([v for v in d["y_mm"] if v is not None])
136
+ fig, ax = plt.subplots(figsize=(6.5, 5.5))
137
+ H, xe, ye = np.histogram2d(x, y, bins=[40, 30])
138
+ im = ax.pcolormesh(xe, ye, H.T, cmap="magma")
139
+ ax.set_xlabel("x (mm)")
140
+ ax.set_ylabel("y (mm)")
141
+ ax.set_title(f"py3DCal calibration grid — probe coverage (n={len(x):,})")
142
+ plt.colorbar(im, ax=ax, label="frames per (x,y) cell")
143
+ plt.tight_layout()
144
+ plt.savefig(f"{OUT}/threedcal_coverage.png", dpi=140)
145
+ plt.close()
146
+ print("wrote threedcal_coverage.png")
147
+
148
+
149
+ # 5. RTM digit-class distribution
150
+ def plot_rtm_digits():
151
+ d = scan_subset("real_tactile_mnist", ["digit_class"])
152
+ from collections import Counter
153
+ c = Counter(x for x in d["digit_class"] if x is not None)
154
+ keys = list(range(10))
155
+ vals = [c.get(k, 0) for k in keys]
156
+ fig, ax = plt.subplots(figsize=(8, 4))
157
+ ax.bar(keys, vals, color="#4c95d6", edgecolor="white")
158
+ for k, v in zip(keys, vals):
159
+ ax.text(k, v + max(vals)*0.005, f"{v:,}",
160
+ ha="center", va="bottom", fontsize=9)
161
+ ax.set_xticks(keys)
162
+ ax.set_xlabel("digit class")
163
+ ax.set_ylabel("frames")
164
+ ax.set_title(f"Real Tactile MNIST · digit-class balance (total {sum(vals):,})")
165
+ ax.spines[["top","right"]].set_visible(False)
166
+ plt.tight_layout()
167
+ plt.savefig(f"{OUT}/rtm_digit_distribution.png", dpi=140)
168
+ plt.close()
169
+ print("wrote rtm_digit_distribution.png")
170
+
171
+
172
+ if __name__ == "__main__":
173
+ plot_composition()
174
+ plot_resolution()
175
+ plot_feats_force()
176
+ plot_threedcal_coverage()
177
+ plot_rtm_digits()
178
+ print("done")
scripts/make_parquet_v2.py ADDED
@@ -0,0 +1,577 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """V2 pipeline: pack GelSLAM, TactileTracking, RealTactileMNIST, FeelAnyForce
3
+ into the unified parquet schema used by `yxma/gelsight-mini-pretrain`.
4
+
5
+ Adaptive subsampling per source:
6
+ - per-source frame budget = min(200_000, contact_frames_available)
7
+ - dynamism-aware stride (high inter-frame delta -> denser sample)
8
+ - validity filter: drop frames where central deformation < threshold
9
+ - perceptual-hash dedupe
10
+
11
+ Outputs sit alongside existing fota_*/threedcal/feats:
12
+ /media/yxma/Disk1/yuxiang/mini_data_parquet/<sub>/{train|...}-####-of-####.parquet
13
+
14
+ Usage:
15
+ python make_parquet_v2.py probe <sub> # measure dynamism + empty fraction
16
+ python make_parquet_v2.py process <sub> # full pipeline + write
17
+ python make_parquet_v2.py stats # show row counts across all subs
18
+ """
19
+
20
+ import io
21
+ import json
22
+ import os
23
+ import sys
24
+ import time
25
+ from collections import defaultdict
26
+ from glob import glob
27
+ from typing import Iterator, Optional, Tuple
28
+
29
+ import numpy as np
30
+ import pyarrow as pa
31
+ import pyarrow.parquet as pq
32
+ from PIL import Image
33
+
34
+ BASE_DATA = "/media/yxma/Disk1/yuxiang/mini_data"
35
+ BASE_OUT = "/media/yxma/Disk1/yuxiang/mini_data_parquet"
36
+ BUDGET = 200_000 # max kept frames per source
37
+ SHARD_TGT = 2 * 1024 ** 3 # 2 GB shard target
38
+ EMPTY_TAU = 4.0 # mean |frame - baseline| threshold (greylevels)
39
+ EMPTY_BUDGET= 0.03 # allow up to 3% empties through
40
+ PHASH_DIST = 4 # max hamming distance for "duplicate"
41
+
42
+ # Existing schema + 3 new nullable cols
43
+ SCHEMA = pa.schema([
44
+ ("image", pa.binary()),
45
+ ("image_format", pa.string()),
46
+ ("source", pa.string()),
47
+ ("markered", pa.bool_()),
48
+ ("capture", pa.string()),
49
+ ("split", pa.string()),
50
+ ("height", pa.int32()),
51
+ ("width", pa.int32()),
52
+ ("obj_name", pa.string()),
53
+ ("init_pose", pa.int32()),
54
+ ("side", pa.string()),
55
+ ("x_mm", pa.float32()),
56
+ ("y_mm", pa.float32()),
57
+ ("z_mm", pa.float32()),
58
+ ("quat_x", pa.float32()),
59
+ ("quat_y", pa.float32()),
60
+ ("quat_z", pa.float32()),
61
+ ("quat_w", pa.float32()),
62
+ ("indenter", pa.string()),
63
+ ("indenter_param", pa.string()),
64
+ ("f_x", pa.float32()),
65
+ ("f_y", pa.float32()),
66
+ ("f_z", pa.float32()),
67
+ ("grid_z_max", pa.float32()),
68
+ ("grid_z_mean", pa.float32()),
69
+ # NEW columns (nullable for old data)
70
+ ("episode", pa.string()),
71
+ ("frame_idx", pa.int32()),
72
+ ("digit_class", pa.int32()),
73
+ ("gel_variant", pa.string()),
74
+ ])
75
+
76
+
77
+ # ─────────────────────────────────────────────────────────────────
78
+ # helpers
79
+ # ─────────────────────────────────────────────────────────────────
80
+
81
+ def encode_jpeg(arr_rgb: np.ndarray, q=92) -> bytes:
82
+ im = Image.fromarray(arr_rgb)
83
+ buf = io.BytesIO()
84
+ im.save(buf, format="JPEG", quality=q, optimize=True)
85
+ return buf.getvalue()
86
+
87
+
88
+ def grey_center(arr: np.ndarray) -> np.ndarray:
89
+ """Central 50% crop, greyscale, float32."""
90
+ if arr.ndim == 3:
91
+ g = arr.mean(axis=2)
92
+ else:
93
+ g = arr
94
+ h, w = g.shape
95
+ return g[h//4:3*h//4, w//4:3*w//4].astype(np.float32)
96
+
97
+
98
+ def phash(arr_rgb: np.ndarray) -> int:
99
+ """8x8 DCT-low-freq perceptual hash, returned as 64-bit int."""
100
+ im = Image.fromarray(arr_rgb).convert("L").resize((32, 32), Image.LANCZOS)
101
+ a = np.array(im, dtype=np.float32)
102
+ # 2D DCT via numpy
103
+ def dct1(x): return np.fft.fft(np.concatenate([x, x[::-1]], axis=-1)).real[..., :x.shape[-1]]
104
+ d = dct1(dct1(a).T).T
105
+ low = d[:8, :8].flatten()
106
+ med = np.median(low[1:]) # skip DC
107
+ h = 0
108
+ for bit in (low > med):
109
+ h = (h << 1) | int(bit)
110
+ return h
111
+
112
+
113
+ def hamming(a: int, b: int) -> int:
114
+ return bin(a ^ b).count("1")
115
+
116
+
117
+ # ─────────────────────────────────────────────────────────────────
118
+ # Per-source iterators
119
+ # Each yields (frame_rgb_np, base_meta_dict) for ONE frame at a time.
120
+ # Within each episode/capture, frames are emitted in order so we can
121
+ # compute a baseline image for the validity filter.
122
+ # ─────────────────────────────────────────────────────────────────
123
+
124
+ def iter_gelslam():
125
+ """GelSLAM: gelsight.avi per episode under tracking_dataset/ and reconstruction_dataset/."""
126
+ import cv2
127
+ root = f"{BASE_DATA}/markerless/GelSLAM"
128
+ # The HF download puts content under root or root/dataset/ depending on extraction
129
+ for sub in ("tracking_dataset", "reconstruction_dataset"):
130
+ candidates = (
131
+ glob(f"{root}/{sub}/*/gelsight.avi") +
132
+ glob(f"{root}/dataset/{sub}/*/gelsight.avi")
133
+ )
134
+ for vid in candidates:
135
+ episode = os.path.basename(os.path.dirname(vid))
136
+ split = "train" if sub == "tracking_dataset" else "recon"
137
+ cap = cv2.VideoCapture(vid)
138
+ fi = 0
139
+ while True:
140
+ ok, fr = cap.read()
141
+ if not ok:
142
+ break
143
+ fr = fr[:, :, ::-1] # BGR->RGB
144
+ yield fr, {
145
+ "source": "gelslam",
146
+ "markered": False,
147
+ "capture": f"{sub}/{episode}",
148
+ "split": split,
149
+ "obj_name": episode,
150
+ "episode": episode,
151
+ "frame_idx": fi,
152
+ }
153
+ fi += 1
154
+ cap.release()
155
+
156
+
157
+ def iter_tactile_tracking():
158
+ import cv2
159
+ import re
160
+ root = f"{BASE_DATA}/markerless/TactileTracking"
161
+ candidates = sorted(glob(f"{root}/normalflow_dataset/*/gelsight.avi"))
162
+ obj_re = re.compile(r"^([a-zA-Z]+)(\d+)$")
163
+ for vid in candidates:
164
+ trial_dir = os.path.basename(os.path.dirname(vid)) # e.g. 'corner3'
165
+ m = obj_re.match(trial_dir)
166
+ if m:
167
+ obj, trial = m.group(1), m.group(2)
168
+ else:
169
+ obj, trial = trial_dir, "0"
170
+ cap = cv2.VideoCapture(vid)
171
+ fi = 0
172
+ while True:
173
+ ok, fr = cap.read()
174
+ if not ok:
175
+ break
176
+ fr = fr[:, :, ::-1]
177
+ yield fr, {
178
+ "source": "tactile_tracking",
179
+ "markered": False,
180
+ "capture": f"{obj}/{trial}",
181
+ "split": "train",
182
+ "obj_name": obj,
183
+ "episode": trial,
184
+ "frame_idx": fi,
185
+ }
186
+ fi += 1
187
+ cap.release()
188
+
189
+
190
+ def iter_real_tactile_mnist():
191
+ """RTM seq-320x240: parquet with 'sensor_video' list-of-struct{bytes,path}.
192
+ Each row in the parquet is one 'round' = one digit object touched ~256 times.
193
+ We keep one frame per touch video (the middle frame, near peak contact).
194
+ """
195
+ import cv2
196
+ root = f"{BASE_DATA}/markerless/RealTactileMNIST"
197
+ pq_files = sorted(glob(f"{root}/data/*.parquet"))
198
+ for p in pq_files:
199
+ split = "test" if "test" in os.path.basename(p).lower() else "train"
200
+ pf = pq.ParquetFile(p)
201
+ for batch in pf.iter_batches(batch_size=4):
202
+ cols = batch.to_pydict()
203
+ n = len(cols.get("label", cols.get("id", [])))
204
+ for i in range(n):
205
+ round_id = cols.get("id", [None]*n)[i]
206
+ label = cols.get("label", [None]*n)[i]
207
+ obj_id = cols.get("object_id", [None]*n)[i]
208
+ videos = cols["sensor_video"][i] or []
209
+ for tj, vid_struct in enumerate(videos):
210
+ if not vid_struct: continue
211
+ vid_bytes = vid_struct.get("bytes") if isinstance(vid_struct, dict) else None
212
+ if not vid_bytes: continue
213
+ tmpf = f"/tmp/_rtm_{os.getpid()}.mp4"
214
+ with open(tmpf, "wb") as f: f.write(vid_bytes)
215
+ cap = cv2.VideoCapture(tmpf)
216
+ frames = []
217
+ while True:
218
+ ok, fr = cap.read()
219
+ if not ok: break
220
+ frames.append(fr[:, :, ::-1])
221
+ cap.release()
222
+ try: os.remove(tmpf)
223
+ except: pass
224
+ if not frames: continue
225
+ # keep only the middle frame (near peak contact)
226
+ mid = frames[len(frames)//2]
227
+ yield mid, {
228
+ "source": "real_tactile_mnist",
229
+ "markered": False,
230
+ "capture": f"r{round_id}_t{tj}",
231
+ "split": split,
232
+ "obj_name": f"digit_{label}",
233
+ "digit_class": int(label) if label is not None else None,
234
+ "episode": str(obj_id) if obj_id is not None else None,
235
+ "frame_idx": len(frames)//2,
236
+ }
237
+
238
+
239
+ def iter_feelanyforce():
240
+ """FAF: loose 320x240 PNG per indentation under dataset/<object>/tactile/."""
241
+ root = f"{BASE_DATA}/markerless/FeelAnyForce/dataset/dataset"
242
+ objects = sorted(d for d in os.listdir(root) if os.path.isdir(f"{root}/{d}"))
243
+ for obj in objects:
244
+ p = f"{root}/{obj}/tactile"
245
+ if not os.path.isdir(p): continue
246
+ files = sorted(os.listdir(p))
247
+ for fi, fn in enumerate(files):
248
+ try:
249
+ fr = np.array(Image.open(f"{p}/{fn}").convert("RGB"))
250
+ except Exception:
251
+ continue
252
+ yield fr, {
253
+ "source": "feelanyforce",
254
+ "markered": False, # visually verified markerless
255
+ "capture": obj,
256
+ "split": "train",
257
+ "obj_name": obj.split("_")[0],
258
+ "episode": obj,
259
+ "frame_idx": fi,
260
+ }
261
+
262
+
263
+ SOURCE_ITERS = {
264
+ "gelslam": iter_gelslam,
265
+ "tactile_tracking": iter_tactile_tracking,
266
+ "real_tactile_mnist": iter_real_tactile_mnist,
267
+ "feelanyforce": iter_feelanyforce,
268
+ }
269
+
270
+ # Per-source overrides for the validity filter.
271
+ # FAF: data is pre-curated, every frame is an indentation moment, baseline median
272
+ # includes contact frames -> filter must be disabled.
273
+ # RTM: we already pick 1 middle frame per video, every frame is peak contact ->
274
+ # filter unnecessary.
275
+ # Video sources: keep filter active (baseline = median of first 10 frames
276
+ # typically captures the pre-contact prologue).
277
+ SKIP_EMPTY_FILTER = {
278
+ "feelanyforce": True,
279
+ "real_tactile_mnist": True,
280
+ "gelslam": False,
281
+ "tactile_tracking": False,
282
+ }
283
+
284
+
285
+ # ─────────────────────────────────────────────────────────────────
286
+ # Probe pass: measure dynamism + empty fraction per source.
287
+ # Samples N frames per capture and computes |frame - capture_baseline|.
288
+ # ─────────────────────────────────────────────────────────────────
289
+
290
+ def probe(sub: str, n_per_capture=30, max_total=2000):
291
+ print(f"probe {sub}...", flush=True)
292
+ by_cap = defaultdict(list)
293
+ total = 0
294
+ for fr, meta in SOURCE_ITERS[sub]():
295
+ c = meta["capture"]
296
+ if len(by_cap[c]) < n_per_capture:
297
+ by_cap[c].append(fr)
298
+ total += 1
299
+ if total >= max_total:
300
+ break
301
+
302
+ # Per-capture baseline = median over the sampled frames
303
+ deltas, dynamisms = [], []
304
+ for c, frames in by_cap.items():
305
+ if len(frames) < 3:
306
+ continue
307
+ stack = np.stack([grey_center(f) for f in frames], axis=0)
308
+ baseline = np.median(stack, axis=0)
309
+ deformation = np.abs(stack - baseline).mean(axis=(1, 2))
310
+ deltas.extend(deformation.tolist())
311
+ # dynamism = mean inter-frame |Δ|
312
+ diffs = np.abs(stack[1:] - stack[:-1]).mean(axis=(1, 2))
313
+ dynamisms.extend(diffs.tolist())
314
+
315
+ deltas = np.array(deltas)
316
+ dyn = np.array(dynamisms) if dynamisms else np.array([0.0])
317
+ empty_frac = float((deltas < EMPTY_TAU).mean()) if len(deltas) else 0.0
318
+ return {
319
+ "n_probed_frames": total,
320
+ "n_probed_captures": len(by_cap),
321
+ "mean_dynamism": float(dyn.mean()),
322
+ "median_dynamism": float(np.median(dyn)),
323
+ "mean_deformation": float(deltas.mean()) if len(deltas) else 0.0,
324
+ "empty_frac": empty_frac,
325
+ "n_captures_with_3plus_frames": int(sum(1 for c, fs in by_cap.items() if len(fs) >= 3)),
326
+ }
327
+
328
+
329
+ # ─────────────────────────────────────────────────────────────────
330
+ # Two-pass full processing:
331
+ # pass 1: scan ALL frames; per capture, store baseline + count valid + collect phashes
332
+ # pass 2: re-iterate, apply stride+validity+dedupe; write parquet
333
+ # To avoid two full scans (RTM is large), we do a single streaming pass:
334
+ # - maintain a per-capture rolling baseline from first 10 frames
335
+ # - then for subsequent frames in same capture, compute validity online
336
+ # - apply stride based on a target_keep_per_capture pre-computed at probe time
337
+ # ─────────────────────────────────────────────────────────────────
338
+
339
+ class ShardWriter:
340
+ def __init__(self, out_dir, prefix):
341
+ self.out_dir = out_dir
342
+ self.prefix = prefix
343
+ os.makedirs(out_dir, exist_ok=True)
344
+ self.rows = []
345
+ self.shard_idx = 0
346
+ self.total = 0
347
+ self.bytes_in = 0
348
+
349
+ def add(self, row):
350
+ # ensure all keys present
351
+ row = {f.name: row.get(f.name) for f in SCHEMA}
352
+ self.rows.append(row)
353
+ self.bytes_in += len(row["image"]) if row["image"] else 0
354
+ self.total += 1
355
+ if self.bytes_in >= SHARD_TGT:
356
+ self._flush()
357
+
358
+ def _flush(self):
359
+ if not self.rows: return
360
+ # Build columns
361
+ cols = {f.name: [r[f.name] for r in self.rows] for f in SCHEMA}
362
+ t = pa.Table.from_pydict(cols, schema=SCHEMA)
363
+ path = f"{self.out_dir}/{self.prefix}-{self.shard_idx:05d}.parquet"
364
+ pq.write_table(t, path, compression="snappy")
365
+ print(f" wrote {path} rows={len(self.rows)} bytes={self.bytes_in/1e9:.2f}GB",
366
+ flush=True)
367
+ self.shard_idx += 1
368
+ self.rows = []
369
+ self.bytes_in = 0
370
+
371
+ def close(self):
372
+ self._flush()
373
+ # rename shards to "PREFIX-NNNNN-of-NNNNN.parquet"
374
+ files = sorted(glob(f"{self.out_dir}/{self.prefix}-?????.parquet"))
375
+ total_shards = len(files)
376
+ for i, fp in enumerate(files):
377
+ base = os.path.dirname(fp)
378
+ new = f"{base}/{self.prefix}-{i:05d}-of-{total_shards:05d}.parquet"
379
+ if fp != new:
380
+ os.rename(fp, new)
381
+
382
+
383
+ def process(sub: str, probe_info: dict):
384
+ """Run pipeline on one source and write parquet shards."""
385
+ print(f"\n=== processing {sub} ===", flush=True)
386
+
387
+ # Decide global stride
388
+ dyn = probe_info["mean_dynamism"]
389
+ # Estimate effective contact frames after empty filter
390
+ # (We'll re-tune as we go since we don't know R_total precisely)
391
+ # Target = BUDGET. We adjust the stride live by checking running fill rate.
392
+ target = BUDGET
393
+
394
+ # Group by split, write to <sub>/<split>-####.parquet
395
+ out_dir = f"{BASE_OUT}/{sub}"
396
+ writers: dict[str, ShardWriter] = {}
397
+
398
+ n_seen = 0
399
+ n_empty_dropped = 0
400
+ n_dup_dropped = 0
401
+ n_stride_dropped = 0
402
+ n_kept = 0
403
+ n_empty_passed = 0
404
+ cur_capture = None
405
+ cap_seen_within = 0
406
+ cap_baseline = None
407
+ cap_buffer: list[np.ndarray] = []
408
+ cap_phashes: list[int] = []
409
+
410
+ # We compute capture-baseline as the median of the first 10 frames seen
411
+ BASE_FRAMES = 10
412
+
413
+ def finish_capture():
414
+ # nothing to do per se; arrays cleared on capture change
415
+ pass
416
+
417
+ t0 = time.time()
418
+ stride_state = {"stride": 1.0, "accum": 0.0}
419
+
420
+ for fr, meta in SOURCE_ITERS[sub]():
421
+ cap = meta["capture"]
422
+ if cap != cur_capture:
423
+ finish_capture()
424
+ cur_capture = cap
425
+ cap_seen_within = 0
426
+ cap_baseline = None
427
+ cap_buffer = []
428
+ cap_phashes = []
429
+
430
+ g_center = grey_center(fr)
431
+ skip_empty = SKIP_EMPTY_FILTER.get(sub, False)
432
+
433
+ # Build baseline from first BASE_FRAMES (only when empty-filter is active)
434
+ if not skip_empty and cap_baseline is None:
435
+ cap_buffer.append(g_center)
436
+ cap_seen_within += 1
437
+ n_seen += 1
438
+ if len(cap_buffer) >= BASE_FRAMES:
439
+ cap_baseline = np.median(np.stack(cap_buffer, axis=0), axis=0)
440
+ continue
441
+
442
+ n_seen += 1
443
+ if skip_empty:
444
+ deformation = 0.0
445
+ is_empty = False
446
+ else:
447
+ deformation = float(np.abs(g_center - cap_baseline).mean())
448
+ is_empty = deformation < EMPTY_TAU
449
+
450
+ # Stride decision (uniform stride based on target/total estimate later)
451
+ # We use a live rate-limiter: every K frames, keep 1 (K adjusted live)
452
+ stride_state["accum"] += 1.0
453
+ if stride_state["accum"] < stride_state["stride"]:
454
+ n_stride_dropped += 1
455
+ continue
456
+ stride_state["accum"] -= stride_state["stride"]
457
+
458
+ # Empty-budget: allow up to EMPTY_BUDGET fraction of kept frames to be empty
459
+ if is_empty:
460
+ # Allow only if we're under budget
461
+ if n_empty_passed >= EMPTY_BUDGET * max(n_kept, 1):
462
+ n_empty_dropped += 1
463
+ continue
464
+
465
+ # Dedupe via phash within capture
466
+ h = phash(fr)
467
+ is_dup = any(hamming(h, hh) <= PHASH_DIST for hh in cap_phashes[-30:])
468
+ if is_dup:
469
+ n_dup_dropped += 1
470
+ continue
471
+ cap_phashes.append(h)
472
+
473
+ # Keep!
474
+ img_bytes = encode_jpeg(fr)
475
+ row = dict(meta)
476
+ row["image"] = img_bytes
477
+ row["image_format"] = "jpeg"
478
+ row["height"] = int(fr.shape[0])
479
+ row["width"] = int(fr.shape[1])
480
+ if is_empty:
481
+ n_empty_passed += 1
482
+ n_kept += 1
483
+
484
+ split = row.get("split", "train") or "train"
485
+ if split not in writers:
486
+ writers[split] = ShardWriter(out_dir, split)
487
+ writers[split].add(row)
488
+
489
+ # Adapt stride live: aim for target frames over the source.
490
+ # We don't know R_total, but we tweak so that fill rate is sensible.
491
+ # If n_kept exceeds BUDGET, raise stride aggressively.
492
+ if n_kept > 0 and n_kept % 5000 == 0:
493
+ if n_kept > BUDGET:
494
+ stride_state["stride"] = max(1.0, stride_state["stride"] * 1.5)
495
+ elif n_kept > BUDGET * 0.95:
496
+ stride_state["stride"] = max(1.0, stride_state["stride"] * 1.2)
497
+
498
+ # Hard cap
499
+ if n_kept >= BUDGET:
500
+ print(f" reached BUDGET={BUDGET}, stopping iteration", flush=True)
501
+ break
502
+
503
+ if n_seen % 20000 == 0:
504
+ dt = time.time() - t0
505
+ print(f" seen={n_seen:,} kept={n_kept:,} "
506
+ f"empty_drop={n_empty_dropped:,} dup_drop={n_dup_dropped:,} "
507
+ f"stride_drop={n_stride_dropped:,} "
508
+ f"({n_seen/max(dt,0.01):.0f} fps)", flush=True)
509
+
510
+ for w in writers.values():
511
+ w.close()
512
+
513
+ stats = {
514
+ "source": sub,
515
+ "n_seen": n_seen,
516
+ "n_kept": n_kept,
517
+ "n_empty_dropped": n_empty_dropped,
518
+ "n_empty_passed": n_empty_passed,
519
+ "n_dup_dropped": n_dup_dropped,
520
+ "n_stride_dropped": n_stride_dropped,
521
+ "splits": {k: w.total for k, w in writers.items()},
522
+ "wall_time_sec": time.time() - t0,
523
+ }
524
+ with open(f"/home/yxma/MultimodalData/stats_v2_{sub}.json", "w") as f:
525
+ json.dump(stats, f, indent=2)
526
+ print(f" {sub} stats: {stats}", flush=True)
527
+ return stats
528
+
529
+
530
+ # ─────────────────────────────────────────────────────────────────
531
+ # CLI
532
+ # ─────────────────────────────────────────────────────────────────
533
+
534
+ def cmd_probe(sub):
535
+ info = probe(sub)
536
+ out = f"/home/yxma/MultimodalData/probe_{sub}.json"
537
+ with open(out, "w") as f:
538
+ json.dump(info, f, indent=2)
539
+ print(json.dumps(info, indent=2))
540
+ print(f"saved {out}")
541
+
542
+
543
+ def cmd_process(sub):
544
+ probe_file = f"/home/yxma/MultimodalData/probe_{sub}.json"
545
+ if os.path.exists(probe_file):
546
+ info = json.load(open(probe_file))
547
+ else:
548
+ info = probe(sub)
549
+ with open(probe_file, "w") as f:
550
+ json.dump(info, f, indent=2)
551
+ process(sub, info)
552
+
553
+
554
+ def cmd_stats():
555
+ totals = {}
556
+ for sub in os.listdir(BASE_OUT):
557
+ p = f"{BASE_OUT}/{sub}"
558
+ if not os.path.isdir(p): continue
559
+ paths = sorted(glob(f"{p}/*.parquet"))
560
+ n = sum(pq.read_metadata(x).num_rows for x in paths)
561
+ bytes_total = sum(os.path.getsize(x) for x in paths)
562
+ totals[sub] = {"rows": n, "bytes": bytes_total, "shards": len(paths)}
563
+ print(json.dumps(totals, indent=2))
564
+
565
+
566
+ if __name__ == "__main__":
567
+ if len(sys.argv) < 2:
568
+ print(__doc__); sys.exit(1)
569
+ cmd = sys.argv[1]
570
+ if cmd == "probe":
571
+ cmd_probe(sys.argv[2])
572
+ elif cmd == "process":
573
+ cmd_process(sys.argv[2])
574
+ elif cmd == "stats":
575
+ cmd_stats()
576
+ else:
577
+ print(f"unknown command: {cmd}"); sys.exit(1)
scripts/make_samples_100.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Sample 100 images per subset into a 10x10 grid."""
3
+
4
+ import glob
5
+ import io
6
+ import os
7
+ import random
8
+ import sys
9
+
10
+ import pyarrow.parquet as pq
11
+ from PIL import Image, ImageDraw, ImageFont
12
+
13
+ BASE = "/media/yxma/Disk1/yuxiang/mini_data_parquet"
14
+ OUT = os.path.join(BASE, "assets")
15
+ os.makedirs(OUT, exist_ok=True)
16
+
17
+ N = 100
18
+ COLS = 10
19
+ THUMB = 144 # smaller to keep image manageable
20
+
21
+
22
+ def list_parquets(sub, split_pat="*"):
23
+ return sorted(glob.glob(os.path.join(BASE, sub, f"{split_pat}-*.parquet")))
24
+
25
+
26
+ def thumbnail(img_bytes, side=THUMB):
27
+ im = Image.open(io.BytesIO(img_bytes)).convert("RGB")
28
+ w, h = im.size
29
+ s = min(w, h)
30
+ im = im.crop(((w - s) // 2, (h - s) // 2, (w + s) // 2, (h + s) // 2))
31
+ return im.resize((side, side), Image.LANCZOS)
32
+
33
+
34
+ def make_grid(images, title, cols=COLS, side=THUMB, pad=4, title_h=44):
35
+ rows = (len(images) + cols - 1) // cols
36
+ W = pad + cols * (side + pad)
37
+ H = title_h + rows * (side + pad) + pad
38
+ canvas = Image.new("RGB", (W, H), (255, 255, 255))
39
+ d = ImageDraw.Draw(canvas)
40
+ try:
41
+ f = ImageFont.truetype("DejaVuSans-Bold.ttf", 24)
42
+ except Exception:
43
+ f = ImageFont.load_default()
44
+ d.text((pad + 4, 8), title, fill=(0, 0, 0), font=f)
45
+ for i, im in enumerate(images):
46
+ r, c = i // cols, i % cols
47
+ x = pad + c * (side + pad)
48
+ y = title_h + r * (side + pad)
49
+ canvas.paste(im, (x, y))
50
+ return canvas
51
+
52
+
53
+ def collect_uniform(sub, n=N, key_cols=None, seed=42):
54
+ """Sample n images uniformly across the parquet.
55
+
56
+ If key_cols given, also try to balance across the (key_cols) keyspace.
57
+ """
58
+ rng = random.Random(seed)
59
+ paths = list_parquets(sub)
60
+ # First, count total rows
61
+ counts = [pq.read_metadata(p).num_rows for p in paths]
62
+ total = sum(counts)
63
+ if total == 0:
64
+ return []
65
+ # Pick global indices uniformly
66
+ n = min(n, total)
67
+ idxs = sorted(rng.sample(range(total), n))
68
+ # Walk shards reading only needed rows
69
+ out = []
70
+ cum = 0
71
+ idx_iter = iter(idxs)
72
+ nxt = next(idx_iter, None)
73
+ for p, c in zip(paths, counts):
74
+ if nxt is None:
75
+ break
76
+ if nxt >= cum + c:
77
+ cum += c
78
+ continue
79
+ # collect local indices in this shard
80
+ local = []
81
+ while nxt is not None and nxt < cum + c:
82
+ local.append(nxt - cum)
83
+ nxt = next(idx_iter, None)
84
+ if local:
85
+ t = pq.read_table(p, columns=["image"])
86
+ for li in local:
87
+ out.append(t.column("image")[li].as_py())
88
+ cum += c
89
+ return out
90
+
91
+
92
+ def main():
93
+ subs = sys.argv[1:] if len(sys.argv) > 1 else [
94
+ "fota_labeled", "fota_unlabeled", "threedcal", "feats"]
95
+ for sub in subs:
96
+ if not list_parquets(sub):
97
+ print(f"skip {sub} (no parquet found)")
98
+ continue
99
+ print(f"sampling 100 from {sub}...", flush=True)
100
+ imgs = collect_uniform(sub, n=N)
101
+ thumbs = [thumbnail(b) for b in imgs]
102
+ title = f"{sub} — 100 random samples"
103
+ if sub == "feats":
104
+ title += " (includes black_dot + different gel variants)"
105
+ g = make_grid(thumbs, title)
106
+ out = os.path.join(OUT, f"samples_100_{sub}.png")
107
+ g.save(out, optimize=True)
108
+ print(f" saved {out} size={g.size}", flush=True)
109
+
110
+
111
+ if __name__ == "__main__":
112
+ main()