File size: 2,894 Bytes
650d06b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()