"""Build the analysis cohort from OASIS-1 per-subject metadata + processed volumes. The central OASIS-1 demographics spreadsheet URL is dead, so we reconstruct the full metadata table by parsing each subject's `OAS1_XXXX_MR1.txt` (present in every subject folder) and pairing it with the atlas-registered, brain-masked processed volume `*_111_t88_masked_gfc.img`. Cohort protocol (see plan): - one row per subject (no repeat scans, no reliability sessions) - age >= 60 only -> breaks the "young brain = CN" age shortcut - label from CDR: 0 -> CN, 0.5 -> VMD (very mild dementia), >=1 -> AD - CDR & MMSE are NEVER model inputs (label leakage); kept only for analysis. """ from __future__ import annotations import glob import re from pathlib import Path import pandas as pd # --- paths ------------------------------------------------------------------- ROOT = Path(__file__).resolve().parents[3] RAW = ROOT / "data" / "raw" META_DIR = ROOT / "data" / "metadata" MIN_AGE = 60 CLASS_NAMES = ["CN", "VMD", "AD"] # subject dir looks like discN/OAS1_0043_MR1/ SUBJECT_RE = re.compile(r"OAS1_\d{4}_MR1") def _parse_txt(txt_path: Path) -> dict: """Parse the OAS1_XXXX_MR1.txt header block into a flat dict. Fields are 'KEY: value'. Empty values (young subjects lack CDR/Educ/SES) become None. We only read the top demographic block; per-scan blocks below repeat 'TYPE:'/'TR:' etc. and are ignored (we stop at the first scan block). """ fields: dict[str, str] = {} for raw_line in txt_path.read_text(errors="ignore").splitlines(): if raw_line.strip().startswith("mpr-") or raw_line.strip().startswith("SCAN NUMBER"): break # reached per-scan section; demographics are all above if ":" not in raw_line: continue key, _, val = raw_line.partition(":") key = key.strip().upper() val = val.strip() if key in {"SESSION ID", "AGE", "M/F", "HAND", "EDUC", "SES", "CDR", "MMSE", "ETIV", "ASF", "NWBV"}: fields[key] = val if val != "" else None return fields def _to_float(v): if v is None or v == "": return None try: return float(v) except ValueError: return None def _cdr_to_class(cdr: float | None) -> int | None: if cdr is None: return None if cdr == 0.0: return 0 # CN if cdr == 0.5: return 1 # VMD / very mild dementia (NOT clinical MCI) if cdr >= 1.0: return 2 # AD (mild/moderate dementia) return None def _find_masked_volume(subject_dir: Path) -> Path | None: hits = glob.glob(str(subject_dir / "PROCESSED" / "MPRAGE" / "T88_111" / "*_111_t88_masked_gfc.img")) return Path(hits[0]) if hits else None def scan_subjects(raw_dir: Path = RAW) -> pd.DataFrame: """Walk extracted discs, parse every subject's txt + locate its masked volume. Returns the FULL table (all ages, all CDR states) before cohort filtering, so the caller can report how many subjects each filter removes. """ rows = [] seen: set[str] = set() for txt in sorted(raw_dir.glob("disc*/OAS1_*_MR1/OAS1_*_MR1.txt")): sid_session = txt.parent.name # OAS1_0043_MR1 subject_id = sid_session.replace("_MR1", "") # OAS1_0043 if subject_id in seen: continue # one row per subject; ignore any duplicate session dirs seen.add(subject_id) f = _parse_txt(txt) vol = _find_masked_volume(txt.parent) cdr = _to_float(f.get("CDR")) rows.append({ "subject_id": subject_id, "session_id": sid_session, "age": _to_float(f.get("AGE")), "sex": 1 if (f.get("M/F") or "").lower().startswith("m") else 0, "sex_str": f.get("M/F"), "education": _to_float(f.get("EDUC")), "ses": _to_float(f.get("SES")), "cdr": cdr, "mmse": _to_float(f.get("MMSE")), "etiv": _to_float(f.get("ETIV")), "nwbv": _to_float(f.get("NWBV")), "asf": _to_float(f.get("ASF")), "class_id": _cdr_to_class(cdr), "volume_path": str(vol) if vol else None, }) return pd.DataFrame(rows) def build_cohort(raw_dir: Path = RAW, min_age: int = MIN_AGE) -> tuple[pd.DataFrame, dict]: """Apply the cohort protocol and return (clean_df, provenance_stats).""" full = scan_subjects(raw_dir) stats = {"n_subjects_total": len(full)} # must have a CDR-derived label (drops young no-assessment subjects) has_label = full[full["class_id"].notna()].copy() stats["n_with_cdr_label"] = len(has_label) # must have a readable masked volume has_vol = has_label[has_label["volume_path"].notna()].copy() stats["n_with_volume"] = len(has_vol) # age >= min_age (break the age shortcut) cohort = has_vol[has_vol["age"] >= min_age].copy() stats["n_age_ge_%d" % min_age] = len(cohort) cohort["class_id"] = cohort["class_id"].astype(int) cohort = cohort.sort_values("subject_id").reset_index(drop=True) stats["class_counts"] = { CLASS_NAMES[i]: int((cohort["class_id"] == i).sum()) for i in range(3) } stats["age_bands"] = { "60-69": int(((cohort.age >= 60) & (cohort.age < 70)).sum()), "70-79": int(((cohort.age >= 70) & (cohort.age < 80)).sum()), "80+": int((cohort.age >= 80).sum()), } stats["sex_counts"] = { "M": int((cohort.sex == 1).sum()), "F": int((cohort.sex == 0).sum()), } stats["missing"] = { c: int(cohort[c].isna().sum()) for c in ["education", "ses", "etiv", "nwbv", "asf", "mmse"] } return cohort, stats def main(): META_DIR.mkdir(parents=True, exist_ok=True) cohort, stats = build_cohort() # the model-input columns exclude cdr & mmse (leakage); keep them in the CSV # for analysis but the datasets module must not read them as features. out_cols = ["subject_id", "session_id", "age", "sex", "education", "ses", "etiv", "nwbv", "asf", "cdr", "mmse", "class_id", "volume_path"] cohort[out_cols].to_csv(META_DIR / "subjects_clean.csv", index=False) import json (META_DIR / "dataset_statistics.json").write_text(json.dumps(stats, indent=2)) print(json.dumps(stats, indent=2)) print(f"\nwrote {META_DIR/'subjects_clean.csv'} ({len(cohort)} subjects)") if __name__ == "__main__": main()