mixle.analysis.kde module¶
Kernel density, mode, and point-process intensity estimation.
Nonparametric estimates of where the mass is without assuming a parametric family:
KDE/kde()– kernel density estimation for a 1-D(n,)sample or, via an axis-aligned Gaussian product kernel with a per-dimension bandwidth, a genuinely multivariate(n, d)sample (rows are observations; row-pairing is preserved, never flattened). Automatic bandwidth selection (Silverman / Scott) chooses each dimension’s bandwidth from that dimension’s own marginal spread, using the joint-dimensionn^{-1/(d+4)}rate. Adaptive (variable) bandwidths that widen in the sparse tails (Abramson) work in any dimension; normalized boundary correction (reflection on a half-line and per-kernel truncation normalization on a finite interval) is supported for 1-D data only.
kde_mode()– the location of a 1-D density’s peak (“where is the mode, and how sure am I?”) with a bootstrap confidence interval.
intensity()– the intensitylambda(t)of a 1-D inhomogeneous Poisson / point process by kernel smoothing of event locations, with optional edge correction (ties to the Cox-process machinery elsewhere in the library).
Bandwidths are in data units; "silverman" and "scott" are the rule-of-thumb selectors.
- class KDE(data, *, bandwidth='silverman', bounds=None, adaptive=False)[source]
Bases:
objectA fitted kernel density estimate, 1-D or multivariate.
Use
kde()to construct. Evaluate withevaluate()(or call the instance). Supports a Gaussian kernel – an axis-aligned product kernel with a per-dimension bandwidth for multivariate(n, d)data, rows treated as observations and never reshaped – adaptive bandwidths (any dimension), and, for 1-D data only, normalized boundary correction (bounds; MXR-080-0099).- data
the fitted sample as
(n, d)observations (d == 1for a 1-D sample).
- n
number of observations.
- d
dimensionality (
1for a 1-D sample).
- bandwidth
the resolved bandwidth – a scalar
floatwhend == 1, else a length-dnumpy.ndarray(one bandwidth per dimension).
- kde(data, *, bandwidth='silverman', bounds=None, adaptive=False)[source]
Construct a kernel density estimate (Gaussian kernel; product kernel for multivariate data).
- Parameters:
data (ndarray) –
(n,)sample, or(n, d)for ad-dimensional sample – rows are observations and must stay paired (never flatten an(n, d)array before calling this; MXR-080-0099).bandwidth –
"silverman","scott", a single positive finite number (used in every dimension), or – for(n, d)data – a length-dsequence of positive finite numbers (one bandwidth per dimension). Automatic selection needs >= 2 observations with nonzero variation in every dimension.bounds –
(lo, hi)support limits for normalized boundary correction; either may beNonefor an unbounded side (e.g.(0.0, None)for a positive variable). Half-lines use an exactly normalized reflected image; finite intervals normalize every truncated kernel. Only supported for 1-D (d == 1) data.adaptive (bool) – use Abramson variable bandwidths (wider where the pilot density is low); supported for any dimension.
- Returns:
A
KDE.- Raises:
ValueError –
datais empty, non-finite, or more than 2-D;bandwidthis an unrecognized method name, the wrong length, or not strictly positive and finite; automatic bandwidth selection is requested on fewer than 2 observations or a constant sample in some dimension (MXR-080-0100); orboundsis given together withd > 1, out of order, or non-finite (MXR-080-0099 / MXR-080-0100).- Return type:
KDE
- silverman_bandwidth(data, *, d=1)[source]
Silverman’s rule-of-thumb bandwidth
0.9 min(sd, IQR/1.34) n^{-1/(d+4)}for a 1-D sample.datais always treated as one 1-D sample (e.g. a single column of a multivariate dataset).donly sets the exponent: it is the dimensionality of the joint sample this bandwidth will be used in a product kernel for – pass it explicitly when selecting one dimension’s bandwidth for a multivariateKDE, so then^{-1/(d+4)}rate reflects the true joint dimension rather than the univariate defaultd=1(n^{-1/5}) rate (MXR-080-0099).- Raises:
ValueError –
datahas fewer than 2 observations, non-finite entries, or zero variation (see_require_variation(); MXR-080-0100).- Parameters:
- Return type:
- scott_bandwidth(data, *, d=1)[source]
Scott’s rule-of-thumb bandwidth
sd * n^{-1/(d+4)}for a 1-D sample.datais always treated as one 1-D sample;donly sets the exponent – seesilverman_bandwidth()(whosedparameter has exactly the same meaning here).- Raises:
ValueError –
datahas fewer than 2 observations, non-finite entries, or zero variation (see_require_variation(); MXR-080-0100).- Parameters:
- Return type:
- 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 1-D density, optionally with a bootstrap CI.
Univariate only: a dense grid search over
ddimensions is exponential indand is not implemented here (unlikeKDE, this never accepted multivariate data as a documented feature, so an(n, d)input is now rejected explicitly instead of being silently flattened with.ravel()– the same silent-flattening defectKDEitself had; MXR-080-0099).- 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.
- Return type:
Bootstrap policy for degenerate resamples (MXR-080-1587): a resample of a perfectly valid, nonconstant sample can itself come out constant –
[0, 0, 1]resamples to[0, 0, 0]roughly one draw in four – and an automatic bandwidth selector has no spread to estimate from, so it raises. That made the interval fail at random, depending on the seed, for a fit that had already succeeded. A degenerate resample is now scored at the ORIGINAL fit’s bandwidth (the sample the bandwidth was selected from is the full one, and a bootstrap replicate is a resample of it, not a new dataset), rather than skipped – skipping would quietly narrow the interval by dropping exactly the least-dispersed replicates. The count of replicates that needed the fallback is reported asn_degenerate_resamplesso a caller can see when the interval rests largely on them.- Returns:
The mode (float), or
{'mode', 'ci_low', 'ci_high', 'n_boot', 'n_degenerate_resamples'}whenciis True.- Raises:
ValueError –
datais empty or not 1-D; or, whenciis True,n_bootis not a positive integer orci_levelis not in the open interval(0, 1)(MXR-080-0100). Also propagates anyKDEconstruction error fromkde()on the ORIGINAL sample (e.g. automatic bandwidth selection on a constant input) – that is a genuine property of the data, unlike a degenerate resample, which is handled by the policy above.- Parameters:
- Return type:
- intensity(events, grid, *, bandwidth='silverman', domain=None, edge_correct=True)[source]
Kernel intensity
lambda(t)of a 1-D 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.Univariate only: like
kde_mode(), this never accepted multivariate data as a documented feature, so an(m, d)input is now rejected explicitly instead of being silently flattened with.ravel()(MXR-080-0099).- Parameters:
events (ndarray) –
(m,)event locations.grid (ndarray) – nonempty finite one-dimensional 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.- Raises:
ValueError –
eventsis empty, non-finite, or not 1-D;bandwidthis an unrecognized method name or a non-positive/non-finite number; automatic bandwidth selection is requested on fewer than 2 events or constant events; or (whenedge_correctis True) the effectivedomain– explicitly passed, or defaulted to the event range – is non-finite or haslo >= hi(MXR-080-0100; a collapsed-to-a-point domain, e.g. from constant events with an explicit numeric bandwidth, previously produced a silent divide-by-near-zero blowup).- Return type: