trifuse-ad-oasis1 / scripts /prepare_data.py
minhy112's picture
Add scripts
9df13b0 verified
Raw
History Blame Contribute Delete
3.12 kB
"""End-to-end data preparation: extract discs -> build cohort -> preprocess.
Usage:
python scripts/prepare_data.py --extract # extract all discs (idempotent)
python scripts/prepare_data.py --cohort # build subjects_clean.csv + stats
python scripts/prepare_data.py --preprocess # 3D volumes + 2.5D slices
python scripts/prepare_data.py --splits # repeated stratified folds
python scripts/prepare_data.py --all # everything in order
"""
from __future__ import annotations
import argparse
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
RAW = ROOT / "data" / "raw"
META = ROOT / "data" / "metadata"
def extract_discs() -> None:
"""Extract every disc tarball into data/raw/ (skips already-extracted)."""
discs = sorted(RAW.glob("oasis_cross-sectional_disc*.tar.gz"))
if not discs:
sys.exit("no disc tarballs found in data/raw/")
for tgz in discs:
n = tgz.name.split("disc")[1].split(".")[0]
marker = RAW / f"disc{n}"
if marker.exists():
print(f"disc{n}: already extracted")
continue
print(f"disc{n}: verifying gzip ...", flush=True)
r = subprocess.run(["gzip", "-t", str(tgz)], capture_output=True)
if r.returncode != 0:
print(f" disc{n} CORRUPT: {r.stderr.decode()[:200]}", flush=True)
continue
print(f"disc{n}: extracting ...", flush=True)
subprocess.run(["tar", "xzf", str(tgz), "-C", str(RAW)], check=True)
print("extraction done")
def build_cohort() -> None:
from trifuse.data.cohort import build_cohort as _bc
_bc(RAW, META)
def preprocess() -> None:
from trifuse.data.preprocess_3d import run as run3d
from trifuse.data.preprocess_2d import run as run2d
csv = META / "subjects_clean.csv"
if not csv.exists():
sys.exit("run --cohort first (subjects_clean.csv missing)")
run3d(csv, ROOT / "data" / "processed_3d")
run2d(csv, ROOT / "data" / "processed_2d")
def make_splits() -> None:
import pandas as pd
from trifuse.data.splits import make_folds
csv = META / "subjects_clean.csv"
df = pd.read_csv(csv)
folds = make_folds(df)
out = META / "folds.csv"
folds.to_csv(out, index=False)
print(f"wrote {out} ({len(folds)} rows = {folds['seed'].nunique()} seeds x {len(df)} subjects)")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--extract", action="store_true")
ap.add_argument("--cohort", action="store_true")
ap.add_argument("--preprocess", action="store_true")
ap.add_argument("--splits", action="store_true")
ap.add_argument("--all", action="store_true")
a = ap.parse_args()
if a.all or a.extract:
extract_discs()
if a.all or a.cohort:
build_cohort()
if a.all or a.preprocess:
preprocess()
if a.all or a.splits:
make_splits()
if not any([a.extract, a.cohort, a.preprocess, a.splits, a.all]):
ap.print_help()
if __name__ == "__main__":
main()