Skip to content

HSMM

Duration laws, HiddenSemiMarkovModel and select_states. A duration law (DurationLaw) is one of the four classes below. The methods match HiddenMarkovModel. See the guide.

Geometric

Geometric duration p (1 - p)^(u - 1) on u = 1, 2, ...: the duration an HMM implies.

Parameters:

Name Type Description Default
p float

0 < p <= 1.

required
frozen bool

Keep the law fixed while fitting.

False

Raises:

Type Description
InvalidInput

When a parameter is outside its range.

Examples:

>>> g = tg.Geometric(0.25)
>>> np.round(g.pmf(4), 4)
array([0.3657, 0.2743, 0.2057, 0.1543])
>>> round(g.mean(1000), 6)
4.0
>>> tg.Geometric.from_json(g.to_json()) == g
True

p property

p: float

Probability of ending the run at each step.

frozen property

frozen: bool

Whether the parameters stay fixed while fitting.

pmf

pmf(max_duration: int) -> NDArray[np.float64]

Probabilities of durations 1..=max_duration, renormalised on that support.

Parameters

max_duration : int Longest duration, at least 1.

Returns

numpy.ndarray (max_duration,) probabilities summing to 1.

Raises

InvalidInput When max_duration is 0 or the law has no mass on the support.

mean

mean(max_duration: int) -> float

Mean duration of the law truncated to 1..=max_duration.

Parameters

max_duration : int Longest duration, at least 1.

Returns

float

Raises

InvalidInput When max_duration is 0 or the law has no mass on the support.

to_json

to_json() -> str

JSON text of this object; from_json reads it back.

Returns

str

from_json staticmethod

from_json(text: str) -> Geometric

An object of this class from the text written by to_json.

Parameters

text : str

Returns

object Of this class.

Raises

InvalidInput When text is not JSON of this class or describes an invalid object.

ShiftedPoisson

Shifted Poisson duration e^-rate rate^(u-1) / (u-1)! on u = 1, 2, ....

Parameters:

Name Type Description Default
rate float

rate >= 0; the mean is 1 + rate.

required
frozen bool
False

Raises:

Type Description
InvalidInput

When a parameter is outside its range.

Examples:

>>> d = tg.ShiftedPoisson(2.0)
>>> np.round(d.pmf(4), 4)
array([0.1579, 0.3158, 0.3158, 0.2105])
>>> round(d.mean(100), 6)
3.0
>>> tg.ShiftedPoisson.from_json(d.to_json()) == d
True

rate property

rate: float

Rate of the shifted law; the mean duration is 1 + rate.

frozen property

frozen: bool

Whether the parameters stay fixed while fitting.

pmf

pmf(max_duration: int) -> NDArray[np.float64]

Probabilities of durations 1..=max_duration, renormalised on that support.

Parameters

max_duration : int Longest duration, at least 1.

Returns

numpy.ndarray (max_duration,) probabilities summing to 1.

Raises

InvalidInput When max_duration is 0 or the law has no mass on the support.

mean

mean(max_duration: int) -> float

Mean duration of the law truncated to 1..=max_duration.

Parameters

max_duration : int Longest duration, at least 1.

Returns

float

Raises

InvalidInput When max_duration is 0 or the law has no mass on the support.

to_json

to_json() -> str

JSON text of this object; from_json reads it back.

Returns

str

from_json staticmethod

from_json(text: str) -> ShiftedPoisson

An object of this class from the text written by to_json.

Parameters

text : str

Returns

object Of this class.

Raises

InvalidInput When text is not JSON of this class or describes an invalid object.

NegativeBinomial

Shifted negative binomial duration C(u + r - 2, u - 1) p^r (1 - p)^(u - 1).

Parameters:

Name Type Description Default
r float

r > 0.

required
p float

0 < p <= 1.

required
frozen bool
False

Raises:

Type Description
InvalidInput

When a parameter is outside its range.

Examples:

>>> d = tg.NegativeBinomial(2.0, 0.5)
>>> np.round(d.pmf(3), 4)
array([0.3636, 0.3636, 0.2727])
>>> round(d.mean(1000), 6)
3.0
>>> tg.NegativeBinomial.from_json(d.to_json()) == d
True

r property

