.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples\00_full_pipeline\plot_01_full_pipeline.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_00_full_pipeline_plot_01_full_pipeline.py: A complete habitat analysis =========================== **Background.** A tumour is not uniform: some parts enhance strongly, some wash out, some are necrotic. Habitat analysis splits the ROI into a few sub-regions (habitats) whose voxels behave alike across the DCE phases, using one definition shared by every patient, and then describes each patient by how much of each habitat they have and how the habitats are arranged. **Purpose.** You will fit habitats on two demo patients, pick the number of habitats with the elbow rule, view the habitat maps, get a one-row-per-patient feature table (volume fractions, MSI, ITH, graph), save the model as a ``.habitatmodel`` file, and label a third patient with it. **Key terms.** Each term has its own page later in the Guide; the beginner definitions are on :doc:`/auto_quickstart/plot_quickstart_python`. * **supervoxel** -- a small patch of similar neighbouring voxels, clustered inside each patient first so the cohort model has fewer, less noisy rows. * **pool / fit / assign** -- stack all patients' supervoxels, learn the habitat centroids once, then give every voxel the id of its nearest centroid. * **MSI** -- how often each pair of habitats touch; **ITH score** -- how fragmented the habitats are (0 = one blob each). * **.habitatmodel** -- the saved habitat definition; loading it labels new patients without refitting. One :class:`~habit.spec.HabitatSpec` declares the whole study. One ``fit_predict`` runs it. The stage list below is the same two-step analysis as :doc:`/auto_quickstart/plot_quickstart_python`: raw DCE intensities, 30 supervoxels, one shared model, then volume, MSI, ITH and graph features. Later Guide pages change one stage, or drop ``partition`` / ``pool``. They are not a second analysis. Change ``DATA`` / ``MODALITIES`` / ``ROI`` to your preprocessed tree. .. GENERATED FROM PYTHON SOURCE LINES 44-50 Load the cohort --------------- Two subjects define the habitats. The third is a new patient at the end of the page. The official demo pack is cached after the first download. sphinx_gallery_thumbnail_number = 3 .. GENERATED FROM PYTHON SOURCE LINES 50-90 .. code-block:: Python from pathlib import Path import matplotlib.pyplot as plt from habit.contracts import HabitatModel, cohort_from_directory from habit.datasets import fetch_demo from habit.kernels import habitat_ith_dispersion, ith_score, spatial_interaction_matrix from habit.recipes import Study from habit.spec import HabitatSpec, Spec, Stage from habit.viz import ( plot_cluster_validation_from_report, plot_habitat_graph_slice, plot_habitat_overlay, plot_habitat_volume_fractions, plot_intensity_slice, plot_ith_summary, plot_msi_matrix, plot_partition_triptych, ) # Change DATA / MODALITIES / ROI to your preprocessed layout. DATA = fetch_demo() MODALITIES = ("pre_contrast", "LAP", "PVP", "delay_3min") ROI = "LAP" cohort = cohort_from_directory(DATA, modalities=MODALITIES, roi=ROI) train, new_patient = cohort[:2], cohort[2:3] print(cohort) subject = train[0] Path("out").mkdir(exist_ok=True) fig = plot_intensity_slice( subject.image("LAP"), roi_mask=subject.mask(ROI), roi_contour=True, image_label="LAP", title=f"{subject.subject_id}: arterial phase and ROI", ) fig.savefig("out/full_pipeline_input.png", dpi=150, bbox_inches="tight") plt.show() .. image-sg:: /auto_examples/00_full_pipeline/images/sphx_glr_plot_01_full_pipeline_001.png :alt: subj001: arterial phase and ROI, LAP :srcset: /auto_examples/00_full_pipeline/images/sphx_glr_plot_01_full_pipeline_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none HABIT demo data (cached) DATA (preprocessed root): C:\Users\dongm\.habit_data\demo-data-v1\preprocessed On-disk inventory of this folder: subjects (5): subj001, subj002, subj003, subj004, subj005 image series: LAP, PVP, delay_3min, pre_contrast mask keys: LAP, PVP, delay_3min, pre_contrast example image: images/subj001/delay_3min/WATER__BH_Ax_LAVA_Flex_3min_Series0012.nrrd example mask: masks/subj001/delay_3min/WATER__BH_Ax_LAVA_Flex_10min_Series0017_mask.nrrd Your own data must use the same folder tree (change IDs / series names): DATA/ images/// masks/// Then load it with the same call the demos use: cohort = cohort_from_directory(DATA, modalities=("LAP",), roi="LAP") Swap DATA / modalities / roi to match your tree. Mask key is often the same as one image series (here LAP). Cohort(5 subjects [subj001, subj002, subj003, subj004, subj005]) F:\work\habit_project\habit\viz\intensity.py:616: UserWarning: Display geometry conflict: image/anatomy direction does not match mask/label direction. Using the mask/label direction so coronal/sagittal superior-up follows the labelled anatomy. Pass direction= to override. resolved_direction, resolved_spacing = resolve_display_geometry( .. GENERATED FROM PYTHON SOURCE LINES 91-102 Declare every stage ------------------- ``Stage``'s first argument is a label you choose. ``Spec`` names a registered component and its parameters. ``random_seed`` seeds every stochastic stage (partition and fit), so a rerun paints the same map. ``two_step_habitat(...)`` builds this list for you. Drop ``pool`` and each subject is clustered alone (one-step). Drop ``partition`` and voxels are clustered directly (direct pooling). Those two designs are :doc:`/auto_examples/04_designs/plot_02_inside_each_subject` and :doc:`/auto_examples/04_designs/plot_03_pool_voxels`. .. GENERATED FROM PYTHON SOURCE LINES 102-142 .. code-block:: Python spec = HabitatSpec( name="full_pipeline_two_step", stages=( # extract: one intensity column per DCE phase, voxels inside the ROI. Stage("extract", Spec("raw", {"modalities": list(MODALITIES), "roi": ROI})), # partition: 30 supervoxels per tumour. These rows, not voxels, # are what the shared model clusters. Stage("partition", Spec("kmeans", {"n_supervoxels": 30})), # pool: stack every training subject's supervoxels into one matrix. Stage("pool", Spec("pool")), # fit: one k-means for the cohort. Try 2..10 habitats, keep the elbow. # n_init=10 restarts each candidate count. Stage( "fit", Spec( "kmeans", { "min_habitats": 2, "max_habitats": 10, "validation": "elbow", "n_init": 10, }, ), ), # assign: nearest centroid paints a habitat id onto every supervoxel, # then onto the voxels that belong to it. Stage("assign", Spec("nearest_centroid")), # quantify: one row per subject. The Spec name is the feature family. Stage("volume", Spec("volume")), Stage("msi", Spec("msi")), Stage("ith", Spec("ith_score")), # graph: 8-voxel cubes, habitat-labelled nodes. Extended metrics off # so the table stays the short default set. Stage("graph", Spec("graph", {"include_extended_metrics": False})), ), random_seed=0, ) result = Study(spec).fit_predict(train) print(result.habitat_model.summary()) .. rst-class:: sphx-glr-script-out .. code-block:: none Cohort.map[_ComputeUnits]: 0%| | 0/2 [00:00` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_01_full_pipeline.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_01_full_pipeline.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_