Template Class KernelDensity

Nested Relationships

Nested Types

Inheritance Relationships

Base Type

Class Documentation

template<typename AuxType = void>
class KernelDensity : public kden::KDTree<KernelDensityData<void>>

A kernel density estimate built on a kd tree of weighted points.

A KDTree whose points, a KernelDensityData, are the weighted kernel centers of a kernel density estimate. Like KDTree, it is a non-owning wrapper around its points, which it reorders in place on construction. On top of the tree it keeps, for every node, the sum of its points’ weights, in a flat array indexed by node.

The weights are normalized on construction, to sum to one. The kernel is a Gaussian, K(d) = exp(-d^T M d), with M the inverse squared bandwidth matrix (see Bandwidth), which is passed to each evaluation, so different threads may evaluate the same estimate with different bandwidths at once. The estimate at x is p(x) = A sum_i w_i K(x - x_i), with A = sqrt(det M) / pi^(n / 2) normalizing each kernel, and so the estimate, to unit integral.

Template Parameters:

AuxType – Type of the auxiliary data each point carries, or void (the default) for none; see KDTreeData

Public Types

using Tree = KDTree<KernelDensityData<AuxType>>

The kd tree this is built on

using Sample = std::tuple<std::vector<double>, std::vector<double>, typename KDTreeAuxStorage<AuxType>::Owned>

What conditionalSample() returns: a conditional estimate’s points (K x nR, point-major), their weights (K), and their auxiliary data (K elements, carried over from this estimate’s points; an empty placeholder if AuxType is void)

Public Functions

inline KernelDensity(KernelDensityData<AuxType> &data, const std::size_t leafSize, const Bandwidth &splitBandwidth, const std::vector<std::size_t> &noSplitDims = {})

Construct a KernelDensity over a set of weighted points.

Parameters:
  • data – The kernel centers; as for the corresponding KDTree constructor. Every weight must also be finite and non-negative (see KernelDensityData::validate()), and they must not all be zero. Besides being reordered, the weights are rescaled in place to sum to one.

  • leafSize – As for the corresponding KDTree constructor

  • splitBandwidth – As for the corresponding KDTree constructor

  • noSplitDims – As for the corresponding KDTree constructor; e.g., the dimensions that evaluations of a marginal density will leave unspecified

Throws:

std::invalid_argument – as for the corresponding KDTree constructor, or if the weights sum to zero

inline explicit KernelDensity(KernelDensityData<AuxType> &data, const std::size_t leafSize = 16, const std::vector<std::size_t> &noSplitDims = {})

Construct a KernelDensity, choosing split dimensions with the Euclidean metric.

Parameters:
  • data – As for the other constructor

  • leafSize – As for the other constructor

  • noSplitDims – As for the other constructor

Throws:

std::invalid_argument – as for the other constructor

inline auto nodeW(const std::size_t idx) const -> double

Sum of the weights of a node’s points.

Parameters:

idx – Index of the node

Returns:

The sum

inline void reweight()

Bring the estimate up to date after its weights are changed in place.

The weights may be changed in place (but the positions may not: the tree is built around them). Afterwards, call this to renormalize the weights to sum to one, in place, and recompute every node’s weight sum. Costs O(N), in parallel if built with OpenMP; unlike construction, it checks only the weights, not the (unchanged) positions. Not thread-safe with respect to evaluation: like any non-const member, it must not run concurrently with pdf() or conditional() on the same estimate (nor may the weights be changed while they run).

Throws:

std::invalid_argument – if the weights are invalid (see KernelDensityData::validate()) or all zero

inline auto pdf(const std::vector<double> &x, const double relTol, const double absTol, const Bandwidth &bandwidth) const -> double

Evaluate the kernel density estimate at a point, to within a tolerance.

Follows kd_pdf in slug2’s bayesphot. A list of tree nodes, starting with just the root, is kept, each with a central estimate of its contribution to p(x) and an uncertainty on it (see nodePdf()); together with the exactly known contributions of the leaves reached so far, these sum to p(x). Until the summed uncertainty meets either tolerance, the node with the largest uncertainty is replaced by its two children; a child that is a leaf goes straight into the leaves’ sum (a sum of non-negative terms only, so with no cancellation to accumulate rounding error) rather than into the list. This ends, at the latest, once every leaf has been reached. The list is a RefinementList, so each step costs O(log n) in the length of the list, while its sums never accumulate rounding error the way running totals would. Thread-safe, as for KDTree::neighbors().