r: float

Shape r > 0.

p property

p: float

Success probability 0 < p <= 1.

frozen property

frozen: bool

Whether the parameters stay fixed while fitting.

pmf

pmf(max_duration: int) -> NDArray[np.float64]

Probabilities of durations 1..=max_duration, renormalised on that support.

Parameters

max_duration : int Longest duration, at least 1.

Returns

numpy.ndarray (max_duration,) probabilities summing to 1.

Raises

InvalidInput When max_duration is 0 or the law has no mass on the support.

mean

mean(max_duration: int) -> float

Mean duration of the law truncated to 1..=max_duration.

Parameters

max_duration : int Longest duration, at least 1.

Returns

float

Raises

InvalidInput When max_duration is 0 or the law has no mass on the support.

to_json

to_json() -> str

JSON text of this object; from_json reads it back.

Returns

str

from_json staticmethod

from_json(text: str) -> NegativeBinomial

An object of this class from the text written by to_json.

Parameters

text : str

Returns

object Of this class.

Raises

InvalidInput When text is not JSON of this class or describes an invalid object.

EmpiricalDuration

Empirical duration: pmf[u - 1] on u = 1..len(pmf).

Parameters:

Name Type Description Default
pmf array_like

Non-negative weights, renormalised.

required
pseudocount float

Added to every duration count in the M-step.

0.0
frozen bool
False

Raises:

Type Description
InvalidInput

When a parameter is outside its range.

Examples:

>>> d = tg.EmpiricalDuration([1.0, 2.0, 1.0])
>>> d.pmf(3)
array([0.25, 0.5 , 0.25])
>>> d.mean(3)
2.0
>>> tg.EmpiricalDuration.from_json(d.to_json()) == d
True

pseudocount property

pseudocount: float

Count added to every symbol or duration count in the M-step.

frozen property

frozen: bool

Whether the parameters stay fixed while fitting.

pmf

pmf(max_duration: int) -> NDArray[np.float64]

Probabilities of durations 1..=max_duration, renormalised on that support.

Parameters

max_duration : int Longest duration, at least 1.

Returns

numpy.ndarray (max_duration,) probabilities summing to 1.

Raises

InvalidInput When max_duration is 0 or the law has no mass on the support.

mean

mean(max_duration: int) -> float

Mean duration of the law truncated to 1..=max_duration.

Parameters

max_duration : int Longest duration, at least 1.

Returns

float

Raises

InvalidInput When max_duration is 0 or the law has no mass on the support.

to_json

to_json() -> str

JSON text of this object; from_json reads it back.

Returns

str

from_json staticmethod

from_json(text: str) -> EmpiricalDuration

An object of this class from the text written by to_json.

Parameters

text : str

Returns

object Of this class.

Raises

InvalidInput When text is not JSON of this class or describes an invalid object.

HiddenSemiMarkovModel

Hidden semi-Markov model: an HMM whose states last an explicit number of steps (bed thickness), with right-censored first and last segments.

Parameters:

Name Type Description Default
distributions int or sequence of distributions

The number of states, or one emission object per state.

required
durations sequence of duration laws

One Geometric, ShiftedPoisson, NegativeBinomial or EmpiricalDuration per state.

None
start array_like

Start probabilities and a transition matrix with a zero diagonal.

None
transition array_like

Start probabilities and a transition matrix with a zero diagonal.

None
duration (geometric, poisson, negative_binomial, empirical)

Duration family fitted when durations is not given.

"geometric"
max_duration int, sequence of int or None

Longest duration per state; None means the longest sequence (no truncation). The forward-backward time grows with T * K * max_duration, so None makes it quadratic in the longest length T; on long logs give a cap and check truncated_mass.

None
params str

Letters of the parts fitted and initialised: s start, t transition, e emissions, d durations.

'sted'
init_params str

Letters of the parts fitted and initialised: s start, t transition, e emissions, d durations.

None
emission Literal['gaussian', 'categorical', 'poisson', 'mixture']

As in HiddenMarkovModel.

'gaussian'
covariance_type Literal['full', 'diag', 'spherical']

As in HiddenMarkovModel.

'diag'
n_symbols int | None

As in HiddenMarkovModel.

None
n_mix int

