# Sulcora Planner

Research desktop application for **neurosurgical trajectory planning** on real MRI.
Loads NIfTI / DICOM, shows the standard axial / coronal / sagittal multiplanar
views plus a 3-D reconstruction, and lets you place a target and entry point and
plan a straight-line stereotactic trajectory with live geometric metrics
(depth, approach angle, and clearance to labelled critical structures).

> ⚠️ **Research software only. Not a medical device. Not for clinical, diagnostic,
> or treatment use.** See `docs/INTENDED_USE.md`. This is the engineering
> foundation for a planned clinical product; the validation and regulatory work
> required before any clinical use is described in `docs/VALIDATION_PLAN.md`.

![MPR with trajectory](docs/images/mpr_trajectory.png)
![Structure-aware risk](docs/images/risk_overlay.png)
![Real-time deformation](docs/images/deformation_field.png)
![Deformation-aware risk](docs/images/deformation_aware_risk.png)
![White-matter tract avoidance](docs/images/tract_avoidance.png)
![Robotics-validation environment](docs/images/robotics_validation.png)
![3D reconstruction](docs/images/surface_trajectory.png)

*(Figures above are real output, generated by `scripts/make_sample_and_proof.py`
and `scripts/make_risk_proof.py` on the open MNI152 reference MRI with the real
Harvard-Oxford anatomical atlas.)*

## What works today

- **Validation, interop & tract avoidance (v1.6)** — evidence and adoption:
  `sulcora.validate` (Dice, Jaccard, Hausdorff-95, ASSD, volume error, trajectory
  entry/target/angle error + dataset `summarize`); `sulcora.interop` (export the
  plan to **3D Slicer FCSV**, JSON, and a **DICOM RT Structure Set** for
  Brainlab/StealthStation); `sulcora.tracts` (rasterize **DTI streamlines** into a
  risk structure for white-matter tract avoidance); a **learned-model adapter**
  (`seg_backends.use_totalsegmentator`) on the pluggable backend; and a
  **PyInstaller** build (`packaging/`) for a double-click desktop app. See
  `scripts/make_validation_proof.py`.
- **Surgical-procedure modules (v1.5)** — a procedures registry
  (`sulcora.procedures`) unifying the toolkit across cranial procedures: ICH
  evacuation, DBS, **multi-electrode SEEG** (conflict-aware, `session.plan_multi`),
  biopsy, LITT, lesion access, and **ventricular catheter / EVD / shunt** (segment
  ventricles → frontal-horn target → catheter, `sulcora.ventricle`). Plus
  **glioma / glioblastoma resection** — two-compartment (enhancing + FLAIR)
  segmentation and **extent-of-resection volumetrics with RANO resect grading**
  (`sulcora.tumor`). See `scripts/make_gbm_proof.py`.
- **Full CT support (v1.4)** — modality-aware loading (Hounsfield Units from
  DICOM, `Modality` tag captured), clinical **window presets** (brain / blood /
  bone / stroke), and HU-threshold **tissue segmentation** — skull, brain
  extraction, CSF/ventricles, and acute clot (`sulcora.ct`). Head CT is the
  primary modality for haemorrhage, trauma, and hydrocephalus; the GUI
  auto-detects CT and defaults to a brain window. See `scripts/make_ct_proof.py`.
- **ICH evacuation planning (v1.3)** — segment an acute clot from non-contrast
  **CT** (hyperdensity window + largest connected component), find its long axis
  (PCA), and plan the corridor that **maximises clot traversal** while clearing
  vessels and eloquent cortex — optionally deformation-aware (`sulcora.hematoma`).
  Ranking by traversal (not just hitting the centroid) mirrors published ICH
  planners; the minimally invasive corridor approach is RCT-supported (ENRICH,
  NEJM 2024). See `scripts/make_ich_proof.py`.
- **Lesion procedures beyond DBS/SEEG (v1.2)** — target any segmented lesion by
  its centroid (volume in cc) for the safest corridor — biopsy, catheter/laser
  placement, or a generic haematoma target (`session.plan_to_lesion`).
