File size: 9,602 Bytes
678a84a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import json
from pathlib import Path

import numpy as np
from tqdm import tqdm


def update_active_stats(x, active_sum, active_sq_sum, active_count):
    vals = x[x != 0]
    if vals.size == 0:
        return active_sum, active_sq_sum, active_count

    active_sum += vals.sum()
    active_sq_sum += (vals ** 2).sum()
    active_count += vals.size
    return active_sum, active_sq_sum, active_count


def compute_dataset_stats(root_dir):
    root_dir = Path(root_dir)

    episodes = [
        p for p in root_dir.rglob("*")
        if p.is_dir() and (p / "masks.json").exists()
    ]

    print(f"Found {len(episodes)} valid episodes")

    # ---------- global stats ----------
    contact_sum = 0.0
    contact_sq_sum = 0.0
    contact_count = 0

    force_sum = 0.0
    force_sq_sum = 0.0
    force_count = 0

    contact_min = np.inf
    contact_max = -np.inf

    force_min = np.inf
    force_max = -np.inf
    force_abs_max = 0.0

    # ---------- active / non-zero stats ----------
    contact_active_sum = 0.0
    contact_active_sq_sum = 0.0
    contact_active_count = 0

    force_active_sum = 0.0
    force_active_sq_sum = 0.0
    force_active_count = 0

    # ---------- channel stats ----------
    contact_ch_sum = np.zeros(2, dtype=np.float64)
    contact_ch_sq_sum = np.zeros(2, dtype=np.float64)
    contact_ch_count = 0

    force_ch_sum = np.zeros(6, dtype=np.float64)
    force_ch_sq_sum = np.zeros(6, dtype=np.float64)
    force_ch_count = 0

    contact_ch_min = np.full(2, np.inf, dtype=np.float64)
    contact_ch_max = np.full(2, -np.inf, dtype=np.float64)

    force_ch_min = np.full(6, np.inf, dtype=np.float64)
    force_ch_max = np.full(6, -np.inf, dtype=np.float64)

    total_frames = 0
    skipped_episodes = 0
    skipped_pairs = 0

    for ep in tqdm(episodes, desc="Episodes"):
        contact_dir = ep / "modalities" / "contact"
        force_dir = ep / "modalities" / "force"

        if not contact_dir.exists() or not force_dir.exists():
            skipped_episodes += 1
            print(f"[SKIP] missing modalities: {ep}")
            continue

        contact_files = sorted(contact_dir.glob("*.npy"))
        force_files = sorted(force_dir.glob("*.npy"))

        if len(contact_files) != len(force_files):
            skipped_episodes += 1
            print(
                f"[SKIP] file count mismatch: {ep} "
                f"contact={len(contact_files)}, force={len(force_files)}"
            )
            continue

        for cfile, ffile in zip(contact_files, force_files):
            if cfile.stem != ffile.stem:
                skipped_pairs += 1
                print(
                    f"[SKIP] frame mismatch in {ep}: "
                    f"{cfile.name} vs {ffile.name}"
                )
                continue

            contact = np.load(cfile).astype(np.float64)  # (2, H, W)
            force = np.load(ffile).astype(np.float64)    # (6, H, W)

            if contact.ndim != 3 or contact.shape[0] != 2:
                skipped_pairs += 1
                print(f"[SKIP] bad contact shape {contact.shape}: {cfile}")
                continue

            if force.ndim != 3 or force.shape[0] != 6:
                skipped_pairs += 1
                print(f"[SKIP] bad force shape {force.shape}: {ffile}")
                continue

            total_frames += 1

            # --------------------------------------------------
            # global contact stats, including background zeros
            # --------------------------------------------------
            contact_sum += contact.sum()
            contact_sq_sum += (contact ** 2).sum()
            contact_count += contact.size

            contact_min = min(contact_min, float(contact.min()))
            contact_max = max(contact_max, float(contact.max()))

            # --------------------------------------------------
            # global force stats, including background zeros
            # --------------------------------------------------
            force_sum += force.sum()
            force_sq_sum += (force ** 2).sum()
            force_count += force.size

            force_min = min(force_min, float(force.min()))
            force_max = max(force_max, float(force.max()))
            force_abs_max = max(force_abs_max, float(np.abs(force).max()))

            # --------------------------------------------------
            # active / non-zero stats
            # --------------------------------------------------
            contact_active_sum, contact_active_sq_sum, contact_active_count = (
                update_active_stats(
                    contact,
                    contact_active_sum,
                    contact_active_sq_sum,
                    contact_active_count,
                )
            )

            force_active_sum, force_active_sq_sum, force_active_count = (
                update_active_stats(
                    force,
                    force_active_sum,
                    force_active_sq_sum,
                    force_active_count,
                )
            )

            # --------------------------------------------------
            # channel-wise stats
            # --------------------------------------------------
            c_flat = contact.reshape(2, -1)

            contact_ch_sum += c_flat.sum(axis=1)
            contact_ch_sq_sum += (c_flat ** 2).sum(axis=1)
            contact_ch_count += c_flat.shape[1]

            contact_ch_min = np.minimum(contact_ch_min, c_flat.min(axis=1))
            contact_ch_max = np.maximum(contact_ch_max, c_flat.max(axis=1))

            f_flat = force.reshape(6, -1)

            force_ch_sum += f_flat.sum(axis=1)
            force_ch_sq_sum += (f_flat ** 2).sum(axis=1)
            force_ch_count += f_flat.shape[1]

            force_ch_min = np.minimum(force_ch_min, f_flat.min(axis=1))
            force_ch_max = np.maximum(force_ch_max, f_flat.max(axis=1))

    if total_frames == 0:
        raise RuntimeError("No valid frames found. Please check dataset path.")

    # ======================================================
    # finalize global stats
    # ======================================================
    contact_mean = contact_sum / contact_count
    contact_std = np.sqrt(
        max(contact_sq_sum / contact_count - contact_mean ** 2, 0.0)
    )

    force_mean = force_sum / force_count
    force_std = np.sqrt(
        max(force_sq_sum / force_count - force_mean ** 2, 0.0)
    )

    # ======================================================
    # finalize active stats
    # ======================================================
    if contact_active_count > 0:
        contact_active_mean = contact_active_sum / contact_active_count
        contact_active_std = np.sqrt(
            max(
                contact_active_sq_sum / contact_active_count
                - contact_active_mean ** 2,
                0.0,
            )
        )
    else:
        contact_active_mean = 0.0
        contact_active_std = 0.0

    if force_active_count > 0:
        force_active_mean = force_active_sum / force_active_count
        force_active_std = np.sqrt(
            max(
                force_active_sq_sum / force_active_count
                - force_active_mean ** 2,
                0.0,
            )
        )
    else:
        force_active_mean = 0.0
        force_active_std = 0.0

    # ======================================================
    # finalize channel stats
    # ======================================================
    contact_ch_mean = contact_ch_sum / contact_ch_count
    contact_ch_std = np.sqrt(
        np.maximum(
            contact_ch_sq_sum / contact_ch_count - contact_ch_mean ** 2,
            0.0,
        )
    )

    force_ch_mean = force_ch_sum / force_ch_count
    force_ch_std = np.sqrt(
        np.maximum(
            force_ch_sq_sum / force_ch_count - force_ch_mean ** 2,
            0.0,
        )
    )

    stats = {
        "num_frames": int(total_frames),
        "skipped_episodes": int(skipped_episodes),
        "skipped_pairs": int(skipped_pairs),

        "contact_mean": float(contact_mean),
        "contact_std": float(contact_std),
        "contact_min": float(contact_min),
        "contact_max": float(contact_max),

        "force_mean": float(force_mean),
        "force_std": float(force_std),
        "force_min": float(force_min),
        "force_max": float(force_max),
        "force_abs_max": float(force_abs_max),

        "contact_active_mean": float(contact_active_mean),
        "contact_active_std": float(contact_active_std),
        "contact_active_count": int(contact_active_count),

        "force_active_mean": float(force_active_mean),
        "force_active_std": float(force_active_std),
        "force_active_count": int(force_active_count),

        "contact_ch_mean": contact_ch_mean.tolist(),
        "contact_ch_std": contact_ch_std.tolist(),
        "contact_ch_min": contact_ch_min.tolist(),
        "contact_ch_max": contact_ch_max.tolist(),

        "force_ch_mean": force_ch_mean.tolist(),
        "force_ch_std": force_ch_std.tolist(),
        "force_ch_min": force_ch_min.tolist(),
        "force_ch_max": force_ch_max.tolist(),
    }

    out_file = root_dir / "dataset_norm_params.json"

    with open(out_file, "w") as f:
        json.dump(stats, f, indent=2)

    print(f"\nSaved -> {out_file}")
    print(f"Frames: {total_frames:,}")
    print(f"Contact max: {contact_max:.6f}")
    print(f"Force abs max: {force_abs_max:.6f}")

    return stats


if __name__ == "__main__":
    compute_dataset_stats(
        "./grasping"
    )