Parameters:
  • x – Position at which to evaluate it; must have nDim elements. Elements may be NaN, to evaluate the marginal density over the other dimensions.

  • relTol – Relative tolerance: stop once the uncertainty is less than relTol times the estimate

  • absTol – Absolute tolerance: stop once the estimate plus its uncertainty is less than absTol

  • bandwidth – The kernel’s inverse squared bandwidth matrix, for nDim dimensions; if x has NaN elements, it is reduced for them as in KDTree::neighbors()

Throws:
  • std::invalid_argument – if x or bandwidth is not for nDim dimensions, or bandwidth has been reduced for a different pattern of NaNs than x’s

  • std::domain_error – if the kernel cannot be normalized (bandwidth is singular over the specified dimensions)

Returns:

The estimate p(x), normalized to unit integral over all space (over the specified dimensions only, if x has NaN elements; marginalizing a Gaussian kernel over the others gives the Gaussian with the reduced bandwidth – see Bandwidth::reduce())

inline auto pdf(const std::vector<double> &x, const double relTol, const double absTol) const -> double

Evaluate the kernel density estimate at a point, with the Euclidean bandwidth.

Parameters:
  • x – As for the other overload

  • relTol – As for the other overload

  • absTol – As for the other overload

Throws:

As – for the other overload

Returns:

As for the other overload, with M the identity

inline auto conditional(const std::vector<double> &x0, const std::vector<std::size_t> &marginalDims, const double massTol, const Bandwidth &bandwidth, const std::size_t leafSize = 16) const -> ConditionalDensity<AuxType>

Condition the estimate on values of some dimensions, optionally marginalizing over others.

Marginalizing a Gaussian over G replaces M by its Schur complement M’ = bandwidth.reduce(G). Then, writing a = x0_F - x_F and b = y - x_R for a point x, completing the square in b gives

d^T M’ d = (b + K a)^T M’_RR (b + K a) + a^T S a,

with K = M’_RR^-1 M’_RF and S = M’_FF - M’_FR M’_RR^-1 M’_RF, the reduction of M over G and R together. So the estimate at (x0_F, y) is itself a kernel density estimate in y, with kernel metric M’_RR, points y’_i = x_i,R + K (x_i,F - x0_F), and weights w’_i = w_i exp(-a_i^T S a_i).

Most points’ weights w’_i are negligible, so only those that matter are kept. The tree is walked as in pdf(), with each node’s total conditional weight bounded by its weight times exp(-a^T S a) at the bounds of a^T S a over its box (see Bandwidth::BoxBounder; dimensions in G and R are ignored, so a tree built with them in noSplitDims suits these queries). The node with the largest upper bound is opened until the upper bounds of the unopened interior nodes sum to at most massTol / 2 of the total weight, and those nodes are dropped; the points of the leaves reached are then sorted by weight, and the lightest dropped, up to another massTol / 2. The weight dropped is thus at most massTol of the total, so the result’s L1 distance from the exact conditional density is at most 2 massTol. Its cost depends on the number of points kept, not the size of the tree. conditionalSample() finds the same points and weights without building the result. Thread-safe, as for pdf().

Parameters:
  • x0 – One element per dimension: a finite value fixes that dimension (the set F); NaN keeps it as a dimension of the result (the set R). Elements for dimensions in marginalDims are ignored.

  • marginalDims – Dimensions to marginalize over (the set G); may be empty

  • massTol – Largest fraction of the conditional estimate’s total weight that may be dropped, in [0, 1); 0 keeps every point with non-zero weight

  • bandwidth – The kernel’s inverse squared bandwidth matrix, for nDim dimensions; must not be reduced

  • leafSize – Leaf size of the result’s tree

