mixle.analysis package¶
Applied statistical methods that are not probability-distribution families.
These are estimators / analysis routines (extreme-value, kernel density, species coverage, geostatistics,
rank aggregation, spatial mixtures, max-stable processes, covariance shrinkage) that operate on data but
are not SequenceEncodableProbabilityDistribution families and are not used by any distribution. They
were previously scattered under mixle.stats; collected here so the distributions package stays focused
on distribution families.
- class GPDFit(shape, scale, threshold, n_exceedances, n_total, method)[source]
Bases:
objectFitted Generalized Pareto Distribution for exceedances over a threshold.
- Parameters:
- shape
tail index
xi(> 0heavy/Pareto tail,= 0exponential,< 0bounded).- Type:
- scale
scale
beta(> 0).- Type:
- threshold
the threshold
uthe exceedances were measured over.- Type:
- n_exceedances / n_total
exceedance and full-sample sizes (for return levels).
- method
"mle"or"pwm".- Type:
- shape: float
- scale: float
- threshold: float
- n_exceedances: int
- n_total: int
- method: str
- property endpoint: float
Right endpoint of the support (finite when
shape < 0, elseinf).
- gpd_fit(exceedances, *, threshold=0.0, method='mle', n_total=None)[source]
Fit a Generalized Pareto Distribution to threshold exceedances.
- Parameters:
exceedances (ndarray) – the excesses
x - ufor observations above the threshold (all positive). If you have raw data, usepeaks_over_threshold()instead.threshold (float) – the threshold
u(stored for return-level computation).method (str) –
"mle"(Newton/Nelder-Mead on the GPD likelihood) or"pwm"(probability-weighted moments, closed form, robust forxi < 0.5).n_total (int | None) – full sample size before thresholding (defaults to the number of exceedances).
- Returns:
A
GPDFit.- Return type:
GPDFit
- peaks_over_threshold(data, threshold, *, method='mle')[source]
Peaks-over-threshold: select exceedances above
thresholdand fit a GPD to the excesses.
- return_level(fit, period)[source]
POT return level: the level exceeded on average once per
periodobservations.x_m = u + (beta/xi) [ (m zeta_u)^xi - 1 ]withzeta_u = n_exceed/n_totalthe exceedance rate (period = m). Forxi = 0it reduces tou + beta log(m zeta_u).
- hill_estimator(data, k)[source]
Hill estimator of the tail index
xi = 1/alphafrom the topkorder statistics.xi_hat = (1/k) sum_{i=1}^{k} log(X_(n-i+1) / X_(n-k))– consistent for heavy (Pareto-type,xi > 0) tails. For a Pareto tail with exponentalphathis estimates1/alpha.
- moment_estimator(data, k)[source]
Dekkers–Einmahl–de Haan moment estimator of the extreme-value index (any tail sign).
Generalises Hill to
xiof either sign by combining the first two log-moments of the topkexceedances; works for heavy, light, and bounded (xi < 0) tails.
- mean_residual_life(data, thresholds)[source]
Mean-excess (mean-residual-life) function for POT threshold selection.
e(u) = mean(X - u | X > u). Over a range where the GPD fits,e(u)is approximately linear inu(slopexi/(1-xi)); the lowest threshold from which the plot is linear is the choice.
- endpoint_estimator(data, k, *, method='gpd')[source]
Estimate the finite right endpoint of a bounded support (frontier / boundary estimation).
Fits a GPD to the top
kexceedances overX_(n-k); when the tail indexxiis negative the support is bounded and the endpoint isx+ = X_(n-k) - beta/xi(which, by the GPD support constraint, necessarily exceeds the observed maximum). Generic to econometric frontier analysis, reliability limits, and image-edge localisation. Returnsinfif the estimated tail is unbounded (xi >= 0).
- n_records(data)[source]
Number of upper records. For an i.i.d. sequence of length
nthe expectation isH_n.
- record_times(data)[source]
Indices at which a new running maximum (upper record) occurs, including the first observation.
- class KDE(data, *, bandwidth='silverman', bounds=None, adaptive=False)[source]
Bases:
objectA fitted kernel density estimate.
Use
kde()to construct. Evaluate withevaluate()(or call the instance). Supports a Gaussian kernel, reflection boundary correction (bounds), and adaptive bandwidths.
- kde(data, *, bandwidth='silverman', bounds=None, adaptive=False)[source]
Construct a kernel density estimate (Gaussian kernel).
- Parameters:
data (ndarray) –
(n,)sample.bandwidth –
"silverman","scott", or a positive float.bounds –
(lo, hi)support limits for reflection boundary correction; either may beNonefor an unbounded side (e.g.(0.0, None)for a positive variable).adaptive (bool) – use Abramson variable bandwidths (wider where the pilot density is low).
- Returns:
A
KDE.- Return type:
KDE
- kde_mode(data, *, bandwidth='silverman', bounds=None, grid=None, ci=False, n_boot=500, ci_level=0.95, seed=0)[source]
Estimate the mode (peak location) of a density, optionally with a bootstrap CI.
- Parameters:
data (ndarray) –
(n,)sample.bandwidth – passed to
kde().bounds – passed to
kde().grid (ndarray | None) – evaluation grid; defaults to 512 points spanning the data range.
ci (bool) – if True return a percentile bootstrap interval for the mode.
n_boot (int) – bootstrap controls.
ci_level (float) – bootstrap controls.
seed (int | RandomState | None) – bootstrap controls.
- Returns:
The mode (float), or
{'mode', 'ci_low', 'ci_high'}whenciis True.- Return type:
- intensity(events, grid, *, bandwidth='silverman', domain=None, edge_correct=True)[source]
Kernel intensity
lambda(t)of an inhomogeneous Poisson / point process.Unlike a density (which integrates to 1), the intensity integrates to the expected number of events:
lambda_hat(t) = sum_i K_h(t - t_i). Withedge_correctthe estimate is divided by the fraction of the kernel falling insidedomain, removing the downward bias near the boundary.- Parameters:
events (ndarray) –
(m,)event locations.grid (ndarray) – points
tat which to evaluate the intensity.bandwidth –
"silverman","scott", or a float.domain (tuple[float, float] | None) –
(lo, hi)observation window (defaults to the event range); used for edge correction.edge_correct (bool) – divide by the in-window kernel mass at each
t.
- Returns:
The intensity evaluated on
grid.- Return type:
- silverman_bandwidth(data)[source]
Silverman’s rule-of-thumb bandwidth
0.9 min(sd, IQR/1.34) n^{-1/5}(1-D).
- scott_bandwidth(data)[source]
Scott’s rule-of-thumb bandwidth
sd * n^{-1/(d+4)}.
- turing_coverage(counts)[source]
Turing’s sample-coverage estimate and the complementary unseen probability mass.
C = 1 - f1 / nwheref1is the number of singletons andnthe total count: the estimated probability that the next observation is a previously seen species.1 - C = f1/nis the Good–Turing estimate of the total probability of all unseen species.
- good_turing(counts)[source]
Simple Good–Turing smoothed probabilities (Gale & Sampson 1995).
Reallocates probability from seen to unseen items using the frequencies of frequencies. Empirical Turing estimates
r* = (r+1) N_{r+1}/N_rare used for smallrand a smoothed log-linear fitS(r)takes over once the two diverge (the Gale switch), giving stable discounts in the sparse tail.- Parameters:
counts (ndarray) – per-species abundances (zeros ignored).
- Returns:
{'p0', 'proba', 'r_star', 'r'}–p0is the total probability assigned to unseen species;probaare the smoothed probabilities of the input species (aligned to the positive entries ofcounts, summing to1 - p0);r_star/rare the discounted and raw frequencies for the distinct abundance classes.- Return type:
- chao1(counts, *, ci_level=0.95)[source]
Chao1 nonparametric richness estimator from abundance data (bias-corrected).
S_chao1 = S_obs + f1 (f1 - 1) / (2 (f2 + 1))(Chao 1984, bias-corrected form), a lower bound on total richness driven by the singleton (f1) and doubleton (f2) counts. Returns a standard error and a log-normal confidence interval for the number of undetected species (Chao 1987), so the interval respectsS_chao1 >= S_obs.
- chao2(incidence, *, ci_level=0.95)[source]
Chao2 richness estimator from replicated incidence (presence/absence) data.
- Parameters:
- Returns:
{'estimate', 'observed', 'q1', 'q2', 'se', 'ci_low', 'ci_high', 'sites'}whereq1/q2are the numbers of species found in exactly one / two sites.- Return type:
- ace(counts, *, rare_threshold=10)[source]
ACE: Abundance-based Coverage Estimator of richness (Chao & Lee 1992).
Splits species into abundant (
> rare_threshold) and rare, estimates sample coverage from the rare group’s singletons, and corrects for the coefficient of variation of the rare abundances.
- ice(incidence, *, rare_threshold=10)[source]
ICE: Incidence-based Coverage Estimator of richness (the Chao–Lee estimator for incidence data).
- hill_numbers(counts, q=(0.0, 1.0, 2.0))[source]
Hill numbers (effective number of species) of order
q.The unified diversity profile:
q=0is observed richness,q=1is the exponential of Shannon entropy,q=2is the inverse Simpson concentration. Largerqweights common species more, so the profileD(q)summarises evenness as well as richness.
- rarefaction_curve(counts, sizes=None)[source]
Individual-based rarefaction: expected richness when subsampling
mindividuals (Hurlbert).E[S(m)] = sum_i (1 - C(n - x_i, m) / C(n, m))– the expected number of species seen in a random subsample ofmof thenindividuals. Used to compare richness between samples at a common sample size (or coverage).
- class Variogram(model, nugget, psill, rng, nu=1.5, anisotropy=None)[source]
Bases:
objectA fitted variogram model
gamma(h) = nugget + psill * shape(h).- Parameters:
- model
"spherical","exponential","gaussian"(aka"squared_exponential"/"rbf"– covariancepsill * exp(-(h/rng)**2)), or"matern".- Type:
- nugget
discontinuity at
h=0(measurement error / micro-scale variance).- Type:
- psill
partial sill (correlated variance);
nugget + psillis the total sill.- Type:
- rng
range (correlation length).
- Type:
- nu
Matern smoothness (ignored by other models).
- Type:
- anisotropy
optional
(angle_rad, ratio)geometric anisotropy – coordinates are rotated byangleand the minor axis scaled by1/ratiobefore distances are taken.
- model: str
- nugget: float
- psill: float
- rng: float
- nu: float = 1.5
- empirical_variogram(coords, values, *, n_bins=15, max_dist=None)[source]
Binned empirical (semi-)variogram: mean
0.5 (z_i - z_j)^2by separation distance.
- fit_variogram(coords, values, *, model='spherical', n_bins=15, nu=1.5)[source]
Fit a variogram model to data by least squares on the empirical variogram.
- ordinary_kriging(coords, values, variogram, query, *, noise=None)[source]
Ordinary kriging: BLUP of the field at
queryunder an unknown constant mean.- Parameters:
coords (ndarray) –
(n, d)data locations.values (ndarray) –
(n,)measured field.variogram (Variogram) – a fitted
Variogram.query (ndarray) –
(q, d)prediction locations.noise (ndarray | None) – optional
(n,)per-observation measurement variance (heteroscedastic nugget); if None the homoscedasticvariogram.nuggetis used on the diagonal.
- Returns:
{'prediction', 'variance'}arrays of lengthq.- Return type:
- universal_kriging(coords, values, variogram, query, *, degree=1, noise=None)[source]
Universal kriging: kriging with a polynomial spatial trend (drift) of the given
degree.degree=1removes a linear trend,degree=2a quadratic one. Use when the field has a large-scale drift on top of the stationary residual the variogram describes.
- calibrate_variance(predicted_var, residuals, *, target=0.9)[source]
Scale factor that makes kriging predictive intervals hit a target coverage.
Finds
cso that standardised residualsresidual / sqrt(c * predicted_var)achieve thetargetcentral coverage under a Gaussian predictive. Returns the variance multiplierc; multiplypredicted_varby it to recalibrate (generic GP/kriging variance recalibration).
- borda_count(rankings)[source]
Borda positional aggregation: each item scores
(m - 1 - position)summed over voters.
- copeland(rankings)[source]
Copeland pairwise-majority aggregation.
Each ordered pair contributes a win/loss by majority across voters; an item’s score is wins minus losses. Closely tracks the Condorcet winner when one exists.
- kemeny_consensus(rankings, *, exact_max_items=8)[source]
Kemeny median ranking: minimise the total Kendall-tau distance to all input orderings.
The Kemeny consensus is the maximum-likelihood aggregation under the Mallows–Kendall model and the Condorcet-consistent choice. Exact by enumeration when
m <= exact_max_items; otherwise a local search (adjacent transpositions) from the Borda ordering.
- mallows_fit(rankings, *, exact_max_items=8)[source]
Fit a Mallows model (Kendall): central ranking + dispersion
theta.The central ranking is the
kemeny_consensus();thetais the MLE concentration, found by matching the observed mean Kendall distance to its expectation under the model. Largerthetameans tighter agreement (theta -> 0is uniform/no-consensus).
- kendall_distance(a, b)[source]
Kendall-tau distance: the number of item pairs ordered oppositely by
aandb.
- spearman_footrule(a, b)[source]
Spearman footrule distance: the sum of absolute position differences across items.
- cayley_distance(a, b)[source]
Cayley distance: the minimum number of transpositions turning
aintob(m - #cycles).
- class SpatialMixture(shape, n_components, emission, beta=1.0)[source]
Bases:
objectA grid-structured mixture with a Potts prior on the latent labels and pluggable mixle emissions.
- Parameters:
shape – grid shape, e.g.
(nx, ny)or(nx, ny, nz)– defines the neighbour structure.n_components (int) – number of mixture components (latent classes).
emission – a mixle
ParameterEstimatorfor the per-component family, e.g.MultivariateGaussianEstimator()– this is what makes the class domain-agnostic.beta (float) – Potts coupling (
>= 0); larger smooths the labels more.0is an ordinary mixture.
- fit(observations, *, max_iter=40, mf_iter=3, seed=0)[source]
Fit by mean-field variational EM.
observationsis a length-prod(shape)sequence of per-cell observations (row order matchesshape.ravel()); each is a single emission datum.Robustness: components are initialized by a short hard-assignment pass and the Potts coupling is annealed from 0 to
betaover the first iterations, so components form before the smoothness prior is applied (a strong prior on a degenerate init otherwise collapses every cell into one).
- responsibilities()[source]
The posterior label probabilities,
(prod(shape), n_components)– a simplex per cell.- Return type:
- entropy()[source]
Per-cell posterior entropy (label uncertainty), reshaped to
shape.- Return type:
- class SmithMaxStable(sigma)[source]
Bases:
objectThe Smith max-stable process with Gaussian storm-profile covariance
sigma(d x d, SPD).A spatial process, not an i.i.d. leaf distribution: its full likelihood is intractable, so it is not a
SequenceEncodableProbabilityDistribution– it exposes the things that do have closed forms (extremal_coefficient,bivariate_cdf) plus asampler, and is fitted by the module-levelfit_smith_maxstable()(composite/madogram estimation), mirroring the functional fit style of the other non-leaf spatial models. Margins are unit Frechet; spatial dependence grows withsigma.- Parameters:
sigma (np.ndarray)
- extremal_coefficient(h)[source]
theta(h) = 2 * Phi(a/2)withathe Mahalanobis lag length – 1 at h=0 (full dependence) rising to 2 as the lag grows (independence).
- bivariate_cdf(z1, z2, h)[source]
P(Z(s) <= z1, Z(s+h) <= z2) = exp(-V(z1, z2))– the Smith bivariate distribution.
- class SmithMaxStableSampler(dist, locations, seed=None)[source]
Bases:
object- Parameters:
dist (SmithMaxStable)
locations (np.ndarray)
seed (int | None)
- fit_smith_maxstable(locations, fields)[source]
Fit an isotropic Smith max-stable process (
sigma = s^2 I) to replicated spatial extremes.locationsis(n_locations, d)andfieldsis(n_replicates, n_locations)of block maxima. Estimation matches the binned empirical extremal coefficient (from the F-madogram) to the model2 Phi(|h| / (2 s)). Returns aSmithMaxStable.
- class LedoitWolfEstimator(dim=None, name=None, keys=None)[source]
Bases:
ParameterEstimatorEstimate a multivariate Gaussian with a Ledoit-Wolf-shrunk covariance.
Returns a
MultivariateGaussianDistributionwhose mean is the sample mean and whose covariance is shrunk toward a scaled identity by the data-driven Ledoit-Wolf intensity. The chosen intensity is exposed on the returned distribution asdist.shrinkagefor inspection.- accumulator_factory()[source]
- Return type:
LedoitWolfAccumulatorFactory
- estimate(nobs, suff_stat)[source]
- Return type:
MultivariateGaussianDistribution