Skip to content

HMM

Emission distributions and HiddenMarkovModel. Sequences is a list of arrays (one per hole) or one array with holes=; Rows is a list of arrays or one array, matching the input. See the guide.

Categorical

Categorical emission over symbols 0..m-1.

Parameters:

Name Type Description Default
probabilities array_like

Probability of each symbol, summing to 1.

required
pseudocount float

Added to every symbol count in the M-step.

0.0
frozen bool

Keep the parameters fixed while fitting.

False

Raises:

Type Description
InvalidInput

When the probabilities are negative or do not sum to 1, or pseudocount is negative.

Examples:

>>> c = tg.Categorical([0.7, 0.2, 0.1])
>>> np.round(c.log_density([0, 2, -1]), 4)
array([-0.3567, -2.3026,  0.    ])
>>> c.sample(5, seed=1).shape
(5,)
>>> tg.Categorical.from_json(c.to_json()) == c
True

probabilities property

probabilities: NDArray[float64]

(m,) probability of each symbol.

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.

log_density

log_density(x: ArrayLike) -> NDArray[np.float64]

Log probability of each observation.

Parameters

x : array_like Codes (n,); -1 or NaN for missing gives 0.

Returns

numpy.ndarray (n,) log values.

Raises

InvalidInput When x has the wrong number of channels or invalid values.

sample

sample(n: int, *, seed: int = 0) -> NDArray

Seeded draws from this distribution.

Parameters

n : int Number of draws. seed : int Seed in 0..2**64-1; equal seeds give equal draws.

Returns

numpy.ndarray int64 (n,) codes.

Raises

InvalidInput When seed is out of range.

to_json

to_json() -> str

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

Returns

str

from_json staticmethod

from_json(text: str) -> Categorical

Categorical from the text written by to_json.

Parameters

text : str

Returns

Categorical

Raises

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

Gaussian

Gaussian emission.

Parameters:

Name Type Description Default
mean array_like

(d,) mean.

required
covariance array_like or float

(d, d) for "full", (d,) for "diag", a scalar for "spherical".

required
covariance_type (full, diag, spherical)
"full"
frozen bool

Keep the parameters fixed while fitting.

False

Raises:

Type Description
InvalidInput

When the covariance has the wrong shape for covariance_type or is not positive definite.

Examples:

>>> g = tg.Gaussian([0.0, 1.0], [1.0, 4.0], covariance_type="diag")
>>> np.round(g.log_density([[0.0, 1.0], [1.0, np.nan]]), 4)
array([-2.531 , -1.4189])
>>> g.sample(4, seed=1).shape
(4, 2)
>>> tg.Gaussian.from_json(g.to_json()) == g
True

mean property

mean: NDArray[float64]

(d,) mean.

covariance property

covariance: NDArray[float64] | float

As constructed: (d, d), (d,) or a float.

covariance_type property

covariance_type: str

"full", "diag" or "spherical".

frozen property

frozen: bool

Whether the parameters stay fixed while fitting.

log_density

log_density(x: ArrayLike) -> NDArray[np.float64]

Log density of each observation.

Parameters

x : array_like (n, d) rows, or (n,) when d = 1; NaN channels are marginalised.

Returns

numpy.ndarray (n,) log values.

Raises

InvalidInput When x has the wrong number of channels or invalid values.

sample

sample(n: int, *, seed: int = 0) -> NDArray

Seeded draws from this distribution.

Parameters

n : int Number of draws. seed : int Seed in 0..2**64-1; equal seeds give equal draws.

Returns

numpy.ndarray (n, d) draws.

Raises

InvalidInput When seed is out of range.

to_json

to_json() -> str

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

Returns

str

from_json staticmethod

from_json(text: str) -> Gaussian

Gaussian from the text written by to_json.

Parameters

text : str

Returns

Gaussian

Raises

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

Poisson

Poisson emission with independent channels.

Parameters:

Name Type Description Default
rate array_like

(d,) rates.

required
frozen bool

Keep the parameters fixed while fitting.

False

Raises:

Type Description
InvalidInput

When a rate is negative or not finite.

Examples:

>>> p = tg.Poisson([2.0, 0.5])
>>> np.round(p.log_density([[2, 0], [0, 1]]), 4)
array([-1.8069, -3.1931])
>>> p.sample(3, seed=1).shape
(3, 2)
>>> tg.Poisson.from_json(p.to_json()) == p
True

rate property

rate: NDArray[float64]

(d,) rate of each channel.

frozen property

frozen: bool

Whether the parameters stay fixed while fitting.

log_density

log_density(x: ArrayLike) -> NDArray[np.float64]

Log probability of each observation.

Parameters

x : array_like (n, d) counts, or (n,) when d = 1.

Returns

numpy.ndarray (n,) log values.

Raises

InvalidInput When x has the wrong number of channels or invalid values.

sample

sample(n: int, *, seed: int = 0) -> NDArray

Seeded draws from this distribution.

Parameters

n : int Number of draws. seed : int Seed in 0..2**64-1; equal seeds give equal draws.

Returns

numpy.ndarray (n, d) counts.

Raises

InvalidInput When seed is out of range.

to_json

to_json() -> str

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

Returns

str

from_json staticmethod

from_json(text: str) -> Poisson

Poisson from the text written by to_json.

Parameters

text : str

Returns

Poisson

Raises

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

GaussianMixture

Mixture of Gaussians sharing one covariance type.

Parameters:

Name Type Description Default
weights array_like

(m,) component weights summing to 1.

required
means array_like

(m, d) component means.

required
covariances array_like

(m, d, d) for "full", (m, d) for "diag", (m,) for "spherical".

required
covariance_type (full, diag, spherical)
"full"
frozen bool

Keep the parameters fixed while fitting.

False

Raises:

Type Description
InvalidInput

When the weights do not sum to 1, the shapes disagree or a covariance is not positive definite.

Examples:

>>> m = tg.GaussianMixture([0.5, 0.5], [[0.0], [4.0]], [1.0, 1.0], covariance_type="spherical")
>>> np.round(m.log_density([0.0, 2.0]), 4)
array([-1.6118, -2.9189])
>>> m.sample(3, seed=1).shape
(3, 1)
>>> tg.GaussianMixture.from_json(m.to_json()) == m
True

weights property

weights: NDArray[float64]

(m,) component weights.

means property

means: NDArray[float64]

(m, d).

covariances property

covariances: NDArray[float64]

One covariance per component, in the constructed form.

covariance_type property

covariance_type: str

"full", "diag" or "spherical".

frozen property

frozen: bool

Whether the parameters stay fixed while fitting.

log_density

log_density(x: ArrayLike) -> NDArray[np.float64]

Log mixture density of each row of x.

Parameters

x : array_like (n, d) observations, or (n,) when d = 1. NaN channels are marginalised in every component.

Returns

numpy.ndarray (n,) values of log sum_k w_k N(x; mu_k, Sigma_k).

Raises

InvalidInput When x has the wrong number of channels.

sample

sample(n: int, *, seed: int = 0) -> NDArray

Seeded draws from this distribution.

Parameters

n : int Number of draws. seed : int Seed in 0..2**64-1; equal seeds give equal draws.

Returns

numpy.ndarray (n, d) draws.

Raises

InvalidInput When seed is out of range.

to_json

to_json() -> str

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

Returns

str

from_json staticmethod

from_json(text: str) -> GaussianMixture

GaussianMixture from the text written by to_json.

Parameters

text : str

Returns

GaussianMixture

Raises

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

HiddenMarkovModel

Hidden Markov model of a geological state sequence observed through logs or assays.

Parameters:

Name Type Description Default
distributions int or sequence of distributions

The number of states, or one emission object per state (Categorical, Gaussian, Poisson or GaussianMixture).

required
start array_like

Start probabilities (K,) and transition matrix (K, K).

None
transition array_like

Start probabilities (K,) and transition matrix (K, K).

None
emission (gaussian, categorical, poisson, mixture)