Throws:
  • std::invalid_argument – if x0 or bandwidth is not for nDim dimensions, bandwidth is reduced, marginalDims has a dimension not below nDim or a repeated one, F or R is empty, or massTol is not in [0, 1)

  • std::domain_error – if the bandwidth’s blocks needed are not positive definite, or every point’s conditional weight underflows to zero (x0_F is too far from every point)

Returns:

The conditional estimate p(y | x0_F) over the dimensions in R, as a ConditionalDensity

inline auto conditionalSample(const std::vector<double> &x0, const std::vector<std::size_t> &marginalDims, const double massTol, const Bandwidth &bandwidth) const -> Sample

Find the sample points, weights, and auxiliary data of a conditional estimate, without building it.

The same points, weights, and auxiliary data as conditional() keeps, in increasing order of weight, without building the conditional estimate’s tree: a KernelDensity over them, with the kernel metric M’_RR – the block of bandwidth.reduce(G) over R, a function of the bandwidth alone – is the conditional estimate. Suited to storing conditional estimates, to be rebuilt as needed. Thread-safe, as for conditional().

Parameters:
Throws:

As – for conditional()

Returns:

The points the conditional estimate p(y | x0_F) keeps, in the dimensions R (in increasing order), K x |R|, point-major; and their weights, K of them, w’_i = w_i exp(-a_i^T S a_i) (see conditional()), with w_i this estimate’s normalized weights: not themselves normalized, so that their sum times sqrt(det S) / pi^(|F|/2) is the marginal density over F at x0_F (conditional()’s marginal()); and, unless AuxType is void, their auxiliary data, carried over from the points they came from (see Sample)

inline auto conditionalSample(const std::vector<double> &x0, const std::vector<std::size_t> &marginalDims, const double massTol) const -> Sample

Find the sample points and weights of a conditional estimate, with the Euclidean bandwidth.

Parameters:
  • x0 – As for the other overload

  • marginalDims – As for the other overload

  • massTol – As for the other overload

Throws:

As – for the other overload

Returns:

As for the other overload, with M the identity

inline auto percentile(const std::size_t dim, const double pct, const double relTol, const double absTol, const Bandwidth &bandwidth) const -> double

A one-dimensional percentile of the estimate.

Marginalizing the kernel over every other dimension leaves a one-dimensional Gaussian exp(-m u^2), with m the bandwidth reduced to dim alone, so F(t) = sum_i w_i Phi(t - x_i), with Phi(u) = erfc(-sqrt(m) u) / 2. Each term is monotone in x_i, so a node of weight W whose points lie in [lo, hi] in dim adds between W Phi(t - hi) and W Phi(t - lo) to F, for every t.

A cut through the tree – unopened nodes, plus points evaluated exactly – thus bounds F between two functions F_L <= F <= F_U, and the percentile t* between the roots of F_U = p and F_L = p. Starting from the root alone, each round finds that bracket and a candidate t_c, the root of (F_L + F_U) / 2 = p, within it (safeguarded Newton iterations, every root-find confined to the current bracket, so that it only ever shrinks). It stops once F_U(t_c) - p and p - F_L(t_c) are both within the tolerance, which guarantees the result; otherwise it opens the nodes that contribute most to F_U - F_L at t_c (every one within a factor of two of the largest), a leaf’s points becoming exact terms. Terms lying wholly to the left or right of the bracket, whose contribution is 1 or 0 there to within a small fraction of the tolerance, are folded into constant bounds (rigorous, since the bracket only shrinks), so the work stays with the points within a few kernel widths of t*: it costs far less than evaluating F over every point at each step of a root-find. That relies on the tree splitting along dim: in a dimension in noSplitDims, every node spans its whole range, so the walk must reach nearly every point (still correct, but much slower). Thread-safe, as for pdf().

Parameters:
  • dim – The dimension

  • pct – The percentile, in (0, 100)

  • relTol – Relative tolerance, in probability (see the return value); non-negative

  • absTol – Absolute tolerance, in probability; non-negative

  • bandwidth – The kernel’s inverse squared bandwidth matrix, for nDim dimensions; must not be reduced

Throws:
  • std::invalid_argument – if dim is not below nDim, pct is not in (0, 100), a tolerance is negative or NaN, or bandwidth is not for nDim dimensions or is reduced

  • std::domain_error – if the estimate has no points, or the bandwidth’s block over the other dimensions is not positive definite

Returns:

A value t of dimension dim at which the estimate’s marginal cumulative distribution in dim, F(t), satisfies |F(t) - p| <= max(absTol, relTol min(p, 1 - p)), with p = pct / 100 – a tolerance in probability, the same relative standard in both tails

inline auto percentile(const std::size_t dim, const double pct, const double relTol, const double absTol) const -> double

A one-dimensional percentile of the estimate, with the Euclidean bandwidth.

Parameters:
  • dim – As for the other overload

  • pct – As for the other overload

  • relTol – As for the other overload

  • absTol – As for the other overload

Throws:

As – for the other overload

Returns:

As for the other overload, with M the identity

inline auto percentile(const std::size_t dim, const std::vector<double> &pct, const double relTol, const double absTol, const Bandwidth &bandwidth) const -> std::vector<double>

Several one-dimensional percentiles of the estimate, in parallel.

Runs the single-percentile version for each, in parallel (dynamically scheduled) if built with OpenMP.

Parameters:
  • dim – As for the single-percentile version

  • pct – The percentiles, each in (0, 100)

  • relTol – As for the single-percentile version

  • absTol – As for the single-percentile version

  • bandwidth – As for the single-percentile version

Throws:

As – for the single-percentile version (the first exception caught, if several are)

Returns:

One value per percentile, each as the single-percentile version returns it

inline auto marginalize(const std::vector<std::size_t> &marginalDims, const Bandwidth &bandwidth, const std::size_t leafSize = 16) const -> ConditionalDensity<AuxType>

Marginalize the estimate over some dimensions.

Marginalizing a Gaussian kernel over G replaces its metric M by the Schur complement M’ = bandwidth.reduce(G), so the marginal estimate is the kernel density estimate over the points’ coordinates in R, with the same weights, and kernel metric M’ over R: conditional() with no dimension fixed, so that every point keeps its full weight, unshifted. Its pdf() at y equals this estimate’s pdf() at the point with y in R and NaN in G. Copies every point’s coordinates in R, weight, and auxiliary data (in parallel, if built with OpenMP), then builds the result’s tree. Thread-safe, as for pdf().

Parameters:
  • marginalDims – Dimensions to marginalize over (the set G): distinct, below nDim, and leaving at least one; may be empty

  • bandwidth – The kernel’s inverse squared bandwidth matrix, for nDim dimensions; must not be reduced

  • leafSize – Leaf size of the result’s tree

Throws:
  • std::invalid_argument – if bandwidth is not for nDim dimensions or is reduced, or marginalDims has a dimension not below nDim or a repeated one, or leaves no dimension

  • std::domain_error – if the bandwidth’s block over G is not positive definite

Returns:

The marginal estimate over the remaining dimensions R (in increasing order), as a ConditionalDensity – with no dimensions fixed, its marginal() is 1

inline auto marginalize(const std::vector<std::size_t> &marginalDims, const std::size_t leafSize = 16) const -> ConditionalDensity<AuxType>

Marginalize the estimate over some dimensions, with the Euclidean bandwidth.

Parameters:
  • marginalDims – As for the other overload

  • leafSize – As for the other overload

Throws:

As – for the other overload

Returns:

As for the other overload, with M the identity

inline auto conditional(const std::vector<double> &x0, const std::vector<std::size_t> &marginalDims, const double massTol, const std::size_t leafSize = 16) const -> ConditionalDensity<AuxType>

Condition the estimate on values of some dimensions, with the Euclidean bandwidth.

Parameters:
  • x0 – As for the other overload

  • marginalDims – As for the other overload

  • massTol – As for the other overload

  • leafSize – As for the other overload

Throws:

As – for the other overload

Returns:

As for the other overload, with M the identity

inline auto pdf(const std::vector<std::vector<double>> &x, const double relTol, const double absTol, const std::vector<Bandwidth> &bandwidth) const -> std::vector<double>

Evaluate the kernel density estimate at each of several points, in parallel.

Runs the single-point pdf() for each point, in parallel (dynamically scheduled, since queries can differ widely in cost) if built with OpenMP.

