HabitatSpec

Note

This page is a reference documentation. It only explains the class signature, and not how to use it. Please refer to the Habitat Guide and Python API guide (v2.0) for usage.

class HabitatSpec(name: str, voxel_feature_extractor: Spec | None = None, supervoxelizer: Spec | None = None, habitat_model_fitter: Spec | None = None, habitat_assigner: Spec | None = None, supervoxel_feature_extractor: Spec | None = None, habitat_features: Tuple[Spec, ...] = (), voxel_feature_preprocessors: Tuple[Spec, ...] = (), supervoxel_feature_preprocessors: Tuple[Spec, ...] = (), cohort_feature_preprocessors: Tuple[Spec, ...] = (), random_seed: int | None = None, on_geometry_mismatch: str = 'resample_mask', pooling: str | None = None, stages: Tuple[Stage, ...] | None = None, postprocess_supervoxel: Spec | None = None, postprocess_habitat: Spec | None = None, version: str = '1.0', _stages_explicit: bool = False, _named_field_compat: bool = False)[source]

Bases: object

Complete specification of a habitat analysis.

A frozen, fingerprintable value object. Author a habitat analysis as an ordered stages list. The named component fields (voxel_feature_extractor, supervoxelizer, pooling, …) are a deprecated constructor kept so historical documents keep their fingerprints. supervoxelizer=None selects the direct clustering designs (one-step / direct-pooling), mirroring the SubjectPipeline contract.

name

Human-readable specification name.

Type:

str

voxel_feature_extractor

Spec of the voxel feature step.

Type:

habit.spec.specs.Spec | None

supervoxelizer

Spec of the supervoxel step, or None.

Type:

habit.spec.specs.Spec | None

supervoxel_feature_extractor

Spec of the step describing the supervoxels, or None to keep the supervoxelizer’s feature means (the v0.1 default).

Type:

habit.spec.specs.Spec | None

habitat_model_fitter

Spec of the cohort-level fitting step.

Type:

habit.spec.specs.Spec | None

habitat_assigner

Spec of the per-subject assignment step.

Type:

habit.spec.specs.Spec | None

habitat_features

Specs of habitat feature families.

Type:

Tuple[habit.spec.specs.Spec, …]

voxel_feature_preprocessors

Ordered method specs of the stateless per-subject chain applied to voxel features BEFORE supervoxelization (v0.1’s preprocessing_for_subject_level).

Type:

Tuple[habit.spec.specs.Spec, …]

supervoxel_feature_preprocessors

Ordered method specs of the stateless per-subject chain applied to supervoxel features. Has no v0.1 equivalent: that version could only preprocess supervoxel features at cohort level, which forced per-supervoxel radiomics through a stateful step it did not need.

Type:

Tuple[habit.spec.specs.Spec, …]

cohort_feature_preprocessors

Ordered method specs of the stateful chain fitted once on the pooled TRAINING units and replayed afterwards (v0.1’s preprocessing_for_group_level). Its fitted state is stored in HabitatModel.preprocessing_state, because a habitat definition is only reproducible together with the feature space it was defined in.

Type:

Tuple[habit.spec.specs.Spec, …]

random_seed

Seed applied to every Seedable component. Seeds change the scientific result, so they live in the spec (and its fingerprint), not in the run policy.

Type:

int | None

on_geometry_mismatch

How to handle image/mask voxel-grid disagreements before Stage-1 extraction. "resample_mask" (default) nearest-neighbour resamples each ROI onto the reference image grid; "strict" raises GeometryError. The default is omitted from to_dict() so historical fingerprints stay stable when the policy is unchanged.

Type:

str

pooling

Cross-subject pooling declaration of the habitat dataflow (deprecated constructor / derived view). Prefer stages with a pool marker. "cohort" pools clustering units across subjects; "none" defines habitats inside each subject (one-step). None (default) means undeclared and resolves to "cohort" for named-field forms without an explicit pool stage; both None and "cohort" are omitted from to_dict() so historical fingerprints stay stable, while "none" is always recorded (with the derived definition_level).

Type:

str | None

stages

Ordered named stages. This is the authoring form for new code. Named component fields remain as a deprecated constructor that normalises to the same internal stage list.

Type:

Tuple[habit.spec.specs.Stage, …] | None

postprocess_supervoxel

Optional Spec for connected-component cleanup of supervoxel label maps (two-step). None skips cleanup and is omitted from to_dict() so historical fingerprints stay stable.

Type:

habit.spec.specs.Spec | None

postprocess_habitat

Optional Spec for connected-component cleanup of final habitat label maps. None skips cleanup and is omitted from to_dict().

Type:

habit.spec.specs.Spec | None

version

Specification schema version.

Type:

str

See also

habit.recipes.Study

Runs this spec via fit / fit_predict.

habit.contracts.HabitatModel

Fitted definition produced from this spec.

habit.recipes.two_step_habitat

Factory that builds a two-step spec.

Examples

