File size: 27,012 Bytes
2f33c28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3d7f60a0",
   "metadata": {},
   "source": [
    "---\n",
    "## Stage 1 β€” Data Exploration\n",
    "\n",
    "### What & Why\n",
    "\n",
    "Before writing any model code, we need to understand the raw data deeply.  \n",
    "BraTS2020 gives us 369 training cases, each with 4 MRI modalities and a segmentation mask.\n",
    "\n",
    "**Key questions this stage answers:**\n",
    "- What shape and dtype are the volumes?\n",
    "- Are intensity ranges consistent across modalities and patients?\n",
    "- What is the class distribution in the segmentation masks?\n",
    "- What label remapping is required before training?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9cb7973b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import nibabel as nib\n",
    "import numpy as np\n",
    "from pathlib import Path\n",
    "\n",
    "# ── Point this at your BraTS2020 training data root ──────────────────────────\n",
    "DATA_ROOT = Path(r\"D:\\personal projects\\Brain-Tumor-Segmentation-with-BraTS\\BraTS2020_TrainingData\\MICCAI_BraTS2020_TrainingData\")\n",
    "CASE_001  = DATA_ROOT / \"BraTS20_Training_001\"\n",
    "MODALITIES = [\"flair\", \"t1\", \"t1ce\", \"t2\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4de818c4",
   "metadata": {},
   "source": [
    "### 1.1 Modality Exploration\n",
    "\n",
    "We load each modality and inspect:\n",
    "- **Shape** β€” should be `(240, 240, 155)` for all BraTS2020 volumes\n",
    "- **Intensity range** β€” will differ across modalities (MRI values are not standardized)\n",
    "- **Non-zero fraction** β€” tells us how much of the volume is actual brain vs background air"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "5328263a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "============================================================\n",
      "MODALITY EXPLORATION β€” Case 001\n",
      "============================================================\n",
      "\n",
      "── FLAIR ──────────────────────────\n",
      "  Shape:           (240, 240, 155)\n",
      "  Dtype:           float64\n",
      "  Global min/max:  0.0  /  625.0\n",
      "  Brain mean:      173.0\n",
      "  Brain std:       64.9\n",
      "  Non-zero voxels: 1,342,885  /  8,928,000  (15.0%)\n",
      "\n",
      "── T1 ──────────────────────────\n",
      "  Shape:           (240, 240, 155)\n",
      "  Dtype:           float64\n",
      "  Global min/max:  0.0  /  678.0\n",
      "  Brain mean:      354.3\n",
      "  Brain std:       84.2\n",
      "  Non-zero voxels: 1,342,885  /  8,928,000  (15.0%)\n",
      "\n",
      "── T1CE ──────────────────────────\n",
      "  Shape:           (240, 240, 155)\n",
      "  Dtype:           float64\n",
      "  Global min/max:  0.0  /  1845.0\n",
      "  Brain mean:      417.3\n",
      "  Brain std:       109.2\n",
      "  Non-zero voxels: 1,342,885  /  8,928,000  (15.0%)\n",
      "\n",
      "── T2 ──────────────────────────\n",
      "  Shape:           (240, 240, 155)\n",
      "  Dtype:           float64\n",
      "  Global min/max:  0.0  /  376.0\n",
      "  Brain mean:      114.7\n",
      "  Brain std:       47.7\n",
      "  Non-zero voxels: 1,342,885  /  8,928,000  (15.0%)\n"
     ]
    }
   ],
   "source": [
    "print(\"=\" * 60)\n",
    "print(\"MODALITY EXPLORATION β€” Case 001\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "for mod in MODALITIES:\n",
    "    path = CASE_001 / f\"BraTS20_Training_001_{mod}.nii\"\n",
    "    img  = nib.load(str(path))\n",
    "    vol  = img.get_fdata()\n",
    "\n",
    "    brain_mask    = vol > 0\n",
    "    brain_voxels  = vol[brain_mask]\n",
    "\n",
    "    print(f\"\\n── {mod.upper()} ──────────────────────────\")\n",
    "    print(f\"  Shape:           {vol.shape}\")\n",
    "    print(f\"  Dtype:           {vol.dtype}\")\n",
    "    print(f\"  Global min/max:  {vol.min():.1f}  /  {vol.max():.1f}\")\n",
    "    print(f\"  Brain mean:      {brain_voxels.mean():.1f}\")\n",
    "    print(f\"  Brain std:       {brain_voxels.std():.1f}\")\n",
    "    print(f\"  Non-zero voxels: {brain_mask.sum():,}  /  {vol.size:,}  ({100*brain_mask.mean():.1f}%)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f39f11f",
   "metadata": {},
   "source": [
    "**What this tells us:**\n",
    "\n",
    "| Observation | Implication |\n",
    "|---|---|\n",
    "| All modalities: shape `(240, 240, 155)` | Pre-registered β€” voxel [x,y,z] is the same tissue in all 4 |\n",
    "| All modalities: same non-zero fraction | Shared brain mask β€” background zeroed identically |\n",
    "| Intensity ranges differ wildly (T2 max=376 vs T1ce max=1845) | Cannot normalize globally β€” must normalize **per modality** |\n",
    "| Only 15% of voxels are non-zero | 85% is background air β€” wasteful for model input, crop it |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ba37626",
   "metadata": {},
   "source": [
    "### 1.2 Segmentation Mask Exploration\n",
    "\n",
    "The segmentation mask is the ground truth we train against.  \n",
    "BraTS2020 uses label set `{0, 1, 2, 4}` β€” note the jump from 2 to 4.  \n",
    "This is a historical artifact. Our model uses output indices `{0,1,2,3}`, so we must remap `4 β†’ 3`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ab2d226c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "============================================================\n",
      "SEGMENTATION MASK β€” Case 001\n",
      "============================================================\n",
      "\n",
      "  Shape:         (240, 240, 155)\n",
      "  Unique labels: [0 1 2 4]\n",
      "\n",
      "  Label 0:  8,716,021 voxels  (97.63%)  ← Background\n",
      "  Label 1:     15,443 voxels  (0.17%)  ← Necrotic Core (NCR)\n",
      "  Label 2:    168,794 voxels  (1.89%)  ← Peritumoral Edema (ED)\n",
      "  Label 4:     27,742 voxels  (0.31%)  ← Enhancing Tumor (ET)\n",
      "\n",
      "⚠  Label 4 will be remapped to 3 before training\n",
      "   Tumor burden: 2.37% of all voxels\n"
     ]
    }
   ],
   "source": [
    "print(\"=\" * 60)\n",
    "print(\"SEGMENTATION MASK β€” Case 001\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "seg_path = CASE_001 / \"BraTS20_Training_001_seg.nii\"\n",
    "seg = nib.load(str(seg_path)).get_fdata().astype(np.uint8)\n",
    "\n",
    "CLASS_NAMES = {0: \"Background\", 1: \"Necrotic Core (NCR)\", 2: \"Peritumoral Edema (ED)\", 4: \"Enhancing Tumor (ET)\"}\n",
    "\n",
    "print(f\"\\n  Shape:         {seg.shape}\")\n",
    "print(f\"  Unique labels: {np.unique(seg)}\")\n",
    "print()\n",
    "\n",
    "for label in np.unique(seg):\n",
    "    count = int((seg == label).sum())\n",
    "    pct   = 100 * count / seg.size\n",
    "    name  = CLASS_NAMES.get(label, \"Unknown\")\n",
    "    print(f\"  Label {label}: {count:>10,} voxels  ({pct:.2f}%)  ← {name}\")\n",
    "\n",
    "print()\n",
    "print(\"⚠  Label 4 will be remapped to 3 before training\")\n",
    "print(f\"   Tumor burden: {100*(seg>0).mean():.2f}% of all voxels\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "982c8657",
   "metadata": {},
   "source": [
    "**Why class imbalance matters:**\n",
    "\n",
    "Background = **97.63%** of all voxels. If a model predicts background everywhere,  \n",
    "it achieves 97.63% voxel accuracy β€” and is clinically worthless.\n",
    "\n",
    "This is why we use **Dice loss** instead of cross-entropy alone.  \n",
    "Dice is computed per class independently, so a 0.17% class gets the same gradient weight as a 50% class.\n",
    "\n",
    "**BraTS Evaluation Regions** (derived from the 4 labels):\n",
    "\n",
    "| Region | Labels | Clinical meaning |\n",
    "|---|---|---|\n",
    "| Whole Tumor (WT) | {1, 2, 3} | Total tumor extent |\n",
    "| Tumor Core (TC) | {1, 3} | Surgically targetable core |\n",
    "| Enhancing Tumor (ET) | {3} | Active, contrast-enhancing tumor |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "240e9ec0",
   "metadata": {},
   "source": [
    "### 1.3 Affine and Voxel Size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4cf35669",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Affine matrix (voxel β†’ world space in mm):\n",
      "[[ -1.  -0.  -0.   0.]\n",
      " [ -0.  -1.  -0. 239.]\n",
      " [  0.   0.   1.   0.]\n",
      " [  0.   0.   0.   1.]]\n",
      "\n",
      "Voxel size: [1. 1. 1.] mm\n",
      "β†’ Isotropic 1mmΒ³ β€” each voxel represents 1mm Γ— 1mm Γ— 1mm of brain tissue\n"
     ]
    }
   ],
   "source": [
    "img = nib.load(str(CASE_001 / \"BraTS20_Training_001_t1.nii\"))\n",
    "print(\"Affine matrix (voxel β†’ world space in mm):\")\n",
    "print(img.affine)\n",
    "print()\n",
    "voxel_size = np.sqrt((img.affine[:3, :3] ** 2).sum(axis=0))\n",
    "print(f\"Voxel size: {voxel_size} mm\")\n",
    "print(\"β†’ Isotropic 1mmΒ³ β€” each voxel represents 1mm Γ— 1mm Γ— 1mm of brain tissue\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "043bd59d",
   "metadata": {},
   "source": [
    "---\n",
    "## Stage 2 β€” Z-Score Normalization\n",
    "\n",
    "### What & Why\n",
    "\n",
    "MRI intensity values are **scanner-dependent** β€” they have no universal physical meaning.  \n",
    "A voxel value of 400 in one patient's T1 is not comparable to 400 in another patient's T1,  \n",
    "even on the same scanner.\n",
    "\n",
    "**Why not min-max normalization?**  \n",
    "MRI volumes often contain bright artifact voxels (motion, metal implants) that would  \n",
    "compress the entire meaningful intensity range into a tiny interval.\n",
    "\n",
    "**The solution: Z-score normalization restricted to brain voxels**\n",
    "\n",
    "$$z = \\frac{x - \\mu_{brain}}{\\sigma_{brain}}$$\n",
    "\n",
    "Where $\\mu_{brain}$ and $\\sigma_{brain}$ are computed only over non-zero (brain) voxels.  \n",
    "Background voxels are left at exactly 0.\n",
    "\n",
    "**Applied independently per modality** β€” never across modalities, never globally."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db65548c",
   "metadata": {},
   "source": [
    "### 2.1 Implementation\n",
    "\n",
    "```\n",
    "CODE                                    β”‚  EXPLANATION\n",
    "────────────────────────────────────────│─────────────────────────────────────────\n",
    "def normalize_modality(vol):            β”‚  Takes one 3D modality volume.\n",
    "                                        β”‚\n",
    "    brain_mask = vol > 0                β”‚  Boolean mask: True = brain tissue.\n",
    "                                        β”‚  Background air is exactly 0 in BraTS.\n",
    "                                        β”‚\n",
    "    if brain_mask.sum() == 0:           β”‚  Edge case: completely empty volume\n",
    "        return vol                      β”‚  (e.g. a corrupted scan). Return as-is,\n",
    "                                        β”‚  do not divide by zero.\n",
    "                                        β”‚\n",
    "    mu  = vol[brain_mask].mean()        β”‚  Mean of brain voxels ONLY.\n",
    "    std = vol[brain_mask].std() + 1e-8  β”‚  Std of brain voxels + epsilon.\n",
    "                                        β”‚  Epsilon (1e-8) prevents div-by-zero\n",
    "                                        β”‚  if a region has constant intensity.\n",
    "                                        β”‚\n",
    "    normalized = np.zeros_like(vol)     β”‚  Start with all zeros β€” background\n",
    "                                        β”‚  stays 0 without any extra masking step.\n",
    "                                        β”‚\n",
    "    normalized[brain_mask] = (          β”‚  Apply z-score to brain voxels only.\n",
    "        vol[brain_mask] - mu) / std     β”‚  Background is untouched (stays 0).\n",
    "                                        β”‚\n",
    "    return normalized                   β”‚  Returns float32 array, same shape.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "99c728a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def normalize_modality(vol: np.ndarray) -> np.ndarray:\n",
    "    \"\"\"\n",
    "    Z-score normalization restricted to brain (non-zero) voxels.\n",
    "    Background voxels remain exactly 0.\n",
    "    Returns float32 array of same shape as input.\n",
    "    \"\"\"\n",
    "    brain_mask = vol > 0\n",
    "\n",
    "    if brain_mask.sum() == 0:\n",
    "        return vol\n",
    "\n",
    "    mu  = vol[brain_mask].mean()\n",
    "    std = vol[brain_mask].std() + 1e-8\n",
    "\n",
    "    normalized = np.zeros_like(vol)\n",
    "    normalized[brain_mask] = (vol[brain_mask] - mu) / std\n",
    "    return normalized.astype(np.float32)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c0de8b9",
   "metadata": {},
   "source": [
    "### 2.2 Verification"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "0b472c6c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== BEFORE ===\n",
      "  mean (brain): 417.33\n",
      "  std  (brain): 109.19\n",
      "  background:   0.0000\n",
      "\n",
      "=== AFTER ===\n",
      "  mean (brain): 0.0000   ← should be β‰ˆ 0.0\n",
      "  std  (brain): 1.0000    ← should be β‰ˆ 1.0\n",
      "  background:   0.0000               ← should be exactly 0.0\n",
      "  dtype:        float32                    ← should be float32\n",
      "\n",
      "=== EDGE CASES ===\n",
      "  Empty volume β€” all zeros: True\n",
      "  Empty volume β€” no NaN:    True\n",
      "  Background unchanged:     True\n",
      "\n",
      "=== ALL MODALITIES ===\n",
      "  flair  β†’ mean: +0.0000  std: 1.0000\n",
      "  t1     β†’ mean: -0.0000  std: 1.0000\n",
      "  t1ce   β†’ mean: +0.0000  std: 1.0000\n",
      "  t2     β†’ mean: +0.0000  std: 1.0000\n"
     ]
    }
   ],
   "source": [
    "vol  = nib.load(str(CASE_001 / \"BraTS20_Training_001_t1ce.nii\")).get_fdata().astype(np.float32)\n",
    "norm = normalize_modality(vol)\n",
    "brain_mask = vol > 0\n",
    "\n",
    "print(\"=== BEFORE ===\")\n",
    "print(f\"  mean (brain): {vol[brain_mask].mean():.2f}\")\n",
    "print(f\"  std  (brain): {vol[brain_mask].std():.2f}\")\n",
    "print(f\"  background:   {vol[0,0,0]:.4f}\")\n",
    "\n",
    "print(\"\\n=== AFTER ===\")\n",
    "print(f\"  mean (brain): {norm[brain_mask].mean():.4f}   ← should be β‰ˆ 0.0\")\n",
    "print(f\"  std  (brain): {norm[brain_mask].std():.4f}    ← should be β‰ˆ 1.0\")\n",
    "print(f\"  background:   {norm[0,0,0]:.4f}               ← should be exactly 0.0\")\n",
    "print(f\"  dtype:        {norm.dtype}                    ← should be float32\")\n",
    "\n",
    "print(\"\\n=== EDGE CASES ===\")\n",
    "empty  = np.zeros((240,240,155), dtype=np.float32)\n",
    "result = normalize_modality(empty)\n",
    "print(f\"  Empty volume β€” all zeros: {(result == 0).all()}\")\n",
    "print(f\"  Empty volume β€” no NaN:    {np.isfinite(result).all()}\")\n",
    "print(f\"  Background unchanged:     {((vol==0) == (norm==0)).all()}\")\n",
    "\n",
    "print(\"\\n=== ALL MODALITIES ===\")\n",
    "for mod in MODALITIES:\n",
    "    v = nib.load(str(CASE_001 / f\"BraTS20_Training_001_{mod}.nii\")).get_fdata().astype(np.float32)\n",
    "    n = normalize_modality(v)\n",
    "    b = v > 0\n",
    "    print(f\"  {mod:6s} β†’ mean: {n[b].mean():+.4f}  std: {n[b].std():.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa3d4a27",
   "metadata": {},
   "source": [
    "---\n",
    "## Stage 3 β€” Bounding Box Crop + Resize\n",
    "\n",
    "### What & Why\n",
    "\n",
    "After normalization the volume is still `(240, 240, 155)` β€” but 85% is background zeros.  \n",
    "Feeding this to a 3D U-Net wastes GPU memory on empty space.\n",
    "\n",
    "**Two-step spatial reduction:**\n",
    "1. **Crop** β€” find the smallest box enclosing all non-zero voxels, discard the rest\n",
    "2. **Resize** β€” interpolate the cropped volume to a fixed `(128, 128, 128)` shape\n",
    "\n",
    "Why `128Β³`? It is the largest cube that fits in ~10GB VRAM with batch size 1  \n",
    "using a standard 3D U-Net with 32 base filters. It is the de facto BraTS standard."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43ed8cf3",
   "metadata": {},
   "source": [
    "### 3.1 Crop to Brain Bounding Box\n",
    "\n",
    "```\n",
    "CODE                                    β”‚  EXPLANATION\n",
    "────────────────────────────────────────│─────────────────────────────────────────\n",
    "def crop_to_brain(vol):                 β”‚  Takes a 3D numpy array.\n",
    "                                        β”‚\n",
    "    coords = np.array(                  β”‚  np.where(vol > 0) returns a tuple of\n",
    "        np.where(vol > 0))              β”‚  3 arrays: (x_idxs, y_idxs, z_idxs)\n",
    "                                        β”‚  for every non-zero voxel.\n",
    "                                        β”‚  np.array(...) stacks them β†’ shape (3, N)\n",
    "                                        β”‚\n",
    "    if coords.shape[1] == 0:            β”‚  Edge case: empty volume.\n",
    "        return vol                      β”‚\n",
    "                                        β”‚\n",
    "    mins = coords.min(axis=1)           β”‚  Minimum index along each axis.\n",
    "                                        β”‚  shape (3,) β†’ [x_min, y_min, z_min]\n",
    "                                        β”‚\n",
    "    maxs = coords.max(axis=1) + 1       β”‚  Maximum index + 1.\n",
    "                                        β”‚  +1 because Python slicing is exclusive\n",
    "                                        β”‚  at the end: vol[0:228] gives indices\n",
    "                                        β”‚  0..227, so last brain voxel at 227\n",
    "                                        β”‚  requires stop index 228.\n",
    "                                        β”‚\n",
    "    return vol[mins[0]:maxs[0],         β”‚  Slice all three axes simultaneously.\n",
    "               mins[1]:maxs[1],         β”‚  Returns a VIEW β€” no data is copied\n",
    "               mins[2]:maxs[2]]         β”‚  until you modify it.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "e678433b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def crop_to_brain(vol: np.ndarray) -> np.ndarray:\n",
    "    \"\"\"\n",
    "    Crop vol to the tight bounding box of non-zero voxels.\n",
    "    If the volume is entirely zero, return it unchanged.\n",
    "    \"\"\"\n",
    "    coords = np.array(np.where(vol > 0))\n",
    "\n",
    "    if coords.shape[1] == 0:\n",
    "        return vol\n",
    "\n",
    "    mins = coords.min(axis=1)\n",
    "    maxs = coords.max(axis=1) + 1\n",
    "\n",
    "    return vol[mins[0]:maxs[0],\n",
    "               mins[1]:maxs[1],\n",
    "               mins[2]:maxs[2]]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "effdef0f",
   "metadata": {},
   "source": [
    "### 3.2 Resize to Target Shape\n",
    "\n",
    "```\n",
    "CODE                                    β”‚  EXPLANATION\n",
    "────────────────────────────────────────│─────────────────────────────────────────\n",
    "def resize_volume(vol, target=          β”‚  Default target is 128Β³.\n",
    "        (128,128,128)):                 β”‚\n",
    "                                        β”‚\n",
    "    tensor = torch.from_numpy(vol)      β”‚  numpy β†’ torch tensor\n",
    "        .float()                        β”‚  Ensure float32\n",
    "        .unsqueeze(0)                   β”‚  Add batch dim:   (H,W,D) β†’ (1,H,W,D)\n",
    "        .unsqueeze(0)                   β”‚  Add channel dim: (1,H,W,D) β†’ (1,1,H,W,D)\n",
    "                                        β”‚  F.interpolate requires (B,C,H,W,D)\n",
    "                                        β”‚\n",
    "    resized = F.interpolate(            β”‚\n",
    "        tensor,                         β”‚\n",
    "        size=target,                    β”‚  Target spatial shape (128,128,128)\n",
    "        mode=\"trilinear\",               β”‚  3D equivalent of bilinear for images.\n",
    "                                        β”‚  Smoothly interpolates between voxels.\n",
    "                                        β”‚  (nearest-neighbor creates blocky edges)\n",
    "        align_corners=True              β”‚  Corner voxels of input map exactly to\n",
    "    )                                   β”‚  corner voxels of output.\n",
    "                                        β”‚  Use True for medical data β€” ensures\n",
    "                                        β”‚  image and mask stay aligned when resized\n",
    "                                        β”‚  separately.\n",
    "                                        β”‚\n",
    "    return resized.squeeze().numpy()    β”‚  Remove batch+channel dims, back to numpy\n",
    "                                        β”‚  (1,1,128,128,128) β†’ (128,128,128)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "9eecc011",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn.functional as F\n",
    "\n",
    "def resize_volume(vol: np.ndarray, target=(128, 128, 128)) -> np.ndarray:\n",
    "    \"\"\"\n",
    "    Resize a 3D volume to target shape using trilinear interpolation.\n",
    "    align_corners=True ensures image and mask stay aligned when resized separately.\n",
    "    \"\"\"\n",
    "    tensor = torch.from_numpy(vol).float().unsqueeze(0).unsqueeze(0)\n",
    "\n",
    "    resized = F.interpolate(\n",
    "        tensor,\n",
    "        size=target,\n",
    "        mode=\"trilinear\",\n",
    "        align_corners=True\n",
    "    )\n",
    "\n",
    "    return resized.squeeze().numpy()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46e24f22",
   "metadata": {},
   "source": [
    "### 3.3 Verification"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c1c0211d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=== CROP ===\n",
      "  Before: (240, 240, 155)\n",
      "  After:  (136, 171, 132)   ← smaller than (240,240,155)\n",
      "  Brain signal preserved: True\n",
      "\n",
      "=== RESIZE ===\n",
      "  Shape: (128, 128, 128)   ← should be (128, 128, 128)\n",
      "  dtype: float32   ← should be float32\n",
      "\n",
      "=== FULL PIPELINE β€” ALL 4 MODALITIES ===\n",
      "  (normalize β†’ crop β†’ resize)\n",
      "  flair  β†’ (128, 128, 128)  mean=+0.932\n",
      "  t1     β†’ (128, 128, 128)  mean=+0.747\n",
      "  t1ce   β†’ (128, 128, 128)  mean=+0.659\n",
      "  t2     β†’ (128, 128, 128)  mean=+0.993\n",
      "\n",
      "  βœ… All modalities: (128, 128, 128) β€” ready for model input\n"
     ]
    }
   ],
   "source": [
    "vol  = nib.load(str(CASE_001 / \"BraTS20_Training_001_t1ce.nii\")).get_fdata().astype(np.float32)\n",
    "norm = normalize_modality(vol)\n",
    "\n",
    "print(\"=== CROP ===\")\n",
    "cropped = crop_to_brain(norm)\n",
    "print(f\"  Before: {norm.shape}\")\n",
    "print(f\"  After:  {cropped.shape}   ← smaller than (240,240,155)\")\n",
    "print(f\"  Brain signal preserved: {(cropped > 0).any()}\")\n",
    "\n",
    "print(\"\\n=== RESIZE ===\")\n",
    "resized = resize_volume(cropped, target=(128, 128, 128))\n",
    "print(f\"  Shape: {resized.shape}   ← should be (128, 128, 128)\")\n",
    "print(f\"  dtype: {resized.dtype}   ← should be float32\")\n",
    "\n",
    "print(\"\\n=== FULL PIPELINE β€” ALL 4 MODALITIES ===\")\n",
    "print(\"  (normalize β†’ crop β†’ resize)\")\n",
    "for mod in MODALITIES:\n",
    "    v = nib.load(str(CASE_001 / f\"BraTS20_Training_001_{mod}.nii\")).get_fdata().astype(np.float32)\n",
    "    processed = resize_volume(crop_to_brain(normalize_modality(v)))\n",
    "    print(f\"  {mod:6s} β†’ {processed.shape}  mean={processed[processed>0].mean():+.3f}\")\n",
    "print(\"\\n  βœ… All modalities: (128, 128, 128) β€” ready for model input\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0787a97b",
   "metadata": {},
   "source": [
    "### 3.4 What the Pipeline Does to One Voxel\n",
    "\n",
    "```\n",
    "Raw T1ce voxel at brain center:   417.3  (scanner units, meaningless across patients)\n",
    "After normalize_modality:           0.0  (mean of brain = 0, std = 1)\n",
    "After crop_to_brain:                0.0  (same value, just in smaller array)\n",
    "After resize_volume:               ~0.0  (trilinear blend of neighbors, close to 0)\n",
    "```\n",
    "\n",
    "```\n",
    "Raw T1ce bright tumor voxel:     1845.0\n",
    "After normalize_modality:          12.9  (13 standard deviations above brain mean)\n",
    "After crop_to_brain:               12.9\n",
    "After resize_volume:              ~12.0  (slightly smoothed by interpolation)\n",
    "```\n",
    "\n",
    "The tumor voxel remains a strong outlier even after normalization.  \n",
    "That outlier signal is exactly what the model learns to detect."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}