Parameters:
  • x – The points, each as for the single-point pdf()

  • relTol – As for the single-point pdf()

  • absTol – As for the single-point pdf()

  • bandwidth – The bandwidth, one per point

Throws:

std::invalid_argument – if x and bandwidth differ in length; otherwise, any exception the single-point pdf() throws for any one of the points (the first one caught, if several do)

Returns:

The estimate at each point, each exactly as the single-point pdf() returns it

inline auto pdf(const std::vector<std::vector<double>> &x, const double relTol, const double absTol, const Bandwidth &bandwidth) const -> std::vector<double>

Evaluate the kernel density estimate at each of several points, in parallel, sharing one bandwidth.

If bandwidth has not been reduced and every point has the same pattern of NaNs, it is reduced once for all of them, rather than once per point.

Parameters:
  • x – The points, each as for the single-point pdf()

  • relTol – As for the single-point pdf()

  • absTol – As for the single-point pdf()

  • bandwidth – The bandwidth, shared by every point

Throws:

As – for the version taking one bandwidth per point

Returns:

As for the version taking one bandwidth per point

inline auto pdf(const std::vector<std::vector<double>> &x, const double relTol, const double absTol) const -> std::vector<double>

Evaluate the kernel density estimate at each of several points, in parallel, with the Euclidean bandwidth.

Parameters:
  • x – As for the other overloads

  • relTol – As for the other overloads

  • absTol – As for the other overloads

Throws:

As – for the other overloads

Returns:

As for the other overloads, with M the identity

inline auto pdf(const std::vector<std::vector<double>> &x, const std::vector<std::size_t> &errDims, const std::vector<Eigen::MatrixXd> &errCov, const double relTol, const double absTol, const Bandwidth &bandwidth) const -> std::vector<double>

Evaluate, in parallel, the density of each of several points measured with errors.

Each point’s bandwidth is convolved with its own errors in the thread that evaluates it. If every point has the same pattern of NaNs, bandwidth is reduced for it once, beforehand, and each convolution done in the reduced space (reduction and convolution with errors in specified dimensions commute).

Parameters:
  • x – The points, each as for the single-point pdf()

  • errDims – The dimensions with measurement errors; each must be finite (specified) in every point

  • errCov – The covariance matrix of each point’s errors, in the dimensions errDims (in that order): one per point, each errDims.size() square, symmetric, and positive semi-definite

  • relTol – As for the single-point pdf()

  • absTol – As for the single-point pdf()

  • bandwidth – The bandwidth, shared by every point

Throws:

std::invalid_argument – if errCov does not have one matrix per point, or one has the wrong size, or errDims has a dimension not below nDim, a repeated one, or one that is NaN in a point; otherwise, as for the other overloads, and as for Bandwidth::convolveCov()

Returns:

For each point x[i], the estimate at x[i] with the kernel convolved with its errors (see Bandwidth::convolveCov()), i.e. the density of measuring x[i] given errors with covariance errCov[i]

inline auto conditional(const std::vector<std::vector<double>> &x0, const std::vector<std::size_t> &marginalDims, const double massTol, const Bandwidth &bandwidth, const std::size_t leafSize = 16) const -> std::vector<ConditionalDensity<AuxType>>

Condition the estimate on each of several points, in parallel.

Runs the single-point conditional() for each point, in parallel (dynamically scheduled) if built with OpenMP. Each result’s own tree is then built on the thread that conditions it: the parallel loops of that build are nested inside this one, so (unless nested parallelism is enabled) run on that thread alone.

Parameters:
  • x0 – The points to condition on, each as for the single-point conditional()

  • marginalDims – As for the single-point conditional(), shared by every point

  • massTol – As for the single-point conditional()

  • bandwidth – As for the single-point conditional(), shared by every point

  • leafSize – As for the single-point conditional()

Throws:

Any – exception the single-point conditional() throws for any one of the points (the first one caught, if several do)

Returns:

One conditional density per point, each exactly as the single-point conditional() returns it

inline auto conditional(const std::vector<std::vector<double>> &x0, const std::vector<std::size_t> &marginalDims, const double massTol, const std::size_t leafSize = 16) const -> std::vector<ConditionalDensity<AuxType>>

