Habitat Spec component catalog

Reference chooser for registered Spec names. Walk-throughs stay in the Habitat Guide (Habitat Guide). This page lists every built-in name, constructor parameter, and the Python / YAML twin.

Concept and embedding: Habitat analysis · Atomic operators.

The gallery scripts (one-step, two-step, direct-pooling) show one worked HabitatSpec. This page is the chooser from that example outward: which registered names exist for each stage, what each parameter means, and how to write the same choice in Python and YAML.

When a recipe shows Spec("raw") or Spec("kmeans"), look up that stage below. Parameter tables are generated at Sphinx build time from each component constructor. Do not copy them into notebooks — look names and constructor signatures up at runtime:

from habit.plugins import list_plugins
from habit.spec import parse_feature_expression
from habit.voxel_features import RawVoxelFeatures, VoxelFeatureExtractorRegistry

print([info.name for info in list_plugins("voxel_feature_extractor")])
print(VoxelFeatureExtractorRegistry.constructor_signature("raw"))
voxel = VoxelFeatureExtractorRegistry.create("raw", modality="T1")
voxel = RawVoxelFeatures(modality="T1")

Full live catalog (every domain): Plugin introspection API.

How a HabitatSpec is assembled

A habitat study is an ordered list of stages. Each Stage is a label plus a Spec. A leaf is one extractor on one series (section 1A). Combining series or families is a tree from parse_feature_expression() (section 1B):

Stage("<label>", Spec("<registered name>", {<params>}))
Stage("<label>", parse_feature_expression('concat(raw("T1"), voxel_radiomics("T2"))'))

Stage labels (extract_voxel_features, quantify2, …) are not role keywords. HABIT infers the scientific role from position + the component’s registry domain. Recommended labels:

Recommended label

Domain (list_plugins)

Role

extract_voxel_features

voxel_feature_extractor

Required first step

preprocess1 / preprocess2 / …

feature_preprocessing_method

Optional; repeatable; position decides voxel vs post-pool

partition

supervoxelizer

two-step only

extract_supervoxel_features

supervoxel_feature_extractor

two-step optional

pool

pooling

two-step / direct-pooling watershed

fit

habitat_model_fitter

Required

assign

habitat_assigner

Required

quantify / quantify2 / …

habitat_feature_extractor

Optional; repeatable

Strategy is inferred from the sequence:

  • two_step — partition + pool

  • direct_pooling — pool only (no partition)

  • one_step — neither partition nor pool (per-subject habitats)

kmeans and gmm exist in two domains (supervoxelizer and habitat-model fitter). Place them before pool to partition, or immediately before assign to fit habitats.

Python and YAML are the same document

Spec.to_dict() is the YAML component block. A v1 habitat document stores the same mapping under spec:.

from habit.spec import HabitatSpec, Spec, Stage

spec = HabitatSpec(
    name="habitat_one_step",
    stages=(
        Stage("extract_voxel_features", Spec("raw", {"modalities": ["LAP"]})),
        Stage("fit", Spec("kmeans", {"min_habitats": 2, "max_habitats": 10, "validation": "elbow"})),
        Stage("assign", Spec("nearest_centroid")),
        Stage("quantify", Spec("volume")),
    ),
    random_seed=42,
)

Equivalent v1 YAML (stages form):

spec:
  name: habitat_one_step
  random_seed: 42
  stages:
    - name: extract_voxel_features
      component:
        name: raw
        params:
          modalities: [LAP]
    - name: fit
      component:
        name: kmeans
        params:
          min_habitats: 2
          max_habitats: 10
          validation: elbow
    - name: assign
      component:
        name: nearest_centroid
        params: {}
    - name: quantify
      component:
        name: volume
        params: {}

The named-field constructor (voxel_feature_extractor:, habitat_model_fitter:, …) is deprecated: it still loads and keeps historical fingerprints, but new Python and YAML should use stages only. See Spec, RunPolicy, and YAML isomorphism and Habitat Segmentation Configuration.

1. Voxel feature extraction

Required. Turns each subject’s images + ROI into a per-voxel feature field. First pick one extractor on one series (a leaf). Only then compose several series or families with a combiner. A longer modalities list is not a substitute for mixing families.

A. Single-modality voxel extraction

One method, one series, one column (or one block of columns). No concat. The expression form quotes the modality; the Spec form uses modality=:

from habit.spec import parse_feature_expression

Stage("extract_voxel_features", Spec("raw", {"modality": "T1"}))
Stage(
    "extract_voxel_features",
    parse_feature_expression('raw("T1")'),
)
Stage(
    "extract_voxel_features",
    parse_feature_expression('local_entropy("T1", kernel_size=3, bins=32)'),
)
Stage(
    "extract_voxel_features",
    parse_feature_expression('voxel_radiomics("T2", kernel_radius=3)'),
)

