transiograms-core: algorithms¶
Signatures are in spec.md section 4.1. This file gives the steps.
1. Sequences¶
from_intervals: group rows by hole id in first-appearance order. Sort each hole's rows byfrom(stable). Validatefrom < to, finite values, andto[i] <= from[i+1] + 1e-9; otherwise raiseInvalidInputnaming the hole id and the depth.from_samples: interval[depth - step/2, depth + step/2]per sample;step > 0.runs(direction, gap): walk each hole in input depth order and cut at a MISSING code or wherefrom[i+1] - to[i] > gap. ForUp, reverse each run and map depth to position-depth(sostart = -to,end = -from). Runs are ordered by hole, then by the order in which they are met along the direction.beds(direction, gap, merge): per run, merge adjacent intervals with the same code whenmerge(sum of thicknesses, an internal gap belowgapadds no thickness). The first bed of each run hasopen_start = true, the lastopen_end = true(a one-bed run has both).regular(direction, step, gap): per run, sample the code at positionsstart_of_run + (i + 1/2) stepwhile the position is< end_of_run. Samples built byfrom_sampleswith the same step reproduce their codes exactly.
2. RNG streams¶
splitmix,realization_seed: copy boitatacrates/core/src/rng.rsexactly (spec section 3.3).Stream::new(seed, keys):key = keys.iter().fold(seed, |s, &k| realization_seed(s, k)). States[i] = splitmix(key.wrapping_add((i as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15)))for i = 0..4; if all four are 0 sets[0] = 1.- xoshiro256++:
result = rotl(s0 + s3, 23) + s0; t = s1 << 17; s2 ^= s0; s3 ^= s1; s1 ^= s2; s0 ^= s3; s2 ^= t; s3 = rotl(s3, 45)(wrapping arithmetic). uniform = (next >> 11) * 2^-53;uniform_open = ((next >> 11) + 0.5) * 2^-53.below(n): Lemire:m = x as u128 * n;l = m as u64; ifl < nthent = n.wrapping_neg() % n, redraw whilel < t; returnm >> 64.normal:sqrt(-2 ln u1) cos(2 pi u2)withu1 = uniform_open,u2 = uniform.gamma(a): Marsaglia-Tsang fora >= 1(d = a - 1/3,c = 1/sqrt(9d), loop:x = normal,v = (1 + c x)^3, rejectv <= 0, accept ifln u < x^2/2 + d - d v + d ln v, returnd v). Fora < 1:gamma(a + 1) * u^(1/a).categorical(w):total = sum w(must be finite and > 0),target = uniform * total, return the first index with cumulative sum> target, skipping zero weights; if rounding exhausts the scan, return the last index with positive weight.
Stream keys per routine (binding)¶
| Routine | Keys |
|---|---|
chain simulate, realization r |
[r] |
chain Sojourn::exponential_test, replicate b |
[tag::BOOTSTRAP, b] |
| hmm/hsmm fit, restart r | [tag::INIT, r] |
hmm/hsmm sample, sequence i |
[tag::SAMPLE, i] |
hmm/hsmm sample_posterior, hole index i |
[tag::SAMPLE, i] (n draws sequential) |
| select_states fold assignment | [tag::FOLD] |
| select_states fold f, K index s, restart r | [tag::FOLD, f, s, r]; full-data fits [tag::INIT, s, r] |
| tpsim and mcrf realization r | path [r, tag::PATH], draws [r, tag::DRAW], quench sweep s [r, tag::QUENCH, s] |
3. Numerics¶
logsumexp¶
m = max xs; if m == -inf return -inf; if m == +inf return +inf; else
m + ln(sum exp(x - m)).
Irreducibility (Tarjan)¶
Graph with an edge i -> j when i != j and a_ij > 0. Irreducible when there is a single
strongly connected component. A 1x1 matrix is irreducible.
GTH stationary distribution¶
Input A = P - I or Q (only off-diagonals are read). Require irreducible, else InvalidInput
"reducible chain: classes {...}".
- Copy off-diagonals into
A. Forkfromm-1down to 1:s = sum_{j<k} A[k, j];A[i, k] /= sfori < k;A[i, j] += A[i, k] * A[k, j]fori, j < k,i != j. x_0 = 1; fork = 1..m-1:x_k = sum_{j<k} x_j A[j, k].- Normalise
xto sum 1.
GTH is subtraction-free and needs no aperiodicity (never use power iteration).
expm_rate (uniformization)¶
mu = max |q_jj|; ifmu == 0orh == 0returnI.R = I + Q / mu(non-negative, stochastic).s= smallest integer>= 0withmu h / 2^s <= 1;lam = mu h / 2^s.T = sum_n w_n R^n,w_0 = e^-lam,w_n = w_{n-1} lam / n, until the remaining Poisson tail1 - sum wis below1e-17(at most 30 terms forlam <= 1).- Square
Tstimes. Divide each row by its sum (the deviation before division is below1e-13; assert it in debug builds).
expm¶
a.clone().exp() from nalgebra (scaling and squaring with Pade, Higham 2005). Used only as a
cross-check and for general (non-generator) matrices.
logm_stochastic (inverse scaling and squaring)¶
X = P,s = 0. While||X - I||_1 > 0.25: replaceXby its principal square root by Denman-Beavers (Y_0 = X,Z_0 = I;Y' = (Y + Z^-1)/2,Z' = (Z + Y^-1)/2until||Y' - Y||_1 < 1e-14 ||Y||_1, at most 100 iterations),s += 1, at most 64 times. Non-convergence or a singular iterate raisesConvergence"transition matrix has no real logarithm".E = X - I;L = sum_{n>=1} (-1)^(n+1) E^n / nuntil the term's 1-norm< 1e-17.- Return
2^s L.
RateMatrix::from_transition (Israel, Rosenthal and Wei diagonal adjustment)¶
Q0 = logm(P) / step. Set negative off-diagonals to 0, set each diagonal to minus its row's
off-diagonal sum. distance = max |Q - Q0|, exact = distance <= 1e-12 max|Q0|.
quasi_independence (IPF with a structural-zero diagonal)¶
Targets rows and cols (same total; zero-margin categories give zero rows and columns).
1. E = 1 off the diagonal and where both margins are positive, else 0.
2. Repeat: scale each row to its target, then each column to its target.
3. Stop when max |E_i. - rows_i| and max |E_.j - cols_j| are both
<= tol * total (default tol = 1e-13). Past max_iter (default 10000) raise
Convergence.
4. m = 2 has the unique solution E = [[0, r0], [r1, 0]] only when r0 = c1 and r1 = c0;
otherwise raise InvalidInput.
fundamental_matrix¶
Z = (I - P + 1 pi^T)^-1 by LU; singular raises InvalidInput.
golden_section, nelder_mead¶
Golden section: standard bracketing on [a, b], stop when b - a < tol (|x| + 1e-12).
Nelder-Mead: coefficients 1, 2, 0.5, 0.5; initial simplex x0 + step e_i; stop when the spread
of function values is below tol (|f_best| + 1e-12) (converged) or after max_eval evaluations
(not converged; the flag is the third element of the result); ties in ordering broken by vertex
index.
4. Special functions¶
ln_gamma: Lanczos (g = 7, n = 9 coefficients) with reflection forx < 0.5.digamma: recurrence up tox >= 6, then the asymptotic series tox^-12.gamma_q(a, x): series forx < a + 1(Pthen1 - P), Lentz continued fraction otherwise;a > 0,x >= 0.chi2_sf(x, df) = gamma_q(df / 2, x / 2).
5. Memory¶
available_bytes: Linux parses MemAvailable: (kB) from /proc/meminfo; Windows takes the
smaller of ullAvailPhys and ullAvailPageFile from GlobalMemoryStatusEx; macOS takes the
installed memory hw.memsize from sysctlbyname, an upper bound because macOS reports no single
reclaimable figure. Both calls are declared by hand, with no new dependency. Any failure or other
OS returns None. check(needed, memory, what): budget = memory.or(available_bytes());
needed > budget raises InvalidInput
"{what} needs {needed} bytes but the memory budget is {budget} bytes; pass memory= or use a
smaller grid".
6. Background fill (Carle 1997, T-PROGS chapter 6)¶
Input: partial k x k with entries read only for i, j != q; proportions p > 0 summing to 1
(within 1e-12, else InvalidInput).
- For
i != q:r_iq = -sum_{j != q} r_ij. - For
j != q:r_qj = -(1 / p_q) sum_{i != q} p_i r_ij. r_qq = -sum_{j != q} r_qj.- Validate with
RateMatrix::new; a negativer_iqorr_qjraisesInvalidInput"rates incompatible with proportions: entry (i, j) = value".
Golden example (Carle): p = (0.5, 0.3, 0.2), L1 = 4, L2 = 2, pi_12 = 0.6, pi_21 = 0.7,
background 3 (index 2). Partial: r_00 = -0.25, r_01 = 0.6/4 = 0.15, r_10 = 0.7/2 = 0.35,
r_11 = -0.5. Result:
Q = [[-0.25, 0.15, 0.10], [0.35, -0.5, 0.15], [0.1, 0.375, -0.475]], L3 = 2.105263157894737,
eigenvalues 0, -0.5, -0.725,
Pi = [[0, 0.6, 0.4], [0.7, 0, 0.3], [0.2105263158, 0.7894736842, 0]],
nu = (0.3378378378, 0.4054054054, 0.2567567568).
T(0.5) = [[0.8894003915, 0.0663597651, 0.0442398434], [0.1474291504, 0.7899162352, 0.0626546144], [0.0553552955, 0.1492262345, 0.79541847]]
T(1) = [[0.8032653299, 0.1180408021, 0.0786938681], [0.2510484883, 0.6431007346, 0.1058507771], [0.115263943, 0.2402468928, 0.6444891642]]
T(5) = [[0.5410424993, 0.2753745004, 0.1835830003], [0.483595679, 0.3205022315, 0.1959020895], [0.4220002332, 0.3308104017, 0.2471893651]]
T(50): every row (0.5, 0.3, 0.2). This Q is not reversible.
7. Maximum entropy rates¶
Given p and L (all k, positive):
1. phi_i = p_i / L_i. Necessary condition: phi_i <= sum_{j != i} phi_j for all i, else
InvalidInput naming i (no valid model exists).
2. E = quasi_independence(phi, phi); Pi = E with rows divided by phi.
3. R = diag(1 / L) (Pi - I). Then p^T R = 0 holds by construction (column sums of E equal
phi); assert it within 1e-12 max|r|.
The result is reversible (E symmetric when row and column targets are equal), which T-PROGS uses for lateral directions.
8. Closed forms used in tests¶
- Two states,
a = q_01,b = q_10,s = a + b:T00 = b/s + (a/s) e^{-sh},T01 = (a/s)(1 - e^{-sh}),p = (b, a) / s. - Single rate:
R = lambda (1 p^T - I)givesT(h) = 1 p^T + (I - 1 p^T) e^{-lambda h},L_i = 1 / (lambda (1 - p_i)); eigenvalue-lambdahas multiplicity k - 1.
Implementer decisions¶
digammauses the recurrence up tox >= 10, not 6: at 6 the first omitted series term is about 1e-12, above the 1e-13 relative accuracy section 4 of spec.md requires.expm_ratestops the Poisson series when the term weight drops below1e-18(at most 40 terms) instead of testing1 - sum w < 1e-17, which rounding can keep above1e-17forever.RateMatrix::newaccepts[[0]]for a single category (the closeness rule "1 when k = 1" needs one-category models); every other diagonal must be negative.RateMatrix::from_partialclamps a filled entry in[-1e-12 max|r|, 0)to 0 and raises below that.TransitionMatrix::reversedraises when a reversed row sums farther than1e-9from 1 (pi not stationary) and renormalises rows within that tolerance;RateMatrix::reversedrescales off-diagonals so rows sum to 0.RateMatrix::is_reversible(p, tol)compares|p_i q_ij - p_j q_ji|withtol * max|q|.numerics::components(public) returns the strongly connected classes used byis_irreducibleand the "reducible chain" message.quasi_independenceraisesInvalidInputwhen a positive margin has no allowed cell, and when row and column totals differ by more than1e-9relative.SequenceSet::regularreturns one Vec per run, possibly empty, aligned withruns; a sample position inside an internal gap takes the code of the interval before it.CategoriesJSON usesdeny_unknown_fields, sofrom_jsonnames an unknown key.serde_matalso hasoptionandvecsubmodules forOption<Mat>andVec<Mat>fields.- New module
synthetic: seeded test data with known parameters for every crate (markov_codes,markov_holes,rate_beds,rate_holes,hmm_sample,layered_field,drillholes). Sequence or holeiusesStream::new(seed, &[tag::SAMPLE, i]). The layered field is a laterally constant layer cake, so its exact transiogram isexp(Q_z h_z). crates/py/src/core.rsexposes two private test hooks,_sequence_runsand_sequences, soargs::sequence_setandargs::sequencesare tested from Python.RowMaphas fieldsrows(input row per step, per sequence, in direction order),n_rows,listanddirection.- When
depthis given, samples spaced wider thanstepleave a gap ofspacing - step, which breaks the run when it exceedsgap(not a separate1e-6 * steprule). - Stub crates carry
#![allow(unused_variables)]inlib.rsandcrates/py/src/args.rscarries#![allow(dead_code)]; owners remove them once their bodies are filled.Hsmm::initializeandtpsim::quenchcarry#[allow(clippy::too_many_arguments)]because the contract fixes eight arguments. - The
linttask checkspython examples ci.ci/compat.pybuilds the wheel once and installs it with pip (venv), uv (Python 3.11), pixi and micromamba (conda-forge), running a smoke check in each. available_bytesalso takes the smallest headroom of the cgroup v2memory.maxchain and of the process's ownulimit -d(VmData) andulimit -v(VmSize) limits, so a capped process raisesInvalidInputinstead of being killed. pytest (python/tests/conftest.py) and the cargo test runner (.cargo/config.toml) set a 4 GiB data limit on test processes only; the library itself has no fixed cap.