As in HiddenMarkovModel.

1
max_iter int

As in HiddenMarkovModel.

100
tol float

As in HiddenMarkovModel.

1e-06
n_init int

As in HiddenMarkovModel.

1
seed int

As in HiddenMarkovModel.

0
start_prior float

As in HiddenMarkovModel.

1.0
transition_prior float

As in HiddenMarkovModel.

1.0
covariance_prior float

As in HiddenMarkovModel.

1e-06
pseudocount float

As in HiddenMarkovModel.

0.0
direction Literal['up', 'down']

As in HiddenMarkovModel.

'up'
ordering Literal['none', 'mean', 'occupancy']

As in HiddenMarkovModel.

'none'

Raises:

Type Description
InvalidInput

When an option is unknown, the given parts disagree in their number of states, a transition diagonal is not zero, or seed is out of range.

Examples:

>>> truth = tg.HiddenSemiMarkovModel(
...     [tg.Gaussian([0.0], 1.0), tg.Gaussian([5.0], 1.0)],
...     [tg.ShiftedPoisson(6.0), tg.ShiftedPoisson(3.0)],
...     start=[0.5, 0.5], transition=[[0.0, 1.0], [1.0, 0.0]], max_duration=30)
>>> states, logs = truth.sample([150, 150], seed=1)
>>> hsmm = tg.HiddenSemiMarkovModel(2, duration="poisson", max_duration=30, ordering="mean", seed=1)
>>> hsmm = hsmm.fit(logs)
>>> hsmm.n_states, [type(d).__name__ for d in hsmm.durations]
(2, ['ShiftedPoisson', 'ShiftedPoisson'])
>>> found = np.concatenate(hsmm.predict(logs))
>>> bool(np.mean(found == np.concatenate(states)) > 0.95)
True
>>> hsmm.predict_proba(logs)[0].shape
(150, 2)
>>> paths, log_p = hsmm.viterbi(logs)
>>> hsmm.score_samples(logs).shape
(2,)
>>> bool(hsmm.score(logs) < 0 and hsmm.aic(logs) < hsmm.bic(logs) <= hsmm.icl(logs))
True
>>> hsmm.sample_posterior(logs[0], n=2, seed=2).shape
(2, 150)
>>> sim_states, sim_logs = hsmm.sample([50], seed=3)
>>> hmm = tg.HiddenMarkovModel(2, seed=1).fit(logs)
>>> tg.HiddenSemiMarkovModel.from_hmm(hmm, max_duration=30).n_states
2
>>> tg.HiddenSemiMarkovModel.from_json(hsmm.to_json()) == hsmm
True

durations property

durations: list[DurationLaw]

Duration law of each state: Geometric, ShiftedPoisson, NegativeBinomial or EmpiricalDuration.

max_duration property

max_duration: NDArray[int64]

Longest duration per state in rows, int64 (K,).

truncated_mass property

truncated_mass: NDArray[float64]

Mass of each untruncated duration law above its max_duration.

n_states property

n_states: int

Number of hidden states K.

start property

start: NDArray[float64]

Start probabilities, float64 (K,).

transition property

transition: NDArray[float64]

Transition matrix between segments, float64 (K, K) with a zero diagonal.

distributions property

distributions: list[Distribution]

Emission distribution of each state.

history property

history: NDArray[float64]

Objective (log-likelihood plus log prior) after each EM iteration.

converged property

converged: bool

Whether EM stopped on tol before max_iter.

n_iter property

n_iter: int

Number of EM iterations run.

from_hmm staticmethod

from_hmm(
    hmm: HiddenMarkovModel, *, max_duration: int
) -> HiddenSemiMarkovModel

The HSMM equivalent to hmm: geometric durations with p = 1 - a_jj and the transition matrix renormalised off the diagonal.

Parameters

hmm : HiddenMarkovModel A fitted or fully specified model. max_duration : int Longest duration of every state.

Returns

HiddenSemiMarkovModel

Raises

InvalidInput When hmm is not fitted, max_duration is 0, or a state is absorbing.

fit

fit(
    sequences: Sequences,
    *,
    holes: ArrayLike | str | None = None,
    labels: ArrayLike | str | None = None,
    allowed: ArrayLike | None = None,
    data: Mapping[str, ArrayLike] | None = None,
) -> HiddenSemiMarkovModel