YAML:

- name: extract_voxel_features
  component:
    name: raw
    params:
      modality: T1

voxel_radiomics needs the pyradiomics extra and is much slower than raw / local_entropy. Matrix construction can use HABIT’s GPU path (use_gpu_matrices) instead of the PyRadiomics C extension; see Voxel texture feature maps.

B. Multi-modality voxel composition

A combiner joins already-extracted leaves on the same voxels (same ROI). Two spellings — expression string or nested children — share one fingerprint. Modalities in the expression form are quoted.

Same family, several series. A leaf still accepts a modality list (raw("T1", "T2") or modalities: [T1, T2]). concat of two raw leaves is the same idea written as a tree:

Stage("extract_voxel_features", Spec("raw", {"modalities": ["T1", "T2"]}))
Stage(
    "extract_voxel_features",
    parse_feature_expression('concat(raw("T1"), raw("T2"))'),
)

YAML:

- name: extract_voxel_features
  component:
    name: raw
    params:
      modalities: [T1, T2]

Different families. Texture on T2, intensity on T1 — this needs a tree, not a longer modalities list:

Stage(
    "extract_voxel_features",
    parse_feature_expression(
        'concat(raw("T1"), voxel_radiomics("T2", kernel_radius=3))'
    ),
)
Stage(
    "extract_voxel_features",
    parse_feature_expression(
        'concat(local_entropy("T1", kernel_size=3, bins=32), raw("T2"))'
    ),
)

Structured form of the first tree (same Spec):

Stage(
    "extract_voxel_features",
    Spec(
        "concat",
        {
            "children": [
                {"name": "raw", "params": {"modality": "T1"}},
                {
                    "name": "voxel_radiomics",
                    "params": {"modality": "T2", "kernel_radius": 3},
                },
            ],
        },
    ),
)

YAML (expression — shortest):

- name: extract_voxel_features
  component: 'concat(raw("T1"), voxel_radiomics("T2", kernel_radius=3))'

YAML (structured):

- name: extract_voxel_features
  component:
    name: concat
    params:
      children:
        - name: raw
          params: {modality: T1}
        - name: voxel_radiomics
          params: {modality: T2, kernel_radius: 3}

Derived channels — one combiner each. Do not nest ratio, weighted_concat, and a texture leaf in one expression on this page. as_="label" renames a single-column node so two branches do not collide:

Stage(
    "extract_voxel_features",
    parse_feature_expression(
        'ratio(raw("T1"), raw("T2"), as_="t1_over_t2")'
    ),
)
Stage(
    "extract_voxel_features",
    parse_feature_expression(
        'weighted_concat(raw("T1", as_="t1w"), raw("T2", as_="t2w"), weights=[2.0, 1.0])'
    ),
)

Built-ins: concat, weighted_concat (weights=[...]), average, ratio, difference, kinetic, expression. Grammar (strict; bad input is rejected, not guessed): modalities are quoted (raw("T1")); parameters are key=value; a quoted string among children is an implicit raw. Bare raw(T1) is v0.1-only.

Nested trees and column names: Feature composition. Arithmetic beyond combiners: Custom features (expression or a custom plugin).

voxel_feature_extractor

concat

Join several voxel feature families side by side for the same voxels. Required: extractors. Optional: roi, modalities, expression. Spec("concat", {"extractors": ...}) Registry.create("concat", extractors=...)

Param

Default

Allowed / type

Meaning

extractors

(required)

Sequence

Child specifications as {"name": ..., "params": {...}} mappings, resolved through the voxel-feature registry in the given order. A child’s own roi is overridden by this operator’s.

roi

None

str | None

Mask key defining the region of interest for every child; None uses the subject’s single mask.

modalities

()

Sequence

Accepted for configuration compatibility and ignored; each child names the modalities it reads.

expression

None

str | None

The original v0 method expression, carried for provenance when this extractor was reached by config translation.

expression

Per-voxel features defined by restricted arithmetic expressions. Required: (none). Optional: features, expressions, feature_names, modalities, roi, eps. Spec("expression") Registry.create("expression")

Param

Default

Allowed / type

Meaning

features

None

Mapping | None

Mapping of feature name to formula. Mutually exclusive with expressions.

expressions

None

Sequence | None

Ordered formulas when names are not provided up front.

feature_names

None

Sequence | None

Names aligned with expressions; defaults to expr_0, expr_1, …

modalities

()

Sequence

Optional explicit modality list. When empty, modality names are inferred from identifiers used in the formulas (excluding builtins and function names).

roi

None

str | None

Mask key; None uses the subject’s single mask.

eps

1e-08

float

Value bound to the name eps inside every formula.

kinetic

Per-voxel enhancement slopes across a dynamic contrast series. Required: timestamps. Optional: phases, roi, time_format, modalities, expression. Spec("kinetic", {"timestamps": ...}) Registry.create("kinetic", timestamps=...)

