HabitatModel

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 HabitatModel(model_id: str, n_habitats: int, feature_names: Tuple[str, ...], centroids: ndarray, preprocessing_state: Mapping[str, Any], spec_payload: Mapping[str, Any], cohort_fingerprint: CohortFingerprint, provenance: Provenance)[source]

Bases: object

Population-level habitat definition – HABIT’s primary scientific artefact.

In v0.1 this was serialised as an opaque habitat_pipeline.pkl byproduct. Promoting it to a first-class, self-describing object is what enables the strategic goal: a habitat definition published alongside a paper can be loaded by other groups and applied to their own cohorts.

model_id

Stable identifier derived from the specification fingerprint.

Type:

str

n_habitats

Number of habitats this model can assign.

Type:

int

feature_names

Features consumed for assignment, in required order.

Type:

Tuple[str, …]

centroids

Population cluster centres, shape (n_habitats, n_features).

Type:

numpy.ndarray

preprocessing_state

State learned at fit time and required at apply time, e.g. binning edges and normalisation statistics. Keeping this inside the model is what guarantees train/predict consistency.

Type:

Mapping[str, Any]

spec_payload

Serialisable form of the full algorithm specification, so the model can describe itself and be exported back to YAML.

Type:

Mapping[str, Any]

cohort_fingerprint

Non-identifiable description of the defining cohort.

Type:

habit.contracts.subject.CohortFingerprint

provenance

Software, dependency, and seed fingerprint.

Type:

habit.contracts.provenance.Provenance

See also

habit.recipes.Study

Fits and applies this model.

habit.spec.HabitatSpec

Analysis declaration this model encodes.

habit.contracts.HabitatMap

Per-subject label image assigned by this model.

Examples

Models are produced by the habitat recipes and round-trip through a self-describing .habitatmodel archive: >>> from habit.contracts import HabitatModel >>> model = HabitatModel.load(“out/habitat_model.habitatmodel”) # doctest: +SKIP >>> model.n_habitats, model.feature_names # doctest: +SKIP (3, (‘T1’, ‘T2’)) >>> print(model.summary()) # doctest: +SKIP >>> assigner = model.assigner() # doctest: +SKIP

See

meth:habit.recipes.Study.predict (via Study.from_model) for projecting a reloaded model onto new subjects. Prediction inherits the model’s persisted postprocess_habitat; an explicit conflicting declaration raises HABITAPIError.

__post_init__() → None[source]

Validate the centroid matrix against the declared dimensions.

summary() → str[source]

Return a human-readable model card.

Named summary (statsmodels convention) rather than describe, because in scientific Python DataFrame.describe() already returns a statistics table, and this returns prose. Intended for both notebook inspection and inclusion in a manuscript’s supplementary material.

Returns:

Multi-line English description of the model.

with_cohort_preprocessing(state: Mapping[str, Any], spec_payload: Mapping[str, Any]) → HabitatModel[source]

Bind the cohort-level feature preprocessing into this model.

A habitat definition is a set of centroids TOGETHER WITH the feature space they live in. Storing the fitted cohort chain here is what lets the model be applied to a new cohort at all: without it, prediction would compute raw features, compare them against centroids fitted on preprocessed features, and return labels that look entirely reasonable.

The model id is recomputed, because two models whose centroids came from differently preprocessed features are different definitions and must not collide. Provenance is derived rather than replaced, so the chain back to each fitting unit stays intact.

Parameters:
  • state – Fitted chain state, from CohortPreprocessingChain.state.

  • spec_payload – The chain’s specification, recorded alongside the fitter’s so the model card states both.

Returns:

A new model carrying the chain. Callers that need the original still hold it – this contract is frozen.

assigner(name: str = 'nearest_centroid', **params: Any) → Any[source]

Build an assigner that projects this model onto individual subjects.

Assigners take their model at construction time, so this factory is the ordinary way to obtain one and keeps the common case to a single call: labels = model.assigner()(supervoxel_map). The registry import is lazy: the contracts layer must stay importable without the domain layer.

Parameters:
  • name – Registered habitat_assigner implementation name.

  • **params – Parameters for that implementation.

Returns:

A one-argument callable from a supervoxel map to a habitat map.

save(path: str | Path) → Path[source]

Persist the model in a versioned, self-describing format.

Deliberately not a bare pickle: a shared scientific artefact must remain readable across HABIT versions, or fail with an explicit incompatibility message rather than a deserialisation error. The .habitatmodel file is a ZIP archive holding a JSON manifest (format name, format version, producing HABIT version, and every scalar field) plus the centroid matrix as a .npy member.

Parameters:

path – Destination file path.

Returns:

The written path.

classmethod load(path: str | Path) → HabitatModel[source]

Load a model previously written by save().

Parameters:

path – Source file path.

Returns:

The reconstructed model.

Raises:

CompatibilityError – If the file was produced by an incompatible format or HABIT version, with guidance on which version can read it.

__init__(model_id: str, n_habitats: int, feature_names: Tuple[str, ...], centroids: ndarray, preprocessing_state: Mapping[str, Any], spec_payload: Mapping[str, Any], cohort_fingerprint: CohortFingerprint, provenance: Provenance) → None

Examples using habit.contracts.HabitatModel

Quickstart: Python API

Quickstart: Python API