Condition the estimate on each of several points, in parallel, with the Euclidean bandwidth.

Parameters:
  • x0 – As for the other overload

  • marginalDims – As for the other overload

  • massTol – As for the other overload

  • leafSize – As for the other overload

Throws:

As – for the other overload

Returns:

As for the other overload, with M the identity

inline auto conditional(const std::vector<std::vector<double>> &x0, const std::vector<std::size_t> &errDims, const std::vector<Eigen::MatrixXd> &errCov, const std::vector<std::size_t> &marginalDims, const double massTol, const Bandwidth &bandwidth, const std::size_t leafSize = 16) const -> std::vector<ConditionalDensity<AuxType>>

Condition the estimate, in parallel, on each of several points measured with errors.

Parameters:
  • x0 – The points to condition on, each as for the single-point conditional()

  • errDims – The dimensions with measurement errors; each must be fixed (finite, and not in marginalDims) in every point

  • errCov – The covariance matrix of each point’s errors, in the dimensions errDims, as for the errors version of pdf()

  • marginalDims – As for the single-point conditional(), shared by every point

  • massTol – As for the single-point conditional()

  • bandwidth – As for the single-point conditional(), shared by every point

  • leafSize – As for the single-point conditional()

Throws:

std::invalid_argument – as for the errors version of pdf(), with errDims required to be fixed rather than merely specified; otherwise, as for the other overloads, and as for Bandwidth::convolveCov()

Returns:

For each point x0[i], the conditional density given x0[i] with the kernel first convolved with its errors (see Bandwidth::convolveCov()): the posterior given a measurement x0[i] with errors of covariance errCov[i]

inline auto conditionalSample(const std::vector<std::vector<double>> &x0, const std::vector<std::size_t> &marginalDims, const double massTol, const Bandwidth &bandwidth) const -> std::vector<Sample>

Find the sample points, weights, and auxiliary data of conditional estimates for each of several points, in parallel.

Runs the single-point conditionalSample() for each point, in parallel (dynamically scheduled) if built with OpenMP.

Parameters:
Throws:

Any – exception the single-point conditionalSample() throws for any one of the points (the first one caught, if several do)

Returns:

One result per point, each exactly as the single-point conditionalSample() returns it

inline auto conditionalSample(const std::vector<std::vector<double>> &x0, const std::vector<std::size_t> &marginalDims, const double massTol) const -> std::vector<Sample>

Find the sample points, weights, and auxiliary data of conditional estimates for each of several points, in parallel, with the Euclidean bandwidth.

Parameters:
  • x0 – As for the other overload

  • marginalDims – As for the other overload

  • massTol – As for the other overload

Throws:

As – for the other overload

Returns:

As for the other overload, with M the identity

inline auto conditionalSample(const std::vector<std::vector<double>> &x0, const std::vector<std::size_t> &errDims, const std::vector<Eigen::MatrixXd> &errCov, const std::vector<std::size_t> &marginalDims, const double massTol, const Bandwidth &bandwidth) const -> std::vector<Sample>

Find, in parallel, the sample points, weights, and auxiliary data of conditional estimates for each of several points measured with errors.

Parameters:
Throws:

As – for the errors version of the batch conditional()

Returns:

For each point x0[i], the sample points, weights, and auxiliary data of the conditional estimate given x0[i] with the kernel first convolved with its errors, as the errors version of the batch conditional() would keep them; its kernel metric is that of the convolved bandwidth

Protected Functions

inline auto evalPercentile(const std::size_t dim, const double p, const double tolP, const double s) const -> double

The work of percentile(), with its arguments checked.

Parameters:
  • dim – The dimension

  • p – The fraction, in (0, 1)

  • tolP – The tolerance in probability

  • s – The square root of the marginal kernel’s metric

Returns:

The percentile (see percentile())

inline auto conditionalPoints(const std::vector<double> &x0, const std::vector<std::size_t> &marginalDims, const double massTol, const Bandwidth &bandwidth) const -> ConditionalPoints

Find a conditional estimate’s points, weights, metric, and marginal.

The work of conditional() and conditionalSample(); see conditional() for the method.

Parameters:
Throws:

As – for conditional()

Returns:

The points and the rest (see ConditionalPoints)

inline auto classifyDims(const std::vector<double> &x0, const std::vector<std::size_t> &marginalDims) const -> std::tuple<std::vector<std::size_t>, std::vector<std::size_t>, std::vector<bool>, std::vector<bool>>

Sort dimensions into fixed, kept, and marginalized, for conditional()

Parameters:
Throws:

std::invalid_argument – if marginalDims has a dimension not below nDim or a repeated one, or F or R is empty

Returns:

The fixed dimensions F and the kept dimensions R, in order, and flags marking the dimensions in G and in G or R

inline auto selectConditional(const std::vector<double> &xF, const Bandwidth &weightMetric, const double massTol) const -> std::pair<std::vector<std::pair<double, std::size_t>>, double>

Select the points carrying all but massTol of the conditional weight.

See conditional(). Here each RefinementList entry’s “estimate” is a lower bound on the node’s conditional weight and its “uncertainty” an upper bound, so the list opens the node with the largest upper bound.

Parameters:
  • xF – The point; NaN except in the fixed dimensions

  • weightMetric – The metric S of the conditional weights; must match xF

  • massTol – As for conditional()

Returns:

The kept points, as (conditional weight, index into data()) pairs, and the sum of their weights

inline auto evalPdf(const std::vector<double> &x, const double relTol, const double absTol, const Bandwidth &bandwidth) const -> double

The evaluation itself, for pdf()

Parameters:
  • x – The point; must match bandwidth (see Bandwidth::matches())

  • relTol – Relative tolerance

  • absTol – Absolute tolerance

  • bandwidth – The bandwidth

Throws:

std::domain_error – as for pdf()

Returns:

As for pdf()

inline auto nodePdf(const std::size_t idx, const std::vector<double> &x, const Bandwidth &bandwidth, const Bandwidth::BoxBounder &bound, std::vector<double> &scratch) const -> std::pair<double, double>

A node’s contribution to the (unnormalized) density estimate at a point.

Parameters:
  • idx – Index of the node

  • x – The point; must match bandwidth

  • bandwidth – The bandwidth

  • bound – A box bounder for x and bandwidth

  • scratch – Scratch space for Bandwidth::dist2()

Returns:

(central estimate, uncertainty) of the node’s contribution sum_i w_i exp(-d_i^T M d_i), summed over its points. For a leaf, the sum itself, with zero uncertainty. For an interior node, with W its total weight and r2min and r2max lower and upper bounds on d^T M d over its bounding box (see Bandwidth::BoxBounder), the midpoint W (exp(-r2min) + exp(-r2max)) / 2 of the range the sum must lie in, and its half-width W (exp(-r2min) - exp(-r2max)) / 2.

inline void setNodeWeights()

Compute every node’s weight sum.

One pass up the tree, from the last level to the root (see accumulateNode()). Nodes on the same level are independent, so each level is processed in parallel if built with OpenMP.

inline void accumulateNode(const std::size_t idx)

Set one node’s weight sum.

A leaf (or an unused slot below one, which has no points) sums over its own points; an interior node adds up its two children’s sums. Writes only this node’s own entry, so nodes may be processed in parallel.

Parameters:

idx – Index of the node; if it is an interior node, its children’s sums must already be set

Protected Attributes

std::vector<double> nodeW_

Sum of the weights of each node’s points

Protected Static Functions

template<typename T, typename Eval>
static inline auto parallelEval(const std::size_t n, const Eval &eval) -> std::vector<T>

Evaluate a function for each of a set of indices, in parallel.

Dynamically scheduled OpenMP loop, if built with OpenMP.

Template Parameters:
  • T – The function’s result type; need only be movable

  • Eval – Callable taking an index and returning a T

Parameters:
  • n – Number of indices

  • eval – The function

Throws:

The – first exception any call throws (one must not escape an OpenMP region, so each is caught in the loop and the first rethrown afterwards)

Returns:

eval(i) for i = 0, …, n - 1, in order

static inline auto conditionalMetric(const Eigen::MatrixXd &m, const std::vector<std::size_t> &dimsF, const std::vector<std::size_t> &dimsR) -> std::pair<Eigen::MatrixXd, Eigen::MatrixXd>

