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-dimension n^{-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 intensity lambda(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: object

A fitted kernel density estimate, 1-D or multivariate.

Use kde() to construct. Evaluate with evaluate() (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).

Parameters:
data

the fitted sample as (n, d) observations (d == 1 for a 1-D sample).

n

number of observations.

d

dimensionality (1 for a 1-D sample).

bandwidth

the resolved bandwidth – a scalar float when d == 1, else a length-d numpy.ndarray (one bandwidth per dimension).

evaluate(x)[source]

Density at points x – (m,) for 1-D, (m, d) for multivariate – with reflection boundary correction if bounds was set (1-D only). Always returns a length-m array.

Parameters:

x (ndarray)

Return type:

ndarray

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 a d-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-d sequence 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 be None for 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 – data is empty, non-finite, or more than 2-D; bandwidth is 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); or bounds is given together with d > 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.

data is always treated as one 1-D sample (e.g. a single column of a multivariate dataset). d only 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 multivariate KDE, so the n^{-1/(d+4)} rate reflects the true joint dimension rather than the univariate default d=1 (n^{-1/5}) rate (MXR-080-0099).

Raises:

ValueError – data has fewer than 2 observations, non-finite entries, or zero variation (see _require_variation(); MXR-080-0100).

Parameters:
Return type:

float

scott_bandwidth(data, *, d=1)[source]

Scott’s rule-of-thumb bandwidth sd * n^{-1/(d+4)} for a 1-D sample.

data is always treated as one 1-D sample; d only sets the exponent – see silverman_bandwidth() (whose d parameter has exactly the same meaning here).

Raises:

ValueError – data has fewer than 2 observations, non-finite entries, or zero variation (see _require_variation(); MXR-080-0100).

Parameters:
Return type:

float

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 d dimensions is exponential in d and is not implemented here (unlike KDE, 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 defect KDE itself 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:

float | dict

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 as n_degenerate_resamples so 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'} when ci is True.

Raises:

ValueError – data is empty or not 1-D; or, when ci is True, n_boot is not a positive integer or ci_level is not in the open interval (0, 1) (MXR-080-0100). Also propagates any KDE construction error from kde() 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:

float | dict

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). With edge_correct the estimate is divided by the fraction of the kernel falling inside domain, 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 t at 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 – events is empty, non-finite, or not 1-D; bandwidth is 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 (when edge_correct is True) the effective domain – explicitly passed, or defaulted to the event range – is non-finite or has lo >= 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:

ndarray