mixle.stats.univariate.continuous.generalized_pareto module¶
Generalized Pareto distribution (GPD): the peaks-over-threshold law of extreme exceedances.
By the Pickands-Balkema-de Haan theorem the distribution of exceedances over a high threshold of
almost any distribution converges to a GPD, which makes it the workhorse for modelling tail risk
(hydrology, finance, reliability). With threshold loc = mu, scale sigma > 0 and shape xi,
for y = x - mu >= 0:
f(x) = (1/sigma) (1 + xi * y / sigma) ** (-1/xi - 1) (xi != 0), f(x) = (1/sigma) exp(-y / sigma) (xi == 0, the exponential tail).
xi > 0 is a heavy (Pareto) tail, xi = 0 exponential, xi < 0 a tail with a finite upper
endpoint at mu - sigma/xi. The threshold mu is treated as a fixed, known level (chosen, not
fit – the standard peaks-over-threshold setup); sigma and xi are fit by method of moments,
which is closed-form: xi = (1 - m^2/v)/2 and sigma = m (1 - xi) from the exceedance mean m
and variance v (valid for xi < 1/2, where the variance is finite).
Reference: Pickands, ‘Statistical inference using extreme order statistics’, Ann. Statist. (1975).
- class GeneralizedParetoSuffStat(sum_, sum2_, count_, anchored=None, max_x=None, max_unverified=False)[source]
Bases:
tupleA
(sum, sum2, count)sufficient statistic that also carries two side payloads.Behaves exactly like the plain 3-tuple everywhere it is indexed, unpacked, or iterated (it is one);
anchoredis the shift-anchored moment payload(anchor, sum_i w_i*(x_i - anchor), sum_i w_i*(x_i - anchor)^2)thatGeneralizedParetoAccumulatormaintains alongside the raw moments so the moment inversion survives a threshold far from zero.max_xis the largest observation actually folded into these moments with positive weight (Nonewhen no such max is known to be trustworthy – seeGeneralizedParetoAccumulator.combine());GeneralizedParetoEstimator.estimate()uses it to keep a shape<0 fit’s implied support consistent with the data it was fit from (T1-01).max_unverifieddisambiguates WHYmax_xisNonefor a prior-carrying accumulator: it isTruewhen a foreign/pre-payloadcombine()left real observations with no tracked max, so the T1-01 protection could not be applied though it is supposed to be unconditional there, versus the ordinaryFalsecase where the max was never relevant to begin with.estimatereads it to disclose that ambiguity vianumerical_repairs()rather than silently falling back to the pre-T1-01 unclamped behaviour (T1-02). Code that doesn’t know about any of these payloads (genericscale_suff_stat, engine kernels, …) sees an ordinary tuple and the estimate falls back to the historical raw path.
- class GeneralizedParetoPriorMoments(mean, second_moment, variance=None, mean_offset=None)[source]
Bases:
tupleThe
(mean, second_moment)prior pair, carrying the variance and mean offset it was built from.This family is the only one of its siblings whose
pseudo_countprior is encoded as RAW MOMENTS: Gumbel, Student-t and Logistic all take(loc, scale)parameters, from which the prior variance is computed exactly at any magnitude. Recovering it here assecond_moment - mean**2is the same cancellation this module repairs everywhere else, and it is worse than the data path because it is a two-number encoding with no second chance: a prior at a threshold of 1.7e9 recovers a variance of 0.0 from a true 10.4167, and at 1e8 recovers 10.0 – 4% low.meanhas the same disease in the OTHER direction: it islocplus anO(1)exceedance offset, and forming that sum rounds the offset away toloc’s own ULP oncelocis large enough – a threshold of 1e17 already loses the entire offset, well before the variance’s cancellation (which destroys a SQUARED quantity, not an additive one) would even register.mean_offsethangs the exact, loc-invariantmean - locbeside the pair for exactly this reason: captured once while it is still precise (at construction, or carried forward UNCHANGED across alocretarget rather than re-derived by subtracting a largelocback out of an already-roundedmean), a consumer that needs the prior’s exceedance mean reads it directly instead of differencing.Keeping the documented pair AS the tuple and hanging the exact variance and mean offset beside it fixes the library’s own
GeneralizedParetoDistribution.estimator()path without changing the shape any caller passes: a plain 2-tuple still means exactly what it always meant.
- class GeneralizedParetoDistribution(scale, shape, loc=0.0, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionGeneralized Pareto distribution with threshold
loc, scale> 0and shapexi.- density(x)[source]
Return the probability density at a single observation.
- log_density(x)[source]
Return the log-density at a single observation (
-infoutside the support).
- seq_log_density(x)[source]
Return vectorized log-density values for sequence-encoded observations.
- classmethod compute_capabilities()[source]
Describe backend support for generated generalized-Pareto kernels.
- classmethod compute_declaration()[source]
Return the structured compute declaration for generalized Pareto distributions.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Per-row GPD moment sums in accumulator order
(sum, sum2, count).
- static backend_log_density_from_params(x, scale, shape, loc, engine)[source]
Engine-neutral GPD log-density; the
abs(xi) < tolexponential limit is selected per element.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Stacked GPD parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of GPD log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Stacked GPD moment sums
(sum, sum2, count)using engine-resident arrays.
- cdf(x)[source]
Cumulative distribution function
P(X <= x)(exact).
- sampler(seed=None)[source]
Return a sampler for drawing observations from this distribution.
- Parameters:
seed (int | None)
- Return type:
GeneralizedParetoSampler
- estimator(pseudo_count=None)[source]
Return a method-of-moments estimator for
scaleandshapeat the fixed thresholdloc.- Parameters:
pseudo_count (float | None)
- Return type:
GeneralizedParetoEstimator
- dist_to_encoder()[source]
Return the data encoder used by this distribution for vectorized methods.
- Return type:
GeneralizedParetoDataEncoder
- class GeneralizedParetoSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDraw iid GPD observations by inverse-CDF transform.
- Parameters:
dist (GeneralizedParetoDistribution)
seed (int | None)
- class GeneralizedParetoAccumulator(loc=0.0, name=None, keys=None, has_prior=False)[source]
Bases:
AnchoredMomentTrack,SequenceEncodableStatisticAccumulatorAccumulate weighted first and second moments for GPD estimation.
Alongside the raw
(sum, sum2, count)the accumulator keeps the conditioning-gated shift-anchored moment track ofAnchoredMomentTrack. Peaks-over-threshold data is the case that needs it most: BOTH moments the inversion uses are differences taken at data magnitude – the exceedance meansum_x/count - locand the varianceE[x^2]-E[x]^2– so a threshold at epoch seconds turned a shape of+0.16into a flat0and the exponential limit, silently. Well-conditioned data never activates the track and accumulates bit-identically to the historical single-pass path.- update(x, weight, estimate)[source]
Accumulate weighted first and second moments for one observation.
- initialize(x, weight, rng)[source]
Initialize statistics from one observation.
- Parameters:
x (float)
weight (float)
rng (RandomState | None)
- Return type:
None
- seq_update(x, weights, estimate)[source]
Accumulate weighted first and second moments from encoded data.
- seq_initialize(x, weights, rng)[source]
Initialize statistics from encoded observations.
- Parameters:
x (ndarray)
weights (ndarray)
rng (RandomState | None)
- Return type:
None
- combine(suff_stat)[source]
Merge another generalized-Pareto sufficient-statistic tuple.
- value()[source]
Return accumulated sum, second moment sum, and count.
A plain 3-tuple for every consumer that treats it as one; once the shift-anchored moment track is live, or a trustworthy observation max is known AND relevant, it is a
GeneralizedParetoSuffStatadditionally carrying the anchored moments in its.anchoredattribute and/or the max in.max_x, socombine()can fold them in andGeneralizedParetoEstimator.estimate()can invert threshold-invariant moments and keep a shape<0 fit’s implied support consistent with the data (T1-01). “Relevant” is always true for a prior-carrying estimator (see_max_x_relevant()); for one without a prior it is the same cheap raw-moment pre-check as before, so ordinary well-conditioned data still returns the historical plain tuple, byte for byte.For a prior-carrying estimator that protection is supposed to be unconditional, but a foreign (pre-payload)
combine()can still leave real observations with no trustworthy max (self._max_tainted); rather than silently degrade to the plain tuple that hides this fromestimate, that case is still reported as aGeneralizedParetoSuffStatwithmax_x=Noneandmax_unverified=True, soestimatecan disclose the ambiguity instead of reproducing the T1-01 crash class with zero signal (T1-02).
- from_value(x)[source]
Replace accumulator contents from a sufficient-statistic tuple.
- scale(c)[source]
Scale the accumulated statistics in place by
c, anchored track included.The structural default round-trips through
value()/from_value()andscale_suff_statrebuilds a PLAIN tuple, which would drop the payload and undo the repair;locis a fixed threshold, not a statistic, and is left alone. The tracked max is likewise left alone: uniform weight scaling reweights the aggregate contribution of the same observations, it does not change which values were actually observed.- Parameters:
c (float)
- Return type:
GeneralizedParetoAccumulator
- acc_to_encoder()[source]
Return the encoder used by this accumulator.
- Return type:
GeneralizedParetoDataEncoder
- class GeneralizedParetoAccumulatorFactory(loc=0.0, name=None, keys=None, has_prior=False)[source]
Bases:
StatisticAccumulatorFactoryFactory for GeneralizedParetoAccumulator.
- make()[source]
Create a fresh generalized-Pareto accumulator.
- Return type:
GeneralizedParetoAccumulator
- class GeneralizedParetoEstimator(loc=0.0, pseudo_count=None, suff_stat=None, min_scale=1.0e-12, xi_max=0.5 - 1.0e-6, xi_min=-10.0, name=None, keys=None)[source]
Bases:
ParameterEstimatorMethod-of-moments estimator for GPD scale and shape at a fixed threshold
loc.Both inverted moments – the exceedance mean
sum_x/count - locand the varianceE[x^2]-E[x]^2– are differences taken at DATA magnitude, so a threshold far from zero destroys them: peaks over a threshold at epoch seconds fittedshape=0(the exponential limit) instead of+0.16, silently. Whenever the accumulated statistics carry the shift-anchored payload (seeGeneralizedParetoAccumulator) both moments are formed about a data anchor instead, which makes the fit THRESHOLD-EQUIVARIANT: estimating onx + cwith the threshold atloc + creturns the samescaleandshape, for any constantcthe data can carry. With a plain raw tuple – statistics the conditioning gate never needed to anchor, or ones that arrived already reduced from an engine kernel or an older serialization – the historical raw path is used bit-identically, andestimatewarns rather than returning moments it cannot stand behind.The
pseudo_countprior is carried as the raw pairsuff_stat = (mean0, second0); a plain 2-tuple has its variance and exceedance-mean offset recovered by differencing (second0 - mean0**2andmean0 - locrespectively), which is the prior’s own encoding and is unaffected by the anchored track – a prior whose mean sits far from zero loses precision in both reconstructions, so express such a prior in threshold-relative coordinates, or build it withGeneralizedParetoDistribution.estimator(), which carries both exactly (seeGeneralizedParetoPriorMoments).locis a property, not a bare attribute: reassigning it re-targets this SAME estimator at a new threshold (the “threshold stability” / mean-residual-life re-thresholding workflow) and, when apseudo_countprior is configured, re-anchors its frozen(mean0, second0)moments to the new origin so the prior keeps meaning what it meant when built instead of being silently reinterpreted relative to the wrongloc(T1-01).- Parameters:
- property loc: float
The fixed threshold
muobservations are exceedances over.
- accumulator_factory()[source]
Return an accumulator factory for generalized-Pareto moments.
- Return type:
GeneralizedParetoAccumulatorFactory
- class GeneralizedParetoDataEncoder(loc=0.0, scale=None, shape=None)[source]
Bases:
DataSequenceEncoderEncode GPD observations as a float array.