action-worldmodel-bench / compute_normalization.py
syCen's picture
Create compute_normalization.py
678a84a verified
Raw
History Blame Contribute Delete
9.6 kB
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"
)