EM fit over all holes, with seeded restarts.

Parameters

sequences : array_like or list of array_like Observations, rows top-down by depth: one array per hole, or one array split by holes. holes : array_like, optional Hole identifier per row of a single sequences array. data : mapping, optional Table whose columns sequences and holes name. labels : array_like, optional Known state per row (-1 where unknown); the posterior is clamped to it. allowed : array_like, optional Boolean (rows, K) mask of the states each row may take.

Returns

HiddenSemiMarkovModel This model, fitted.

Raises

InvalidInput When the sequences do not match the emissions or labels and allowed leave a row no state. ConvergenceError When every restart degenerates.

score

score(
    sequences: Sequences,
    *,
    holes: ArrayLike | str | None = None,
    data: Mapping[str, ArrayLike] | None = None,
) -> float

Total log-likelihood over holes (unclamped), summed over the segmentations of each hole.

Parameters

sequences : array_like or list of array_like Observations, rows top-down by depth: one array per hole, or one array split by holes. holes : array_like, optional Hole identifier per row of a single sequences array. data : mapping, optional Table whose columns sequences and holes name.

Returns

float Sum of the per-hole log-likelihoods. Raises


InvalidInput When the model is not fitted, or the sequences do not match its emissions.

score_samples

score_samples(
    sequences: Sequences,
    *,
    holes: ArrayLike | str | None = None,
    data: Mapping[str, ArrayLike] | None = None,
) -> NDArray[np.float64]

Log-likelihood of each hole (unclamped).

Parameters

sequences : array_like or list of array_like Observations, rows top-down by depth: one array per hole, or one array split by holes. holes : array_like, optional Hole identifier per row of a single sequences array. data : mapping, optional Table whose columns sequences and holes name.

Returns

numpy.ndarray float64 (n_holes,) in hole order; it sums to score. Raises


InvalidInput When the model is not fitted, or the sequences do not match its emissions.

predict

predict(
    sequences: Sequences,
    *,
    holes: ArrayLike | str | None = None,
    labels: ArrayLike | str | None = None,
    allowed: ArrayLike | None = None,
    data: Mapping[str, ArrayLike] | None = None,
    algorithm: Literal["viterbi", "map"] = "viterbi",
) -> Rows

Most likely states per row.

Parameters

sequences : array_like or list of array_like Observations, rows top-down by depth: one array per hole, or one array split by holes. holes : array_like, optional Hole identifier per row of a single sequences array. data : mapping, optional Table whose columns sequences and holes name. labels : array_like, optional Known state per row (-1 where unknown); the posterior is clamped to it. allowed : array_like, optional Boolean (rows, K) mask of the states each row may take. algorithm : {"viterbi", "map"} Best segmentation, or per-row posterior argmax.

Returns

numpy.ndarray or list of numpy.ndarray int64 states in input row order.

Raises

InvalidInput When the model is not fitted, the sequences do not match its emissions, or algorithm is unknown.

predict_proba

predict_proba(
    sequences: Sequences,
    *,
    holes: ArrayLike | str | None = None,
    labels: ArrayLike | str | None = None,
    allowed: ArrayLike | None = None,
    data: Mapping[str, ArrayLike] | None = None,
) -> Rows

Posterior state probabilities per row, (rows, K), from segment starts and ends.

Parameters

sequences : array_like or list of array_like Observations, rows top-down by depth: one array per hole, or one array split by holes. holes : array_like, optional Hole identifier per row of a single sequences array. data : mapping, optional Table whose columns sequences and holes name. labels : array_like, optional Known state per row (-1 where unknown); the posterior is clamped to it. allowed : array_like, optional Boolean (rows, K) mask of the states each row may take.

Returns

numpy.ndarray or list of numpy.ndarray float64 (rows, K) in input row order, or one (t, K) array per hole when sequences is a list; each row sums to 1. Raises


InvalidInput When the model is not fitted, or the sequences do not match its emissions.

viterbi

viterbi(
    sequences: Sequences,
    *,
    holes: ArrayLike | str | None = None,
    labels: ArrayLike | str | None = None,
    allowed: ArrayLike | None = None,
    data: Mapping[str, ArrayLike] | None = None,
) -> tuple[Rows, NDArray[np.float64]]

Best segmentation per hole and its joint log-probability, durations included.

Parameters

sequences : array_like or list of array_like Observations, rows top-down by depth: one array per hole, or one array split by holes. holes : array_like, optional Hole identifier per row of a single sequences array. data : mapping, optional Table whose columns sequences and holes name. labels : array_like, optional Known state per row (-1 where unknown); the posterior is clamped to it. allowed : array_like, optional Boolean (rows, K) mask of the states each row may take.

Returns

tuple of (numpy.ndarray or list of numpy.ndarray, numpy.ndarray) int64 states in input row order (a list when sequences is a list), and float64 log-probability per hole. Raises


InvalidInput When the model is not fitted, or the sequences do not match its emissions.

sample

sample(
    lengths: int | Sequence[int], *, seed: int = 0
) -> tuple[list[NDArray[np.int64]], list[NDArray]]

Seeded state paths and observations, one per length, rows top-down.

Durations are drawn from the truncated laws; the last segment is cut at the length.

Parameters

lengths : int or sequence of int Rows per simulated hole. seed : int Seed; the same seed gives the same draws for any thread count.

Returns

tuple of (list of numpy.ndarray, list of numpy.ndarray) States (int64) and observations ((t, d); int64 (t,) codes when categorical). Raises


InvalidInput When the model is not fitted, or the sequences do not match its emissions.

sample_posterior

sample_posterior(
    sequences: Sequences,
    *,
    n: int = 100,
    seed: int = 0,
    holes: ArrayLike | str | None = None,
    labels: ArrayLike | str | None = None,
    allowed: ArrayLike | None = None,
    data: Mapping[str, ArrayLike] | None = None,
) -> NDArray[np.int64]

n seeded segmentations drawn from the posterior by forward filtering, backward sampling.

Parameters

sequences : array_like or list of array_like Observations, rows top-down by depth: one array per hole, or one array split by holes. n : int Number of draws. seed : int Seed; draws do not depend on thread count. holes : array_like, optional Hole identifier per row of a single sequences array. data : mapping, optional Table whose columns sequences and holes name. labels : array_like, optional Known state per row (-1 where unknown); the posterior is clamped to it. allowed : array_like, optional Boolean (rows, K) mask of the states each row may take.

Returns

numpy.ndarray int64 (n, rows), columns in input row order. Raises


InvalidInput When the model is not fitted, or the sequences do not match its emissions.

aic

aic(
    sequences: Sequences,
    *,
    holes: ArrayLike | str | None = None,
    data: Mapping[str, ArrayLike] | None = None,
) -> float

Akaike information criterion (lower is better): -2 log L + 2 p.

p counts the free parameters fitted under params, durations included.

Parameters

sequences : array_like or list of array_like Observations, rows top-down by depth: one array per hole, or one array split by holes. holes : array_like, optional Hole identifier per row of a single sequences array. data : mapping, optional Table whose columns sequences and holes name.

Returns

float Raises


InvalidInput When the model is not fitted, or the sequences do not match its emissions.

bic

bic(
    sequences: Sequences,
    *,
    holes: ArrayLike | str | None = None,
    data: Mapping[str, ArrayLike] | None = None,
) -> float

Bayesian information criterion (lower is better): -2 log L + p ln n.

n is the number of rows. Depth samples are autocorrelated, so BIC tends to favour too many states on dense logs.

Parameters

sequences : array_like or list of array_like Observations, rows top-down by depth: one array per hole, or one array split by holes. holes : array_like, optional Hole identifier per row of a single sequences array. data : mapping, optional Table whose columns sequences and holes name.

Returns

float Raises


InvalidInput When the model is not fitted, or the sequences do not match its emissions.

icl

icl(
    sequences: Sequences,
    *,
    holes: ArrayLike | str | None = None,
    data: Mapping[str, ArrayLike] | None = None,
) -> float

Integrated completed likelihood (lower is better): BIC + 2 H.

H is the exact entropy of the segmentation given the data, summed over holes.

Parameters

