pakkinlau's picture
> Make dataset viewer‑ready: preview/dev Parquet, scripts, README, .gitignore
650d06b
#!/usr/bin/env python3
"""
Generate precomputed 8x8 correlation previews as JSON for the preview split.
Usage:
# From a JSONL manifest listing parcellation/subject/corr_path
python scripts/make_preview.py --manifest manifests/preview.jsonl --size 8
Notes:
- Attempts to load correlation .mat using scipy.io.loadmat, falling back to mat73 if needed.
- Variable name fallbacks: correlation_matrix | corr | A
- Writes files under preview/<parc>__<subject>__corr8x8.json
"""
import argparse
import json
import os
from pathlib import Path
from typing import Dict, Optional
def try_import():
try:
import scipy.io as sio # type: ignore
except Exception:
sio = None
try:
import mat73 # type: ignore
except Exception:
mat73 = None
return sio, mat73
def load_mat(path: Path) -> Optional[Dict]:
sio, mat73 = try_import()
if sio is not None:
try:
return sio.loadmat(str(path), squeeze_me=True, simplify_cells=True) # type: ignore[arg-type]
except Exception:
pass
if mat73 is not None:
try:
return mat73.loadmat(str(path)) # type: ignore[attr-defined]
except Exception:
pass
return None
def top_left_8x8(arr, size=8):
import numpy as np
a = np.asarray(arr)
if a.ndim < 2:
return None
n = min(size, a.shape[-1])
return a[:n, :n].astype("float32").tolist()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--manifest", type=Path, required=True)
ap.add_argument("--size", type=int, default=8)
args = ap.parse_args()
repo = Path(__file__).resolve().parents[1]
out_dir = repo / "preview"
out_dir.mkdir(parents=True, exist_ok=True)
with args.manifest.open("r", encoding="utf-8") as f:
rows = [json.loads(line) for line in f if line.strip()]
wrote = 0
for r in rows:
parc = r.get("parcellation")
subject = r.get("subject")
corr_path = r.get("corr_path")
if not (parc and subject and corr_path):
continue
dst = out_dir / f"{parc}__{subject}__corr8x8.json"
if dst.exists():
continue
src = repo / corr_path
if not src.exists():
print("skip missing:", src)
continue
data = load_mat(src)
if not isinstance(data, dict):
print("cannot load .mat (no scipy/mat73?)", src)
continue
for k in ("correlation_matrix", "corr", "A"):
if k in data:
sl = top_left_8x8(data[k], size=args.size)
if sl is not None:
with dst.open("w", encoding="utf-8") as g:
json.dump(sl, g)
wrote += 1
break
print(f"Wrote {wrote} preview tiles to {out_dir}")
if __name__ == "__main__":
main()