Program Listing for File KernelDensity.hpp
↰ Return to documentation for file (src/kden/KernelDensity.hpp)
#ifndef KERNELDENSITY_HPP
#define KERNELDENSITY_HPP
#include "Bandwidth.hpp"
#include "KDTree.hpp"
#include <algorithm>
#include <bit>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <functional>
#include <limits>
#include <memory>
#include <numbers>
#include <optional>
#include <span>
#include <stdexcept>
#include <tuple>
#include <utility>
#include <vector>
namespace kden {
template <typename AuxType = void>
struct KernelDensityData : public KDTreeData<AuxType>
{
std::span<double> w_;
[[nodiscard]] auto weight(const std::size_t i) const -> double { return w_[i]; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
void validate() const
{
KDTreeData<AuxType>::validate();
if (w_.size() != this->size())
{
throw std::invalid_argument("KernelDensityData: w_ must hold one element per point");
}
if (!std::ranges::all_of(w_, [](const double v) -> bool { return std::isfinite(v) && v >= 0.0; }))
{
throw std::invalid_argument("KernelDensityData: weights must be finite and non-negative");
}
}
void swap(const std::size_t i, const std::size_t j)
{
KDTreeData<AuxType>::swap(i, j);
std::swap(w_[i], w_[j]); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
};
template <typename AuxType = void>
struct OwnedKernelDensityData : public OwnedKDTreeData<AuxType>
{
std::vector<double> w_;
[[nodiscard]] auto view() -> KernelDensityData<AuxType>
{
KernelDensityData<AuxType> v;
static_cast<KDTreeData<AuxType>&>(v) = OwnedKDTreeData<AuxType>::view();
v.w_ = std::span<double>(w_);
return v;
}
};
class RefinementList
{
public:
explicit RefinementList(const std::size_t capacity = 64)
{
reset(std::bit_ceil(std::max<std::size_t>(capacity, 1)));
}
[[nodiscard]] auto estimate() const -> double { return est_[1]; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
[[nodiscard]] auto uncertainty() const -> double { return err_[1]; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
[[nodiscard]] auto worst() const -> std::size_t { return arg_[1] - capacity_; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
[[nodiscard]] auto uncertainty(const std::size_t slot) const -> double { return err_[capacity_ + slot]; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
[[nodiscard]] auto node(const std::size_t slot) const -> std::size_t { return node_[slot]; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
[[nodiscard]] auto size() const -> std::size_t { return used_ - free_.size(); }
void insert(const std::size_t node, const double est, const double err)
{
std::size_t slot = 0;
if (!free_.empty())
{
slot = free_.back();
free_.pop_back();
}
else
{
if (used_ == capacity_) { grow(); }
slot = used_++;
}
replace(slot, node, est, err);
}
void replace(const std::size_t slot, const std::size_t node, const double est, const double err)
{
node_[slot] = node; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
set(slot, est, err);
}
void erase(const std::size_t slot)
{
set(slot, 0.0, 0.0);
free_.push_back(slot);
}
private:
void set(const std::size_t slot, const double est, const double err)
{
std::size_t i = capacity_ + slot;
est_[i] = est; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
err_[i] = err; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
for (i >>= 1; i > 0; i >>= 1) { pull(i); }
}
void pull(const std::size_t i)
{
const std::size_t l = 2 * i;
const std::size_t r = l + 1;
est_[i] = est_[l] + est_[r]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
err_[i] = err_[l] + err_[r]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
arg_[i] = err_[arg_[l]] >= err_[arg_[r]] ? arg_[l] : arg_[r]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
void reset(const std::size_t capacity)
{
capacity_ = capacity;
est_.assign(2 * capacity, 0.0);
err_.assign(2 * capacity, 0.0);
arg_.assign(2 * capacity, 0);
node_.assign(capacity, 0);
for (std::size_t s = 0; s < capacity; ++s) { arg_[capacity + s] = capacity + s; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
for (std::size_t i = capacity - 1; i > 0; --i) { pull(i); }
}
void grow()
{
const std::vector<double> est(est_.begin() + static_cast<std::ptrdiff_t>(capacity_), est_.end());
const std::vector<double> err(err_.begin() + static_cast<std::ptrdiff_t>(capacity_), err_.end());
const std::vector<std::size_t> node = node_;
const std::size_t old = capacity_;
reset(2 * old);
for (std::size_t s = 0; s < old; ++s)
{
est_[capacity_ + s] = est[s]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
err_[capacity_ + s] = err[s]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
node_[s] = node[s]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
for (std::size_t i = capacity_ - 1; i > 0; --i) { pull(i); }
}
std::size_t capacity_ = 0;
std::size_t used_ = 0;
std::vector<double> est_;
std::vector<double> err_;
std::vector<std::size_t> arg_;
std::vector<std::size_t> node_;
std::vector<std::size_t> free_;
};
template <typename AuxType>
class ConditionalDensity;
template <typename AuxType = void>
class KernelDensity : public KDTree<KernelDensityData<AuxType>>
{
public:
using Tree = KDTree<KernelDensityData<AuxType>>;
using Sample = std::tuple<std::vector<double>, std::vector<double>,
typename KDTreeAuxStorage<AuxType>::Owned>;
KernelDensity(KernelDensityData<AuxType>& data,
const std::size_t leafSize,
const Bandwidth& splitBandwidth,
const std::vector<std::size_t>& noSplitDims = {}) :
Tree(normalizeWeights(data), leafSize, splitBandwidth, noSplitDims)
{
setNodeWeights();
}
explicit KernelDensity(KernelDensityData<AuxType>& data, const std::size_t leafSize = 16,
const std::vector<std::size_t>& noSplitDims = {}) :
Tree(normalizeWeights(data), leafSize, noSplitDims)
{
setNodeWeights();
}
[[nodiscard]] auto nodeW(const std::size_t idx) const -> double { return nodeW_[idx]; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
void reweight()
{
normalizeWeightArray(this->data_.get().w_);
setNodeWeights();
}
[[nodiscard]] auto pdf(const std::vector<double>& x,
const double relTol,
const double absTol,
const Bandwidth& bandwidth) const -> double
{
if (x.size() != this->nDim_ || bandwidth.nDim() != this->nDim_)
{
throw std::invalid_argument("KernelDensity::pdf: x and bandwidth must be "
"for nDim dimensions");
}
if (bandwidth.matches(x)) { return evalPdf(x, relTol, absTol, bandwidth); }
if (bandwidth.isReduced())
{
throw std::invalid_argument("KernelDensity::pdf: bandwidth was reduced for "
"a different pattern of NaNs than x's");
}
return evalPdf(x, relTol, absTol, bandwidth.reduce(Bandwidth::nanPattern(x)));
}
[[nodiscard]] auto pdf(const std::vector<double>& x,
const double relTol,
const double absTol) const -> double
{
return pdf(x, relTol, absTol, this->euclidean_);
}
[[nodiscard]] 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>
{
auto pts = conditionalPoints(x0, marginalDims, massTol, bandwidth);
return ConditionalDensity<AuxType>(std::move(pts.data_), Bandwidth(pts.metric_),
std::move(pts.dims_), pts.marginal_, leafSize);
}
[[nodiscard]] auto conditionalSample(const std::vector<double>& x0,
const std::vector<std::size_t>& marginalDims,
const double massTol,
const Bandwidth& bandwidth) const -> Sample
{
auto pts = conditionalPoints(x0, marginalDims, massTol, bandwidth);
return {std::move(pts.data_.x_), std::move(pts.data_.w_), std::move(pts.data_.aux_)};
}
[[nodiscard]] auto conditionalSample(const std::vector<double>& x0,
const std::vector<std::size_t>& marginalDims,
const double massTol) const -> Sample
{
return conditionalSample(x0, marginalDims, massTol, this->euclidean_);
}
[[nodiscard]] auto percentile(const std::size_t dim,
const double pct,
const double relTol,
const double absTol,
const Bandwidth& bandwidth) const -> double
{
const std::size_t nDim = this->nDim_;
if (dim >= nDim)
{
throw std::invalid_argument("KernelDensity::percentile: dim must be below nDim");
}
if (!(pct > 0.0) || !(pct < 100.0)) // written to reject NaN too
{
throw std::invalid_argument("KernelDensity::percentile: pct must be in (0, 100)");
}
if (!(relTol >= 0.0) || !(absTol >= 0.0))
{
throw std::invalid_argument("KernelDensity::percentile: relTol and absTol must be non-negative");
}
if (bandwidth.nDim() != nDim)
{
throw std::invalid_argument("KernelDensity::percentile: bandwidth must be for nDim dimensions");
}
if (bandwidth.isReduced())
{
throw std::invalid_argument("KernelDensity::percentile: bandwidth must not be reduced");
}
if (this->data_.get().size() == 0)
{
throw std::domain_error("KernelDensity::percentile: the estimate has no points");
}
// The marginal kernel in dim: the bandwidth reduced to dim alone
std::vector<bool> others(nDim, true);
others[dim] = false; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
const auto di = static_cast<Eigen::Index>(dim); // NOLINT(misc-include-cleaner) -- Eigen::Index is provided by <Eigen/Dense> (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that
const double m = bandwidth.reduce(others).h2Inv()(di, di);
if (!(m > 0.0) || !std::isfinite(m))
{
throw std::domain_error("KernelDensity::percentile: the bandwidth's marginal in dim is not positive");
}
const double p = pct / 100.0;
return evalPercentile(dim, p, std::max(absTol, relTol * std::min(p, 1.0 - p)), std::sqrt(m));
}
[[nodiscard]] auto percentile(const std::size_t dim,
const double pct,
const double relTol,
const double absTol) const -> double
{
return percentile(dim, pct, relTol, absTol, this->euclidean_);
}
[[nodiscard]] 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>
{
return parallelEval<double>(pct.size(), [&](const std::size_t i) -> double
{ return percentile(dim, pct[i], relTol, absTol, bandwidth); }); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
[[nodiscard]] auto marginalize(const std::vector<std::size_t>& marginalDims,
const Bandwidth& bandwidth,
const std::size_t leafSize = 16) const -> ConditionalDensity<AuxType>
{
const std::size_t nDim = this->nDim_;
if (bandwidth.nDim() != nDim)
{
throw std::invalid_argument("KernelDensity::marginalize: bandwidth must be for nDim dimensions");
}
if (bandwidth.isReduced())
{
throw std::invalid_argument("KernelDensity::marginalize: bandwidth must not be reduced");
}
std::vector<bool> inG(nDim, false);
for (const std::size_t d : marginalDims)
{
if (d >= nDim || inG[d]) // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
{
throw std::invalid_argument("KernelDensity::marginalize: marginalDims must hold "
"distinct dimensions below nDim");
}
inG[d] = true; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
std::vector<std::size_t> dimsR;
for (std::size_t d = 0; d < nDim; ++d)
{
if (!inG[d]) { dimsR.push_back(d); } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
if (dimsR.empty())
{
throw std::invalid_argument("KernelDensity::marginalize: marginalDims must leave at least one dimension");
}
// The kernel metric: the Schur complement over R
const Eigen::MatrixXd mPrime = bandwidth.reduce(inG).h2Inv(); // NOLINT(misc-include-cleaner) -- Eigen::MatrixXd is provided by <Eigen/Dense> (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that
const auto nR = static_cast<Eigen::Index>(dimsR.size()); // NOLINT(misc-include-cleaner) -- Eigen::Index is provided by <Eigen/Dense> (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that
Eigen::MatrixXd metric(nR, nR);
for (Eigen::Index r = 0; r < nR; ++r)
{
for (Eigen::Index c = 0; c < nR; ++c)
{
metric(r, c) = mPrime(static_cast<Eigen::Index>(dimsR[static_cast<std::size_t>(r)]), // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
static_cast<Eigen::Index>(dimsR[static_cast<std::size_t>(c)])); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
}
// Every point's coordinates in R, weight, and auxiliary data
const auto& pts = this->data_.get();
const std::size_t n = pts.size();
const std::size_t nKept = dimsR.size();
OwnedKernelDensityData<AuxType> data;
data.nDim_ = nKept;
data.x_.resize(n * nKept);
data.w_.assign(pts.w_.begin(), pts.w_.end());
if constexpr (KernelDensityData<AuxType>::hasAux) { data.aux_.assign(pts.aux_.begin(), pts.aux_.end()); }
#ifdef _OPENMP
# pragma omp parallel for
#endif
for (std::size_t i = 0; i < n; ++i)
{
for (std::size_t r = 0; r < nKept; ++r)
{
data.x_[(i * nKept) + r] = pts.x_[(i * nDim) + dimsR[r]]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
}
return ConditionalDensity<AuxType>(std::move(data), Bandwidth(metric), std::move(dimsR), 1.0, leafSize);
}
[[nodiscard]] auto marginalize(const std::vector<std::size_t>& marginalDims,
const std::size_t leafSize = 16) const -> ConditionalDensity<AuxType>
{
return marginalize(marginalDims, this->euclidean_, leafSize);
}
protected:
class PercentileCut
{
public:
enum class Bound : std::uint8_t
{
lower,
upper,
mean
};
PercentileCut(const KernelDensity& kde, const std::size_t dim, const double s, const double tolP) :
kde_(std::cref(kde)), dim_(dim), s_(s), dnorm_(s / std::sqrt(std::numbers::pi)),
slackBudget_(0.5 * tolP), retireTol_(1e-6 * tolP), tolP_(tolP)
{
addNode(rootNode, active_);
}
[[nodiscard]] auto eval(const double t, const Bound which) const -> std::pair<double, double>
{
double f = which == Bound::upper ? cU_ : cL_;
if (which == Bound::mean) { f = 0.5 * (cL_ + cU_); }
double df = 0.0;
for (const auto& term : active_)
{
if (which == Bound::mean && term.node_ != nullNode)
{
f += 0.5 * term.w_ * (cdf(t - term.lo_) + cdf(t - term.hi_));
df += 0.5 * term.w_ * (dens(t - term.lo_) + dens(t - term.hi_));
continue;
}
const double u = t - (which == Bound::upper ? term.lo_ : term.hi_); // lo_ == hi_ for a point
f += term.w_ * cdf(u);
df += term.w_ * dens(u);
}
return {f, df};
}
[[nodiscard]] auto solve(const Bound which, const double target, double a, double b,
const double ftol) const -> std::pair<double, double>
{
if (eval(a, which).first >= target) { return {a, a}; }
if (eval(b, which).first <= target) { return {b, b}; }
double x = 0.5 * (a + b);
for (int it = 0; it < 200; ++it)
{
const auto [g, dg] = eval(x, which);
if (g < target) { a = x; }
else if (g > target) { b = x; }
else { return {x, x}; }
if (std::abs(g - target) <= ftol || atRounding(a, b)) { break; }
double next = dg > 0.0 ? x + ((target - g) / dg) : a;
if (!(next > a) || !(next < b)) { next = 0.5 * (a + b); }
x = next;
}
return {a, b};
}
[[nodiscard]] auto hasNodes() const -> bool
{
return std::ranges::any_of(active_, [](const Term& t) -> bool { return t.node_ != nullNode; });
}
void refine(const double tLo, const double tHi, const double tC)
{
std::vector<Term> kept;
kept.reserve(active_.size());
std::vector<std::pair<double, std::size_t>> gaps; // (gap at tC, index in kept)
for (const auto& term : active_)
{
if (retire(term, tLo, tHi)) { continue; }
if (term.node_ != nullNode)
{
gaps.emplace_back(term.w_ * (cdf(tC - term.lo_) - cdf(tC - term.hi_)), kept.size());
}
kept.push_back(term);
}
const std::vector<bool> open = toOpen(gaps, kept.size());
active_.clear();
for (std::size_t k = 0; k < kept.size(); ++k)
{
const auto& term = kept[k]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
if (!open[k]) // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
{
active_.push_back(term);
continue;
}
const auto& node = kde_.get().nodes()[term.node_]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
addNode(node.lchild_, active_);
addNode(node.rchild_, active_);
}
}
private:
struct Term
{
double w_;
double lo_;
double hi_;
std::size_t node_;
};
[[nodiscard]] auto cdf(const double u) const -> double { return 0.5 * std::erfc(-s_ * u); }
[[nodiscard]] auto ccdf(const double u) const -> double { return 0.5 * std::erfc(s_ * u); }
[[nodiscard]] auto dens(const double u) const -> double { return dnorm_ * std::exp(-s_ * s_ * u * u); }
[[nodiscard]] static auto atRounding(const double a, const double b) -> bool
{
return b - a <= 4.0 * std::numeric_limits<double>::epsilon() * std::max(std::abs(a), std::abs(b));
}
void addNode(const std::size_t idx, std::vector<Term>& terms) const
{
if (!(kde_.get().nodeW(idx) > 0.0)) { return; }
const auto& node = kde_.get().nodes()[idx]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
if (node.splitDim_ >= 0)
{
terms.push_back({.w_ = kde_.get().nodeW(idx), .lo_ = kde_.get().nodeLo(idx)[dim_], // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
.hi_ = kde_.get().nodeHi(idx)[dim_], .node_ = idx}); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
return;
}
const auto& pts = kde_.get().data();
for (std::size_t i = node.start_; i < node.start_ + node.count_; ++i)
{
const double wi = pts.w_[i]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
const double xi = pts.position(i)[dim_]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
if (wi > 0.0) { terms.push_back({.w_ = wi, .lo_ = xi, .hi_ = xi, .node_ = nullNode}); }
}
}
auto retire(const Term& term, const double tLo, const double tHi) -> bool
{
const double leftSlack = term.w_ * ccdf(tLo - term.hi_);
if (leftSlack <= retireTol_ && slack_ + leftSlack <= slackBudget_)
{
cL_ += term.w_ - leftSlack;
cU_ += term.w_;
slack_ += leftSlack;
return true;
}
const double rightSlack = term.w_ * cdf(tHi - term.lo_);
if (rightSlack <= retireTol_ && slack_ + rightSlack <= slackBudget_)
{
cU_ += rightSlack;
slack_ += rightSlack;
return true;
}
return false;
}
[[nodiscard]] auto toOpen(std::vector<std::pair<double, std::size_t>>& gaps, const std::size_t n) const
-> std::vector<bool>
{
std::vector<bool> open(n, false);
std::ranges::sort(gaps, std::greater<>());
double rest = 0.0;
for (const auto& gap : gaps) { rest += gap.first; }
for (const auto& [gap, k] : gaps)
{
if (rest <= 0.25 * tolP_ && rest < gaps.front().first) { break; }
open[k] = true; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
rest -= gap;
}
return open;
}
std::reference_wrapper<const KernelDensity> kde_;
std::size_t dim_;
double s_;
double dnorm_;
double slackBudget_;
double retireTol_;
double tolP_;
std::vector<Term> active_;
double cL_ = 0.0;
double cU_ = 0.0;
double slack_ = 0.0;
};
[[nodiscard]] auto evalPercentile(const std::size_t dim, const double p, const double tolP,
const double s) const -> double
{
using Bound = typename PercentileCut::Bound;
PercentileCut cut(*this, dim, s, tolP);
// An initial bracket, wide enough that every term's kernel
// cumulative distribution is 0 at its left end, 1 at its right
const double reach = 40.0 / s;
double tLo = this->nodeLo(rootNode)[dim] - reach; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
double tHi = this->nodeHi(rootNode)[dim] + reach; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
while (true)
{
// The bracket: t* is no less than where F_U reaches p, no
// more than where F_L does; then the candidate, the end of
// its own bracket where (F_L + F_U) / 2 is nearer p
tLo = cut.solve(Bound::upper, p, tLo, tHi, tolP).first;
tHi = cut.solve(Bound::lower, p, tLo, tHi, tolP).second;
const auto [cl, cr] = cut.solve(Bound::mean, p, tLo, tHi, 0.1 * tolP);
const double tC = std::abs(cut.eval(cl, Bound::mean).first - p) <=
std::abs(cut.eval(cr, Bound::mean).first - p) ? cl : cr;
if (cut.eval(tC, Bound::upper).first - p <= tolP && p - cut.eval(tC, Bound::lower).first <= tolP)
{
return tC;
}
if (!cut.hasNodes()) { return tC; } // every term exact: tC is the root, to rounding
cut.refine(tLo, tHi, tC);
}
}
struct ConditionalPoints
{
OwnedKernelDensityData<AuxType> data_;
std::vector<std::size_t> dims_;
Eigen::MatrixXd metric_; // NOLINT(misc-include-cleaner) -- Eigen::MatrixXd is provided by <Eigen/Dense> (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that
double marginal_ = 0.0;
};
[[nodiscard]] auto conditionalPoints(const std::vector<double>& x0,
const std::vector<std::size_t>& marginalDims,
const double massTol,
const Bandwidth& bandwidth) const -> ConditionalPoints
{
// Sort the dimensions into fixed (F), kept (R), and
// marginalized (G)
const std::size_t nDim = this->nDim_;
if (x0.size() != nDim || bandwidth.nDim() != nDim)
{
throw std::invalid_argument("KernelDensity::conditional: x0 and bandwidth must be "
"for nDim dimensions");
}
if (bandwidth.isReduced())
{
throw std::invalid_argument("KernelDensity::conditional: bandwidth must not be reduced");
}
if (!(massTol >= 0.0) || !(massTol < 1.0)) // written to reject NaN too
{
throw std::invalid_argument("KernelDensity::conditional: massTol must be in [0, 1)");
}
auto [dimsF, dimsR, inG, inGR] = classifyDims(x0, marginalDims);
// The metrics: M' over F and R, S over F, and the shift K
const Bandwidth mPrime = bandwidth.reduce(inG);
const Bandwidth weightMetric = bandwidth.reduce(inGR);
const auto [kernelMetric, shift] = conditionalMetric(mPrime.h2Inv(), dimsF, dimsR);
// Walk the tree, collecting the points of the leaves reached
std::vector<double> xF(nDim, std::numeric_limits<double>::quiet_NaN());
for (const std::size_t d : dimsF) { xF[d] = x0[d]; }
const auto [kept, keptMass] = selectConditional(xF, weightMetric, massTol);
if (!(keptMass > 0.0))
{
throw std::domain_error("KernelDensity::conditional: every point's conditional "
"weight underflows to zero");
}
// The new points, in the kept dimensions
const auto& pts = this->data_.get();
const std::size_t nF = dimsF.size();
const std::size_t nR = dimsR.size();
OwnedKernelDensityData<AuxType> data;
data.nDim_ = nR;
data.x_.resize(kept.size() * nR);
data.w_.resize(kept.size());
if constexpr (KernelDensityData<AuxType>::hasAux) { data.aux_.reserve(kept.size()); }
Eigen::VectorXd a(static_cast<Eigen::Index>(nF)); // NOLINT(misc-include-cleaner) -- Eigen::VectorXd is provided by <Eigen/Dense> (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that
for (std::size_t k = 0; k < kept.size(); ++k)
{
const auto [w, i] = kept[k]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
const auto pos = pts.position(i);
for (std::size_t f = 0; f < nF; ++f) { a(static_cast<Eigen::Index>(f)) = pos[dimsF[f]] - x0[dimsF[f]]; } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
const Eigen::VectorXd ka = shift * a;
for (std::size_t r = 0; r < nR; ++r)
{
data.x_[(k * nR) + r] = pos[dimsR[r]] + ka(static_cast<Eigen::Index>(r)); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
data.w_[k] = w; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
if constexpr (KernelDensityData<AuxType>::hasAux) { data.aux_.push_back(pts.aux(i)); }
}
// Density of the marginal over F at x0_F: the original
// weights sum to one, so the conditional weights sum to it,
// up to the normalization of S's kernel
const double marginal = keptMass * std::sqrt(weightMetric.det()) /
std::pow(std::numbers::pi, 0.5 * static_cast<double>(nF));
return {.data_ = std::move(data), .dims_ = std::move(dimsR), .metric_ = kernelMetric,
.marginal_ = marginal};
}
public:
[[nodiscard]] 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>
{
return conditional(x0, marginalDims, massTol, this->euclidean_, leafSize);
}
[[nodiscard]] auto pdf(const std::vector<std::vector<double>>& x,
const double relTol,
const double absTol,
const std::vector<Bandwidth>& bandwidth) const -> std::vector<double>
{
if (bandwidth.size() != x.size())
{
throw std::invalid_argument("KernelDensity::pdf: x and bandwidth must have the same "
"number of elements");
}
return parallelEval<double>(x.size(), [&](const std::size_t i) -> double
{ return pdf(x[i], relTol, absTol, bandwidth[i]); }); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
[[nodiscard]] auto pdf(const std::vector<std::vector<double>>& x,
const double relTol,
const double absTol,
const Bandwidth& bandwidth) const -> std::vector<double>
{
const Bandwidth bw = this->sharedReduction(x, bandwidth);
return parallelEval<double>(x.size(), [&](const std::size_t i) -> double
{ return pdf(x[i], relTol, absTol, bw); }); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
[[nodiscard]] auto pdf(const std::vector<std::vector<double>>& x,
const double relTol,
const double absTol) const -> std::vector<double>
{
return pdf(x, relTol, absTol, this->euclidean_);
}
[[nodiscard]] auto pdf(const std::vector<std::vector<double>>& x,
const std::vector<std::size_t>& errDims,
const std::vector<Eigen::MatrixXd>& errCov, // NOLINT(misc-include-cleaner) -- Eigen::MatrixXd is provided by <Eigen/Dense> (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that
const double relTol,
const double absTol,
const Bandwidth& bandwidth) const -> std::vector<double>
{
this->checkErrors(x, errDims, errCov, {}, "KernelDensity::pdf");
const Bandwidth bw = this->sharedReduction(x, bandwidth);
return parallelEval<double>(x.size(), [&](const std::size_t i) -> double
{
return pdf(x[i], relTol, absTol, bw.convolveCov(this->embedErrors(errDims, errCov[i]))); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
});
}
[[nodiscard]] 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>>
{
return parallelEval<ConditionalDensity<AuxType>>(x0.size(),
[&](const std::size_t i) -> ConditionalDensity<AuxType>
{ return conditional(x0[i], marginalDims, massTol, bandwidth, leafSize); }); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
[[nodiscard]] 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>>
{
return conditional(x0, marginalDims, massTol, this->euclidean_, leafSize);
}
[[nodiscard]] 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>>
{
this->checkErrors(x0, errDims, errCov, marginalDims, "KernelDensity::conditional");
return parallelEval<ConditionalDensity<AuxType>>(x0.size(),
[&](const std::size_t i) -> ConditionalDensity<AuxType>
{
return conditional(x0[i], marginalDims, massTol, // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
bandwidth.convolveCov(this->embedErrors(errDims, errCov[i])), leafSize); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
});
}
[[nodiscard]] 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>
{
return parallelEval<Sample>(x0.size(),
[&](const std::size_t i) -> Sample
{ return conditionalSample(x0[i], marginalDims, massTol, bandwidth); }); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
[[nodiscard]] auto conditionalSample(const std::vector<std::vector<double>>& x0,
const std::vector<std::size_t>& marginalDims,
const double massTol) const
-> std::vector<Sample>
{
return conditionalSample(x0, marginalDims, massTol, this->euclidean_);
}
[[nodiscard]] 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>
{
this->checkErrors(x0, errDims, errCov, marginalDims, "KernelDensity::conditionalSample");
return parallelEval<Sample>(x0.size(),
[&](const std::size_t i) -> Sample
{
return conditionalSample(x0[i], marginalDims, massTol, // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
bandwidth.convolveCov(this->embedErrors(errDims, errCov[i]))); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
});
}
protected:
template <typename T, typename Eval>
[[nodiscard]] static auto parallelEval(const std::size_t n, const Eval& eval) -> std::vector<T>
{
std::vector<std::optional<T>> results(n);
std::exception_ptr error = nullptr;
#ifdef _OPENMP
# pragma omp parallel for schedule(dynamic)
#endif
for (std::size_t i = 0; i < n; ++i)
{
try
{
results[i].emplace(eval(i)); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
catch (...)
{
#ifdef _OPENMP
# pragma omp critical(kernelDensityBatchError)
#endif
{
if (!error) { error = std::current_exception(); }
}
}
}
if (error) { std::rethrow_exception(error); }
std::vector<T> out;
out.reserve(n);
for (auto& r : results) { out.push_back(std::move(*r)); } // NOLINT(bugprone-unchecked-optional-access) -- every element was set, or an exception rethrown above
return out;
}
[[nodiscard]] 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>>
{
const std::size_t nDim = this->nDim_;
std::vector<bool> inG(nDim, false);
for (const std::size_t d : marginalDims)
{
if (d >= nDim || inG[d])
{
throw std::invalid_argument("KernelDensity::conditional: marginalDims must hold "
"distinct dimensions below nDim");
}
inG[d] = true;
}
std::vector<std::size_t> dimsF;
std::vector<std::size_t> dimsR;
std::vector<bool> inGR = inG;
for (std::size_t d = 0; d < nDim; ++d)
{
if (inG[d]) { continue; }
if (std::isnan(x0[d])) // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
{
dimsR.push_back(d);
inGR[d] = true;
}
else { dimsF.push_back(d); }
}
if (dimsF.empty() || dimsR.empty())
{
throw std::invalid_argument("KernelDensity::conditional: x0 must fix at least one "
"dimension and leave at least one unfixed");
}
return {std::move(dimsF), std::move(dimsR), std::move(inG), std::move(inGR)};
}
[[nodiscard]] static 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> // NOLINT(misc-include-cleaner) -- Eigen::MatrixXd is provided by <Eigen/Dense> (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that
{
const auto nF = static_cast<Eigen::Index>(dimsF.size());
const auto nR = static_cast<Eigen::Index>(dimsR.size());
Eigen::MatrixXd mRR(nR, nR);
Eigen::MatrixXd mRF(nR, nF);
for (Eigen::Index r = 0; r < nR; ++r)
{
const auto ri = static_cast<Eigen::Index>(dimsR[static_cast<std::size_t>(r)]); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
for (Eigen::Index c = 0; c < nR; ++c) { mRR(r, c) = m(ri, static_cast<Eigen::Index>(dimsR[static_cast<std::size_t>(c)])); } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
for (Eigen::Index c = 0; c < nF; ++c) { mRF(r, c) = m(ri, static_cast<Eigen::Index>(dimsF[static_cast<std::size_t>(c)])); } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
const Eigen::LLT<Eigen::MatrixXd> llt(mRR); // NOLINT(misc-include-cleaner) -- Eigen::LLT is provided by <Eigen/Dense> (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that
if (llt.info() != Eigen::Success) // NOLINT(misc-include-cleaner) -- Eigen::Success is provided by <Eigen/Dense> (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that
{
throw std::domain_error("KernelDensity::conditional: the bandwidth's block over the "
"kept dimensions is not positive definite");
}
Eigen::MatrixXd k = llt.solve(mRF);
return {std::move(mRR), std::move(k)};
}
[[nodiscard]] 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>
{
const auto& pts = this->data_.get();
const auto bound = weightMetric.boxBounder(xF);
std::vector<double> scratch;
RefinementList list;
std::vector<std::pair<double, std::size_t>> candidates;
double leafMass = 0.0;
auto add = [&](const std::size_t idx, const std::size_t slot) -> void
{
const auto& node = this->nodes_[idx];
if (node.splitDim_ < 0)
{
for (std::size_t i = node.start_; i < node.start_ + node.count_; ++i)
{
const double w = pts.weight(i) * std::exp(-weightMetric.dist2(xF, pts.position(i), scratch));
if (w > 0.0)
{
candidates.emplace_back(w, i);
leafMass += w;
}
}
if (slot != nullNode) { list.erase(slot); }
return;
}
const auto [r2min, r2max] = bound.bounds(this->nodeLo(idx), this->nodeHi(idx));
const double w = nodeW_[idx]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
const double lo = w * std::exp(-r2max);
const double hi = w * std::exp(-r2min);
if (slot != nullNode) { list.replace(slot, idx, lo, hi); }
else { list.insert(idx, lo, hi); }
};
// Open nodes until the unopened ones can carry at most
// massTol / 2 of the total
add(rootNode, nullNode);
while (list.uncertainty() > 0.5 * massTol * (leafMass + list.estimate()))
{
const std::size_t worst = list.worst();
const auto& node = this->nodes_[list.node(worst)];
add(node.lchild_, worst);
add(node.rchild_, nullNode);
}
// Drop the lightest points, up to another massTol / 2
const double budget = 0.5 * massTol * (leafMass + list.estimate());
std::ranges::sort(candidates);
double dropped = 0.0;
std::size_t first = 0;
while (first < candidates.size() && dropped + candidates[first].first <= budget) // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
{
dropped += candidates[first].first; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
++first;
}
candidates.erase(candidates.begin(), candidates.begin() + static_cast<std::ptrdiff_t>(first));
double keptMass = 0.0;
for (const auto& c : candidates) { keptMass += c.first; }
return {std::move(candidates), keptMass};
}
[[nodiscard]] auto evalPdf(const std::vector<double>& x,
const double relTol,
const double absTol,
const Bandwidth& bandwidth) const -> double
{
// Normalization: exp(-d^T M d) integrates to
// pi^(n / 2) / sqrt(det M) over the n specified dimensions,
// and the weights sum to one
const double det = bandwidth.det();
if (!(det > 0.0))
{
throw std::domain_error("KernelDensity::pdf: cannot normalize: bandwidth is singular");
}
const double norm = std::sqrt(det) /
std::pow(std::numbers::pi, 0.5 * static_cast<double>(bandwidth.nSpecified()));
// Evaluate a node, adding it to the list (in a given slot,
// or a new one if slot is nullNode) or, if it is a leaf, to
// the leaves' sum (freeing the slot)
const auto bound = bandwidth.boxBounder(x);
std::vector<double> scratch;
RefinementList list;
double leafSum = 0.0;
auto add = [&](const std::size_t idx, const std::size_t slot) -> void
{
const auto [est, err] = nodePdf(idx, x, bandwidth, bound, scratch);
if (this->nodes_[idx].splitDim_ < 0)
{
leafSum += est;
if (slot != nullNode) { list.erase(slot); }
}
else if (slot != nullNode) { list.replace(slot, idx, est, err); }
else { list.insert(idx, est, err); }
};
add(rootNode, nullNode);
while (true)
{
// Converged, or exact (only leaves remain, or the
// remaining nodes' kernel values have underflowed to zero)
const double est = leafSum + list.estimate();
const double err = list.uncertainty();
const std::size_t worst = list.worst();
if (err < relTol * est || (est + err) * norm < absTol || list.uncertainty(worst) == 0.0)
{
return est * norm;
}
// Replace the worst node by its children
const auto& node = this->nodes_[list.node(worst)];
add(node.lchild_, worst);
add(node.rchild_, nullNode);
}
}
[[nodiscard]] 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>
{
const auto& node = this->nodes_[idx];
if (node.splitDim_ < 0)
{
const auto& pts = this->data_.get();
double sum = 0.0;
for (std::size_t i = node.start_; i < node.start_ + node.count_; ++i)
{
sum += pts.weight(i) * std::exp(-bandwidth.dist2(x, pts.position(i), scratch));
}
return {sum, 0.0};
}
const auto [r2min, r2max] = bound.bounds(this->nodeLo(idx), this->nodeHi(idx));
const double kMax = std::exp(-r2min);
const double kMin = std::exp(-r2max);
const double w = nodeW_[idx]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
return {0.5 * w * (kMax + kMin), 0.5 * w * (kMax - kMin)};
}
static auto normalizeWeights(KernelDensityData<AuxType>& data) -> KernelDensityData<AuxType>&
{
data.validate();
normalizeWeightArray(data.w_);
return data;
}
static void normalizeWeightArray(const std::span<double> w)
{
const std::size_t n = w.size();
double wMax = 0.0;
bool valid = true;
#ifdef _OPENMP
# pragma omp parallel for reduction(max:wMax) reduction(&&:valid)
#endif
for (std::size_t i = 0; i < n; ++i)
{
const double v = w[i]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
valid = valid && std::isfinite(v) && v >= 0.0;
wMax = std::max(wMax, v);
}
if (!valid)
{
throw std::invalid_argument("KernelDensity: weights must be finite and non-negative");
}
if (!(wMax > 0.0))
{
throw std::invalid_argument("KernelDensity: weights must not all be zero");
}
double wTot = 0.0;
#ifdef _OPENMP
# pragma omp parallel for reduction(+:wTot)
#endif
for (std::size_t i = 0; i < n; ++i)
{
w[i] /= wMax; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
wTot += w[i]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
#ifdef _OPENMP
# pragma omp parallel for
#endif
for (std::size_t i = 0; i < n; ++i)
{
w[i] /= wTot; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
}
void setNodeWeights()
{
const std::size_t nNodes = this->nodes_.size();
nodeW_.assign(nNodes, 0.0);
// Level k holds nodes 2^k - 1 through 2^(k+1) - 2
for (std::size_t level = this->nLevels_; level-- > 0;)
{
const std::size_t first = (std::size_t{1} << level) - 1;
const std::size_t last = std::min((std::size_t{2} << level) - 1, nNodes);
#ifdef _OPENMP
# pragma omp parallel for
#endif
for (std::size_t idx = first; idx < last; ++idx) { accumulateNode(idx); }
}
}
void accumulateNode(const std::size_t idx)
{
const auto& node = this->nodes_[idx];
if (node.splitDim_ < 0)
{
const auto& pts = this->data_.get();
double w = 0.0;
for (std::size_t i = node.start_; i < node.start_ + node.count_; ++i) { w += pts.weight(i); }
nodeW_[idx] = w; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
return;
}
nodeW_[idx] = nodeW_[node.lchild_] + nodeW_[node.rchild_]; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access)
}
std::vector<double> nodeW_;
};
template <typename AuxType = void>
class ConditionalDensity
{
public:
[[nodiscard]] auto pdf(const std::vector<double>& y, const double relTol, const double absTol) const -> double
{
return kde_.pdf(y, relTol, absTol, bandwidth_);
}
[[nodiscard]] auto pdf(const std::vector<std::vector<double>>& y, const double relTol,
const double absTol) const -> std::vector<double>
{
return kde_.pdf(y, relTol, absTol, bandwidth_);
}
[[nodiscard]] auto percentile(const std::size_t dim, const double pct, const double relTol,
const double absTol) const -> double
{
return kde_.percentile(dim, pct, relTol, absTol, bandwidth_);
}
[[nodiscard]] auto percentile(const std::size_t dim, const std::vector<double>& pct, const double relTol,
const double absTol) const -> std::vector<double>
{
return kde_.percentile(dim, pct, relTol, absTol, bandwidth_);
}
[[nodiscard]] auto dims() const -> const std::vector<std::size_t>& { return dims_; }
[[nodiscard]] auto marginal() const -> double { return marginal_; }
[[nodiscard]] auto bandwidth() const -> const Bandwidth& { return bandwidth_; }
[[nodiscard]] auto kde() const -> const KernelDensity<AuxType>& { return kde_; }
[[nodiscard]] auto data() const -> const KernelDensityData<AuxType>& { return points_->view_; }
private:
friend class KernelDensity<AuxType>;
struct Points
{
OwnedKernelDensityData<AuxType> owned_;
KernelDensityData<AuxType> view_;
};
static auto makePoints(OwnedKernelDensityData<AuxType>&& data) -> std::unique_ptr<Points>
{
auto p = std::make_unique<Points>();
p->owned_ = std::move(data);
p->view_ = p->owned_.view();
return p;
}
ConditionalDensity(OwnedKernelDensityData<AuxType>&& data, Bandwidth bandwidth,
std::vector<std::size_t> dims, const double marginal, const std::size_t leafSize) :
points_(makePoints(std::move(data))),
kde_(points_->view_, leafSize, bandwidth),
bandwidth_(std::move(bandwidth)),
dims_(std::move(dims)),
marginal_(marginal)
{}
std::unique_ptr<Points> points_;
KernelDensity<AuxType> kde_;
Bandwidth bandwidth_;
std::vector<std::size_t> dims_;
double marginal_;
};
} // namespace kden
#endif // KERNELDENSITY_HPP