Habitat Segmentation Configuration
Habitat Analysis Configuration Parameters
This section covers habitat analysis configuration. CLI: habit get-habitat -c <yaml>. Demo training: config/habitat/config_habitat_two_step.yaml; prediction: config/habitat/config_habitat_two_step_predict.yaml; SLIC supervoxel example: config/habitat/config_habitat_two_step_supervoxel_slic.yaml (parameter details in “habitat_segmentation.supervoxel — SLIC Superpixel Configuration” below).
Example configuration file:
run_mode: train
pipeline_path: ./results/habitat_pipeline.pkl
data_dir: ./file_habitat.yaml
out_dir: ./results/habitat/train
feature_construction:
voxel_level:
method: concat(raw(delay2), raw(delay3), raw(delay5))
supervoxel_level:
supervoxel_file_keyword: '*_supervoxel.nrrd'
method: mean_voxel_features()
preprocessing_for_subject_level:
methods:
- method: winsorize
winsor_limits: [0.05, 0.05]
global_normalize: true
- method: minmax
global_normalize: true
preprocessing_for_group_level:
methods:
- method: binning
n_bins: 10
bin_strategy: uniform
global_normalize: false
habitat_segmentation:
clustering_mode: two_step
supervoxel:
algorithm: kmeans
n_clusters: 50
random_state: 42
max_iter: 300
n_init: 10
habitat:
algorithm: kmeans
max_clusters: 10
habitat_cluster_selection_method:
- inertia
- silhouette
fixed_n_clusters: null
random_state: 42
max_iter: 300
n_init: 10
processes: 2
cap_processes_to_gpu_pool: false
individual_subject_timeout_sec: 900
individual_subject_spawn_timeout_sec: 120
resume: true
strict_checkpoint_hash: false
checkpoint_dir: null
force_rerun_subjects: []
retry_failed_subjects: false
individual_subject_auto_retry_rounds: 2
individual_subject_parallel_mode: persistent
persistent_worker_max_consecutive_failures: 1
persistent_worker_recycle_after_tasks: 0
clear_checkpoint_on_success: false
plot_curves: true
save_images: true
save_results_csv: true
random_state: 42
verbose: true
debug: false
run_mode: Run mode
Type: string
Required: no
Default:
trainAllowed values:
train,predictDescription:
traintrains a new model;predictruns inference with a pretrained pipeline.Example:
train
pipeline_path: Pipeline file path
Type: string
Required: no (required in
predictmode)Default:
nullDescription: Path to the trained pipeline file.
Example:
./results/habitat_pipeline.pkl
data_dir/out_dir (habitat analysis top level)
Type: string
Required: yes
Default: none (required)
Description:
data_dirmay be a directory or a manifest such asfile_habitat.yaml;out_diris the default parent directory for results and checkpoints.
feature_construction: Feature extraction settings
Type: object
Required: required in
train; may be omitted inpredictDefault:
nullDescription: If unset, validation rejects the config or errors according to run mode. Sub-blocks
voxel_level/supervoxel_level/preprocessing_*are documented below.
YAML field naming in this workflow (avoid confusing method / methods / algorithm):
feature_construction.*.method(singular): one functional expression string (concat(voxel_radiomics(T2))).preprocessing_for_* .methods(plural): an ordered list of preprocessing steps; each item has its ownmethod: winsorizestep type.habitat_segmentation.*.algorithm: clustering backend (kmeans,gmm,slic), not a feature extractor.habitat_cluster_selection_method/selection_method: cluster-count validation metric (elbow,silhouette, …).
voxel_level: Voxel-level feature extraction
method: Feature extraction method expressionType: string
Required: yes
Default: none (required)
Description: Supports functional syntax to combine multiple extractors.
Expression conventions (shared by
voxel_level/supervoxel_level):When extracting per modality (
raw,voxel_radiomics,supervoxel_radiomics, etc.), even for a single modality wrap with an outer combiner such asconcat(...); inner expressions are per-modality sub-expressions; the outer layer merges results across modalities.Comma-separated tokens inside parentheses are parameter name placeholders or image modality names (matching
images/<subject>/<modality>/subdirectories), not Python keyword arguments; actual paths and numeric values go in a siblingparamsdict.Binding rule: a parameter binds to function
Fonly when its name appears insideF(...)parentheses (modality names excepted). Keys inparamsthat are not listed in any function’s parentheses trigger a deprecation warning.Defaults: optional parameters omitted from both parentheses and
paramsreceive built-in defaults from each method’smethod_param_spec(see extractor classes underhabit/core/habitat_analysis/clustering_features/).Bundled ``params_file``: for
voxel_radiomics/supervoxel_radiomics,params_fileis optional. When omitted, HABIT uses bundled presets shipped inhabit/resources/radiomics/(CT R3B12 voxel preset; full-set supervoxel preset). The resolved absolute path is logged at runtime.Recommended minimal form:
concat(voxel_radiomics(T2))withparams: {}— uses bundled CT R3B12params_file,kernel_radius: 3,voxel_batch: 1000,use_torch_radiomics: auto. List a name in parentheses only when overriding (e.g.concat(voxel_radiomics(T2, kernel_radius))withkernel_radius: 1for MRI).
params: Voxel-level extractor parameter dictionaryType: dict
Required: no
Default:
{}Description: Key-value pairs passed to extractors referenced in
method(e.g.params_fileforvoxel_radiomicsmay live inparamsdepending on resolver behavior). Omit the entireparamsblock when there are no extra parameters (defaults to empty dict).Available methods and parameters:
raw(image_name):
Description: Extract raw image voxel values (most basic feature)
Parameters: none
Example:
raw(delay2)
concat(…):
Description: Concatenate multiple feature vectors
Parameters: accepts multiple feature extraction expressions
Example:
concat(raw(delay2), raw(delay3), raw(delay5))
kinetic(…):
Description: Extract kinetic features (wash-in/wash-out slopes, etc.)
Parameters:
timestamps(str, required): path to timestamps fileaccepts multiple
raw(image_name)expressionsExample:
kinetic(raw(LAP), raw(PVP), raw(delay_3min), timestamps=...)Extracted features:
wash_in_slope: wash-in slope
wash_out_slope_lap_pvp: wash-out slope from LAP to PVP
wash_out_slope_pvp_dp: wash-out slope from PVP to delay phase
local_entropy(…):
Description: Compute local entropy (local texture complexity)
Parameters:
kernel_size(int, default:3): local neighborhood size
bins(int, default:32): histogram bin countExample:
local_entropy(raw(delay2), kernel_size=5, bins=32)
voxel_radiomics(…):
Description: Extract voxel-level radiomics features
Parameters:
params_file(str, optional): PyRadiomics parameter file path; omit for bundled CT R3B12 preset
kernel_radius(int, default:3for CT R3B12 bundled preset;1= 3×3×3,3= 7×7×7): local neighborhood radius
voxel_batch(int, default:1000): voxel batch size;-1processes all ROI voxels at once (native PyRadiomics, no batching). Positive values limit memory (GPU or large ROI:512–1000recommended)
use_torch_radiomics(str, default:auto):autouses TorchRadiomics when torch is installed and CUDA is available, otherwise CPU PyRadiomics;trueforces torch;falsealways CPU
torch_device(str, default:auto): single GPU device whentorch_gpusis unset
torch_gpus(list/int/str): allowed GPU indices, e.g.[0, 1, 2]or"0,1,2"; overridestorch_devicewhen set
torch_gpu_count(int, optional): use first N GPUs fromtorch_gpus
torch_dtype(str, default:float32): Torch compute dtype (float32orfloat64;float64closer to CPU PyRadiomics)Voxel GLCM note: Use
config/radiomics/params_voxel_radiomics.yaml(explicit list of 21 stable GLCM features). Ifparams_filelists onlyglcm:without feature names, PyRadiomics computes all 24 GLCM features; in small neighborhoods with many uniform voxels, GLCM degenerates to 1×1 matrices and MCC / Imc1 / Imc2 feature values or mutual information can crash or produce NaN on CUDA/MKL. HABIT auto-replaces with the 21 stable features and logs a warning when GLCM is unrestricted; if features are explicitly listed inparams_file, user configuration is respected.CT voxel texture (R3B12): Literature recommends
kernel_radius: 3andbinWidth: 12HU (R3B12 configuration; better repeatability and robustness to kernel/binning than R1B25). Omitparams_fileto use bundledparams_voxel_radiomics.yaml;kernel_radiusdefaults to 3. Reference: Petersen A, et al. Radiol Artif Intell. 2024;6(2):e230118. https://doi.org/10.1148/ryai.230118Example:
concat(voxel_radiomics(T2))withparams: {}(CT R3B12 defaults); override example:concat(voxel_radiomics(T2, kernel_radius))withkernel_radius: 1inparams
Full examples:
# Simple concatenation of raw images voxel_level: method: concat(raw(delay2), raw(delay3), raw(delay5)) # Kinetic features voxel_level: method: kinetic(raw(LAP), raw(PVP), raw(delay_3min)) params: timestamps: ./timestamps.txt # Combine local entropy and raw values voxel_level: method: concat(raw(delay2), local_entropy(raw(delay2))) params: kernel_size: 5 bins: 32 # Voxel-level radiomics (texture features, slower; single modality still needs concat) voxel_level: method: concat(voxel_radiomics(T2)) params: {}
params: Global parametersType: dict
Required: no
Default:
{}Description: Shared parameters for all extractors.
voxel_radiomics-specific keys (voxel_batch,use_torch_radiomics, etc.) belong inparamsand need not appear in themethodexpression string; keys not listed in the expression are auto-merged and forwarded.Common parameters:
timestamps(str): timestamps file path (for kinetic)kernel_size(int): local neighborhood size (for local_entropy)bins(int): histogram bin count (for local_entropy)params_file(str): PyRadiomics parameter file (for voxel_radiomics)kernel_radius(int): voxel radiomics neighborhood radius (for voxel_radiomics)voxel_batch(int): voxel radiomics batch size (for voxel_radiomics; default1000;-1= no batching)use_torch_radiomics(str): TorchRadiomics acceleration (auto/true/false)torch_device(str): single GPU device (whentorch_gpusunset)torch_gpus(list/int/str): allowed GPU listtorch_gpu_count(int): cap on GPUs actually usedtorch_dtype(str): Torch dtype (voxel_radiomics torch backend)
supervoxel_level: Superpixel-level feature extraction (optional)
Block default:
null(omit = no supervoxel block;two_steptraining usually requires it)supervoxel_file_keyword: Superpixel file glob patternType: string
Required: no (when
supervoxel_levelis configured)Default:
*_supervoxel.nrrdDescription: Matches existing supervoxel segmentation files (from two_step mode).
Example:
"*_supervoxel.nrrd"
method: Feature aggregation/extraction methodType: string
Required: no (recommended when
supervoxel_levelis configured)Default:
mean_voxel_features()Description: Defines how voxel features aggregate to supervoxels, or direct supervoxel extraction. For multi-modality extractors such as
supervoxel_radiomics, expression conventions matchvoxel_level(single modality still needs outerconcat(...)etc.; see “Expression conventions” above).Available methods and parameters:
mean_voxel_features():
Description: Mean of voxel features within each supervoxel (most common)
Parameters: none
Use case: Aggregate voxel-level features (from
voxel_level) to supervoxel levelExample:
mean_voxel_features()
concat(supervoxel_radiomics(<modality>, params_file), …):
Description: Per supervoxel label, extract whole-ROI radiomics texture (not voxel kernel neighborhoods). Must sit inside
concat(...)(or another outer combiner); single-modality example:concat(supervoxel_radiomics(T2, params_file)).Discretization: One PyRadiomics
_applyBinningon the union mask of all supervoxels (sv_map > 0), then per-labelcMatricesMatrix backend:
use_supervoxel_cextdefaultauto: use C extension batch matrix build whensupervoxel_cextis compiled (pip install -e .); otherwise fallback Torch/PyRadiomics stacked matrix path.falseforces Torch/PyRadiomics stacked matrices (matrix_backend=torch_cmatrices) even if C extension existsFeature backend: When
use_torch_radiomicsresolves to torch, TorchRadiomics (GPU/CPU torch); else CPU PyRadiomics (same semantics)Parameters (in
feature_construction.supervoxel_level.params; may inherit torch keys fromvoxel_level.params):
params_file(str, optional): PyRadiomics parameter YAML; omit for bundled full-set preset
supervoxel_batch(int): batch group size, default64(not kernel radius)
supervoxel_union_bbox_crop(bool): crop to union bbox, defaulttrue
use_supervoxel_cext(str | bool):auto/true/false, defaultauto; must be insupervoxel_level.params(not inparams_file)
use_torch_radiomics(str):auto/true/false
torch_gpus/torch_gpu_count/torch_device/torch_dtype: same as voxel levelNote:
kernel_radiusis forvoxel_radiomicsonly;supervoxel_radiomicsdoes not use itUse case: Texture radiomics directly from supervoxel regions without
voxel_levelfeaturesExample:
concat(supervoxel_radiomics(T2))withparams: {}(bundled preset)
Method comparison:
mean_voxel_features(): depends onvoxel_levelfeatures; fast; suitable for most cases
concat(supervoxel_radiomics(...), ...): standalone ROI radiomics; union-mask bin once + per-label extract; feature values differ from legacy per-labelexecute(per-label bin)Full examples:
# Scenario 1: aggregate voxel features (recommended) supervoxel_level: supervoxel_file_keyword: '*_supervoxel.nrrd' method: mean_voxel_features() # Scenario 2: direct radiomics (single modality still needs concat; replace T2 with modality under data_dir) supervoxel_level: supervoxel_file_keyword: '*_supervoxel.nrrd' method: concat(supervoxel_radiomics(T2)) params: {} # Scenario 2b: multi-modality supervoxel radiomics supervoxel_level: supervoxel_file_keyword: '*_supervoxel.nrrd' method: concat( supervoxel_radiomics(T1), supervoxel_radiomics(T2)) params: {}
params: ParametersType: dict
Required: no
Default:
{}Description: Parameters for extractors. Omit
paramsfor parameterless methods likemean_voxel_features(). Commonsupervoxel_radiomicskeys:params_file,supervoxel_batch,supervoxel_union_bbox_crop,use_supervoxel_cext,use_torch_radiomics,torch_gpus,torch_gpu_count,torch_dtype(torch keys may inherit fromvoxel_level.params).
preprocessing_for_subject_level: Subject-level preprocessing (optional)
methods: Preprocessing method listType: list
Required: no
Default:
[]Description: Preprocess features per subject to reduce within-subject outliers and scale differences. Dispatched by
PreprocessingMethodFactorywith DataFrame in/out (see “Habitat feature preprocessing implementation and extension” below).Note: In
two_stepanddirect_pooling, subject level must not use column-dropping methods (variance_filter,correlation_filter), or concatenated subjects will have inconsistent columns;two_steprejects such configs at validation.one_stepmay use column-dropping methods at subject level (per-subject clustering).Supported methods and parameters:
winsorize (winsorization):
winsor_limits(list, default:[0.05, 0.05]): lower and upper tail truncation fractions
global_normalize(bool, default:false): global normalization across all features
minmax (min-max normalization):
global_normalize(bool, default:false): global normalization
zscore (Z-score standardization):
global_normalize(bool, default:false): global standardization
robust (robust standardization):
global_normalize(bool, default:false): global normalizationScales using interquartile range (IQR); robust to outliers
log (log transform):
global_normalize(bool, default:false): global transformHandles negative values (shift then log)
variance_filter (low-variance filter):
variance_threshold(float, default:0.0): keep features with variance above thresholdNote: drops feature columns
correlation_filter (high-correlation filter):
corr_threshold(float, default:0.95): drop redundant features when |correlation| exceeds threshold
corr_method(str, default:spearman):pearson/spearman/kendallNote: drops feature columns
Examples:
# Winsorize then normalize - method: winsorize winsor_limits: [0.05, 0.05] global_normalize: true - method: minmax global_normalize: true # Z-score standardization - method: zscore global_normalize: false
preprocessing_for_group_level: Group-level preprocessing (optional)
methods: Preprocessing method listType: list
Required: no
Default:
[]Description: Preprocess features at cohort level; often used for discretization to stabilize clustering.
Applicable modes:
two_stepanddirect_poolingonly;one_steppipeline has no group step—configured group preprocessing has no effect.Supported methods and parameters:
binning (feature discretization / binning):
n_bins(int, default:10): number of bins
bin_strategy(str, default:uniform): binning strategy:
uniform: equal-width bins
quantile: quantile (equal-frequency) bins
kmeans: K-means cluster binning
global_normalize(bool, default:false): global binning across features
winsorize (winsorization):
winsor_limits(list, default:[0.05, 0.05]): lower and upper tail truncation fractions
global_normalize(bool, default:false): global normalization
minmax / zscore / robust / log:
Same as
preprocessing_for_subject_level, applied after group aggregation
variance_filter / correlation_filter (recommended at group level):
Column dropping for unsupervised feature selection; reduces noise and redundancy
variance_filterparameter:variance_threshold
correlation_filterparameters:corr_threshold,corr_methodRecommendation: fit column set during training; reuse same columns at prediction
Examples:
# Uniform binning (recommended for habitat analysis) - method: binning n_bins: 10 bin_strategy: uniform global_normalize: false # Quantile binning (equal frequency) - method: binning n_bins: 20 bin_strategy: quantile global_normalize: false
YAML structure essentials
preprocessing_for_*_level must contain a single methods: key whose value is a list; do not duplicate methods: or place list items outside the methods: block:
# Correct
preprocessing_for_group_level:
methods:
- method: winsorize
winsor_limits: [0.05, 0.05]
- method: variance_filter
variance_threshold: 0.0
# Wrong: duplicate methods key; variance_filter not in list
preprocessing_for_group_level:
methods:
- method: winsorize
methods:
- method: variance_filter
Preprocessing activation matrix by clustering_mode
Preprocessing block |
one_step |
two_step |
direct_pooling |
|---|---|---|---|
|
active |
active ( |
active |
|
inactive |
active (Stage 2 group level) |
active (after pooling, group level) |
Recommended pipeline (train → predict reuse)
two_step / direct_pooling (train): subject-level
winsorize+minmax(orzscore) → group-levelbinning(discretization aids clustering) → optionalvariance_filter/correlation_filter(column-dropping;fitcaches column set during training).two_step / direct_pooling (predict): same
methodsorder as training;PreprocessingStateloaded fromhabitat_pipeline.pkl—do not change thresholds on column-dropping methods to avoid column mismatch.one_step: configure
preprocessing_for_subject_levelonly; group block is ignored.
Habitat feature preprocessing implementation and extension
Unified interface: Built-in and custom methods implement
BaseFeaturePreprocessing, registered via@PreprocessingMethodFactory.register.Execution path:
preprocessing_for_subject_level→ stateless subject-levelapply_stateless_preprocessing;preprocessing_for_group_level→PreprocessingState.fit/transform(training cachesbaselineand per-stepstep_states; prediction reuses).Column-dropping methods:
variance_filter,correlation_filtersetchanges_columns=True;two_stepforbids them at subject level (see note above).Adding a method:
See
habit/core/habitat_analysis/feature_preprocessing/custom_preprocessing_template.pyRegister the method name in
habit/core/schemas/workflows/habitat.py(PreprocessingMethod.methodLiteral) or rely on schema extension hooks documented in Extension and Plugin GuideIf column-dropping, update
DROPPING_PREPROCESSING_METHODSEnsure module import so registration decorator runs
Compatibility: YAML format unchanged; legacy
habitat_pipeline.pklwith pre-refactorPreprocessingStaterequires re-train.
habitat_segmentation: Habitat segmentation settings
Type: object
Required: required in
train; recommended inpredict(at leastclustering_mode)Default:
null(if fully omitted, Pydantic usesHabitatSegmentationConfigdefault sub-blocks; see table below)clustering_mode: Clustering strategyType: string
Required: no
Default:
two_stepAllowed values:
one_step: cluster voxels directly.two_step: build supervoxels first, then cluster supervoxels into habitats.direct_pooling: pool voxels across all subjects then cluster (compute-heavy).
Example:
two_step
supervoxel: Supervoxel clustering settings
Applicable modes:
two_step: this block configures per-subject voxel → supervoxel clustering (algorithm,n_clusters, etc.).one_step:algorithmandone_step_settingsfor per-subject voxel → habitat;n_clustersoverridden when auto-selecting k.direct_pooling: supervoxel block not used for clustering (schema defaults may remain).
algorithm: Clustering or segmentation algorithmType: string
Default:
kmeansAllowed values (aligned with
SupervoxelClusteringConfig):kmeans: K-means; clusters by feature vectors only—supervoxels may be spatially scattered.gmm: Gaussian mixture; underlying defaultcovariance_type='full';SupervoxelClusteringConfigdoes not expose this field—YAML may ignore it.slic: SLIC superpixels; joint multi-channel features and 3D coordinates for spatially compact supervoxels. Dedicated parameters (compactness/sigma/enforce_connectivityand tuning) see habitat_segmentation.supervoxel — SLIC Superpixel Configuration below.
n_clusters: Supervoxel count (or SLICn_segments)Type: integer
Default:
50Description:
two_step: fixed supervoxel count per subject; must be less than ROI voxel count. Typical 30–100; small ROI 20–30.one_stepwith emptyfixed_n_clusters: upper bound for auto k search (seeone_step_settings.max_clusters), not the final fixed value.
random_state: Random seedType: integer or
nullDefault:
null(inheritsHabitatAnalysisConfig.random_state)
max_iter: Maximum iterationsType: integer
Default:
300Description:
kmeans/gmm: sklearn max iterations;slicdiffers—see habitat_segmentation.supervoxel — SLIC Superpixel Configuration.
n_init: Number of initializationsType: integer
Default:
10Description:
kmeans/gmm: sklearnn_init;slic: only inone_stepauto k—see habitat_segmentation.supervoxel — SLIC Superpixel Configuration.
compactness/sigma/enforce_connectivity: active only whenalgorithm: slic—see habitat_segmentation.supervoxel — SLIC Superpixel Configuration.one_step_settings: Nested one-step auto cluster count (see one_step_settings below). Not used for per-subject supervoxel clustering in ``two_step`` (two-step always uses fixedn_clusters).Full example (K-Means supervoxels):
supervoxel: algorithm: kmeans n_clusters: 50 random_state: 42 max_iter: 300 n_init: 10
habitat_segmentation.supervoxel — SLIC Superpixel Configuration
When habitat_segmentation.supervoxel.algorithm: slic, habit calls
skimage.segmentation.slic inside the ROI, jointly segmenting multi-channel voxel features
(last dimension = feature channel) with 3D spatial coordinates into n_clusters supervoxels. Anisotropic voxel spacing spacing
is read automatically from the mask NIfTI header—no YAML entry required.
Use cases
Recommended for
two_stepstage 1: supervoxels are more spatially compact than pure K-Means supervoxels.one_stepmay also useslicwithone_step_settingsfor per-subject auto k.High-dimensional
voxel_radiomicsfeatures incur much higher compute and memory thanraw/mean_voxel_features(builds[Z, Y, X, n_features]feature volume in ROI bbox).
YAML path: keys under habitat_segmentation.supervoxel; repo template
config/habitat/config_habitat_two_step_supervoxel_slic.yaml.
Parameter reference
n_clusters: Target supervoxel count (n_segments)Default:
50(shared withsupervoxelblock)Tuning: small ROI 20–30; finer texture 60–100; must be less than total ROI voxels.
compactness: Balance between feature similarity and spatial compactnessType: float
Default:
0.1Description: Passed to
skimage.segmentation.slic. Features are usually winsorized / minmax-normalized before SLIC, so 0.1 is a reasonable start (different scale from large compactness values common on RGB images).Tuning:
Increase (
0.15–0.3): more spatial grouping, smoother boundaries, fewer fragments.Decrease (
0.05): follows feature differences more closely; boundaries track intensity/texture change but may fragment.
sigma: Gaussian smoothing width before SLICType: float
Default:
0.0(no smoothing)Description: Gaussian smooth on multi-channel feature volume inside ROI before segmentation; units are voxels (with auto
spacingfor anisotropy). Suppresses high-frequency noise in voxel/texture features; does not replace winsorize etc. inpreprocessing_for_subject_level.Tuning:
0.0: sharpest boundaries; use when preprocessing is already strong.0.3–0.5: mild denoising; try first for voxel radiomics (e.g.0.5).> 1.0: may blur real small structures—generally not recommended.
enforce_connectivity: Enforce spatial connectivityType: bool
Default:
trueDescription: When
true, merges isolated small regions to avoid “floating” supervoxels; keep true for medical ROIs.
max_iter: SLIC iteration countType: integer
Schema default:
300(shared field name with kmeans; do not use 300 for SLIC)Recommended:
10(maps tomax_num_iter);15–20possible with diminishing returns.
n_init: Number of initializationsType: integer
Default:
10Description: Only for embedded KMeans in
find_optimal_clustersunderone_step; no effect on SLICfitintwo_step.
random_state: Random seedDefault:
null(inherits top-levelrandom_state); explicit42recommended for reproducibility.
Comparison with K-Means supervoxels
Algorithm |
Advantages |
Caveats |
|---|---|---|
|
Fast; simple |
No spatial adjacency constraint; supervoxels may scatter |
|
Spatially compact supervoxels; good two-step local units |
Slower, more memory with high-dim radiomics; needs mask / coordinates |
Recommended example (two_step supervoxel stage):
habitat_segmentation:
clustering_mode: two_step
supervoxel:
algorithm: slic
n_clusters: 50
compactness: 0.1
sigma: 0.5
enforce_connectivity: true
max_iter: 10
random_state: 42
one_step_settings note: Nested block is one_step only; under two_step, SLIC supervoxel count is fixed by n_clusters—do not rely on one_step_settings for k selection.
one_step_settings: One-step mode settings (one_step only)
min_clusters: Minimum cluster countType: integer
Default:
2Description: Lower bound for automatic selection
max_clusters: Maximum cluster countType: integer
Default:
10Description: Upper bound for automatic selection
fixed_n_clusters: Fixed cluster countType: integer or null
Default:
nullDescription: If set, skips auto selection and uses this value.
selection_method: Auto-selection metricType: string
Default:
elbowAllowed values and meaning:
elbow: elbow on inertia curve (default)silhouette: silhouette coefficient (-1 to 1; closer to 1 = tighter clusters)calinski_harabasz: Calinski-Harabasz index (higher = better)davies_bouldin: Davies-Bouldin index (lower = better)inertia: within-cluster sum of squares (lower = tighter; Kneedle elbow internally)kneedle: Kneedle on normalized inertia curve (max deviation point)gap: gap statisticaic/bic: information criteria (gmm-oriented)
Recommendation:
elbow(schema default) orsilhouettefor interpretability
plot_validation_curves: Plot validation curvesType: bool
Default:
trueDescription: Plots metrics vs cluster count to interpret auto selection
habitat: Habitat clustering settings
algorithm: Clustering algorithmType: string
Default:
kmeansAllowed values:
kmeans: K-means clusteringgmm: Gaussian mixture model
max_clusters: Maximum habitat countType: integer
Required: no
Default:
10Description: Upper bound when auto-selecting habitat count. Recommended: 5–10.
Example:
10
min_clusters: Minimum habitat countType: integer
Default:
2Description: Lower bound when auto-selecting habitat count.
habitat_cluster_selection_method: Auto-selection metricsType: list or string
Default:
elbow(YAML may use string or single-element list)Allowed values and meaning:
inertia: within-cluster SS (lower better for kmeans; Kneedle internally)kneedle: Kneedle on normalized inertia curvesilhouette: silhouette (-1 to 1; closer to 1 better)calinski_harabasz: Calinski-Harabasz (higher better)davies_bouldin: Davies-Bouldin (lower better)aic: Akaike information criterion (lower better; gmm only)bic: Bayesian information criterion (lower better; gmm only)
Description: Multiple metrics may be specified; system combines them to pick best habitat count.
Example:
[inertia, silhouette]
fixed_n_clusters: Fixed habitat countType: integer or null
Default:
nullDescription: If set to a number, skips auto selection and uses that habitat count.
random_state: Random seedType: integer or
nullDefault:
null(inheritsHabitatAnalysisConfig.random_state)Description: direct_pooling / two_step group habitat clustering; one_step per-subject voxel→habitat (overrides
supervoxel.random_statewhen set explicitly).
max_iter: Maximum iterationsType: integer
Default:
300(bothkmeansandgmminHabitatClusteringConfig)
n_init: Number of initializationsType: integer
Default:
10(bothkmeansandgmm)
Full examples:
# Auto-select habitat count (recommended) habitat: algorithm: kmeans max_clusters: 10 min_clusters: 2 habitat_cluster_selection_method: - inertia - silhouette fixed_n_clusters: null random_state: 42 # Fixed habitat count habitat: algorithm: kmeans fixed_n_clusters: 5 random_state: 42
postprocess_supervoxel / postprocess_habitat: Connected-component postprocessing
Type: dict
Required: no
Default:
enabled: falseDescription:
postprocess_supervoxelapplies to supervoxel label maps (mainly two_step stage).postprocess_habitatapplies to final habitat label maps (one_step/two_step/direct_pooling).Current implementation uses SimpleITK fast path: remove small components per label, then reassign by nearest seed label.
Reduces fragmentation while preserving ROI voxel coverage.
Sub-parameters (aligned with
ConnectedComponentPostprocessConfig):enabled(bool, default:false)min_component_size(int, default:30, ≥1)connectivity(1 / 2 / 3): 6/18/26-neighborreassign_method: currently onlyneighbor_vote(placeholder)max_iterations(int, default3, ≥1): cleanup iteration cap
Example:
habitat_segmentation: postprocess_supervoxel: enabled: false min_component_size: 30 connectivity: 1 reassign_method: neighbor_vote max_iterations: 3 postprocess_habitat: enabled: true min_component_size: 30 connectivity: 1 reassign_method: neighbor_vote max_iterations: 3
plot_curves: Generate and save plots
Type: bool
Default:
trueDescription: During group clustering auto k search, if a logger is passed, logs
Trying N cluster(s) [i/total]andCluster search finished: selected k=...for progress (forced off inpredictmode).
Habitat Stage-1 Parallelism and Checkpoint Resume (Top-Level Field Reference)
These fields sit at the top level of the habitat YAML (same level as data_dir). Both train and predict use processes, checkpoint paths, and resume where applicable (predict checkpoints default to <out_dir>/.habitat_predict_checkpoint). CLI: habit get-habitat --resume.
Field |
Type |
Default |
config_hash |
Summary |
|---|---|---|---|---|
|
int |
|
no |
Stage 1 max parallel workers; peak memory ≈ |
|
bool |
|
no |
Torch CUDA radiomics: |
|
float / |
|
no |
Per-subject wall-clock cap (seconds); |
|
float |
|
no |
Seconds to wait after |
|
float / |
|
no |
Spawn-phase cap; |
|
str |
|
no |
|
|
bool |
|
no |
After |
|
int |
|
no |
Workers removed per OOM event |
|
bool |
|
— |
Skip completed subjects from checkpoint; |
|
str / |
|
no |
Default |
|
list[str] |
|
no |
Subject IDs to force rerun on resume |
|
bool |
|
no |
On next |
|
int |
|
no |
In-run Stage 1 auto-retry rounds; |
|
str |
|
no |
|
|
int |
|
no |
Under |
|
int |
|
no |
Under |
|
bool |
|
no |
Delete checkpoint dir after full train success |
processes (habitat analysis top level): Parallel workers for per-subject steps
Type: integer
Default:
2(must be> 0)Description: See table above; interacts with
cap_processes_to_gpu_poolandtorch_gpusinfeature_construction.*.params.
cap_processes_to_gpu_pool (habitat analysis top level): Cap Stage 1 workers to GPU pool size
Type: bool
Default:
trueDescription: When
use_torch_radiomicsuses CUDA (trueorautowith CUDA detected):true(default): effective workersmin(processes, len(torch_gpus)), one GPU per slot (gpu_slot_index), less VRAM contention;false: fullprocesses; workers share GPUs viagpu_slot_index % len(torch_gpus)—good for “single GPU, many CPU” parallel non-GPU steps, but GPU radiomics may OOM on same card.
Not in config_hash; may change on resume.
No effect on CPU-only (
use_torch_radiomics: falseor no CUDA).
individual_subject_timeout_sec (habitat analysis top level): Per-subject wall-clock cap in parallel Stage 1
Type: float / int (seconds) or
nullDefault:
900(15 minutes); omit in YAML to use default.Description: On timeout, skip subject (record failure) and continue;
nulldisables per-subject timeout. Child processes may still run in background until they exit.
individual_subject_graceful_shutdown_sec (habitat analysis top level): Grace period after timeout before kill
Type: float (seconds)
Default:
15Description: After
individual_subject_timeout_sec, parent callsterminate(), waits this many seconds, thenkill()on isolated child.
individual_subject_spawn_timeout_sec (habitat analysis top level): Spawn-phase wall-clock cap
Type: float / int (seconds) or
nullDefault:
120Description: Cap from dispatch to subject processing start; on timeout, mark subject failed and continue—avoids parent blocked forever on spawn/import.
null= no spawn time limit.
on_subject_failure (habitat analysis top level): Failure policy for parallel per-subject Stage 1
Type: string
Default:
continueAllowed values:
continue: record failed subjects; continue to Stage 2 if any succeededfail_fast: abort entire run on first failure or timeout
oom_backoff (habitat analysis top level): Reduce parallelism after memory errors
Type: bool
Default:
true(built-in default); repoconfig/habitat/*.yamlexamples often usefalse—tune for your RAMDescription: When
true, isolated childMemoryErrorreduces worker count for pending subjects byoom_reduce_workers_by(minimum 1). Does not handle native crashes (e.g. Windows exit3221225477/0xC0000005).
oom_reduce_workers_by (habitat analysis top level): Workers removed per OOM
Type: integer
Default:
1Description: Only when
oom_backoff: true.
resume (habitat analysis top level): Stage 1 checkpoint resume
Type: bool
Default:
trueDescription: When
true, readsmanifest.jsonfromcheckpoint_dir(default<out_dir>/.habitat_checkpointfor train,<out_dir>/.habitat_predict_checkpointfor predict), skipscompleted_subjects, loads per-subject pickles; subjects infailed_subjectsare not auto-retried on nextresumeunlessretry_failed_subjects: trueor listed inforce_rerun_subjects. Within the same run,individual_subject_auto_retry_roundsretries Stage 1 failures by default. Applies to bothtrainandpredict.CLI:
habit get-habitat --resumeequivalent toresume: true.See also: checkpoint /
resumefields on this page.Parallel reliability plan:
docs/HABITAT_PARALLEL_RELIABILITY_PLAN.mdat repo root (GPU worker slots, processes cap, Phase 2/3 roadmap).
strict_checkpoint_hash (habitat analysis top level): Error on incompatible checkpoint hash
Type: bool
Default:
falseDescription: With
resume: true. Whentrue,manifest.jsonconfig_hashorrun_modemismatch raisesCheckpointConfigHashErrorand preserves checkpoint; whenfalse(default), logs warning and deletes checkpoint for fresh run. Legacy hash migration for Stage-2-only changes still allows resume.Not in config_hash; may change on resume.
checkpoint_dir (habitat analysis top level): Checkpoint root directory
Type: string or
nullDefault:
null(train→<out_dir>/.habitat_checkpoint;predict→<out_dir>/.habitat_predict_checkpoint)Description: Must match previous run for resume; may differ from
out_dirwhen set explicitly.
force_rerun_subjects (habitat analysis top level): Subject IDs to force rerun
Type: list of strings
Default:
[]Description: With
resume: true, still reprocess listed subjects (removed from completed/failed and rerun).
retry_failed_subjects (habitat analysis top level): Rerun all failed subjects from checkpoint
Type: bool
Default:
falseDescription: With
resume: true, enqueue allfailed_subjectsfrommanifest.jsonfor Stage 1 rerun. Successful subjects still skipped unless also inforce_rerun_subjects.
individual_subject_auto_retry_rounds (habitat analysis top level): In-run auto-retry for failed subjects
Type: integer
Default:
2Description: After first Stage 1 parallel pass, if
failed_subjectsremain, rerun up to this many rounds in the same process (failed only).0disables (legacy behavior). Unlikeretry_failed_subjects(next resume only), this applies in the currentget-habitat/fit()call. Withon_subject_failure: fail_fast, error only after all retry rounds exhausted.
individual_subject_parallel_mode (habitat analysis top level): Stage 1 parallel execution strategy
Type: string
Default:
persistentAllowed values:
isolated,persistentDescription:
persistent(default): one long-lived child per worker slot, reused within the same run (including auto-retry rounds), amortizing import/spawn.isolated: spawn per subject (stronger isolation; unpickleable pipeline or spawn debugging). Single GPU persistent is still serial—main benefit is startup cost. Whenprocesses=1andindividual_subject_timeout_sec: null, both modes run sequentially in main process without spawn. Used in bothtrainandpredictindividual-level stages.
persistent_worker_max_consecutive_failures (habitat analysis top level): Persistent worker restart threshold
Type: integer
Default:
1Description: Only when
individual_subject_parallel_mode: persistent. After this many consecutive failures on a slot, parent terminates and restarts that worker.
persistent_worker_recycle_after_tasks (habitat analysis top level): Periodic persistent worker recycle
Type: integer
Default:
0Description:
persistentonly. Worker exits after this many successful tasks and parent respawns—mitigates slow GPU memory leaks.0disables.
clear_checkpoint_on_success (habitat analysis top level): Delete checkpoint after successful train
Type: bool
Default:
falseDescription: When
true, deletes entire checkpoint directory after Stage 1 + Stage 2 complete successfully.
config_hash and resume compatibility
In hash (Stage 1 per-subject; change clears checkpoint):
data_dir,feature_construction.voxel_level/preprocessing_for_subject_level/supervoxel_level,habitat_segmentation.clustering_mode, per-subject clustering block (two_step→supervoxel;one_step→supervoxel+habitat).Not in hash (may
resume: true):preprocessing_for_group_level, grouphabitat.*fortwo_step/direct_pooling,processes,cap_processes_to_gpu_pool,strict_checkpoint_hash,individual_subject_timeout_sec,individual_subject_graceful_shutdown_sec,individual_subject_spawn_timeout_sec,plot_curves,save_results_csv,habitats_results_format,save_images,verbose,debug,on_subject_failure,oom_backoff,oom_reduce_workers_by,retry_failed_subjects,individual_subject_auto_retry_rounds,individual_subject_parallel_mode,persistent_worker_max_consecutive_failures,persistent_worker_recycle_after_tasks,force_rerun_subjects,out_dir, etc.manifest.jsonalso storesindividual_config_hash(same asconfig_hash); legacy full-hash-only manifests migrate hash on Stage 2-only changes and keep pkls.On
resume: truestartup, program compares hash. Individual hash mismatch without Stage 2 drift: default (strict_checkpoint_hash: false) warns and deletes checkpoint;trueraisesCheckpointConfigHashError.
Checkpoint directory layout
<checkpoint_dir>/
├── manifest.json # completed_subjects, failed_subjects, config_hash, individual_config_hash, stage
└── subjects/
└── {subject_id}.pkl
Checkpoint boundaries by clustering_mode
two_step/one_step: saved aftermerge_supervoxel_features(supervoxel_df)direct_pooling: saved afterindividual_preprocessing(voxel-levelfeatures; larger pkls)Stage 2 (combine / concat / group clustering) has no checkpoint
save_results_csv: Save habitat results table
Type: bool
Default:
trueDescription: When
true, writeshabitats.parquet(default) orhabitats.csvperhabitats_results_format.
habitats_results_format: Habitat results table file format
Type: string
Default:
parquetAllowed values:
parquet,csvDescription:
parquetsmaller and faster—good for largedirect_poolingvoxel tables;csvopens in Excel. Output filename ishabitats.parquetorhabitats.csv.Example:
save_results_csv: true habitats_results_format: parquet
random_state (habitat analysis top level)
Type: integer
Default:
42
debug (habitat analysis top level)
Type: bool
Default:
false
habitat_pipeline.pkl (training artifact at <out_dir>/habitat_pipeline.pkl)
Contents: joblib-serialized fitted
HabitatPipeline(group clustering model,PreprocessingState, config, etc.).Auto slimming on save (
HabitatPipeline.save()callsprepare_pipeline_for_save):Removes training
labels_(prediction needs centers/model params only)Does not write
mask_info_cache(NRRD write loads mask fromdata_diron demand viaFeatureService.load_mask_info)Does not write
_train_checkpoint(checkpoints remain incheckpoint_dir)
Size:
No longer inflated by
save_images: true: mask volume decoupled from pkl;direct_poolinglarge queues typically tens to hundreds of MB (mainly feature dimension and model params vs subject count)Legacy pkls embedding
mask_arrayneed re-train and save to shrink
save_images: Save image outputs from the run (*_habitats.nrrd, etc.)
Type: bool
Default:
trueDescription: Maps to
HabitatAnalysisConfig.save_images. Whentrue, train/predict write habitat label maps; masks load fromconfig.data_dirat write time—not stored inhabitat_pipeline.pkl. Whenfalse, downstream analysis viahabitats.parquet/habitats.csvwithout NRRD output.
verbose: Verbose run logging
Type: bool
Default:
true