sequences : array_like or list of array_like Observations, rows top-down by depth: one array per hole, or one array split by holes. holes : array_like, optional Hole identifier per row of a single sequences array. data : mapping, optional Table whose columns sequences and holes name.

Returns

float Raises


InvalidInput When the model is not fitted, or the sequences do not match its emissions.

to_json

to_json() -> str

JSON text of this object; HiddenSemiMarkovModel.from_json reads it back.

Returns

str

from_json staticmethod

from_json(text: str) -> HiddenSemiMarkovModel

HiddenSemiMarkovModel from the text written by to_json.

Parameters

text : str

Returns

HiddenSemiMarkovModel

Raises

InvalidInput When text is not HiddenSemiMarkovModel JSON or describes an invalid HiddenSemiMarkovModel.

select_states builtin

select_states(
    sequences: Sequences,
    *,
    holes: ArrayLike | str | None = None,
    data: Mapping[str, ArrayLike] | None = None,
    labels: ArrayLike | str | None = None,
    allowed: ArrayLike | None = None,
    states: Sequence[int] | None = None,
    model: Literal["hmm", "hsmm"] = "hmm",
    emission: Literal[
        "gaussian", "categorical", "poisson", "mixture"
    ] = "gaussian",
    covariance_type: Literal[
        "full", "diag", "spherical"
    ] = "diag",
    n_symbols: int | None = None,
    n_mix: int = 1,
    duration: Literal[
        "geometric",
        "poisson",
        "negative_binomial",
        "empirical",
    ] = "geometric",
    max_duration: int | None = None,
    cv_folds: int | None = None,
    n_init: int = 5,
    seed: int = 0,
    max_iter: int = 100,
    tol: float = 1e-06,
    direction: Literal["up", "down"] = "up",
) -> dict[str, NDArray]

Fits models with each number of states and tabulates information criteria and cross-validated log-likelihood.

Depth samples are autocorrelated, so BIC tends to favour too many states on dense logs; the cross-validated score is the honest check.

Parameters:

Name Type Description Default
sequences Sequences

As in HiddenMarkovModel.fit.

required
holes Sequences

As in HiddenMarkovModel.fit.

required
data Sequences

As in HiddenMarkovModel.fit.

required
labels ArrayLike | str | None

Clamps; only with a single entry in states.

None
allowed ArrayLike | str | None

Clamps; only with a single entry in states.

None
states sequence of int

Numbers of states to try; None means 1 to 6.

None
model (hmm, hsmm)
"hmm"
emission Literal['gaussian', 'categorical', 'poisson', 'mixture']

Model family, as in the classes.

'gaussian'
covariance_type Literal['gaussian', 'categorical', 'poisson', 'mixture']

Model family, as in the classes.

'gaussian'
n_symbols Literal['gaussian', 'categorical', 'poisson', 'mixture']

Model family, as in the classes.

'gaussian'
n_mix Literal['gaussian', 'categorical', 'poisson', 'mixture']

Model family, as in the classes.

'gaussian'
duration Literal['gaussian', 'categorical', 'poisson', 'mixture']

Model family, as in the classes.

'gaussian'
max_duration Literal['gaussian', 'categorical', 'poisson', 'mixture']

Model family, as in the classes.

'gaussian'
cv_folds int

None leaves one hole out, 0 skips cross-validation, k > 0 uses k seeded folds.

None
n_init int

Fit settings.

5
seed int

Fit settings.

5
max_iter int

Fit settings.

5
tol int

Fit settings.

5
direction int

Fit settings.

5

Returns:

Type Description
dict

states, log_likelihood, n_params, aic, bic, icl, cv_log_likelihood and cv_per_step.

Raises:

Type Description
InvalidInput

When an option is unknown, clamps come with more than one entry in states, or cv_folds exceeds the number of holes.

Examples:

>>> d = tg.datasets.electrofacies_logs()
>>> keep = np.isin(d["HOLE_ID"], ["W01", "W02", "W03", "W04"])
>>> x = np.column_stack([d["GR"], d["RHOB"]])[keep]
>>> table = tg.select_states(x, holes=d["HOLE_ID"][keep], states=[2, 3], n_init=1, cv_folds=0)
>>> table["states"]
array([2, 3])
>>> int(table["states"][np.argmin(table["bic"])])
3