Family fitted when distributions is an int.

"gaussian"
covariance_type (full, diag, spherical)
"full"
n_symbols int

Categorical symbols; the largest observed code plus 1 by default.

None
n_mix int

Components per state of a mixture.

1
max_iter int

Baum-Welch iterations, gain per observed step that stops it, seeded restarts.

100
tol float

Baum-Welch iterations, gain per observed step that stops it, seeded restarts.

1e-06
n_init int

Baum-Welch iterations, gain per observed step that stops it, seeded restarts.

1
seed int

Baum-Welch iterations, gain per observed step that stops it, seeded restarts.

0
params str

Letters of the parts fitted (s start, t transition, e emissions) and initialised; by default init_params is "ste" minus the parts given.

'ste'
init_params str

Letters of the parts fitted (s start, t transition, e emissions) and initialised; by default init_params is "ste" minus the parts given.

None
start_prior float

Dirichlet concentrations (>= 1) and the covariance shrinkage of the MAP M-step.

1.0
transition_prior float

Dirichlet concentrations (>= 1) and the covariance shrinkage of the MAP M-step.

1.0
covariance_prior float

Dirichlet concentrations (>= 1) and the covariance shrinkage of the MAP M-step.

1e-06
pseudocount float

Categorical emissions: added to symbol counts.

0.0
direction (up, down)

"up" runs each hole from its deepest row to its shallowest.

"up"
implementation (log, scaled)

Forward-backward arithmetic used while fitting.

"log"
ordering (none, mean, occupancy)

Relabel the fitted states by first-channel mean or by stationary occupancy.

"none"

Raises:

Type Description
InvalidInput

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

Examples:

>>> truth = tg.HiddenMarkovModel(
...     [tg.Gaussian([0.0], 1.0), tg.Gaussian([5.0], 1.0)],
...     start=[0.5, 0.5], transition=[[0.9, 0.1], [0.1, 0.9]])
>>> states, logs = truth.sample([200, 200], seed=1)
>>> hmm = tg.HiddenMarkovModel(2, ordering="mean", seed=1).fit(logs)
>>> hmm.n_states, hmm.converged
(2, True)
>>> found = np.concatenate(hmm.predict(logs))
>>> bool(np.mean(found == np.concatenate(states)) > 0.95)
True
>>> hmm.predict_proba(logs)[0].shape
(200, 2)
>>> paths, log_p = hmm.viterbi(logs)
>>> len(paths), log_p.shape
(2, (2,))
>>> hmm.score_samples(logs).shape
(2,)
>>> bool(hmm.score(logs) < 0 and hmm.aic(logs) < hmm.bic(logs) <= hmm.icl(logs))
True
>>> hmm.sample_posterior(logs[0], n=3, seed=2).shape
(3, 200)
>>> tg.HiddenMarkovModel.from_json(hmm.to_json()) == hmm
True

direction property

direction: str

"up" or "down": the order in which rows are read.

n_states property

n_states: int

Number of hidden states.

start property

start: NDArray[float64]

(n_states,) initial state probabilities; InvalidInput before fitting.

transition property

transition: NDArray[float64]

(n_states, n_states) row-stochastic transition matrix; InvalidInput before fitting.

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 the last fit met tol before max_iter.

n_iter property

n_iter: int

EM iterations of the best start in the last fit.

fit

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

Baum-Welch (EM) fit over all holes, with seeded restarts.

Parameters

sequences : array_like, list of array_like or str One array per hole (rows top-down, (t,) or (t, d)), or one array with holes. holes : array_like or str, optional Per-row hole ids when sequences is one array. labels : array_like or str, optional Per-row known state, -1 where unknown (logged core intervals). allowed : array_like, optional (rows, K) booleans: the states each row may take. data : mapping, optional Strings above name its columns.

Returns

HiddenMarkovModel 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).

Parameters

sequences : array_like, list of array_like or str One array per hole (rows top-down, (t,) or (t, d)), or one array with holes. holes : array_like or str, optional Per-row hole ids when sequences is one array. data : mapping, optional Strings above name its columns.