Param

Default

Allowed / type

Meaning

timestamps

(required)

str | Mapping

Acquisition times per subject, either as a mapping {subject_id: {phase: "HH-MM-SS"}} for API callers, or a path to the v0.1 timestamp table.

phases

('pre_contrast', 'LAP', 'PVP', 'delay_3min')

Sequence

Modality keys of the series in acquisition order: unenhanced, arterial, portal-venous, delayed.

roi

None

str | None

Mask key defining the region of interest; None uses the subject’s single mask.

time_format

'%H-%M-%S'

str

strptime format of the timestamp values.

modalities

()

Sequence

Accepted for configuration compatibility and ignored; phases defines which images are read, because the four phases have fixed roles that a flat list cannot express.

expression

None

str | None

The original v0 method expression, carried for provenance when this extractor was reached by config translation.

local_entropy

Shannon entropy of each voxel’s intensity neighbourhood. Required: (none). Optional: modalities, roi, kernel_size, bins, modality, as_. Spec("local_entropy") Registry.create("local_entropy")

Param

Default

Allowed / type

Meaning

modalities

()

Sequence

Modality keys to describe, in feature order; empty selects every image the subject carries.

roi

None

str | None

Mask key defining the region of interest; None uses the subject’s single mask.

kernel_size

3

int

Neighbourhood edge length in voxels. Even values are incremented to keep the neighbourhood centred, as in v0.1.

bins

32

int

Histogram bins used to discretise intensities.

modality

None

str | None

Single modality key – the explicit form used inside feature trees. Mutually exclusive with modalities.

as_

None

str | None

Optional output-column alias. Valid only with exactly one resolved modality; the column suffix then uses the alias.

raw

Per-voxel raw intensity of every requested modality inside the ROI. Required: (none). Optional: modalities, roi, modality, as_. Spec("raw") Registry.create("raw")

Param

Default

Allowed / type

Meaning

modalities

()

Sequence

Modality keys to read from the subject, in feature order – the historical convenience that stacks several modalities into one node without a concat combiner.

roi

None

str | None

Mask key defining the region of interest; None uses the subject’s single mask.

modality

None

str | None

Single modality key – the explicit form used inside feature trees (raw("T1")). Mutually exclusive with modalities.

as_

None

str | None

Optional output-column alias. Valid only with exactly one resolved modality; the column is then named after the alias instead of the modality.

voxel_radiomics

Describe every ROI voxel by a PyRadiomics feature vector. Required: (none). Optional: modalities, roi, params_file, params, kernel_radius, voxel_batch, use_torch_radiomics, torch_device, torch_dtype, use_gpu_matrices, output_float32, class_progress, crop_to_roi, cache_dir, modality, as_. Spec("voxel_radiomics") Registry.create("voxel_radiomics")

Param

Default

Allowed / type

Meaning

modalities

()

Sequence

Modality keys to extract from, in feature order; empty selects every image the subject carries.

roi

None

str | None

Mask key defining the region of interest; None uses the subject’s single mask.

params_file

None

str | None

Path to a PyRadiomics parameter YAML; None selects the bundled voxel preset.

params

None

dict | None

Inline PyRadiomics settings, for API callers holding settings in memory. Mutually exclusive with params_file.

kernel_radius

3

int

Neighbourhood radius in voxels; radius 1 is a 3x3x3 cube, radius 3 a 7x7x7 cube.

voxel_batch

1000

int | str

ROI voxels per batch. Default 1000. Pass a larger integer on a 12–24 GB GPU, or "auto" to pick from VRAM.

use_torch_radiomics

'auto'

str | bool

"auto", True or False – whether to use the TorchRadiomics path when torch and CUDA are present.

torch_device

'auto'

str

Torch device string, or "auto" to select one.

torch_dtype

'float64'

str

"float64" (default) or "float32" for the torch path.

use_gpu_matrices

'auto'

str | bool

"auto", True or False – whether the TorchRadiomics texture matrices (GLCM, …) are built on GPU by habit.kernels.radiomics.gpumatrices instead of the single-threaded PyRadiomics C extension. "auto" follows the torch device. Bit-identical counts either way.

output_float32

True

bool

Downcast the feature columns to float32, the v0.1 default that keeps large voxel tables manageable.

class_progress

False

bool

When True, print and tqdm each PyRadiomics class (firstorder, glcm, …). Default False: one execute() with no per-class lines; Cohort.map still shows subject progress.

crop_to_roi

True

bool

When True (default), crop image and mask to the ROI bounding box plus kernel_radius padding before calling execute. PyRadiomics re-applies the identical crop internally, so feature values are bit-identical; the pre-crop just keeps the full-volume diagnostics (sitk.Hash, whole-image statistics) and mask checks off the big volume, saving several seconds per modality on whole-body scans.