The kernel metric and point shift of a conditional estimate.

Parameters:
  • m – The (possibly reduced) inverse squared bandwidth matrix, nDim x nDim

  • dimsF – The fixed dimensions

  • dimsR – The kept dimensions

Throws:

std::domain_error – if M_RR is not positive definite

Returns:

(M_RR, K = M_RR^-1 M_RF), |R| x |R| and |R| x |F|

static inline auto normalizeWeights(KernelDensityData<AuxType> &data) -> KernelDensityData<AuxType>&

Check a set of weighted points and rescale their weights to sum to one.

Parameters:

data – The points

Throws:

std::invalid_argument – if data is invalid (see KernelDensityData::validate(), which also rejects negative weights), or its weights sum to zero

Returns:

data, for use in the constructors’ initializer lists

static inline void normalizeWeightArray(const std::span<double> w)

Check a set of weights and rescale them to sum to one, in place.

The weights are scaled by the largest first, so that summing finite weights cannot overflow. Each pass over the weights runs in parallel if built with OpenMP, since reweight() calls this whenever the weights are changed, e.g. on every step of an optimization over them.

Parameters:

w – The weights

Throws:

std::invalid_argument – if any weight is negative or not finite, or all are zero

struct ConditionalPoints

What conditional() and conditionalSample() find: a conditional estimate’s points, before its tree is built.

Public Members

OwnedKernelDensityData<AuxType> data_

The kept points, in the dimensions R; their unnormalized weights; and their auxiliary data

std::vector<std::size_t> dims_

The kept dimensions R, in increasing order

Eigen::MatrixXd metric_

The conditional kernel metric M’_RR

double marginal_ = 0.0

The marginal density over F at x0_F

class PercentileCut

A cut through the tree, bounding a marginal cumulative distribution, for percentile()

Holds the active terms – unopened nodes, each with its weight and extent in the dimension, and points evaluated exactly – and constant bounds on the terms retired from them, with the slack those add to the gap between the bounds. With s the square root of the marginal kernel’s metric, each term’s kernel cumulative distribution is Phi(u) = erfc(-s u) / 2.

Public Types

enum class Bound : std::uint8_t

Which bound on the cumulative distribution to evaluate

Values:

enumerator lower

F_L

enumerator upper

F_U

enumerator mean

(F_L + F_U) / 2

Public Functions

inline PercentileCut(const KernelDensity &kde, const std::size_t dim, const double s, const double tolP)

Start the cut at the root.

Parameters:
  • kde – The estimate

  • dim – The dimension

  • s – The square root of the marginal kernel’s metric

  • tolP – The tolerance in probability

inline auto eval(const double t, const Bound which) const -> std::pair<double, double>

Evaluate a bound and its derivative.

Parameters:
  • t – Where to evaluate it

  • which – The bound

Returns:

The bound and its derivative at t

inline auto solve(const Bound which, const double target, double a, double b, const double ftol) const -> std::pair<double, double>

Narrow a bracket on where a bound reaches a target.

Parameters:
  • which – The bound (non-decreasing)

  • target – The target

  • a – Left end of the bracket

  • b – Right end of the bracket

  • ftol – Stop once the bound at an end is within ftol of target

Returns:

[l, r] within [a, b], with the bound at l at most, and at r at least, the target (l = r = a if the bound at a is at least the target, b if the bound at b is at most it), narrowed by safeguarded Newton iterations until the bound at an end is within ftol of the target, or [l, r] is at rounding

inline auto hasNodes() const -> bool

Whether any active term is a node.

Returns:

True if some node is still unopened

inline void refine(const double tLo, const double tHi, const double tC)

Refine the cut for a bracket and candidate.

Retires the terms wholly left or right of [tLo, tHi] whose slack fits the budget, then opens the nodes contributing most to F_U - F_L at tC, largest first, until those left unopened sum to at most a quarter of the tolerance (all of them, for a zero tolerance), a leaf’s points becoming exact terms.

Parameters:
  • tLo – Left end of the bracket on the percentile

  • tHi – Right end of the bracket

  • tC – The candidate