- **Rich OR plan report (v1.2)** — an exported multi-page PDF: per trajectory,
  tri-planar + in-line/probe's-eye reformats, a **clearance-vs-depth profile**,
  full geometry (entry/target mm + voxel, depth, approach angle), and a
  **per-structure clearance table** (static and deformation-aware). Manual
  numeric target/entry entry (frame/atlas RAS mm) is supported in the GUI.
- **Automatic trajectory optimizer (v1.0)** — name a deep target and Sulcora
  searches candidate entry corridors and ranks them by clearance to *every*
  critical structure at once (vessels, eloquent cortex, deep nuclei, tracts) —
  optionally against the **predicted deformed** anatomy — returning the
  recommended safest corridor and ranked alternatives, subject to hard
  constraints (per-structure margin, max approach angle, max depth). This is the
  "name a target → safest path" engine; `scripts/make_optimizer_proof.py` shows
  it beating a naive straight-down approach.
- **Proximity heatmap** — shade a critical structure grey→red by its per-voxel
  clearance to the trajectory (`session.clearance_field`), so the danger *along*
  a structure is visible, not just a single number. See
  `scripts/make_clearance_color_proof.py`.
- **Probe-aligned reformation (v1.1)** — reformat the volume along any plane:
  the **in-line view** (the plane containing the whole entry→target path) and the
  **probe's-eye view** (the cross-section the advancing tip faces) — the views
  surgeons actually plan trajectories in, beyond the axis-aligned MPR
  (`sulcora.reslice`). See `scripts/make_probeseye_proof.py`.
- **Real image IO** — NIfTI (`.nii/.nii.gz`) and DICOM series, into a `Volume`
  with a correct voxel→world (mm) affine.
- **Tested geometry core** — world↔voxel transforms, MPR slicing, trajectory
  length / approach angle, and clearance-to-structure metrics (unit-tested).
- **Structure-aware risk (v0.2)** — loads the real Harvard-Oxford anatomical
  atlas, identifies eloquent cortex (motor, speech/language, visual), and reports
  the nearest structure, clearance (mm), and a risk band for a planned trajectory.
- **Real-time tissue deformation (v0.3)** — analytical probe-induced displacement
  field (incompressible cavity-expansion model) predicting local tissue shift
  along the trajectory in real time. A first-order approximation for planning
  preview; the validated FEM/AI model is the funded Phase I/II work.
- **Finite-element deformation (v0.9)** — a real linear-elasticity FEM solver
  (`sulcora.fem`, 8-node hexahedral elements solving the Navier-Cauchy equations
  with a displacement-driven cavity and a fixed far field). Drop-in compatible
  with the deformation-aware risk and robotics modules, it replaces the
  closed-form heuristic with an actual elastostatic solve (respecting the Poisson
  effect, domain geometry, and fixed skull boundary). Still a research model
  (homogeneous, isotropic, small-strain) — the stepping stone to the validated
  FEM-trained AI surrogate. See `scripts/make_fem_proof.py`.
- **Deformation-aware risk + deep structures (v0.4)** — risk recomputed against
  the *predicted deformed* anatomy (not only the preoperative scan), plus
  cortical **and** subcortical/deep critical structures (thalamus, hippocampus,
  brainstem, basal ganglia). This static-vs-deformed comparison is the core
  differentiator.
- **Vessel avoidance (v0.9)** — segment cerebral vasculature from an
  angiographic volume (CTA / MR angiography / TOF) with a multiscale **Frangi
  vesselness** filter (no learned weights, no network), and report **clearance
  to the vessel tree** with a KD-tree — static and deformation-aware. Hitting a
  vessel is the dominant SEEG/biopsy risk, so this is the key safety metric;
  `scripts/make_vessel_proof.py` also searches entry corridors for the
  vessel-avoidant path.
- **White-matter tract avoidance (v0.7)** — real fiber tracts from the Juelich
  histological atlas (corticospinal tract, optic radiation, cingulum, fornix)
  scored alongside cortical and deep structures — 30 critical structures total.
- **Robotics-validation environment (v0.5)** — treats the virtual brain as a
  test bench: simulate repeated robotic executions of a planned trajectory with
  realistic placement/angular error, and score targeting accuracy (TRE) and
  deformation-aware safety over many runs. The "for the Development of
  Neurosurgical Robotics" piece of Topic 7.