Returns

float

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, list of array_like or str One array per hole (rows top-down, (t,) or (t, d)), or one array with holes. holes : array_like or str, optional Per-row hole ids when sequences is one array. data : mapping, optional Strings above name its columns.

Returns

numpy.ndarray (n_holes,).

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", "posterior_viterbi"
    ] = "viterbi",
) -> Rows

Most likely states per row.

Parameters

sequences : array_like, list of array_like or str One array per hole (rows top-down, (t,) or (t, d)), or one array with holes. holes : array_like or str, optional Per-row hole ids when sequences is one array. labels : array_like or str, optional Per-row known state, -1 where unknown. allowed : array_like, optional (rows, K) booleans: the states each row may take. data : mapping, optional Strings above name its columns. algorithm : {"viterbi", "map", "posterior_viterbi"} Best joint path, per-row posterior argmax, or the best path through rows with non-zero posterior.

Returns

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

Raises

InvalidInput When the model is not fitted, or the sequences do not match its emissions. Also when 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.

Parameters

sequences : array_like, list of array_like or str One array per hole (rows top-down, (t,) or (t, d)), or one array with holes. holes : array_like or str, optional Per-row hole ids when sequences is one array. labels : array_like or str, optional Per-row known state, -1 where unknown. allowed : array_like, optional (rows, K) booleans: the states each row may take. data : mapping, optional Strings above name its columns.

Returns

numpy.ndarray or list of numpy.ndarray (rows, K), rows summing 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]]

Viterbi path per row and its log-probability per hole.

Parameters

sequences : array_like, list of array_like or str One array per hole (rows top-down, (t,) or (t, d)), or one array with holes. holes : array_like or str, optional Per-row hole ids when sequences is one array. labels : array_like or str, optional Per-row known state, -1 where unknown. allowed : array_like, optional (rows, K) booleans: the states each row may take. data : mapping, optional Strings above name its columns.

Returns

paths : numpy.ndarray or list of numpy.ndarray int64 states in input row order. log_probability : numpy.ndarray (n_holes,).

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.

Parameters

lengths : sequence of int Rows of each sampled hole. seed : int Seed in 0..2**64-1.

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 seed is out of range.

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]

Seeded state paths drawn from the posterior.

Parameters

sequences : array_like, list of array_like or str One array per hole (rows top-down, (t,) or (t, d)), or one array with holes. n : int Number of paths. seed : int Seed in 0..2**64-1. holes : array_like or str, optional Per-row hole ids when sequences is one array. labels : array_like or str, optional Per-row known state, -1 where unknown. allowed : array_like, optional (rows, K) booleans: the states each row may take. data : mapping, optional Strings above name its columns.

Returns

numpy.ndarray int64 (n, rows).

Raises

InvalidInput When the model is not fitted, or the sequences do not match its emissions. Also when seed is out of range.

aic

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

Akaike information criterion (lower is better).

Parameters

sequences : array_like, list of array_like or str One array per hole (rows top-down, (t,) or (t, d)), or one array with holes. holes : array_like or str, optional Per-row hole ids when sequences is one array. data : mapping, optional Strings above name its columns.

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).

Depth samples are autocorrelated, so BIC tends to favour too many states on dense logs.

Parameters

sequences : array_like, list of array_like or str One array per hole (rows top-down, (t,) or (t, d)), or one array with holes. holes : array_like or str, optional Per-row hole ids when sequences is one array. data : mapping, optional Strings above name its columns.

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: BIC plus twice the path entropy (lower is better).

Parameters

sequences : array_like, list of array_like or str One array per hole (rows top-down, (t,) or (t, d)), or one array with holes. holes : array_like or str, optional Per-row hole ids when sequences is one array. data : mapping, optional Strings above name its columns.

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; HiddenMarkovModel.from_json reads it back.

Returns

str

from_json staticmethod

from_json(text: str) -> HiddenMarkovModel

HiddenMarkovModel from the text written by to_json.

Parameters

text : str

Returns

HiddenMarkovModel

Raises

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