cache_dir

None

str | None

Optional directory for extracted fields. A hit skips PyRadiomics. The cache key ignores voxel_batch and device knobs so a later run with a larger batch can reuse the file.

modality

None

str | None

Single modality key – the explicit form used inside feature trees. Mutually exclusive with modalities.

as_

None

str | None

Optional output-column alias. Valid only with exactly one resolved modality; the column suffix then uses the alias.

2. Feature preprocessing

Optional, repeatable. Same method names before and after pool. Before partition / fit they scale the units that clustering sees; after pool they are cohort-level and travel with HabitatModel.

Typical voxel-level chain: winsorize then minmax. Do not skip scaling on two-step / direct-pooling runs — see Feature preprocessing.

Python:

Stage("preprocess1", Spec("winsorize", {"winsor_limits": (0.05, 0.05), "across_features": False}))
Stage("preprocess2", Spec("minmax", {"across_features": False}))

YAML:

- name: preprocess1
  component:
    name: winsorize
    params:
      winsor_limits: [0.05, 0.05]
      across_features: false
- name: preprocess2
  component:
    name: minmax
    params:
      across_features: false

feature_preprocessing_method

binning

Discretise features into ordinal bin indices. Required: (none). Optional: n_bins, bin_strategy, across_features. Spec("binning") Registry.create("binning")

Param

Default

Allowed / type

Meaning

n_bins

10

int

Number of bins.

bin_strategy

'uniform'

str

uniform, quantile or kmeans.

across_features

False

bool

Learn one set of edges from the pooled values.

correlation_filter

Greedily drop redundant, highly correlated feature columns. Required: (none). Optional: corr_threshold, corr_method. Spec("correlation_filter") Registry.create("correlation_filter")

Param

Default

Allowed / type

Meaning

corr_threshold

0.95

float

Absolute-correlation cut-off above which later columns are dropped.

corr_method

'spearman'

str

pearson, spearman or kendall.

feature_whitelist

Restrict the feature matrix to an explicit, externally derived list. Required: features. Optional: (none). Spec("feature_whitelist", {"features": ...}) Registry.create("feature_whitelist", features=...)

Param

Default

Allowed / type

Meaning

features

(required)

Sequence

Feature names to keep, in output order. At least one is required, and every name must be present in the matrix – a missing feature breaks the “same features” contract and raises rather than being silently dropped.

impute

Replace non-finite feature values with a learned per-column statistic. Required: (none). Optional: strategy. Spec("impute") Registry.create("impute")

Param

Default

Allowed / type

Meaning

strategy

'mean'

str

mean or median of each column’s finite values, or zero. Columns with no finite value at all impute to 0.0 regardless, so one unusable modality cannot invalidate a subject.

l2

Scale each row (voxel / supervoxel) to unit Euclidean length. Required: (none). Optional: (none). Spec("l2") Registry.create("l2")

log

Compress right-skewed features with log(x - min + 1). Required: (none). Optional: across_features. Spec("log") Registry.create("log")

Param

Default

Allowed / type

Meaning

across_features

False

bool

See the component docstring.

maxabs

Scale features by the maximum absolute value. Required: (none). Optional: across_features. Spec("maxabs") Registry.create("maxabs")

Param

Default

Allowed / type

Meaning

across_features

False

bool

See the component docstring.

minmax

Scale features to [0, 1]. Required: (none). Optional: across_features. Spec("minmax") Registry.create("minmax")

Param

Default

Allowed / type

Meaning

across_features

False

bool

See the component docstring.

precise_correlation_filter

Prior 2024 Spearman screen: signed r, p-value, keep the later column. Required: (none). Optional: corr_threshold, p_threshold. Spec("precise_correlation_filter") Registry.create("precise_correlation_filter")

Param

Default

Allowed / type

Meaning

corr_threshold

0.7

float

Signed Spearman cut-off; drop when r is greater.

p_threshold

0.05

float

Spearman p-value cut-off; drop only when p is smaller.

quantile

Map each feature onto a uniform or normal distribution by percentile rank. Required: (none). Optional: across_features, n_quantiles, output_distribution. Spec("quantile") Registry.create("quantile")

Param

Default

Allowed / type

Meaning

across_features

False

bool

See the component docstring.

n_quantiles

1000

int

See the component docstring.

output_distribution

'uniform'

str

See the component docstring.

robust

Centre features on the median and scale by the interquartile range. Required: (none). Optional: across_features. Spec("robust") Registry.create("robust")

Param

Default

Allowed / type

Meaning

across_features

False

bool

See the component docstring.

variance_filter

Drop feature columns whose variance is at or below a threshold. Required: (none). Optional: variance_threshold. Spec("variance_filter") Registry.create("variance_filter")

Param

Default

Allowed / type

Meaning

variance_threshold

0.0

float