- **Patient-specific segmentation (v0.8, optional)** — label eloquent cortex,
  ventricles, and deep structures **directly from the patient T1** with a
  pretrained model (TotalSegmentator brain-structures, or FreeSurfer SynthSeg),
  instead of registering a population atlas. Removes the registration step that
  limits atlas-based risk to atlas-space images. Behind the optional `seg`
  extra; `scripts/make_segmentation_proof.py` runs it on the sample scan and
  reports per-structure Dice overlap against the atlas labels. Automated
  segmentations are unverified research output — never for patient care.
- **Desktop GUI** — three MPR viewers + 3-D surface reconstruction with
  **linked-crosshair navigation** (click any view to drive all three), anatomical
  **orientation labels (R/L/A/P/S/I)** derived from the image affine, smooth
  (interpolated) slices, interactive brightness/contrast, a live cursor mm/voxel
  readout, click-to-place target/entry, and an in-slice trajectory overlay. Load
  structures (**Load Atlas** for eloquent + deep, **Load Vessels…** for a CTA/MRA)
  and the panel shows a **live risk readout** — nearest structure, clearance,
  colour-coded band, and the deformation-aware value — while **④ Optimize** runs
  the trajectory optimizer and snaps to the recommended safest corridor with the
  feasible-corridor count.
- **Reproducible proof** — one script fetches a real MRI and renders the figures
  above end-to-end through the package.

## Install

```bash
# 1. clone / unzip, then from the project root:
python -m venv .venv && source .venv/bin/activate     # (Windows: .venv\Scripts\activate)
pip install -e ".[gui,sample,dev]"
```

VTK and PyQt5 ship as binary wheels for Windows, macOS, and Linux, so no
compilation is needed on a normal workstation.

Optional patient-specific segmentation (heavier — pulls in a deep-learning
model; not required for the core planner or the test suite):

```bash
pip install -e ".[seg]"          # TotalSegmentator backend
# The SynthSeg backend instead uses FreeSurfer's `mri_synthseg` command
# (install FreeSurfer separately; no pip dependency).
python scripts/make_segmentation_proof.py   # runs it on the sample scan + compares to the atlas
```

TotalSegmentator's MR brain tasks require a free non-commercial license key
(`totalseg_set_license -l <KEY>`) and are trained on clinical ~1 mm T1 MRI; on
CPU with GPU strongly recommended. On the smooth, downsampled 2 mm MNI152 sample
the model typically returns empty labels — supply a real ~1 mm patient T1 for a
meaningful segmentation. The pipeline, mask/Dice logic, and atlas comparison are
covered by the unit tests independently of any specific scan.

## Run

```bash
# generate the bundled sample MRI + proof figures
python scripts/make_sample_and_proof.py

# (optional) fetch a crisp 1 mm sample — 2 mm slices look blocky
python scripts/make_hires_sample.py

# launch the planner (optionally pass a NIfTI file or a DICOM folder)
sulcora sample_data/mni152_t1_1mm.nii.gz
# or
python -m sulcora.app /path/to/your/scan.nii.gz
```

In the app: **click any view** to navigate (linked crosshair; the cursor mm/voxel
readout updates), **left-drag** to adjust brightness/contrast, then **① Set
Target**, **② Set Entry** (click in any MPR view), then **③ Plan**. Edge labels
show anatomical orientation (R/L/A/P/S/I).

## Test

```bash
pytest -q
```

## Project layout

```
sulcora/
  io.py        NIfTI + DICOM loading -> Volume
  volume.py    Volume: affine, world<->voxel, MPR reslice, trilinear sampling
  planning.py  Trajectory: length, angle, clearance-to-mask, risk band
  vtk_utils.py Volume -> vtkImageData bridge
  app.py       VTK + PyQt5 desktop GUI
tests/         unit tests for the geometry/planning core
scripts/       sample-data + proof-figure generator
docs/          INTENDED_USE, VALIDATION_PLAN, ROADMAP
```

## Roadmap to a clinical product

See `docs/ROADMAP.md` and `docs/VALIDATION_PLAN.md`. In short: add automated
segmentation of eloquent structures and vasculature, the validated soft-tissue
deformation model, accuracy validation (phantom → cadaveric → retrospective
imaging), and the regulatory pathway — the substance of the ARPA-H Phase I/II
effort and the basis for clinical-study discussions with neurosurgical partners.
