Chain¶
Markov chains, statistical tests, sojourns and 1D simulation. The guide explains the methods.
TestResult
¶
Result of a statistical test.
Attributes¶
name : str "independence", "order 2 vs 1", "symmetry", "homogeneity" or "exponential". method : str "g", "pearson", "bowker" or "ks". statistic : float df : int Degrees of freedom; 0 for "ks". p_value : float expected : numpy.ndarray or None Expected counts under the null hypothesis when the test is tabular. small_expected : float Fraction of allowed cells whose expected count is below 5.
Examples¶
codes = tg.MarkovChain.from_matrix([[0.9, 0.1], [0.2, 0.8]]).simulate(500, seed=1)[0] r = tg.MarkovChain(kind="fixed", step=1.0).fit(codes).independence_test() r.name, r.method, r.df ('independence', 'g', 1) bool(r.p_value < 0.001) True tg.TestResult.from_json(r.to_json()).to_json() == r.to_json() True
name
property
¶
name: str
"independence", "order 2 vs 1", "symmetry", "homogeneity" or "exponential".
expected
property
¶
expected: NDArray[float64] | None
Expected counts under the null hypothesis for a tabular test, else None.
small_expected
property
¶
small_expected: float
Fraction of allowed cells whose expected count is below 5.
to_json
¶
to_json() -> str
Entropy
¶
Entropies of a chain, in bits.
Attributes:
| Name | Type | Description |
|---|---|---|
post |
ndarray
|
Entropy of the row (what follows each category) and of the column (what precedes it). |
pre |
ndarray
|
Entropy of the row (what follows each category) and of the column (what precedes it). |
post_normalized |
ndarray
|
The same divided by their maximum. |
pre_normalized |
ndarray
|
The same divided by their maximum. |
chain |
float
|
Entropy rate of the whole chain. |
max |
float
|
Its maximum for this number of categories. |
Examples:
>>> e = tg.MarkovChain.from_matrix([[0.0, 1.0], [1.0, 0.0]], kind="embedded").entropy()
>>> e.post, e.chain
(array([0., 0.]), 0.0)
>>> tg.Entropy.from_json(e.to_json()) == e
True
post
property
¶
post: NDArray[float64]
(k,) entropy in bits of what follows each category (row entropy).
pre
property
¶
pre: NDArray[float64]
(k,) entropy in bits of what precedes each category (column entropy).
post_normalized
property
¶
post_normalized: NDArray[float64]
post divided by its maximum, in [0, 1].
MarkovChain
¶
Markov chain of categories along drillholes.
kind="embedded" counts transitions between successive beds (diagonal zero) and estimates
mean bed lengths and the continuous-lag generator Q from bed thicknesses.
kind="fixed" counts transitions between samples one step apart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
(embedded, fixed)
|
|
"embedded"
|
direction
|
(up, down)
|
"up" runs from the deepest row to the shallowest (older to younger). |
"up"
|
step
|
float
|
Step of a fixed chain; defaults to the sampling step of the data. |
None
|
self_transitions
|
bool
|
Embedded only: keep adjacent intervals of one category as separate beds. |
False
|
pseudocount
|
float
|
Added to every allowed count. |
0.0
|
on_empty_row
|
('raise', uniform)
|
What a category with no transition out gives when |
"raise"
|
Raises:
| Type | Description |
|---|---|
InvalidInput
|
When an option is unknown or |
Examples:
>>> d = tg.datasets.varved_sequence()
>>> chain = tg.MarkovChain().fit(d["CODE"], holes=d["HOLE_ID"], from_=d["FROM"], to=d["TO"])
>>> chain.kind, chain.n_categories
('embedded', 3)
>>> bool(np.allclose(chain.transition_matrix.sum(axis=1), 1.0))
True
>>> chain.transition_at(2.0).shape, chain.transition_at([1.0, 2.0]).shape
((3, 3), (2, 3, 3))
>>> bool(chain.independence_test().p_value < 0.01)
True
>>> chain.symmetry_test().name
'symmetry'
>>> e = chain.entropy()
>>> bool(0.0 < e.chain <= e.max)
True
>>> chain.difference_matrix().shape, chain.asymmetry().shape, chain.proportion_std(100).shape
((3, 3), (3, 3), (3,))
>>> sorted(chain.simulate(10.0, n=2, seed=1))
['code', 'from', 'realization', 'to']
>>> chain.simulate_beds(5, n=2, seed=1).shape
(2, 5)
>>> fixed = tg.MarkovChain.from_matrix([[0.9, 0.1], [0.2, 0.8]])
>>> fixed.simulate(5, seed=1).shape
(1, 5)
>>> np.round(tg.MarkovChain.from_rates([[-0.5, 0.5], [0.25, -0.25]]).proportions, 4)
array([0.3333, 0.6667])
>>> tg.MarkovChain.from_geology([0.5, 0.3, 0.2], [2.0, 1.0, 0.5]).kind
'continuous'
>>> tg.MarkovChain.from_json(chain.to_json()) == chain
True
counts
property
¶
counts: NDArray[float64] | None
Transition counts (bed transitions for embedded, step transitions for fixed), or None.
transition_matrix
property
¶
transition_matrix: NDArray[float64]
(k, k) row-stochastic transition matrix (embedded or one step).
mean_lengths
property
¶
mean_lengths: NDArray[float64] | None
(k,) mean bed length per category, or None for a fixed chain.
bed_frequencies
property
¶
bed_frequencies: NDArray[float64]
(k,) frequency of each category among beds (embedded) or steps (fixed).
projection_distance
property
¶
projection_distance: float | None
Fixed chains: largest change made to logm(P) / step to make it a generator.
fit
¶
fit(
codes: ArrayLike | str | object,
*,
holes: ArrayLike | str | None = None,
from_: ArrayLike | str | None = None,
to: ArrayLike | str | None = None,
depth: ArrayLike | str | None = None,
step: float | None = None,
gap: float = 1e-06,
categories: Categories | int | object | None = None,
data: Mapping[str, ArrayLike] | object | None = None,
) -> MarkovChain
Fits the chain to categorical sequences.
Parameters¶
codes : array_like or str
Category code per row, 0..k-1, -1 or NaN for missing.
holes
The shared sequence arguments: per-row hole ids; interval tops and bottoms; or regular
sample depths with their step; gap is the largest gap that keeps a run;
categories gives k; strings name columns of data.
from_
The shared sequence arguments: per-row hole ids; interval tops and bottoms; or regular
sample depths with their step; gap is the largest gap that keeps a run;
categories gives k; strings name columns of data.
to
The shared sequence arguments: per-row hole ids; interval tops and bottoms; or regular
sample depths with their step; gap is the largest gap that keeps a run;
categories gives k; strings name columns of data.
depth
The shared sequence arguments: per-row hole ids; interval tops and bottoms; or regular
sample depths with their step; gap is the largest gap that keeps a run;
categories gives k; strings name columns of data.
step
The shared sequence arguments: per-row hole ids; interval tops and bottoms; or regular
sample depths with their step; gap is the largest gap that keeps a run;
categories gives k; strings name columns of data.
gap
The shared sequence arguments: per-row hole ids; interval tops and bottoms; or regular
sample depths with their step; gap is the largest gap that keeps a run;
categories gives k; strings name columns of data.
categories
The shared sequence arguments: per-row hole ids; interval tops and bottoms; or regular
sample depths with their step; gap is the largest gap that keeps a run;
categories gives k; strings name columns of data.
data
The shared sequence arguments: per-row hole ids; interval tops and bottoms; or regular
sample depths with their step; gap is the largest gap that keeps a run;
categories gives k; strings name columns of data.
Returns¶
MarkovChain This chain, fitted.
Raises¶
InvalidInput
When a code is out of range, the sequence arguments disagree in length, a named
column is missing from data, or a category has no transition out and
on_empty_row="raise".
from_matrix
staticmethod
¶
from_matrix(
matrix: ArrayLike,
*,
kind: Literal["embedded", "fixed"] = "fixed",
step: float = 1.0,
mean_lengths: ArrayLike | None = None,
direction: Literal["up", "down"] = "up",
) -> MarkovChain
Chain from a transition matrix.
Parameters¶
matrix : array_like
(k, k) row-stochastic matrix; zero diagonal for kind="embedded".
kind : {"fixed", "embedded"}
step : float
Step of a fixed chain.
mean_lengths : array_like, optional
Embedded only: mean bed length per category, which gives the generator.
direction : {"up", "down"}
Returns¶
MarkovChain
Raises¶
InvalidInput
When matrix is not row-stochastic, an embedded diagonal is not zero, or
mean_lengths has another length or a non-positive entry.
from_rates
staticmethod
¶
from_rates(
rates: ArrayLike,
*,
direction: Literal["up", "down"] = "up",
) -> MarkovChain
from_geology
staticmethod
¶
from_geology(
proportions: ArrayLike,
mean_lengths: ArrayLike,
embedded: ArrayLike | None = None,
*,
background: int = -1,
symmetric: bool = False,
direction: Literal["up", "down"] = "up",
) -> MarkovChain
Continuous-lag chain from proportions, mean bed lengths and optional embedded juxtapositions (Carle and Fogg).
Parameters¶
proportions : array_like
Volume proportion of each category.
mean_lengths : array_like
Mean bed length of each category.
embedded : array_like, optional
(k, k) embedded transition probabilities; the background row and column are
filled from the others. Without it, the maximum-entropy chain.
background : int
Background category; -1 means the last.
symmetric : bool
Read only the upper triangle of embedded and fill the rest by symmetry.
direction : {"up", "down"}
Returns¶
MarkovChain
Raises¶
InvalidInput When the proportions do not sum to 1, a mean length is not positive, or the juxtapositions give no valid generator.
transition_at
¶
transition_at(h: float | ArrayLike) -> NDArray[np.float64]
Transition matrix at lag h.
Parameters¶
h : float or array_like Lag along the direction; whole steps for a fixed chain without a generator.
Returns¶
numpy.ndarray
(k, k) for a scalar, (n, k, k) for an array.
Raises¶
InvalidInput When the chain is not fitted, a lag is invalid for it, or the stack exceeds the available memory.
independence_test
¶
independence_test(
*, method: Literal["g", "pearson"] = "g"
) -> TestResult
symmetry_test
¶
symmetry_test() -> TestResult
entropy
¶
entropy() -> Entropy
difference_matrix
¶
difference_matrix() -> NDArray[np.float64]
asymmetry
¶
asymmetry() -> NDArray[np.float64]
proportion_std
¶
proportion_std(n_steps: int) -> NDArray[np.float64]
simulate
¶
simulate(
length: float,
*,
n: int = 1,
seed: int = 0,
hard_from: ArrayLike | None = None,
hard_to: ArrayLike | None = None,
hard_codes: ArrayLike | None = None,
start: int | Literal["stationary"] | None = None,
) -> NDArray[np.int64] | dict[str, NDArray]
Seeded simulation over a length along the direction.
Parameters¶
length : float
Fixed chains: a multiple of step. Chains with a generator: any positive length.
n : int
Number of realizations.
seed : int
hard_from : array_like, optional
Conditioning intervals as lengths along the direction from 0; a point has
from == to. Fixed chains freeze the cells whose centres an interval covers, and
the cell that contains a point.
hard_to : array_like, optional
Conditioning intervals as lengths along the direction from 0; a point has
from == to. Fixed chains freeze the cells whose centres an interval covers, and
the cell that contains a point.
hard_codes : array_like, optional
Conditioning intervals as lengths along the direction from 0; a point has
from == to. Fixed chains freeze the cells whose centres an interval covers, and
the cell that contains a point.
start : int, "stationary" or None
Category at position 0, or a draw from the stationary law (None).
Returns¶
numpy.ndarray or dict
Fixed chains: int64 (n, length / step), column i the i-th step along the
direction (for "up", column 0 is the deepest; reverse the columns for top-down rows).
Chains with a generator: a dict of arrays realization, from, to and
code, one entry per bed, positions along the direction.
Raises¶
InvalidInput
When the chain is not fitted, length is not a positive multiple of a fixed
step, the conditioning contradicts itself, or seed is out of range.
simulate_beds
¶
simulate_beds(
n_beds: int,
*,
n: int = 1,
seed: int = 0,
hard_from: ArrayLike | None = None,
hard_to: ArrayLike | None = None,
hard_codes: ArrayLike | None = None,
start: int | Literal["stationary"] | None = None,
) -> NDArray[np.int64]
Seeded simulation of a number of beds with an embedded transition matrix.
Parameters¶
n_beds : int n : int seed : int hard_from : array_like, optional Conditioning as bed indices (inclusive). hard_to : array_like, optional Conditioning as bed indices (inclusive). hard_codes : array_like, optional Conditioning as bed indices (inclusive). start : int, "stationary" or None Category of the first bed, or a draw from the stationary law (None).
Returns¶
numpy.ndarray
int64 (n, n_beds), beds in order along the direction.
Raises¶
InvalidInput
When the chain has no embedded matrix, the conditioning contradicts itself, or
seed is out of range.
to_json
¶
to_json() -> str
Sojourn
¶
Bed statistics per category.
Attributes:
| Name | Type | Description |
|---|---|---|
n_beds |
ndarray
|
Beds per category, and how many of them are cut by the end of a run (censored). |
n_open |
ndarray
|
Beds per category, and how many of them are cut by the end of a run (censored). |
total |
ndarray
|
Total thickness, and thickness over closed beds (the censored exponential MLE). |
mean_length |
ndarray
|
Total thickness, and thickness over closed beds (the censored exponential MLE). |
Examples:
>>> d = tg.datasets.varved_sequence()
>>> s = tg.sojourn(d["CODE"], holes=d["HOLE_ID"], from_=d["FROM"], to=d["TO"])
>>> s.n_beds.shape, s.mean_length.shape
((3,), (3,))
>>> thickness, is_open = s.thickness(0)
>>> thickness.shape == is_open.shape
True
>>> at, survival = s.survival(0)
>>> bool(np.all(np.diff(survival) <= 0))
True
>>> s.exponential_test(0, n_bootstrap=99, seed=1).name
'exponential'
>>> tg.Sojourn.from_json(s.to_json()).to_json() == s.to_json()
True
mean_length
property
¶
mean_length: NDArray[float64]
(k,) total thickness divided by the number of closed beds (the censored
exponential MLE).
thickness
¶
thickness(
code: int,
) -> tuple[NDArray[np.float64], NDArray[np.bool_]]
survival
¶
survival(
code: int,
) -> tuple[NDArray[np.float64], NDArray[np.float64]]
exponential_test
¶
exponential_test(
code: int, *, n_bootstrap: int = 999, seed: int = 0
) -> TestResult
Kolmogorov-Smirnov test of exponential thickness for code, p value by seeded
parametric bootstrap.
Parameters¶
code : int
n_bootstrap : int
Bootstrap samples.
seed : int
Seed in 0..2**64-1.
Returns¶
TestResult
Raises¶
InvalidInput
When code is not a category, it has no closed bed, or seed is out of range.
order_test
builtin
¶
order_test(
codes: ArrayLike | str | object,
*,
order: int = 2,
kind: Literal["embedded", "fixed"] = "fixed",
direction: Literal["up", "down"] = "up",
method: Literal["g", "pearson"] = "g",
holes: ArrayLike | str | None = None,
from_: ArrayLike | str | None = None,
to: ArrayLike | str | None = None,
depth: ArrayLike | str | None = None,
step: float | None = None,
gap: float = 1e-06,
categories: Categories | int | object | None = None,
data: Mapping[str, ArrayLike] | object | None = None,
) -> TestResult
Test of Markov order order against order - 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
codes
|
array_like or str
|
|
required |
order
|
int
|
Fixed chains: any order >= 1 with no more histories ( |
2
|
kind
|
(fixed, embedded)
|
|
"fixed"
|
direction
|
(up, down)
|
|
"up"
|
method
|
(g, pearson)
|
|
"g"
|
holes
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
from_
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
to
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
depth
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
step
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
gap
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
categories
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
data
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
Returns:
| Type | Description |
|---|---|
TestResult
|
|
Raises:
| Type | Description |
|---|---|
InvalidInput
|
When a code is out of range, the sequence arguments disagree in length, a named column
is missing from |
Examples:
>>> codes = tg.MarkovChain.from_matrix([[0.9, 0.1], [0.2, 0.8]]).simulate(2000, seed=1)[0]
>>> r = tg.order_test(codes, order=2)
>>> r.name, r.df
('order 2 vs 1', 2)
>>> bool(r.p_value > 0.01)
True
select_order
builtin
¶
select_order(
codes: ArrayLike | str | object,
*,
max_order: int = 3,
direction: Literal["up", "down"] = "up",
holes: ArrayLike | str | None = None,
from_: ArrayLike | str | None = None,
to: ArrayLike | str | None = None,
depth: ArrayLike | str | None = None,
step: float | None = None,
gap: float = 1e-06,
categories: Categories | int | object | None = None,
data: Mapping[str, ArrayLike] | object | None = None,
) -> dict[str, NDArray]
AIC and BIC of fixed-step chains of order 0 to max_order, all fitted on the same
transitions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
codes
|
array_like or str
|
|
required |
max_order
|
int
|
Highest order fitted; the first |
3
|
direction
|
(up, down)
|
|
"up"
|
holes
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
from_
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
to
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
depth
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
step
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
gap
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
categories
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
data
|
ArrayLike | str | None
|
The shared sequence arguments, as in |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
|
Raises:
| Type | Description |
|---|---|
InvalidInput
|
When a code is out of range, the sequence arguments disagree in length, a named column
is missing from |
Examples:
>>> codes = tg.MarkovChain.from_matrix([[0.9, 0.1], [0.2, 0.8]]).simulate(2000, seed=1)[0]
>>> table = tg.select_order(codes, max_order=2)
>>> table["order"]
array([0, 1, 2])
>>> int(table["order"][np.argmin(table["bic"])])
1
homogeneity_test
builtin
¶
homogeneity_test(
codes: ArrayLike | str | object,
groups: ArrayLike | str,
*,
kind: Literal["embedded", "fixed"] = "embedded",
direction: Literal["up", "down"] = "up",
method: Literal["g", "pearson"] = "g",
holes: ArrayLike | str | None = None,
from_: ArrayLike | str | None = None,
to: ArrayLike | str | None = None,
depth: ArrayLike | str | None = None,
step: float | None = None,
gap: float = 1e-06,
categories: Categories | int | object | None = None,
data: Mapping[str, ArrayLike] | object | None = None,
) -> TestResult
Test that groups of holes share one transition matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
codes
|
array_like or str
|
|
required |
groups
|
array_like or str
|
Group label per row; transitions are counted only between rows of one group. |
required |
kind
|
Literal['embedded', 'fixed']
|
As in |
'embedded'
|
direction
|
Literal['embedded', 'fixed']
|
As in |
'embedded'
|
method
|
Literal['embedded', 'fixed']
|
As in |
'embedded'
|
holes
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
from_
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
to
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
depth
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
step
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
gap
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
categories
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
data
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
Returns:
| Type | Description |
|---|---|
TestResult
|
|
Raises:
| Type | Description |
|---|---|
InvalidInput
|
When a code is out of range, the sequence arguments disagree in length, a named column
is missing from |
Examples:
>>> d = tg.datasets.varved_sequence()
>>> groups = np.where(np.isin(d["HOLE_ID"], ["DH01", "DH02", "DH03", "DH04", "DH05", "DH06"]), "A", "B")
>>> r = tg.homogeneity_test(d["CODE"], groups, holes=d["HOLE_ID"], from_=d["FROM"], to=d["TO"])
>>> r.name
'homogeneity'
>>> bool(r.p_value > 0.01)
True
sojourn
builtin
¶
sojourn(
codes: ArrayLike | str | object,
*,
direction: Literal["up", "down"] = "up",
holes: ArrayLike | str | None = None,
from_: ArrayLike | str | None = None,
to: ArrayLike | str | None = None,
depth: ArrayLike | str | None = None,
step: float | None = None,
gap: float = 1e-06,
categories: Categories | int | object | None = None,
data: Mapping[str, ArrayLike] | object | None = None,
) -> Sojourn
Bed thickness statistics per category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
codes
|
array_like or str
|
|
required |
direction
|
(up, down)
|
|
"up"
|
holes
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
from_
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
to
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
depth
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
step
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
gap
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
categories
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
data
|
ArrayLike | str | None
|
The shared sequence arguments. |
None
|
Returns:
| Type | Description |
|---|---|
Sojourn
|
|
Raises:
| Type | Description |
|---|---|
InvalidInput
|
When a code is out of range, the sequence arguments disagree in length, a named column
is missing from |
Examples:
>>> d = tg.datasets.varved_sequence()
>>> s = tg.sojourn(d["CODE"], holes=d["HOLE_ID"], from_=d["FROM"], to=d["TO"])
>>> int(s.n_beds.sum()) > 0
True