Columns with var <= threshold are dropped; 0.0 removes only constant columns.

winsorize

Clip extreme values at tail quantiles instead of discarding them. Required: (none). Optional: winsor_limits, across_features. Spec("winsorize") Registry.create("winsorize")

Param

Default

Allowed / type

Meaning

winsor_limits

(0.05, 0.05)

tuple[float, float]

Lower and upper tail fractions to clip, each in [0, 0.5).

across_features

False

bool

Pool statistics across feature columns.

zscore

Standardise features to zero mean and unit variance. Required: (none). Optional: across_features. Spec("zscore") Registry.create("zscore")

Param

Default

Allowed / type

Meaning

across_features

False

bool

See the component docstring.

3. Supervoxel partition

two-step only. All built-in names use n_supervoxels (not sklearn’s n_clusters / n_components).

Python:

Stage("partition", Spec("slic", {"n_supervoxels": 50}))
Stage("partition", Spec("kmeans", {"n_supervoxels": 50, "n_init": 10}))

YAML:

- name: partition
  component:
    name: kmeans
    params:
      n_supervoxels: 50
      n_init: 10

supervoxelizer

gmm

Partition the ROI by a Gaussian mixture over voxel features. Required: (none). Optional: n_supervoxels, max_iter, n_init, covariance_type. Spec("gmm") Registry.create("gmm")

Param

Default

Allowed / type

Meaning

n_supervoxels

50

int

Requested number of supervoxels, clamped to the ROI voxel count.

max_iter

300

int

Maximum EM iterations.

n_init

10

int

Number of EM restarts.

covariance_type

'full'

str

scikit-learn covariance parameterisation ("full", "tied", "diag", "spherical").

kmeans

Partition the ROI by k-means over voxel features. Required: (none). Optional: n_supervoxels, max_iter, n_init. Spec("kmeans") Registry.create("kmeans")

Param

Default

Allowed / type

Meaning

n_supervoxels

50

int

Requested number of supervoxels, clamped to the ROI voxel count.

max_iter

300

int

Maximum k-means iterations per restart.

n_init

10

int

Number of k-means restarts.

slic

Partition the ROI into SLIC supervoxels and average features within each. Required: (none). Optional: n_supervoxels, compactness, enforce_connectivity, estimator_params. Spec("slic") Registry.create("slic")

Param

Default

Allowed / type

Meaning

n_supervoxels

100

int

Requested number of supervoxels. Clamped to the number of ROI voxels (a partition cannot have more non-empty regions than voxels).

compactness

10.0

float

Balance between colour similarity and spatial proximity (skimage.segmentation.slic semantics).

enforce_connectivity

True

bool

When True, disconnected segments are relabelled so every supervoxel is connected.

estimator_params

None

Mapping | None

Extra keyword arguments forwarded verbatim to skimage.segmentation.slic (e.g. {"sigma": 1.0}), for vendor parameters HABIT does not declare. Keys colliding with a declared parameter or with a call argument HABIT controls (n_segments, mask, channel_axis, start_label) are rejected, and every key is validated against the vendor signature at call time: a key recorded in the spec fingerprint must reach the vendor function, never be silently dropped.

4. Supervoxel features

two-step optional. This stage describes each supervoxel, after partition. It does not replace voxel extraction: mixed T1/T2 science is usually built in section 1, then aggregated here.

The default is to average the voxel field you already built (mean_voxel_features). Omit this stage unless you need a different description; many two-step recipes rely on the partition’s attached means:

Stage("extract_supervoxel_features", Spec("mean_voxel_features"))

YAML:

- name: extract_supervoxel_features
  component:
    name: mean_voxel_features
    params: {}

A. Single-modality supervoxel extraction

One method, one series. mean / std / percentile aggregate that series’ voxel signal per supervoxel. source="working" (default) uses the preprocessed voxel field; source="original" uses the raw series the partition saw. supervoxel_radiomics is whole-region texture per supervoxel label (not a sliding voxel kernel):

Stage(
    "extract_supervoxel_features",
    parse_feature_expression('mean("T1")'),
)
Stage(
    "extract_supervoxel_features",
    parse_feature_expression('std("T1", as_="t1_spread")'),
)
Stage(
    "extract_supervoxel_features",
    parse_feature_expression('percentile("T2", q=90)'),
)
Stage(
    "extract_supervoxel_features",
    parse_feature_expression('supervoxel_radiomics("T2")'),
)

supervoxel_radiomics needs pyradiomics. Values differ from voxel_radiomics (different spatial support).

B. Multi-modality supervoxel composition

Compose the leaves the same way as voxel combiners. Keep each combiner to one job — statistics together, or a statistic plus radiomics — and leave nested trees to Feature composition:

Stage(
    "extract_supervoxel_features",
    parse_feature_expression(
        'concat(mean("T1"), std("T1", as_="t1_spread"), percentile("T2", q=90))'
    ),
)
Stage(
    "extract_supervoxel_features",
    parse_feature_expression(
        'concat(mean("T1"), supervoxel_radiomics("T2"))'
    ),
)

YAML:

- name: extract_supervoxel_features
  component: 'concat(mean("T1"), std("T1", as_="t1_spread"), percentile("T2", q=90))'

supervoxel_feature_extractor

mean

Average the voxel signal within each supervoxel, one modality at a time. Required: (none). Optional: modality, source, as_. Spec("mean") Registry.create("mean")

Param

Default

Allowed / type

Meaning

modality

None

str | None

See the component docstring.

source

'working'

str

See the component docstring.

as_

None

str | None

See the component docstring.

mean_voxel_features

Describe each supervoxel by the mean of the voxel features within it. Required: (none). Optional: field. Spec("mean_voxel_features") Registry.create("mean_voxel_features")

Param

Default

Allowed / type

Meaning

field

None

VoxelFeatureField | None

Voxel features to aggregate. Optional; see above.

percentile

A percentile of the voxel signal within each supervoxel. Required: (none). Optional: modality, source, q, as_. Spec("percentile") Registry.create("percentile")

Param

Default

Allowed / type

Meaning

modality

None

str | None

See the component docstring.

source

'working'

str

See the component docstring.

q

90.0

float

See the component docstring.

as_

None

str | None

See the component docstring.

std

Sample standard deviation of the voxel signal within each supervoxel. Required: (none). Optional: modality, source, as_. Spec("std") Registry.create("std")

Param

Default

Allowed / type

Meaning

modality

None

str | None

See the component docstring.

source

'working'

str

See the component docstring.

as_

None

str | None

See the component docstring.

supervoxel_radiomics

Describe each supervoxel by PyRadiomics features of the original images. Required: (none). Optional: modality, modalities, as_, params_file, params, supervoxel_batch, supervoxel_union_bbox_crop, supervoxel_pad_distance, use_supervoxel_cext, union_bin, use_torch_radiomics, torch_device, torch_dtype, output_float32. Spec("supervoxel_radiomics") Registry.create("supervoxel_radiomics")

Param

Default

Allowed / type

Meaning

modality

None

str | None

Single modality name; mutually exclusive with modalities.

modalities

()

Sequence

Modality names to extract from; empty selects all the subject carries.

as_

None

str | None

Alias used as the column suffix instead of the modality name; requires modality.

params_file

None

str | None

Path to a PyRadiomics parameter YAML, or None for PyRadiomics defaults.

params

None

dict | None

Inline PyRadiomics settings mapping, for API users holding settings in memory. Mutually exclusive with params_file.

supervoxel_batch

64

int

Labels processed per batch. Larger batches trade memory for speed and never change the numbers.

supervoxel_union_bbox_crop

True

bool

Crop image and masks to the bounding box of the union of all supervoxels before extraction.

supervoxel_pad_distance

None

int | None

Padding around that bounding box; None keeps the PyRadiomics padDistance setting.

use_supervoxel_cext

True

str | bool

True (default), "auto", or False – whether to use the habit native C extension for texture matrices.

union_bin

False

bool

When False (default) each supervoxel is discretized with its own binWidth edges, matching PyRadiomics execute(). When True, all labels share one union-mask bin.

use_torch_radiomics

'auto'

str | bool

"auto", True or False – whether to use the TorchRadiomics GPU path when torch and CUDA are present.

torch_device

'auto'

str

Torch device string, or "auto" to select one.

torch_dtype

'float64'

str

"float64" (default) or "float32" for the torch path.

output_float32

True

bool

Downcast the resulting feature columns to float32, the v0.1 default that keeps large supervoxel tables manageable.

5. Pool

two-step and direct-pooling. Marks the subject → cohort watershed. There is one built-in name.

Python:

Stage("pool", Spec("pool"))

YAML:

- name: pool
  component:
    name: pool
    params: {}

pooling

pool

Marker component that declares the subject→cohort fan-in watershed. Required: (none). Optional: (none). Spec("pool") Registry.create("pool")

6. Fit habitats

Required. Built-in names: kmeans and gmm. Learns centroids (cohort-level when pool is present; per-subject otherwise).

Shared parameters: n_habitats, min_habitats, max_habitats, validation, n_init, max_iter. gmm also takes covariance_type (full / tied / diag / spherical).

Omit n_habitats (or pass None) to select K over min_habitats..max_habitats by validation. There is no string "auto".

Allowed validation values:

  • kmeans — elbow (default; alias of kneedle), kneedle, inertia, silhouette, calinski_harabasz, davies_bouldin, gap. A list of these casts one vote each.

  • gmm — bic (default), aic, davies_bouldin (minimise); silhouette, calinski_harabasz, gap (maximise).

