EI Namespace¶
The exported unibm.ei namespace groups the persistence-side workflow:
sample preparation, BM-path construction, stable-window selection, pooled
BM estimators, threshold estimators, plotting helpers, and bootstrap-based
covariance support.
prepare_ei_bundle owns the observed paths and candidate threshold quantiles.
It requires an explicit allow_zeros choice and preserves the caller's observation
clock. A threshold estimator's omitted candidate list uses the bundle's list;
an explicit subset must be increasing and present in that bundle.
For pooled FGLS, first call bootstrap_bm_ei_path with the same data, base_path,
sliding/disjoint scheme, and block-size grid. Then pass its result to
estimate_pooled_bm_ei. OLS does not accept a bootstrap result. See the
complete FGLS example
and precision diagnostics.
ei
¶
Canonical EI-facing UniBM subpackage.
EI_DEFAULT_COVARIANCE_SHRINKAGE = 0.37
module-attribute
¶
EI_ALPHA = 0.05
module-attribute
¶
EI_CI_LEVEL = 1.0 - EI_ALPHA
module-attribute
¶
EI_TINY = 1e-08
module-attribute
¶
__all__ = ['EI_ALPHA', 'EI_CI_LEVEL', 'EI_DEFAULT_COVARIANCE_SHRINKAGE', 'EI_TINY', 'EiPathBundle', 'EiPreparedBundle', 'EiStableWindow', 'ExtremalIndexEstimate', 'ThresholdCandidate', 'bootstrap_bm_ei_path', 'bootstrap_bm_ei_path_draws', 'estimate_ferro_segers', 'estimate_k_gaps', 'estimate_native_bm_ei', 'estimate_pooled_bm_ei', 'extract_stable_path_window', 'plot_ei_fit', 'plot_ei_path', 'prepare_ei_bundle', 'select_stable_path_window']
module-attribute
¶
EiPathBundle
dataclass
¶
Observed BM-EI path ingredients for one base-path and block scheme.
theta_path and z_path are computed from the observed series over the
candidate block-size grid. stable_window and selected_level record
where that observed path is judged stable. For an explicitly fixed single
block size, stable_window is None and selected_level is that size.
sample_statistics
preserves the per-block-size window statistics reused by native fixed-b
estimators.
EiPreparedBundle
dataclass
¶
Reusable EI preparation outputs derived from one observed series.
The bundle stores the validated observed values without filtering, the block-size
grid, requested BM path variants, and threshold-side exceedance candidates so the
native BM, pooled BM, and threshold estimators can all reuse the same
preparation step. paths uses (base_path, sliding) keys, while
threshold_candidates maps quantiles to strict-exceedance index arrays.
Threshold-only preparation has an empty block-size grid and empty paths.
Frozen fields do not make the contained arrays and dictionaries immutable.
EiStableWindow
dataclass
¶
Inclusive lower and upper tuning levels, rather than array positions.
ExtremalIndexEstimate
dataclass
¶
Unified formal-EI result container.
Most users should read theta_hat and confidence_interval first, then
inspect stable_window, regression, and base_path to understand
which formal estimator produced the headline result. standard_error is
always on the native theta scale; pooled BM fits additionally expose the
regression-scale uncertainty in z_standard_error. path_level,
path_theta, and path_eir are retained for path diagnostics and
plotting rather than for headline reporting.
ThresholdCandidate
dataclass
¶
One threshold-side EI fit before cross-threshold selection.
bootstrap_bm_ei_path(vec, *, allow_zeros, base_path, sliding, block_sizes, reps='adaptive', random_state=0, bootstrap_block_length=None, covariance_shrinkage=None, n_threads=None)
¶
Bootstrap BM-EI covariance; default adaptive precision targets pooled theta and z.
Resample contiguous circular blocks of the observed series. The raw
resampling length defaults to min(n, max(16, round(sqrt(n)))) and can be
set with bootstrap_block_length; it is separate from the increasing
block_sizes grid used to evaluate the EI path. random_state seeds
NumPy's generator (default 0); None requests non-reproducible seeding.
n_threads=None chooses at most 8 threads from CPU/workload size;
a positive integer caps this pool and 1 stays serial. It does not modify
BLAS settings. Outer parallel callers should allocate the inner cap.
Batch/thread choices preserve draws, path order and adaptive stopping.
An explicit integer of at least two retains fixed-R sampling and rejects
an explicit covariance_shrinkage. That parameter only controls the
pooled fit monitored by adaptive stopping; None resolves to 0.37.
Neither mode shrinks the returned sample covariance. Adaptive precision
is conditional on the original stable window and the monitoring shrinkage.
Checkpoints are 128, 256, 512, 768, and 1024. The target vector includes theta
and its CI endpoints plus the unconstrained z fit and endpoints, so the
theta=1 boundary cannot hide Monte Carlo error. The cap retains the result
with a warning and bootstrap_precision_met=False if tolerance is unmet.
This flag measures Monte Carlo precision, not confidence-interval coverage.
The returned in-memory dictionary contains full-grid covariance, path draws,
block-size labels, estimator identity, and sampling/precision metadata. Pass
it to estimate_pooled_bm_ei with matching data, path, and block scheme.
Reusing adaptive precision metadata also requires matching the monitored
shrinkage (default 0.37). This function does not write intermediate files.
allow_zeros declares whether observed zeros are legal; non-finite inputs
are always rejected rather than removed from the observation clock.
bootstrap_bm_ei_path_draws(bootstrap_samples, *, block_sizes, allow_zeros, path_keys=BM_PATH_KEYS, n_threads=None)
¶
Transform supplied resamples into BM-EI paths without generating new draws.
bootstrap_samples is a 2D array with one series per row and at least 32
observations per series. Values must be finite and positive, or non-negative
when allow_zeros=True; zeros retain their positions. block_sizes is
an increasing integer grid from 2 through the number of observations.
Return a dictionary keyed by requested (base_path, sliding) pairs, where
base_path is "northrop" or "bb". Each value is an array of shape
(n_draws, n_block_sizes) containing z = log(1 / theta). All four paths
are returned by default. The caller controls the resampling design and clock.
n_threads=None selects up to eight threads from CPUs and workload;
a positive integer caps the pool, and 1 is serial. BLAS is not reconfigured.
estimate_native_bm_ei(bundle, *, base_path, sliding, use_adjusted_chandwich=False)
¶
Estimate theta with a native single-block-size BM estimator.
bundle comes from prepare_ei_bundle. Choose base_path="northrop"
or "bb" and a prepared sliding/disjoint scheme. Fit at an explicitly
supplied single block size, or the smallest size in the selected stable
window, and retain the path for diagnostics.
Northrop uses a nominal 95% profile interval and observed-information SE,
or a score-based Chandler--Bate adjustment when use_adjusted_chandwich
is true. BB rejects this Northrop-only option and uses a bounded 95% Wald
interval and delta-method SE. All returned SEs are on the theta scale.
These intervals condition on the selected block size. Their variance estimates do not include cross-block score/statistic covariances, so using sliding blocks does not by itself provide dependence-adjusted coverage.
estimate_pooled_bm_ei(bundle, *, base_path, sliding, regression, bootstrap_result=None, covariance_shrinkage=None)
¶
Estimate theta by pooling an observed BM path over a stable window.
bundle comes from prepare_ei_bundle; base_path is "northrop"
or "bb" and sliding chooses the prepared block scheme. Each finite
path level in the inclusive stable window contributes to the pooled fit.
The fitted intercept is constrained to z = log(1 / theta) >= 0.
standard_error is delta-transformed to the theta scale, while
z_standard_error retains the regression-scale uncertainty.
regression must be OLS or FGLS. OLS rejects a bootstrap result; FGLS
requires covariance from the matching base path and sliding/disjoint scheme
and never falls back to OLS. Full-grid covariance is subset by block-size
labels. Omitted shrinkage uses 0.37 for FGLS. OLS rejects an explicit
shrinkage value; it estimates variance from between-level residuals and
does not model their dependence. A fixed-b path requires native inference.
Return an ExtremalIndexEstimate with a nominal 95% interval and retained
path, covariance, and bootstrap diagnostics.
Adaptive precision metadata is retained only when the bootstrap's checked window and shrinkage match this fit. The log-scale interval is clipped to the legal theta upper boundary of 1 and remains conditional on the selected window; it is not a post-selection or bootstrap-percentile interval.
prepare_ei_bundle(vec, *, allow_zeros, block_sizes=None, path_keys=BM_PATH_KEYS, threshold_quantiles=(0.9, 0.95))
¶
Prepare EI paths and a strictly increasing threshold grid without changing the clock.
vec must be a finite 1D series of at least 32 observations. Values must
be positive unless allow_zeros=True; zeros are then retained at their
original positions. The caller defines what one observation step represents.
block_sizes is an increasing integer grid from 2 through the sample
size, or a generated grid from max(5, ceil(n**(1/3))) through
min(floor(sqrt(n)), floor(n/17)) when omitted. The bounds are not
expanded when too few levels remain for selection. path_keys
selects unique (base_path, sliding) pairs; all four Northrop/BB and
sliding/disjoint pairs are prepared by default. Use path_keys=() for
threshold-only preparation, without a block grid or BM computation.
A single supplied block size fixes native inference at that level without
selecting a stable window. Otherwise selection requires at least four
finite path levels.
Threshold quantiles must be strictly increasing and in (0, 1), defaulting
to (0.90, 0.95). The bundle stores indices strictly above each empirical
quantile; ties equal to the threshold are excluded. Estimators consume this
order unless the caller requests a validated subset.
extract_stable_path_window(path)
¶
Return aligned finite block levels and z values inside the stored window.
Include both window endpoints; raise ValueError if no levels remain
or if the path fixes a single block size without selecting a window.
The returned arrays preserve the original path order.
select_stable_path_window(block_sizes, z_path, *, min_points=4, roughness_penalty=0.75, curvature_penalty=0.5)
¶
Select a flat window of z = log(1 / theta) over increasing block sizes.
z_path must be 1D and aligned with block_sizes. Drop non-finite z
entries and examine every contiguous window of at least min_points
retained levels across the full supplied range.
Minimize variance plus weighted mean absolute first and second differences, divided by the square root of the window length. Differences are across adjacent retained levels, without adjusting for block-size spacing. Exact ties keep the first window encountered. Return inclusive block-size bounds and a boolean mask aligned with the finite path, not the original grid. This is a tuning heuristic, not a test of stationarity or constant theta.
estimate_ferro_segers(bundle, *, threshold_quantiles=None)
¶
Estimate theta from Ferro--Segers inter-exceedance-time moments.
Use prepare_ei_bundle output and either all its threshold quantiles or
an increasing subset of existing quantiles. Skip thresholds with fewer than
three strict exceedances; raise ValueError if none are usable.
Traverse thresholds in order, retaining the current candidate when its
nominal 95% Wald interval overlaps the next candidate's interval, otherwise
replacing it. Return the selected theta, bounded interval, delta-method SE,
and threshold metadata in an ExtremalIndexEstimate. The interval
conditions on the selected threshold and does not include tuning uncertainty
or serial covariance between successive gaps.
estimate_k_gaps(bundle, *, threshold_quantiles=None, k_grid=(1, 2))
¶
Estimate theta from K-gap likelihoods and select a threshold/run-length pair.
bundle supplies strict-exceedance indices on the caller's observation
clock. threshold_quantiles selects an increasing subset of prepared
quantiles or all of them when omitted. k_grid is an increasing sequence
of non-negative integer run lengths in observation steps (default 1 and 2).
At each threshold with at least three exceedances, compare candidates in
increasing K order: retain the current fit if its nominal 95% profile CI
overlaps the next, otherwise replace it. Apply the same rule across threshold
winners. Raise ValueError if no threshold has enough exceedances.
Return theta, its profile interval and observed-information SE, and selected threshold/K metadata. Inference conditions on this selected pair; it does not include tuning uncertainty or a serial-dependence score adjustment.
plot_ei_fit(fit, *, file_path=None, dpi=150, title=None, close=False)
¶
Plot one EI fit either as a retained path view or a threshold summary.
Fits with retained path levels and theta values use a log-block-size view; other fits use a single point with the stored interval when finite. The plotted interval is supplied by the estimator, not recomputed by this helper.
Return (fig, ax) at the requested dpi. Saving requires a non-None
file_path; missing parent directories are
created and existing files may be overwritten. close=True closes the
pyplot figure after drawing/saving while still returning its objects.
plot_ei_path(path, *, file_path=None, dpi=150, title=None, close=False, xlabel='log(block size)', ylabel='extremal index')
¶
Plot one observed EI path and any selected stable window.
Plot finite theta values against the natural log of block size, shade the
stored stable window when present, and mark the native estimator's level. Raise
ValueError if the path has no finite theta values.
Return (fig, ax) for customization at the requested dpi. Saving
requires a non-None file_path; parent directories
are created and an existing file may be overwritten. close=True closes
the figure in pyplot after drawing/saving but still returns its objects.
__getattr__(name)
¶
Load and cache public plotting helpers only when they are first requested.
Unknown names raise AttributeError. Keeping plotting imports here lets
estimation-only imports avoid loading the plotting module.