File size: 26,436 Bytes
854025a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
# BrainAge — Complete End-to-End Pipeline Guide

> **Purpose**: This document describes every step to reproduce the BrainAge
> brain-age prediction system from raw MRI scans to a deployed web
> application. Provide this file to any AI assistant or human collaborator
> and they can replicate the full workflow.

---

## Table of Contents

1. [Project Overview](#1-project-overview)
2. [Hardware & Software Prerequisites](#2-hardware--software-prerequisites)
3. [Repository Layout](#3-repository-layout)
4. [Dataset: The Golden Collection](#4-dataset-the-golden-collection)
5. [Phase 1 — Preprocessing (batch_preprocess)](#5-phase-1--preprocessing)
6. [Phase 2 — Cache Preparation (cache_prep)](#6-phase-2--cache-preparation)
7. [Phase 3 — Train/Val/Test Split (data_split)](#7-phase-3--trainvaltest-split)
8. [Phase 4 — Model Training (train)](#8-phase-4--model-training)
9. [Phase 5 — Evaluation (evaluate)](#9-phase-5--evaluation)
10. [Phase 6 — Post-Training Clinical Finalization (finalize)](#10-phase-6--post-training-finalization)
11. [Phase 7 — Single-Subject Inference (infer_age)](#11-phase-7--single-subject-inference)
12. [Phase 8 — 3D Viewer Demo (viewer)](#12-phase-8--3d-viewer-demo)
13. [Phase 9 — FastAPI Web Application (webapp)](#13-phase-9--fastapi-web-application)
14. [Phase 10 — Deployment](#14-phase-10--deployment)
15. [Troubleshooting](#15-troubleshooting)
16. [File Reference Table](#16-file-reference-table)

---

## 1. Project Overview

BrainAge predicts **brain age** from T1-weighted MRI scans using a dual-branch
deep learning model (3D SFCN + tabular MLP). A positive brain-age gap (BAG =
predicted − chronological) may indicate accelerated brain aging; a negative
BAG may suggest delayed maturation.

**Pipeline stages:**

```
Raw T1 NIfTI
  → skull-strip (HD-BET, GPU)
  → bias correction (N4, ANTs)
  → MNI registration (ANTs affine)
  → z-score normalization
  → segmentation (Harvard-Oxford atlas, 69 regions)
  → volumetric measurements (per-region mm³)
  → cache tensor (.pt: 128×144×112 volume + 86-dim tabular vector)
  → train BrainAgeDual model (SFCN 3D CNN + MLP, regression)
  → evaluate (MAE, per-age-bin, TTA)
  → post-training: ComBat harmonization, normative curves, QC
  → inference: predict brain age for new subjects
  → 3D viewer: interactive NiiVue + Three.js visualization
  → web app: FastAPI dashboard + chatbot + PDF reports
```

---

## 2. Hardware & Software Prerequisites

### Minimum hardware
| Component | Requirement |
|-----------|------------|
| GPU | NVIDIA GPU with ≥ 16 GB VRAM (tested on A10G 24 GB) |
| RAM | 16 GB (batch preprocess uses memory watchdog) |
| Disk | 200 GB free (raw ~55 GB + cache ~25 GB + outputs + scratch) |

### Software stack
```bash
# OS: Ubuntu 22.04+ (tested on 24.04)
# Python 3.12+

# Create virtual environment
python3.12 -m venv .venv
source .venv/bin/activate

# Core ML
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121
pip install monai nibabel nilearn antspyx scikit-image

# Brain extraction
pip install HD-BET  # provides `hd-bet` CLI

# Pipeline utilities
pip install pandas numpy psutil pynvml

# Web app (optional, for Phase 9+)
pip install fastapi uvicorn[standard] python-multipart jinja2 itsdangerous
pip install pydantic-settings sqlalchemy alembic
pip install "passlib[bcrypt]" "bcrypt>=4.0,<4.2"
pip install groq sentence-transformers faiss-cpu
pip install "weasyprint>=62,<63" markdown pypdf httpx

# All versions are pinned in webapp/requirements.txt
```

### Environment variables (`.env`)
```ini
GROQ_API_KEY=<your-groq-api-key>       # for chatbot + PDF narrative
GROQ_MODEL=openai/gpt-oss-120b
ANTHROPIC_API_KEY=<optional>            # for Claude-based clinical reports
SESSION_SECRET=<64-random-chars>        # for webapp sessions
```

---

## 3. Repository Layout

```
/home/MRI-DataSet/
├── Golden-0-to-25/          # Raw NIfTIs, 4782 subjects age 0–25
│   ├── manifest.csv         # subject_id, age, sex, dataset, file_path, …
│   └── DataSet-*_*/         # per-source-dataset folders with NIfTI files
├── Golden-25plus/           # Raw NIfTIs, 1370 subjects age 25–86
│   ├── manifest.csv
│   └── DataSet-*_*/
├── _train/                  # Training workspace (gitignored)
│   ├── cache/               # .pt tensors (one per subject)
│   ├── scratch/             # temporary preprocessing working dirs
│   ├── outputs/             # Tier-B clinical artifacts per subject
│   └── logs/                # preprocess_status.csv, master.log, err_*.log
├── _demo/
│   └── runs/                # 10 demo subjects with full outputs + meshes
├── pipeline_v2/             # All pipeline code
│   ├── preprocess.py        # skull-strip + N4 + MNI register + z-norm
│   ├── segment.py           # Harvard-Oxford atlas segmentation
│   ├── batch_preprocess.py  # Memory-safe parallel batch driver
│   ├── cache_prep.py        # Build .pt cache tensors
│   ├── data_split.py        # Stratified train/val/test split
│   ├── model.py             # BrainAgeDual (SFCN + tabular MLP)
│   ├── train.py             # Two-phase training with early stopping
│   ├── evaluate.py          # Test-set evaluation with TTA
│   ├── infer_age.py         # Single-subject inference (checkpoint-aware)
│   ├── anomaly.py           # Per-region z-score anomaly detection
│   ├── normative_fit.py     # Fit age-conditional region norms
│   ├── harmonize.py         # ComBat multi-site harmonization
│   ├── finalize.py          # Post-training orchestrator
│   ├── qc.py                # Automated quality control
│   ├── cognitive_rollup.py  # Map regions → cognitive domains
│   ├── pattern_detect.py    # Detect clinical patterns in region data
│   ├── llm_explain.py       # Generate clinical narrative (Claude/MedGemma)
│   ├── volume_age_prior.py  # Literature-based volume-to-age fallback
│   ├── backfill_outputs.py  # Reconstruct outputs from cache for old runs
│   ├── regen_reports.py     # Regenerate all report.md files
│   ├── run_pipeline.py      # Single-subject end-to-end orchestrator
│   ├── run_demo_10.py       # Quick 10-subject demo
│   ├── brainage_sfcn.pt     # ← trained checkpoint (created in Phase 4)
│   ├── norms.json           # ← normative curves (created in Phase 6)
│   ├── combat_params.json   # ← ComBat params (created in Phase 6)
│   ├── vol_age_prior.json   # Volume-to-age lookup table
│   ├── mni152_T1_1mm_brain.nii.gz
│   └── viewer/              # Standalone 3D viewer
│       ├── serve.py
│       ├── mesh_builder.py
│       └── static/          # index.html, viewer.html
└── webapp/                  # FastAPI web application
    ├── app/
    │   ├── main.py
    │   ├── config.py
    │   ├── db.py
    │   ├── security.py
    │   ├── deps.py
    │   ├── models/          # User, Patient, Scan, ChatMessage, AuditLog
    │   ├── routers/         # auth, index, dashboard, patients, viewer, …
    │   ├── services/        # groq_client, rag, stats, preprocess_sync, …
    │   ├── templates/       # Jinja2 HTML
    │   └── static/          # JS, CSS
    ├── alembic/
    ├── docs/                # RAG corpus (markdown)
    ├── data/                # DB, uploads, outputs, reports, rag_index
    ├── Dockerfile
    ├── docker-compose.yml
    ├── run_dev.sh
    └── requirements.txt
```

---

## 4. Dataset: The Golden Collection

### Manifests

Two CSV manifests define the full dataset:

| File | Subjects | Age range |
|------|----------|-----------|
| `Golden-0-to-25/manifest.csv` | 4,782 | 0 – 25 years |
| `Golden-25plus/manifest.csv` | 1,370 | 25 – 86 years |
| **Total** | **6,152** | **0 – 86 years** |

### Manifest columns
```
dataset, subject_id, split, age_years, age_label_type, chronological_age,
brain_age, sex, healthy, modality, notes, file_path, golden_path
```

### Source datasets (12 total)
| ID | Name | Age focus |
|----|------|-----------|
| DataSet-1 | BCP (Baby Connectome) | 0–5 y |
| DataSet-2 | Calgary Preschool | 2–7 y |
| DataSet-3 | ds002726 | 3–21 y |
| DataSet-4 | ds000248 | 30 y (single adult) |
| DataSet-5 | PTBP (Pediatric Template Brain) | 5–18 y |
| DataSet-6 | IXI | 20–86 y |
| DataSet-7 | MPI-Leipzig | 20–40 y |
| DataSet-8 | AOMIC-ID1000 | 18–33 y |
| DataSet-9 | NKI-Rockland | 6–85 y |
| DataSet-10 | ABIDE-I | 6–56 y |
| DataSet-11 | ABIDE-II | 5–60 y |
| DataSet-12 | ADHD-200 | 7–22 y |

### Hosted copies
- **Hugging Face**: `bilalahmad176176/BrainAge-Golden-Raw` (public)
- Each golden_path is a symlink/copy named `<subject_id>__<original>.nii.gz`

---

## 5. Phase 1 — Preprocessing

**Module**: `pipeline_v2/batch_preprocess.py`
**Input**: Raw T1w NIfTIs listed in manifest.csv
**Output**: Preprocessed files in `_train/scratch/proc_<sid>/` → cached to `_train/cache/<sid>.pt`

### What each step does

| Step | Tool | Time/subject | Output |
|------|------|-------------|--------|
| Skull-strip | HD-BET (GPU) | ~15-30 s | `brain.nii.gz`, `brain_bet.nii.gz` (mask) |
| Bias correction | N4 (ANTsPy) | ~10 s | `brain_n4.nii.gz` |
| MNI registration | ANTs Affine | ~30 s | `brain_mni.nii.gz`, `brain_mask_mni.nii.gz` |
| Z-score normalize | NumPy | <1 s | `brain_mni_znorm.nii.gz` |
| Segmentation | Harvard-Oxford atlas | ~2 s | `segmentation.nii.gz`, `measurements.csv` |
| Volume rescaling | — | — | Rescales MNI volumes back to native-space proportions |
| Anomaly scoring | `anomaly.py` | <1 s | `anomalies.csv` |
| Cache tensor | `cache_prep.py` | <1 s | `<sid>.pt` (volume fp16 + tab fp32 + age + meta) |

### Command

```bash
cd /home/MRI-DataSet
source .venv/bin/activate

python -m pipeline_v2.batch_preprocess \
    --manifests Golden-0-to-25/manifest.csv \
                Golden-25plus/manifest.csv \
    --cache_dir  _train/cache \
    --scratch_root _train/scratch \
    --logs_dir   _train/logs \
    --workers 2
```

### Memory safety

The batch driver has a built-in watchdog:
- **RAM throttle at 75 %**, panic SIGSTOP at 85 %
- **VRAM throttle at 80 %**, panic SIGSTOP at 90 %
- Workers are recycled every N subjects to prevent C-allocator memory creep
- `OMP_NUM_THREADS=2` per worker to prevent ANTs from spawning 16 threads

### Resumability

- If `cache/<sid>.pt` exists → **skipped** (idempotent)
- `preprocess_status.csv` is append-only, flushed after every subject
- Safe to SIGKILL and restart — picks up where it left off

### Monitoring

```bash
# Live progress
tail -f _train/logs/master.log

# Status counts
awk -F, 'NR>1{c[$5]++} END{for(k in c) print k,c[k]}' \
    _train/logs/preprocess_status.csv

# Cache count
ls _train/cache/*.pt | wc -l
```

### Expected runtime
- 6,152 subjects × ~85 s / 2 workers ≈ **72 hours** on A10G
- Expect ~1–2 % failures on first pass (mostly input quality issues)
- Retry with `--retry-failed` or just rerun (cache skips successes)

### Retry fix (built into preprocess.py)

`skull_strip()` has `retries=2` and verifies output file size.
`_ants_write_retry()` retries ITK NIfTI writes up to 3× with backoff.
These recover ~80 % of transient I/O failures.

---

## 6. Phase 2 — Cache Preparation

**Module**: `pipeline_v2/cache_prep.py`
**Note**: This is integrated INTO `batch_preprocess.py` — each worker calls
cache_prep at the end of its subject processing. No separate run needed.

### Cache tensor format (`<sid>.pt`)
```python
{
    "volume": torch.float16,   # shape (128, 144, 112) — resized from 182×218×182
    "tab":    torch.float32,   # shape (86,) — 70 region vols (log1p/12) + 3 sex + 13 site
    "age":    torch.float32,   # scalar — chronological age in years
    "meta":   dict,            # {subject_id, site, sex, age, split}
}
```

### Tabular vector breakdown (86 dimensions)
- Dims 0–69: log1p(volume_mm³) / 12 for each of the 70 Harvard-Oxford regions
- Dims 70–72: one-hot sex encoding [M, F, U]
- Dims 73–85: one-hot site encoding (13 datasets)

### Volume shape
Standard resize to `(128, 144, 112)` via trilinear interpolation.
Input: `brain_mni_znorm.nii.gz` (182×218×182 in MNI space).

---

## 7. Phase 3 — Train/Val/Test Split

**Module**: `pipeline_v2/data_split.py`
**Input**: Manifest CSV(s)
**Output**: `split.csv` with train/val/test assignments

```bash
python -m pipeline_v2.data_split \
    --manifests Golden-0-to-25/manifest.csv \
                Golden-25plus/manifest.csv \
    --out _train/split.csv
```

### Split strategy
- **Stratified by (site, age_bin)** — ensures every site × age combination
  is represented in all splits
- **Age bins**: 0–2, 2–5, 5–12, 12–18, 18–25, 25–50, 50–80
- **Ratios**: 75 % train / 10 % validation / 15 % test
- **Deterministic**: seed=42, reproducible

### Result (approximate)
| Split | Count |
|-------|-------|
| train | ~4,614 |
| val   | ~615 |
| test  | ~923 |

---

## 8. Phase 4 — Model Training

**Module**: `pipeline_v2/train.py`
**Architecture**: `pipeline_v2/model.py` — `BrainAgeDual`

### Model architecture: BrainAgeDual

```
Image branch (SFCN — Peng 2021):
  3D CNN: Conv3d(1→32→64→128→256→256→64) with BN + MaxPool + ReLU
  → AdaptiveAvgPool3d(1) → flatten → emb_dim=128

Tabular branch (MLP):
  Linear(86→128) → ReLU → Dropout(0.3) → Linear(128→128)

Fusion:
  concat(image_emb, tab_emb) → Linear(256→64) → ReLU → Dropout → Linear(64→1)

Total params: ~3M
Output: predicted age (scalar, years)
Loss: L1Loss (MAE)
```

### Training strategy

**Two-phase approach:**

#### Phase A — Lifespan pretraining
```bash
python -m pipeline_v2.train \
    --cache_dir _train/cache \
    --split_csv _train/split.csv \
    --out_ckpt  pipeline_v2/brainage_sfcn.pt \
    --epochs 60 \
    --batch 4 \
    --lr 3e-4
```

#### Phase B — Fine-tune on 0–25 subset (pediatric focus)
```bash
python -m pipeline_v2.train \
    --cache_dir _train/cache \
    --split_csv _train/split.csv \
    --resume_ckpt pipeline_v2/brainage_sfcn.pt \
    --age_max 25 \
    --epochs 30 \
    --lr 1e-4 \
    --out_ckpt pipeline_v2/brainage_sfcn.pt
```

### Training features
- **Mixed precision** (fp16) + gradient clipping
- **Linear warmup** (5 epochs) + **cosine LR decay**
- **Weighted sampler** for age-bin balance (prevents bias toward
  over-represented age groups)
- **MONAI augmentation**: random affine, random flip, intensity shift
- **Val-MAE early stopping** (patience=10)
- **CSV metrics log**: epoch, train_loss, val_loss, val_mae, lr

### Checkpoint format
```python
{
    "model": state_dict,
    "optimizer": optimizer_state,
    "epoch": int,
    "val_mae": float,
    "n_tabular": 86,
    "config": {...}
}
```

### Expected results (on this dataset)
| Metric | Expected range |
|--------|---------------|
| Overall MAE | 2.0 – 3.5 years |
| 0–2 y MAE | 1.0 – 2.0 years |
| 2–18 y MAE | 1.5 – 3.0 years |
| 18+ y MAE | 2.5 – 4.0 years |

---

## 9. Phase 5 — Evaluation

**Module**: `pipeline_v2/evaluate.py`

```bash
python -m pipeline_v2.evaluate \
    --cache_dir _train/cache \
    --split_csv _train/split.csv \
    --ckpt pipeline_v2/brainage_sfcn.pt \
    --out_csv _train/eval_results.csv \
    --tta 5
```

### What it computes
- Per-subject predictions with 5× flip TTA
- Overall MAE, median AE, R², correlation
- Per-age-bin MAE breakdown
- Per-site MAE breakdown
- Scatter plot data (true age vs predicted)

---

## 10. Phase 6 — Post-Training Finalization

**Module**: `pipeline_v2/finalize.py`

This orchestrator runs sequentially after training completes:

```bash
python -m pipeline_v2.finalize \
    --manifests Golden-0-to-25/manifest.csv \
                Golden-25plus/manifest.csv \
    --cache_dir _train/cache \
    --outputs_dir _train/outputs
```

### Stage 1: ComBat harmonization (`harmonize.py`)
- Removes scanner/site batch effects from per-region volumes
- Preserves biological variance (age, sex as covariates)
- Output: `pipeline_v2/combat_params.json`

### Stage 2: Normative curve fitting (`normative_fit.py`)
- Fits age-conditional mean and SD for each of 70 regions, stratified by sex
- Uses monotone cubic splines (similar to Bethlehem 2022 brain charts)
- Output: `pipeline_v2/norms.json`
- This replaces the synthetic `expected_region_volume()` baseline

### Stage 3: Rebuild anomaly tables
- Reruns `anomaly.py` on all subjects using fitted norms instead of crude σ
- z-scores become properly calibrated

### Stage 4: BAG confidence intervals
- Monte Carlo dropout on the trained model
- Adds confidence intervals to each subject's report

### Stage 5: QC re-check
- Volume sanity, z-norm range, registration quality
- Flags ~3–5 % for manual review

### Manual commands (if not using finalize.py)
```bash
# Harmonization alone
python -m pipeline_v2.harmonize \
    --cache _train/cache \
    --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \
    --out pipeline_v2/combat_params.json

# Normative fit alone
python -m pipeline_v2.normative_fit \
    --cache _train/cache \
    --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \
    --out pipeline_v2/norms.json

# Backfill outputs for subjects cached before outputs existed
python -m pipeline_v2.backfill_outputs \
    --cache_dir _train/cache \
    --outputs_dir _train/outputs
```

---

## 11. Phase 7 — Single-Subject Inference

**Module**: `pipeline_v2/infer_age.py`

### How it works
1. Checks for `pipeline_v2/brainage_sfcn.pt`
2. **If checkpoint exists**: loads BrainAgeDual, runs 5× flip-TTA inference
3. **If no checkpoint**: falls back to `volume_age_prior.py` (literature-based
   volume-to-age curve). The response includes `"predicted_source":
   "volume_prior_untrained"` as an honesty flag.

### Programmatic usage
```python
from pipeline_v2.infer_age import predict_age
result = predict_age(
    mni_znorm=Path("brain_mni_znorm.nii.gz"),
    meas_csv=Path("measurements.csv"),
    total_brain_mm3=1240000.0,
    sex="F",
    site="DataSet-6_IXI"
)
# result = {"predicted_brain_age": 32.5, "predicted_source": "sfcn_tta", ...}
```

### End-to-end single subject
```bash
python -m pipeline_v2.run_pipeline \
    /path/to/t1.nii.gz \
    sub-001 \
    25.0 \
    F \
    /tmp/output_sub001
```

---

## 12. Phase 8 — 3D Viewer Demo

**Module**: `pipeline_v2/viewer/serve.py`

```bash
# Start the standalone viewer
python -m uvicorn pipeline_v2.viewer.serve:app --host 0.0.0.0 --port 8765
# Open http://localhost:8765
```

### Features
- Subject list with age, predicted age, BAG
- NiiVue 2D slice views (axial/coronal/sagittal)
- Three.js 3D mesh rendering (marching cubes from segmentation)
- Per-region panel: volume, expected, deviation %, z-score, percentile
- Tissue composition (GM/WM/CSF ratios)
- Bilateral asymmetry index
- Lobe-wise abnormality summaries
- Cognitive domain rollup
- Clinical pattern detection
- Top findings bullets

### Demo data
10 subjects in `_demo/runs/` with full outputs including pre-built meshes.

### Hosted version
HF Space: `bilalahmad176176/BrainAge-3D-Viewer`

---

## 13. Phase 9 — FastAPI Web Application

**Location**: `webapp/`

### Architecture
- **Backend**: FastAPI + SQLAlchemy (SQLite) + Alembic migrations
- **Frontend**: Jinja2 templates + Tailwind CSS + vanilla JS + Chart.js
- **Auth**: Cookie-signed sessions, bcrypt passwords, admin + staff roles
- **LLM**: Groq `gpt-oss-120b` streaming via SSE
- **RAG**: FAISS + sentence-transformers/all-MiniLM-L6-v2 over project docs
- **PDF**: WeasyPrint HTML→PDF with Groq narrative + user signature

### Pages / features
| Route | Feature |
|-------|---------|
| `/` | Landing page + RAG chatbot (project Q&A) |
| `/login` | Authentication |
| `/dashboard` | KPIs, Chart.js graphs, activity heatmap, recent uploads |
| `/patients` | Patient list (CRUD) |
| `/patients/new` | Create patient |
| `/patients/{pid}/upload` | Upload MRI NIfTI → triggers full pipeline |
| `/scans/{id}/view` | 3D viewer + patient-scoped medical chatbot |
| `/scans/{id}/report` | Generate + download PDF clinical report |
| `/admin/users` | Admin user management |
| `/settings` | Signature upload for PDF reports |

### Quick start
```bash
cd webapp
cp .env.example .env  # fill SESSION_SECRET + GROQ_API_KEY
./run_dev.sh
# or
python -m uvicorn app.main:app --host 0.0.0.0 --port 8011 --reload
```

### Default credentials
| Username | Password | Role |
|----------|----------|------|
| `admin` | `admin` | admin |

**Change the admin password after first login.**

### Database models
- `User` (username, email, role, pwd_hash, signature_image_path)
- `Patient` (first_name, last_name, dob, sex, notes)
- `Scan` (patient_id, uploaded_at, status, predicted_age, bag, file_path)
- `ChatMessage` (scan_id, role, content, created_at)
- `AuditLog` (user_id, action, detail, created_at)

### How upload processing works
1. User uploads `.nii.gz` on `/patients/{pid}/upload`
2. Server validates NIfTI header, saves to `data/uploads/{pid}/`
3. Creates Scan row (status=processing)
4. Shows full-page spinner (`patients/processing.html`)
5. Blocking call to `preprocess_sync.run_pipeline_for_scan()`:
   - preprocess → segment → infer_age → score_regions
   - Copies all outputs (including NIfTIs!) to `data/outputs/{scan_id}/`
   - Updates Scan row with predicted_age, bag, status=completed
6. Redirects to 3D viewer

---

## 14. Phase 10 — Deployment

### Docker
```bash
cd webapp
cp .env.example .env   # edit SESSION_SECRET, GROQ_API_KEY
docker compose up -d --build
# browse http://localhost:8000
```

### Production checklist
1. Set a real `SESSION_SECRET` (64+ random chars)
2. Set `COOKIE_SECURE=1` behind HTTPS (nginx/Caddy reverse proxy)
3. Restrict `TRUSTED_HOSTS` to your real domain(s)
4. Change admin password after first login
5. Back up `data/webapp.db` and `data/outputs/` regularly
6. Run migrations on upgrade: `docker compose exec web alembic upgrade head`

### Hugging Face Spaces
A Docker-based Space is deployed at `bilalahmad176176/BrainAge-3D-Viewer`
(standalone viewer with 10 demo subjects, no auth).

---

## 15. Troubleshooting

### Preprocessing

| Problem | Cause | Fix |
|---------|-------|-----|
| `skull_strip: 16000+ s` | Running on CPU (no CUDA) | Ensure `nvidia-smi` works, torch sees GPU |
| `NiftiImageIO failed to write` | Transient I/O contention | Built-in `_ants_write_retry()` handles it; if persistent, check disk space |
| `brain_bet.nii.gz does not exist` | HD-BET silently failed | `skull_strip()` retries 2×; if persistent, the input NIfTI is likely corrupt |
| OOM during batch | Too many workers / too little RAM | Reduce `--workers 1`; watchdog will SIGSTOP at 85% RAM |

### Training

| Problem | Fix |
|---------|-----|
| CUDA OOM | Reduce `--batch 2` or `--batch 1` |
| Loss not decreasing | Check split.csv exists and has all subjects; verify cache integrity |
| Slow training | Ensure `.pt` cache is on SSD, not NFS |

### Webapp

| Problem | Fix |
|---------|-----|
| `unhashable type: 'dict'` | Starlette TemplateResponse signature changed — pass `request` as 1st arg |
| `password cannot be longer than 72 bytes` | Pin `bcrypt>=4.0,<4.2` for passlib compatibility |
| Viewer stuck on "loading…" | `brain_mni_znorm.nii.gz` missing from scan output dir — rerun preprocess or backfill |
| Port 8000 in use | Change port: `PORT=8011 ./run_dev.sh` |

---

## 16. File Reference Table

| File | Purpose | Created by |
|------|---------|-----------|
| `Golden-*/manifest.csv` | Dataset manifests with age, sex, paths | Manual curation |
| `_train/cache/<sid>.pt` | Preprocessed tensor cache | `batch_preprocess.py` |
| `_train/logs/preprocess_status.csv` | Per-subject status log | `batch_preprocess.py` |
| `_train/logs/master.log` | Driver log with progress/ETA | `batch_preprocess.py` |
| `_train/split.csv` | Train/val/test assignments | `data_split.py` |
| `pipeline_v2/brainage_sfcn.pt` | Trained model checkpoint | `train.py` |
| `pipeline_v2/norms.json` | Normative curves (per-region) | `normative_fit.py` |
| `pipeline_v2/combat_params.json` | ComBat harmonization params | `harmonize.py` |
| `pipeline_v2/vol_age_prior.json` | Volume-to-age fallback curve | `volume_age_prior.py` |
| `_train/outputs/<sid>/` | Tier-B clinical artifacts | `batch_preprocess.py` or `backfill_outputs.py` |
| `_demo/runs/<sid>/` | Demo subjects with full outputs + meshes | `run_demo_10.py` |
| `webapp/data/webapp.db` | SQLite database | FastAPI lifespan |
| `webapp/data/outputs/<scan_id>/` | Web upload scan outputs | `preprocess_sync.py` |
| `webapp/data/reports/<scan_id>/` | Generated PDF reports | `pdf_generator.py` |

---

## Quick-Start Cheat Sheet

```bash
# 1. Preprocess all 6,152 subjects (~72h)
python -m pipeline_v2.batch_preprocess \
    --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \
    --cache_dir _train/cache --scratch_root _train/scratch \
    --logs_dir _train/logs --workers 2

# 2. Generate train/val/test split
python -m pipeline_v2.data_split \
    --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \
    --out _train/split.csv

# 3. Train (lifespan → finetune)
python -m pipeline_v2.train \
    --cache_dir _train/cache --split_csv _train/split.csv \
    --out_ckpt pipeline_v2/brainage_sfcn.pt --epochs 60 --batch 4

python -m pipeline_v2.train \
    --cache_dir _train/cache --split_csv _train/split.csv \
    --resume_ckpt pipeline_v2/brainage_sfcn.pt \
    --age_max 25 --epochs 30 --lr 1e-4 \
    --out_ckpt pipeline_v2/brainage_sfcn.pt

# 4. Evaluate
python -m pipeline_v2.evaluate \
    --cache_dir _train/cache --split_csv _train/split.csv \
    --ckpt pipeline_v2/brainage_sfcn.pt --tta 5

# 5. Post-training finalization
python -m pipeline_v2.finalize \
    --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \
    --cache_dir _train/cache --outputs_dir _train/outputs

# 6. Launch webapp
cd webapp && ./run_dev.sh
```

---

*Last updated: 2026-04-24. Generated from the live BrainAge pipeline on
an NVIDIA A10G (24 GB VRAM) / 16 GB RAM / 193 GB disk Ubuntu server.*