Copy-paste a fit stage:

Stage(
    "fit",
    Spec(
        "kmeans",
        {
            "min_habitats": 2,
            "max_habitats": 10,
            "validation": "elbow",
            "n_init": 5,
        },
    ),
)
Stage("fit", Spec("gmm", {"n_habitats": 4, "covariance_type": "full"}))

YAML:

- name: fit
  component:
    name: kmeans
    params:
      min_habitats: 2
      max_habitats: 10
      validation: elbow
      n_init: 5

habitat_model_fitter

gmm

Learn population habitats by a Gaussian mixture over pooled features. Required: (none). Optional: n_habitats, min_habitats, max_habitats, validation, covariance_type, n_init, max_iter. Spec("gmm") Registry.create("gmm")

Param

Default

Allowed / type

Meaning

n_habitats

None

int | None

Fixed habitat count, or None to select it by validation.

min_habitats

2

int

Smallest candidate count during selection.

max_habitats

10

int

Largest candidate count during selection.

validation

'bic'

str | Sequence

Selection criterion, or a list of criteria that each cast one vote: "bic" / "aic" / "davies_bouldin" (minimise), "bic_elbow" (Prior 2024 BIC-slope elbow, not minimum BIC), or "silhouette" / "calinski_harabasz" / "gap" (maximise).

covariance_type

'full'

str

GaussianMixture covariance structure.

n_init

50

int

Number of mixture initialisations per candidate count; the best-likelihood run is kept (sklearn n_init).

max_iter

100

int

EM iteration limit per candidate count.

kmeans

Learn population habitats by k-means over pooled supervoxel features. Required: (none). Optional: n_habitats, min_habitats, max_habitats, validation, n_init, max_iter. Spec("kmeans") Registry.create("kmeans")

Param

Default

Allowed / type

Meaning

n_habitats

None

int | None

Fixed habitat count, or None to select it by validation.

min_habitats

2

int

Smallest candidate count during selection.

max_habitats

10

int

Largest candidate count during selection.

validation

'elbow'

str | Sequence

Selection criterion, or a list of criteria that each cast one vote: "elbow" / "kneedle" / "inertia" (Kneedle knee of the inertia curve; default "elbow"), "silhouette" / "calinski_harabasz" / "gap" (maximise), or "davies_bouldin" (minimise). Since v1.0 elbow is an alias of kneedle; see habit.kernels.cluster_selection. The default is the community-used inertia elbow over min_habitats=2 .. max_habitats=10.

n_init

50

int

k-means restarts per candidate count.

max_iter

300

int

Maximum k-means iterations per fit. Defaults to the scikit-learn default (300), which is also the value the v0.1 configuration schema recorded.

7. Assign

Required. Maps each unit to the nearest habitat centroid. The built-in name is nearest_centroid. After fit, model.assigner() is the same object.

Python:

Stage("assign", Spec("nearest_centroid"))

YAML:

- name: assign
  component:
    name: nearest_centroid
    params: {}

habitat_assigner

nearest_centroid

Assign each supervoxel to the habitat of its nearest centroid. Required: model. Optional: (none). Spec("nearest_centroid", {"model": ...}) Registry.create("nearest_centroid", model=...)

Param

Default

Allowed / type

Meaning

model

(required)

HabitatModel

The fitted habitat definition to project.

8. Quantify

Optional, repeatable. Does not change the habitat map. Light families (volume, msi, ith_score, non_radiomics, graph) need no extra extra. traditional / whole_habitat / each_habitat need pyradiomics.

Python:

Stage("quantify", Spec("volume"))
Stage("quantify2", Spec("msi"))
Stage("quantify3", Spec("ith_score"))
Stage("quantify4", Spec("non_radiomics"))
Stage(
    "quantify5",
    Spec("graph", {"edge_method": "min_distance", "node_method": "uniform_grid"}),
)

One-step streaming figures (not stages — do not enter the fingerprint). Pass the same HabitatGraphFeatureOptions to Spec("graph") and the graph atoms. Catalog: Figures and methods.

Python:

from habit.adapters import DirectoryResultWriter
from habit.kernels import HabitatGraphFeatureOptions
from habit.report import (
    ClusterValidation,
    GraphNetwork2D,
    GraphSlice,
    ITH,
    MSI,
    Overlay,
    Report,
    VolumeFractions,
)

graph = HabitatGraphFeatureOptions(edge_method="min_distance", block_size=8)
writer = DirectoryResultWriter("out/study")
report = Report(
    figures=(
        Overlay(modality="T1"),
        VolumeFractions(),
        MSI(),
        ITH(),
        ClusterValidation(),
        GraphSlice(options=graph),
        GraphNetwork2D(options=graph),
    ),
    figure_layout="by_subject",
    writer=writer,
)

YAML:

- name: quantify
  component:
    name: volume
    params: {}
