.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_quickstart\plot_quickstart_python.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_quickstart_plot_quickstart_python.py: Quickstart: Python API ====================== **Background.** Habitat analysis splits a tumour into sub-regions that behave alike across the input images (here, DCE phases), then describes each tumour by how much of each sub-region it has and how they are arranged. **Purpose.** You get your first habitat maps, a per-subject feature table (volume fractions, MSI, ITH, graph), and a saved model that labels a new patient without refitting. **Key terms.** * **habitat** -- a sub-region inside the tumour (the ROI) whose voxels behave alike across the input images; HABIT paints each ROI voxel with a habitat id (1, 2, 3, ...). * **ROI / mask** -- the region of interest, usually the whole tumour, stored as an integer mask; only voxels inside it are analysed (0 = background). * **voxel feature** -- the numbers that describe one voxel (here its intensity in each DCE phase); one column per feature. * **supervoxel** -- a small patch of neighbouring voxels with similar features, clustered inside one subject first (``partition``), so the cohort model clusters tens of rows per subject instead of every voxel. * **pool** -- stacks every training subject's rows into one matrix so one model is fitted to the whole cohort and habitat ids mean the same thing in every patient. * **fit** -- learns the habitat definition (for k-means: the number of habitats and their centroids). * **assign** -- gives every supervoxel / voxel the id of its nearest centroid, producing the habitat map. * **Stage / Spec / HabitatSpec** -- a ``Stage`` is one step with a label you choose; a ``Spec`` names a registered component and its parameters; a ``HabitatSpec`` is the ordered list of stages plus ``random_seed``, i.e. the whole study definition. * **elbow** -- a rule for picking the number of habitats: the candidate count after which adding one more habitat stops reducing within-cluster spread much. A short list of stages declares the analysis; one call fits it on a cohort. Everything after that is looking at the result: the habitat map, the per-habitat features a paper would report, and reusing the fitted model on a new patient. No YAML. Install first (:doc:`/tutorial/installation`). This page uses the official demo pack (five liver lesions, four DCE phases). Change ``DATA`` / ``MODALITIES`` / ``ROI`` to your own preprocessed tree. .. GENERATED FROM PYTHON SOURCE LINES 51-56 Load the images --------------- Four subjects define the habitats; the fifth plays a new patient later. The downloaded pack is cached after the first run. sphinx_gallery_thumbnail_number = 4 .. GENERATED FROM PYTHON SOURCE LINES 56-97 .. code-block:: Python from pathlib import Path import matplotlib.pyplot as plt import numpy as np 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, two_step_habitat 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[:4], cohort[4:] 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/quickstart_input.png", dpi=150, bbox_inches="tight") plt.show() .. image-sg:: /auto_quickstart/images/sphx_glr_plot_quickstart_python_001.png :alt: subj001: arterial phase and ROI, LAP :srcset: /auto_quickstart/images/sphx_glr_plot_quickstart_python_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 98-107 Build the analysis step by step ------------------------------- A habitat analysis is a list of stages. This is the two-step design: each tumour is split into 30 supervoxels (``partition``), the supervoxels of all subjects are put together (``pool``) and clustered once (``fit``), so habitat 2 means the same enhancement pattern in every patient. Drop ``pool`` and every subject is clustered on its own (one-step); drop ``partition`` and voxels are clustered directly (direct pooling). The fitter tries 2 to 10 habitats and keeps the elbow. .. GENERATED FROM PYTHON SOURCE LINES 107-134 .. code-block:: Python spec = HabitatSpec( name="quickstart_two_step", stages=( # extract: one intensity column per DCE phase, inside the ROI. Stage("extract", Spec("raw", {"modalities": list(MODALITIES), "roi": ROI})), # partition: 30 supervoxels per tumour; these rows are clustered. Stage("partition", Spec("kmeans", {"n_supervoxels": 30})), # pool: one matrix for every training subject, then one fit. Stage("pool", Spec("pool")), # fit: search 2..10 habitats and keep the elbow. n_init=10 restarts. Stage("fit", Spec("kmeans", {"min_habitats": 2, "max_habitats": 10, "validation": "elbow", "n_init": 10})), # assign: nearest centroid writes the shared habitat ids. Stage("assign", Spec("nearest_centroid")), # quantify: one row per subject. Spec name is the feature family. Stage("volume", Spec("volume")), Stage("msi", Spec("msi")), Stage("ith", Spec("ith_score")), Stage("graph", Spec("graph", {"include_extended_metrics": False})), ), # Seeds partition and fit. It is not a RunPolicy setting. random_seed=0, ) # Study runs the spec: fit_predict learns the habitats on the four training # subjects and labels those same subjects in one call. 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/4 [00:00` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_quickstart_python.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_quickstart_python.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_