|
| 1 | +"""Pseudo-CT validation: compare MRI-derived HU against real CT. |
| 2 | +
|
| 3 | +Validates the chain: T1 MRI → pseudo-CT (HU) → acoustic properties |
| 4 | +using datasets with paired MRI and CT scans. |
| 5 | +
|
| 6 | +Supported datasets: |
| 7 | + - SynthRAD2023: 180 paired T1/CT brain scans |
| 8 | + - BabelBrain: 5 subjects with varying skull density ratios |
| 9 | + - Any paired MRI/CT in NIfTI format |
| 10 | +
|
| 11 | +Usage: |
| 12 | + .venv/bin/python benchmarks/pseudo_ct_validation.py --mri t1.nii.gz --ct ct.nii.gz |
| 13 | +""" |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import argparse |
| 17 | +import logging |
| 18 | +from pathlib import Path |
| 19 | + |
| 20 | +import numpy as np |
| 21 | + |
| 22 | +logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") |
| 23 | +log = logging.getLogger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +def load_nifti(path: str) -> tuple[np.ndarray, np.ndarray]: |
| 27 | + """Load NIfTI volume. Returns (data, affine).""" |
| 28 | + import nibabel as nib |
| 29 | + img = nib.load(path) |
| 30 | + return np.asarray(img.get_fdata(), dtype=np.float32), img.affine |
| 31 | + |
| 32 | + |
| 33 | +def t1_to_pseudo_ct(t1: np.ndarray, method: str = "plymouth") -> np.ndarray: |
| 34 | + """Convert T1w MRI to pseudo-CT Hounsfield units. |
| 35 | +
|
| 36 | + Plymouth method: inverse relationship (dark in T1 = dense bone = high HU). |
| 37 | + """ |
| 38 | + # Normalize T1 to [0, 1] |
| 39 | + t1_norm = (t1 - t1.min()) / (t1.max() - t1.min() + 1e-8) |
| 40 | + |
| 41 | + if method == "plymouth": |
| 42 | + # T1: bone is dark (low signal) → high HU |
| 43 | + hu = 1700.0 * (1.0 - t1_norm) + 300.0 |
| 44 | + elif method == "linear": |
| 45 | + # Simple linear: higher T1 → lower HU (bone is dark in T1) |
| 46 | + hu = 2000.0 * (1.0 - t1_norm) |
| 47 | + else: |
| 48 | + raise ValueError(f"Unknown method: {method}") |
| 49 | + |
| 50 | + return hu |
| 51 | + |
| 52 | + |
| 53 | +def compute_skull_mask(ct: np.ndarray, hu_min: float = 300, hu_max: float = 3000) -> np.ndarray: |
| 54 | + """Extract skull mask from CT using HU thresholds.""" |
| 55 | + return (ct >= hu_min) & (ct <= hu_max) |
| 56 | + |
| 57 | + |
| 58 | +def hu_to_acoustic_properties(hu: np.ndarray) -> dict[str, np.ndarray]: |
| 59 | + """Convert HU to acoustic properties using empirical relationships. |
| 60 | +
|
| 61 | + References: |
| 62 | + - Schneider et al. (2000): HU → density |
| 63 | + - Mast (2000): density → sound speed, attenuation |
| 64 | + - Connor et al. (2002): combined relationships |
| 65 | + """ |
| 66 | + # Schneider: density from HU |
| 67 | + # rho = 1.0 + 0.000790 * HU (for HU > 0, soft tissue/bone) |
| 68 | + rho = np.where(hu > 0, |
| 69 | + 1000.0 * (1.0 + 0.000790 * hu), |
| 70 | + 1000.0) # kg/m³ |
| 71 | + |
| 72 | + # Mast: sound speed from density (simplified) |
| 73 | + # c = 1500 + 2.5 * (rho - 1000) for soft tissue |
| 74 | + # c = 1500 + 3.7 * (rho - 1000) for bone |
| 75 | + bone_mask = hu > 300 |
| 76 | + c = np.where(bone_mask, |
| 77 | + 1500.0 + 3.7 * (rho - 1000.0), |
| 78 | + 1500.0 + 2.5 * (rho - 1000.0)) |
| 79 | + c = np.clip(c, 1400, 4500) |
| 80 | + |
| 81 | + # Attenuation: roughly proportional to density deviation |
| 82 | + alpha = np.where(bone_mask, |
| 83 | + 4.0 * (rho - 1000.0) / 900.0, # scale to ~4 dB/cm for cortical |
| 84 | + 0.3 * (rho - 1000.0) / 40.0) # scale to ~0.3 for brain |
| 85 | + alpha = np.clip(alpha, 0.0, 10.0) |
| 86 | + |
| 87 | + return {"sound_speed": c, "density": rho, "attenuation": alpha} |
| 88 | + |
| 89 | + |
| 90 | +def compute_validation_metrics( |
| 91 | + pseudo_hu: np.ndarray, |
| 92 | + real_hu: np.ndarray, |
| 93 | + skull_mask: np.ndarray | None = None, |
| 94 | +) -> dict: |
| 95 | + """Compare pseudo-CT against real CT. |
| 96 | +
|
| 97 | + Args: |
| 98 | + pseudo_hu: Predicted HU from MRI |
| 99 | + real_hu: Ground-truth HU from CT |
| 100 | + skull_mask: Optional mask to restrict comparison to skull region |
| 101 | +
|
| 102 | + Returns: |
| 103 | + Dict of metrics: MAE, RMSE, correlation, Dice for bone segmentation |
| 104 | + """ |
| 105 | + if skull_mask is not None: |
| 106 | + p = pseudo_hu[skull_mask] |
| 107 | + r = real_hu[skull_mask] |
| 108 | + else: |
| 109 | + # Use all non-zero voxels |
| 110 | + mask = (real_hu > -500) & (pseudo_hu > -500) |
| 111 | + p = pseudo_hu[mask] |
| 112 | + r = real_hu[mask] |
| 113 | + |
| 114 | + if len(p) == 0 or len(r) == 0: |
| 115 | + return {"error": "No valid voxels for comparison"} |
| 116 | + |
| 117 | + mae = float(np.mean(np.abs(p - r))) |
| 118 | + rmse = float(np.sqrt(np.mean((p - r) ** 2))) |
| 119 | + corr = float(np.corrcoef(p.ravel(), r.ravel())[0, 1]) if len(p) > 1 else 0.0 |
| 120 | + |
| 121 | + # Dice coefficient for bone segmentation (HU > 300) |
| 122 | + pred_bone = pseudo_hu > 300 |
| 123 | + real_bone = real_hu > 300 |
| 124 | + intersection = np.sum(pred_bone & real_bone) |
| 125 | + dice = 2 * intersection / (np.sum(pred_bone) + np.sum(real_bone) + 1e-8) |
| 126 | + |
| 127 | + # Acoustic property error in skull region |
| 128 | + skull = real_hu > 300 |
| 129 | + if skull.any(): |
| 130 | + pred_props = hu_to_acoustic_properties(pseudo_hu[skull]) |
| 131 | + real_props = hu_to_acoustic_properties(real_hu[skull]) |
| 132 | + c_error = float(np.mean(np.abs(pred_props["sound_speed"] - real_props["sound_speed"]))) |
| 133 | + rho_error = float(np.mean(np.abs(pred_props["density"] - real_props["density"]))) |
| 134 | + else: |
| 135 | + c_error = rho_error = 0.0 |
| 136 | + |
| 137 | + return { |
| 138 | + "mae_hu": mae, |
| 139 | + "rmse_hu": rmse, |
| 140 | + "correlation": corr, |
| 141 | + "dice_bone": float(dice), |
| 142 | + "n_voxels": int(len(p)), |
| 143 | + "c_mae_ms": c_error, |
| 144 | + "rho_mae_kgm3": rho_error, |
| 145 | + } |
| 146 | + |
| 147 | + |
| 148 | +def run_validation(mri_path: str, ct_path: str, method: str = "plymouth", |
| 149 | + save_png: str | None = None) -> dict: |
| 150 | + """Full validation pipeline: load MRI/CT, predict pseudo-CT, compare.""" |
| 151 | + log.info("Loading MRI: %s", mri_path) |
| 152 | + mri, _ = load_nifti(mri_path) |
| 153 | + log.info("Loading CT: %s", ct_path) |
| 154 | + ct, _ = load_nifti(ct_path) |
| 155 | + |
| 156 | + if mri.shape != ct.shape: |
| 157 | + log.warning("Shape mismatch: MRI=%s, CT=%s — resampling needed", mri.shape, ct.shape) |
| 158 | + |
| 159 | + log.info("Computing pseudo-CT (method=%s)...", method) |
| 160 | + pseudo = t1_to_pseudo_ct(mri, method=method) |
| 161 | + |
| 162 | + log.info("Computing validation metrics...") |
| 163 | + metrics = compute_validation_metrics(pseudo, ct) |
| 164 | + |
| 165 | + log.info("Results:") |
| 166 | + for k, v in metrics.items(): |
| 167 | + log.info(" %s: %s", k, v) |
| 168 | + |
| 169 | + if save_png: |
| 170 | + _plot_comparison(mri, ct, pseudo, metrics, save_png) |
| 171 | + |
| 172 | + return metrics |
| 173 | + |
| 174 | + |
| 175 | +def _plot_comparison(mri, ct, pseudo, metrics, save_png): |
| 176 | + import matplotlib |
| 177 | + matplotlib.use("Agg") |
| 178 | + import matplotlib.pyplot as plt |
| 179 | + |
| 180 | + mid = mri.shape[2] // 2 |
| 181 | + fig, axes = plt.subplots(1, 4, figsize=(16, 4)) |
| 182 | + |
| 183 | + ax = axes[0] |
| 184 | + ax.imshow(mri[:, :, mid].T, origin="lower", cmap="gray") |
| 185 | + ax.set_title("T1 MRI") |
| 186 | + |
| 187 | + ax = axes[1] |
| 188 | + im = ax.imshow(ct[:, :, mid].T, origin="lower", cmap="bone", vmin=-200, vmax=2000) |
| 189 | + ax.set_title("Real CT (HU)") |
| 190 | + fig.colorbar(im, ax=ax, shrink=0.8) |
| 191 | + |
| 192 | + ax = axes[2] |
| 193 | + im = ax.imshow(pseudo[:, :, mid].T, origin="lower", cmap="bone", vmin=-200, vmax=2000) |
| 194 | + ax.set_title("Pseudo-CT (HU)") |
| 195 | + fig.colorbar(im, ax=ax, shrink=0.8) |
| 196 | + |
| 197 | + ax = axes[3] |
| 198 | + diff = pseudo[:, :, mid] - ct[:, :, mid] |
| 199 | + im = ax.imshow(diff.T, origin="lower", cmap="RdBu_r", vmin=-500, vmax=500) |
| 200 | + ax.set_title(f"Difference (MAE={metrics['mae_hu']:.0f} HU)") |
| 201 | + fig.colorbar(im, ax=ax, shrink=0.8) |
| 202 | + |
| 203 | + fig.suptitle(f"Pseudo-CT Validation (Dice={metrics['dice_bone']:.3f}, r={metrics['correlation']:.3f})") |
| 204 | + fig.tight_layout() |
| 205 | + fig.savefig(save_png, dpi=150) |
| 206 | + log.info("Saved %s", save_png) |
| 207 | + |
| 208 | + |
| 209 | +if __name__ == "__main__": |
| 210 | + parser = argparse.ArgumentParser() |
| 211 | + parser.add_argument("--mri", required=True, help="Path to T1 MRI NIfTI") |
| 212 | + parser.add_argument("--ct", required=True, help="Path to CT NIfTI") |
| 213 | + parser.add_argument("--method", default="plymouth", choices=["plymouth", "linear"]) |
| 214 | + parser.add_argument("--save-png", default=None) |
| 215 | + args = parser.parse_args() |
| 216 | + run_validation(args.mri, args.ct, args.method, args.save_png) |
0 commit comments