- name: quantify2
  component:
    name: msi
    params: {}

habitat_feature_extractor

each_habitat

PyRadiomics features of the raw image(s) within each habitat label. Required: (none). Optional: params_file, params, modalities, modality, as_, use_torch_radiomics, torch_device, torch_dtype. Spec("each_habitat") Registry.create("each_habitat")

Param

Default

Allowed / type

Meaning

params_file

None

str | None

See the component docstring.

params

None

dict | None

See the component docstring.

modalities

None

Sequence | None

See the component docstring.

modality

None

str | None

See the component docstring.

as_

None

str | None

See the component docstring.

use_torch_radiomics

False

str | bool

See the component docstring.

torch_device

'auto'

str

See the component docstring.

torch_dtype

'float64'

str

See the component docstring.

graph

Graph-topology features of one subject’s habitat map. Required: (none). Optional: include_single_habitat_graph, include_pairwise_habitat_graph, edge_method, distance_threshold, adjacency_connectivity, adjacency_min_voxels, edge_weight, min_region_voxels, connectivity, erosion_radius, node_method, subdivide_region_voxels, block_size, block_min_coverage, pairwise_include_intra_edges, include_extended_metrics, extended_min_nodes, small_world_nrand, small_world_niter, rich_club_q, graph_null_sampler, graph_null_device. Spec("graph") Registry.create("graph")

Param

Default

Allowed / type

Meaning

include_single_habitat_graph

True

bool

See the component docstring.

include_pairwise_habitat_graph

True

bool

See the component docstring.

edge_method

'min_distance'

‘centroid_distance’ | ‘adjacency’ | ‘min_distance’

See the component docstring.

distance_threshold

5.0

float

See the component docstring.

adjacency_connectivity

'corner'

‘face’ | ‘edge’ | ‘corner’

See the component docstring.

adjacency_min_voxels

10

int

See the component docstring.

edge_weight

'none'

‘none’ | ‘distance’ | ‘inverse_distance’ | ‘contact_voxels’

See the component docstring.

min_region_voxels

1

int

See the component docstring.

connectivity

'full'

‘face’ | ‘full’

See the component docstring.

erosion_radius

0

int

See the component docstring.

node_method

'uniform_grid'

‘uniform_grid’ | ‘component’

See the component docstring.

subdivide_region_voxels

1000

int

See the component docstring.

block_size

8

int

See the component docstring.

block_min_coverage

0.2

float

See the component docstring.

pairwise_include_intra_edges

True

bool

See the component docstring.

include_extended_metrics

True

bool

See the component docstring.

extended_min_nodes

10

int

See the component docstring.

small_world_nrand

100

int

See the component docstring.

small_world_niter

100

int

See the component docstring.

rich_club_q

100

int

See the component docstring.

graph_null_sampler

'analytic'

‘analytic’ | ‘config’ | ‘rewire’

See the component docstring.

graph_null_device

'auto'

str

See the component docstring.

ith_score

ITH score for one subject’s habitat map. Required: (none). Optional: include_auxiliary. Spec("ith_score") Registry.create("ith_score")

Param

Default

Allowed / type

Meaning

include_auxiliary

False

bool

See the component docstring.

msi

Multiregional spatial interaction features of one subject’s habitat map. Required: (none). Optional: (none). Spec("msi") Registry.create("msi")

non_radiomics

Basic spatial features of one subject’s habitat map. Required: (none). Optional: (none). Spec("non_radiomics") Registry.create("non_radiomics")

traditional

PyRadiomics features of the raw image(s) within the whole ROI. Required: (none). Optional: params_file, params, modalities, modality, as_, use_torch_radiomics, torch_device, torch_dtype. Spec("traditional") Registry.create("traditional")

Param

Default

Allowed / type

Meaning

params_file

None

str | None

See the component docstring.

params

None

dict | None

See the component docstring.

modalities

None

Sequence | None

See the component docstring.

modality

None

str | None

See the component docstring.

as_

None

str | None

See the component docstring.

use_torch_radiomics

False

str | bool

See the component docstring.

torch_device

'auto'

str

See the component docstring.

torch_dtype

'float64'

str

See the component docstring.

volume

Voxel counts and volume fractions of every habitat for one subject. Required: (none). Optional: (none). Spec("volume") Registry.create("volume")

whole_habitat

PyRadiomics features of the habitat map treated as the image itself. Required: (none). Optional: params_file, params, use_torch_radiomics, torch_device, torch_dtype. Spec("whole_habitat") Registry.create("whole_habitat")

Param

Default

Allowed / type

Meaning

params_file

None

str | None

See the component docstring.

params

None

dict | None

See the component docstring.

use_torch_radiomics

False

str | bool

See the component docstring.

torch_device

'auto'

str

See the component docstring.

torch_dtype

'float64'

str

See the component docstring.