Skip to content

Plots, datasets, checks

These submodules are not star-exported: write tg.plot.transiogram(...).

tg.plot

Every function takes ax=None (or axes=None), returns (fig, ax) or (fig, axes), forwards **kwargs to its main matplotlib call and imports matplotlib only when called (pip install 'transiograms[plot]').

Function Draws
transition_matrix(matrix, *, categories=None, annotate=True) heat map of a matrix or a MarkovChain
sojourn(sojourn, code, *, exponential=True) Kaplan-Meier thickness survival and the exponential law
strip_log(codes, *, depth=None, from_=None, to=None, posterior=None, categories=None) a categorical log, with posterior bands
selection(table, *, criteria=("aic", "bic", "icl")) a select_states table
transiogram(experimental=None, model=None, *, h=None, categories=None) the k x k grid of transiograms
grid_slice(values, grid, *, axis="z", index=0, categories=None) one slice of a grid property

Figures for transiograms results (tg.plot). Every function takes ax=None and returns (fig, ax).

grid_slice

grid_slice(
    values,
    grid,
    *,
    axis="z",
    index=0,
    categories=None,
    ax=None,
    **kwargs,
)

One slice of a grid property.

Parameters:

Name Type Description Default
values array_like

One value per cell, x fastest (a realization, most_likely, an entropy).

required
grid Grid
required
axis (x, y, z)

Axis normal to the slice.

"x"
index int

Cell index along axis.

0
categories Categories

Draw integer codes with category colours (-1 blank).

None
ax Axes
None
**kwargs

Passed to imshow.

{}

Returns:

Type Description
(fig, ax)

Raises:

Type Description
ImportError

When matplotlib is not installed.

InvalidInput

When axis is not "x", "y" or "z", or categories has fewer names than the codes need.

Examples:

>>> grid = tg.Grid((0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (4, 3, 2))
>>> fig, ax = tg.plot.grid_slice(np.arange(24) % 3, grid, axis="z", index=1)
>>> ax.get_xlabel(), ax.get_ylabel()
('x', 'y')

selection

selection(
    table,
    *,
    criteria=("aic", "bic", "icl"),
    ax=None,
    **kwargs,
)

Information criteria against the number of states, from select_states.

Parameters:

Name Type Description Default
table dict

The select_states result.

required
criteria sequence of str

Keys to draw; the minimum of each is marked.

('aic', 'bic', 'icl')
ax Axes
None
**kwargs

Passed to plot.

{}

Returns:

Type Description
(fig, ax)

Raises:

Type Description
ImportError

When matplotlib is not installed.

KeyError

When a criterion is not a key of table.

Examples:

>>> table = {"states": [1, 2, 3], "aic": [30.0, 20.0, 25.0], "bic": [31.0, 24.0, 33.0]}
>>> fig, ax = tg.plot.selection(table, criteria=("aic", "bic"))
>>> [t.get_text() for t in ax.get_legend().get_texts()]
['AIC', 'BIC']

sojourn

sojourn(
    sojourn, code, *, exponential=True, ax=None, **kwargs
)

Kaplan-Meier survival of bed thickness for one category, open beds censored.

Parameters:

Name Type Description Default
sojourn Sojourn
required
code int
required
exponential bool

Overlay exp(-t / mean_length), the survival a Markov chain implies.

True
ax Axes
None
**kwargs

Passed to the survival step call.

{}

Returns:

Type Description
(fig, ax)

Raises:

Type Description
ImportError

When matplotlib is not installed.

InvalidInput

When code is not a category.

Examples:

>>> d = tg.datasets.varved_sequence()
>>> s = tg.sojourn(d["CODE"], holes=d["HOLE_ID"], from_=d["FROM"], to=d["TO"])
>>> fig, ax = tg.plot.sojourn(s, 0)
>>> ax.get_ylabel()
'P(thickness > t)'

strip_log

strip_log(
    codes,
    *,
    depth=None,
    from_=None,
    to=None,
    posterior=None,
    categories=None,
    ax=None,
    **kwargs,
)

A categorical log as coloured intervals, depth increasing downward.

Parameters:

Name Type Description Default
codes array_like

Category per row, -1 missing.

required
depth array_like

Sample depths; intervals span half the spacing either side.

None
from_ array_like

Interval tops and bottoms, instead of depth.

None
to array_like

Interval tops and bottoms, instead of depth.

None
posterior array_like

(rows, K) probabilities, drawn as stacked bands in a second panel.

None
categories Categories
None
ax matplotlib.axes.Axes or sequence of two
None
**kwargs

Passed to barh.

{}

Returns:

Type Description
(fig, ax) or (fig, axes)

Raises:

Type Description
ImportError

When matplotlib is not installed.

InvalidInput

When categories has fewer names than the codes need.

Examples:

>>> fig, axes = tg.plot.strip_log([0, 0, 1, 2], depth=[0.5, 1.5, 2.5, 3.5], posterior=np.eye(3)[[0, 0, 1, 2]])
>>> len(axes)
2

transiogram

transiogram(
    experimental=None,
    model=None,
    *,
    h=None,
    categories=None,
    axes=None,
    **kwargs,
)

Grid of auto- (diagonal) and cross-transiograms.

Parameters:

Name Type Description Default
experimental ExperimentalTransiogram

Drawn as points at the mean lag of each class.

None
model TransiogramModel or TransitionModel

Drawn as curves; a TransitionModel along +z unless h is (n, 3).

None
h array_like

Lags of the curves; up to the largest experimental lag by default.

None
categories Categories
None
axes array of matplotlib.axes.Axes

(k, k).

None
**kwargs

Passed to the model plot calls.

{}

Returns:

Type Description
(fig, axes)

Raises:

Type Description
ImportError

When matplotlib is not installed.

InvalidInput

When neither experimental nor model is given, or categories has another number of names than the data needs.

Examples:

>>> m = tg.TransiogramModel.markov([[-0.5, 0.5], [1.0, -1.0]])
>>> fig, axes = tg.plot.transiogram(model=m, h=np.linspace(0.0, 5.0, 20))
>>> axes.shape
(2, 2)

transition_matrix

transition_matrix(
    matrix,
    *,
    categories=None,
    annotate=True,
    ax=None,
    **kwargs,
)

Heat map of a transition matrix, rows "from" and columns "to".

Parameters:

Name Type Description Default
matrix array_like or MarkovChain

(k, k) matrix, or a chain whose transition_matrix is drawn.

required
categories Categories

Names for the axes.

None
annotate bool

Write each probability in its cell.

True
ax Axes
None
**kwargs

Passed to imshow.

{}

Returns:

Type Description
(fig, ax)

Raises:

Type Description
ImportError

When matplotlib is not installed.

InvalidInput

When categories has another number of names than the data needs.

Examples:

>>> chain = tg.MarkovChain.from_matrix([[0.9, 0.1], [0.2, 0.8]])
>>> fig, ax = tg.plot.transition_matrix(chain, categories=tg.Categories(["sand", "clay"]))
>>> [t.get_text() for t in ax.get_xticklabels()]
['sand', 'clay']

tg.datasets

Seeded synthetic data with known parameters; each takes seed=0 and returns a dict.

Function Content
varved_sequence() 12 holes of sand, silt and clay intervals: HOLE_ID, FROM, TO, CODE, names, generator
electrofacies_logs() 20 wells x 300 samples from a 3-state Gaussian HMM: HOLE_ID, DEPTH, GR, RHOB, STATE, model
layered_drillholes() 25 vertical holes through an unconditional MCRF field, which departs from its model (quantified in the docstring): X, Y, Z, FROM, TO, HOLE_ID, CODE, field, model, grid

Seeded synthetic datasets (tg.datasets). Each function takes seed=0 and returns a dict of NumPy arrays and model JSON strings.

electrofacies_logs

electrofacies_logs(seed=0)

Gamma-ray and density logs of 20 holes from a 3-state Gaussian HMM.

Each hole has 300 samples 0.1 m apart. The hidden states (shale, silty sand, clean sand) are sticky (0.95 on the diagonal) and well separated in both channels.

Parameters:

Name Type Description Default
seed int
0

Returns:

Type Description
dict

HOLE_ID, DEPTH, GR (API), RHOB (g/cm3) and STATE per row, top-down, and model: the true HiddenMarkovModel (on the scaled channels) as JSON.

Raises:

Type Description
InvalidInput

When seed is outside 0..2**64-1.

Examples:

>>> d = tg.datasets.electrofacies_logs()
>>> d["GR"].shape, tg.HiddenMarkovModel.from_json(d["model"]).n_states
((6000,), 3)

layered_drillholes

layered_drillholes(seed=0)

Vertical drillholes through a seeded realization of a known 3D transition model.

Three facies (proportions 0.5, 0.3, 0.2; mean lengths 60, 40, 30 m along x and y, 6, 4, 3 m along z) are simulated by MCRF on a 32 x 32 x 30 grid of 10 x 10 x 1 m cells, then sampled by 25 vertical holes on a regular pattern at 1 m composites.

The field does not follow model: unconditional MCRF does not reproduce its own model (see the MCRF guide). At seed=0 the field proportions are 0.525, 0.263 and 0.211, a Markov fit to the field's vertical transiograms gives mean lengths of 10.54, 6.79 and 5.24 m, and its vertical transiograms at lags 1 to 12 m miss model by up to 0.231 (0.423 at seed=2). Compare fits of the holes with field as well as with model.

Parameters:

Name Type Description Default
seed int
0

Returns:

Type Description
dict

X, Y, Z (composite midpoints), HOLE_ID, CODE; FROM and TO (depth below the grid top); field (the realization, one code per cell, x fastest); model (TransitionModel JSON) and grid (Grid JSON).

Raises:

Type Description
InvalidInput

When seed is outside 0..2**64-1.

Examples:

>>> d = tg.datasets.layered_drillholes()
>>> grid = tg.Grid.from_json(d["grid"])
>>> d["field"].shape == (grid.n_cells,), len(np.unique(d["HOLE_ID"]))
(True, 25)

varved_sequence

varved_sequence(seed=0)

Fining-upward cycles of sand, silt and clay in 12 vertical holes, 30 m each.

Beds come from a continuous-lag Markov chain run upward (older to younger) whose embedded matrix favours sand to silt to clay to sand, with mean thicknesses 1.2, 0.8 and 0.5 m.

Parameters:

Name Type Description Default
seed int
0

Returns:

Type Description
dict

HOLE_ID (str), FROM and TO (depth, top-down), CODE (0 sand, 1 silt, 2 clay), names and generator (the true MarkovChain as JSON).

Raises:

Type Description
InvalidInput

When seed is outside 0..2**64-1.

Examples:

>>> d = tg.datasets.varved_sequence()
>>> d["names"], len(np.unique(d["HOLE_ID"]))
(['sand', 'silt', 'clay'], 12)
>>> bool(np.all(d["TO"] > d["FROM"]))
True

tg.checks

Pure NumPy reference implementations the tests compare against.

Function Computes
quasi_independence(counts) expected embedded counts by iterative proportional fitting
kemeny_snell_std(P, n) standard deviation of chain proportions over n steps
markov_bridge_marginal(P, a, b, n, t) P(x_t = j | x_0 = a, x_n = b)
brute_force_hmm(start, transition, log_b) log-likelihood, best path and its log-probability, posteriors and path entropy over all paths
brute_force_hsmm(start, transition, log_d, log_survivor, log_b) the same for a semi-Markov model
mcp_brute_force(p, T_list, codes) the MCP conditional from the maximum-entropy joint table

Pure NumPy reference implementations (tg.checks) used by tests and examples as oracles.

brute_force_hmm

brute_force_hmm(start, transition, log_b)

Exhaustive HMM inference over all K^T state paths.

Parameters:

Name Type Description Default
start array_like

(K,) start probabilities.

required
transition array_like

(K, K) transition matrix.

required
log_b array_like

(T, K) emission log densities.

required

Returns:

Type Description
tuple

(log_likelihood, best_path, best_log_probability, gamma, path_entropy); ties of the best path go to the lexicographically smallest path.

Raises:

Type Description
ValueError

When K^T exceeds the 500 000 paths a check enumerates.

Examples:

>>> ll, path, best, gamma, h = tg.checks.brute_force_hmm(
...     [0.5, 0.5], [[0.9, 0.1], [0.1, 0.9]], np.log([[0.9, 0.1], [0.8, 0.2], [0.01, 0.99]]))
>>> path, gamma.shape
(array([0, 0, 1]), (3, 2))

brute_force_hsmm

brute_force_hsmm(
    start, transition, log_d, log_survivor, log_b
)

Exhaustive HSMM inference with a right-censored last segment.

Every state path is cut into runs; runs longer than their state's len(log_d[j]) are impossible. A path weighs pi * prod p (between runs) * prod d (non-final runs) * D (final run) * prod b.

Parameters:

Name Type Description Default
start array_like

(K,) and (K, K) with a zero diagonal.

required
transition array_like

(K,) and (K, K) with a zero diagonal.

required
log_d sequence of array_like

Per state, the duration log pmf and log survivor log P(U >= u), index u - 1.

required
log_survivor sequence of array_like

Per state, the duration log pmf and log survivor log P(U >= u), index u - 1.

required
log_b array_like

(T, K) emission log densities.

required

Returns:

Type Description
tuple

As brute_force_hmm.

Raises:

Type Description
ValueError

When K^T exceeds the 500 000 paths a check enumerates.

Examples:

>>> log_d = [np.log([0.5, 0.5]), np.log([0.5, 0.5])]
>>> log_s = [np.log([1.0, 0.5]), np.log([1.0, 0.5])]
>>> out = tg.checks.brute_force_hsmm(
...     [0.5, 0.5], [[0.0, 1.0], [1.0, 0.0]], log_d, log_s, np.log([[0.9, 0.1], [0.9, 0.1], [0.1, 0.9]]))
>>> out[1]
array([0, 0, 1])

kemeny_snell_std

kemeny_snell_std(P, n)

Kemeny and Snell standard deviation of the state proportions over n steps.

sqrt(pi_k (2 Z_kk - 1 - pi_k) / n) with Z = (I - P + 1 pi^T)^-1.

Parameters:

Name Type Description Default
P array_like

(m, m) row-stochastic, irreducible transition matrix.

required
n int

Number of steps.

required

Returns:

Type Description
ndarray

(m,) standard deviations.

Raises:

Type Description
LinAlgError

When I - P + 1 pi^T is singular (a reducible chain).

Examples:

>>> P = [[0.9, 0.1], [0.2, 0.8]]
>>> bool(np.allclose(tg.checks.kemeny_snell_std(P, 100), tg.MarkovChain.from_matrix(P).proportion_std(100)))
True

markov_bridge_marginal

markov_bridge_marginal(P, a, b, n, t)

P(x_t = j | x_0 = a, x_n = b) = (P^t)_aj (P^(n-t))_jb / (P^n)_ab for every j.

Parameters:

Name Type Description Default
P array_like

(m, m) transition matrix.

required
a int

States at steps 0 and n.

required
b int

States at steps 0 and n.

required
n int

Bridge length and the step asked for, 0 <= t <= n.

required
t int

Bridge length and the step asked for, 0 <= t <= n.

required

Returns:

Type Description
ndarray

(m,) probabilities summing to 1.

Raises:

Type Description
ValueError

When t is outside 0..n (a negative matrix power).

Examples:

>>> tg.checks.markov_bridge_marginal([[0.5, 0.5], [0.5, 0.5]], 0, 1, 2, 1)
array([0.5, 0.5])

mcp_brute_force

mcp_brute_force(
    p, T_list, codes, *, tol=1e-13, max_iter=10000
)

MCP conditional by maximum entropy on the full joint table.

Iterative proportional fitting of the K^(G+1) table of (x_0, x_1, ..., x_G) to the pairwise margins P(x_0 = k, x_g = c) = p_k T_g[k, c], then the distribution of x_0 given x_g = codes[g].

Parameters:

Name Type Description Default
p array_like

(K,) proportions.

required
T_list sequence of array_like

One (K, K) transition matrix T(x_g - x_0) per neighbour.

required
codes sequence of int

Category of each neighbour.

required
tol float

Stop when every margin matches to tol.

1e-13
max_iter int

Largest number of fitting sweeps.

10000

Returns:

Type Description
ndarray

(K,) conditional probabilities of x_0.

Raises:

Type Description
ValueError

When the K^(G+1) table exceeds the 500 000 cells a check enumerates.

Examples:

>>> p = np.array([0.6, 0.4])
>>> T = np.array([[0.8, 0.2], [0.3, 0.7]])
>>> np.round(tg.checks.mcp_brute_force(p, [T], [0]), 4)
array([0.8, 0.2])

quasi_independence

quasi_independence(counts, *, tol=1e-12, max_iter=10000)

Expected counts of an embedded table under quasi-independence (zero diagonal).

Iterative proportional fitting of E_ij = a_i b_j (i != j) to the row and column totals.

Parameters:

Name Type Description Default
counts array_like

(m, m) transition counts with a zero diagonal.

required
tol float

Stop when the row totals match to tol times the total count.

1e-12
max_iter int

Largest number of fitting sweeps.

10000

Returns:

Type Description
ndarray

(m, m) expected counts, zero diagonal.

Raises:

Type Description
ValueError

When counts is not a square numeric table.

Examples:

>>> e = tg.checks.quasi_independence([[0, 30, 10], [20, 0, 20], [10, 30, 0]])
>>> np.round(e.sum(axis=1), 6)
array([40., 40., 40.])
>>> float(np.trace(e))
0.0