A two-step design (supervoxels per subject, habitats across the cohort) declared as an ordered stage list: >>> from habit.spec import HabitatSpec, Spec, Stage >>> spec = HabitatSpec( … name=”habitat_two_step”, … stages=( … Stage(“extract_voxel_features”, Spec(“raw”, {“modalities”: [“T1”, “T2”]})), … Stage(“partition”, Spec(“kmeans”, {“n_supervoxels”: 50, “n_init”: 10})), … Stage(“pool”, Spec(“pool”)), … Stage( … “fit”, … Spec( … “kmeans”, … {“min_habitats”: 2, “max_habitats”: 10, “validation”: “elbow”}, … ), … ), … Stage(“assign”, Spec(“nearest_centroid”)), … Stage(“quantify”, Spec(“volume”)), … Stage(“quantify2”, Spec(“msi”)), … Stage(“quantify3”, Spec(“ith_score”)), … ), … random_seed=42, … ) >>> spec.fingerprint() # doctest: +ELLIPSIS ‘…’ The same document expressed as YAML (version: '1.0' / workflow: habitat) loads with load_habitat_spec(); see config/habitat/config_habitat_two_step_v1.yaml for a complete annotated example.

__post_init__() → None[source]

Coerce component payloads into Spec instances and tuples.

component_specs() → Mapping[str, Spec | None][source]

Return the pipeline component specs keyed by domain name.

property definition_level: str

Level at which the habitat definition is learned, DERIVED from the declared dataflow.

"subject" when there is no pool stage / pooling="none" (each subject defines its own habitats; the one-step design), otherwise "cohort". This is a read-only view of the spec graph, not a free-form field.

Explicit stages lists derive the level from the sequence itself (presence of a pool marker / role). Named-field sugar still treats undeclared pooling as cohort-level.

resolved_stages() → Tuple[Stage, ...][source]

Return the ordered stages (explicit or sugar-expanded).

Sugar expansion is computed here (not stored on stages) so replacing named fields such as pooling rebuilds the sequence.

Returns:

The effective stage tuple used by the executor and fingerprints of explicit-stage specs.

validate_dataflow() → None[source]

Check cross-field / stage-sequence consistency of the dataflow.

Construction (__post_init__()) only enforces value domains so a spec stays a constructible value object; scientifically meaningless combinations are rejected here at entry points (recipes / habit check-config). Role inference that needs registries runs in habit.pipeline.stages and is invoked from Study.fit.

Raises:

HABITAPIError – On illegal sugar combinations or structural stage errors (duplicate names already rejected at construction; partition without pool; subject-level + cohort preprocess).

describe_methods(style: str = 'radiology') → str[source]

Render the specification as a manuscript methods paragraph.

Deliberately the same verb and signature as habit.contracts.manifest.RunManifest.describe_methods(); the difference is completeness, not vocabulary. This describes what was INTENDED and can be read before anything runs – a spec carries no software versions, no executed steps and no excluded subjects, so none are stated. Every configured step appears with its parameters, which is what makes the paragraph useful for preregistration and for checking a YAML against the paper draft before the compute starts.

Parameters:

style – Target venue convention. "radiology" opens with the design sentence; "nature" closes with it. Ordering and wording only – the stated facts are identical.

Returns:

English prose describing every configured step and its parameters.

Raises:

HABITAPIError – On an unknown style.

fingerprint() → str[source]

Return a stable hash identifying this exact specification.

to_dict() → Dict[str, Any][source]

Serialise to a plain dict (YAML isomorphic).

to_effective_dict() → Dict[str, Any][source]

Serialise with fingerprint-stable defaults expanded for YAML export.

Unlike to_dict(), this always includes on_geometry_mismatch, the resolved pooling / stages view with its derived definition_level, and both postprocess slots (null when unset) so a saved document records the full effective analysis, not only overridden fields. Fingerprints still use to_dict().

to_yaml(path: str | Path | None = None) → str[source]

Export the effective specification as YAML text.

This is the Python→YAML half of the Spec/YAML isomorphism for the spec: section. For a runnable document that also carries data / policy / output (so CLI and run_from_yaml() can replay the run), use save_habitat_config().

Parameters:

path – Optional destination file; when set, the YAML is written.

Returns:

The YAML text of to_effective_dict().

classmethod from_dict(payload: Mapping[str, Any]) → HabitatSpec[source]

Rebuild a habitat specification from its dict form.

Parameters:

payload – Mapping as produced by to_dict().

Returns:

The reconstructed specification.

Raises:

HABITAPIError – If a required component is missing.

__init__(name: str, voxel_feature_extractor: Spec | None = None, supervoxelizer: Spec | None = None, habitat_model_fitter: Spec | None = None, habitat_assigner: Spec | None = None, supervoxel_feature_extractor: Spec | None = None, habitat_features: Tuple[Spec, ...] = (), voxel_feature_preprocessors: Tuple[Spec, ...] = (), supervoxel_feature_preprocessors: Tuple[Spec, ...] = (), cohort_feature_preprocessors: Tuple[Spec, ...] = (), random_seed: int | None = None, on_geometry_mismatch: str = 'resample_mask', pooling: str | None = None, stages: Tuple[Stage, ...] | None = None, postprocess_supervoxel: Spec | None = None, postprocess_habitat: Spec | None = None, version: str = '1.0', _stages_explicit: bool = False, _named_field_compat: bool = False) → None

Examples using habit.spec.HabitatSpec

Quickstart: Python API

Quickstart: Python API