.. _program_listing_file_src_kden_KernelDensity.hpp: Program Listing for File KernelDensity.hpp ========================================== |exhale_lsh| :ref:`Return to documentation for file ` (``src/kden/KernelDensity.hpp``) .. |exhale_lsh| unicode:: U+021B0 .. UPWARDS ARROW WITH TIP LEFTWARDS .. code-block:: cpp #ifndef KERNELDENSITY_HPP #define KERNELDENSITY_HPP #include "Bandwidth.hpp" #include "KDTree.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace kden { template struct KernelDensityData : public KDTreeData { std::span 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::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::swap(i, j); std::swap(w_[i], w_[j]); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) } }; template struct OwnedKernelDensityData : public OwnedKDTreeData { std::vector w_; [[nodiscard]] auto view() -> KernelDensityData { KernelDensityData v; static_cast&>(v) = OwnedKDTreeData::view(); v.w_ = std::span(w_); return v; } }; class RefinementList { public: explicit RefinementList(const std::size_t capacity = 64) { reset(std::bit_ceil(std::max(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 est(est_.begin() + static_cast(capacity_), est_.end()); const std::vector err(err_.begin() + static_cast(capacity_), err_.end()); const std::vector 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 est_; std::vector err_; std::vector arg_; std::vector node_; std::vector free_; }; template class ConditionalDensity; template class KernelDensity : public KDTree> { public: using Tree = KDTree>; using Sample = std::tuple, std::vector, typename KDTreeAuxStorage::Owned>; KernelDensity(KernelDensityData& data, const std::size_t leafSize, const Bandwidth& splitBandwidth, const std::vector& noSplitDims = {}) : Tree(normalizeWeights(data), leafSize, splitBandwidth, noSplitDims) { setNodeWeights(); } explicit KernelDensity(KernelDensityData& data, const std::size_t leafSize = 16, const std::vector& 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& 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& x, const double relTol, const double absTol) const -> double { return pdf(x, relTol, absTol, this->euclidean_); } [[nodiscard]] auto conditional(const std::vector& x0, const std::vector& marginalDims, const double massTol, const Bandwidth& bandwidth, const std::size_t leafSize = 16) const -> ConditionalDensity { auto pts = conditionalPoints(x0, marginalDims, massTol, bandwidth); return ConditionalDensity(std::move(pts.data_), Bandwidth(pts.metric_), std::move(pts.dims_), pts.marginal_, leafSize); } [[nodiscard]] auto conditionalSample(const std::vector& x0, const std::vector& 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& x0, const std::vector& 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 others(nDim, true); others[dim] = false; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) const auto di = static_cast(dim); // NOLINT(misc-include-cleaner) -- Eigen::Index is provided by (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& pct, const double relTol, const double absTol, const Bandwidth& bandwidth) const -> std::vector { return parallelEval(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& marginalDims, const Bandwidth& bandwidth, const std::size_t leafSize = 16) const -> ConditionalDensity { 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 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 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 (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that const auto nR = static_cast(dimsR.size()); // NOLINT(misc-include-cleaner) -- Eigen::Index is provided by (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(dimsR[static_cast(r)]), // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) static_cast(dimsR[static_cast(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 data; data.nDim_ = nKept; data.x_.resize(n * nKept); data.w_.assign(pts.w_.begin(), pts.w_.end()); if constexpr (KernelDensityData::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(std::move(data), Bandwidth(metric), std::move(dimsR), 1.0, leafSize); } [[nodiscard]] auto marginalize(const std::vector& marginalDims, const std::size_t leafSize = 16) const -> ConditionalDensity { 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 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 { 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 kept; kept.reserve(active_.size()); std::vector> 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 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::epsilon() * std::max(std::abs(a), std::abs(b)); } void addNode(const std::size_t idx, std::vector& 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>& gaps, const std::size_t n) const -> std::vector { std::vector 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 kde_; std::size_t dim_; double s_; double dnorm_; double slackBudget_; double retireTol_; double tolP_; std::vector 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 data_; std::vector dims_; Eigen::MatrixXd metric_; // NOLINT(misc-include-cleaner) -- Eigen::MatrixXd is provided by (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that double marginal_ = 0.0; }; [[nodiscard]] auto conditionalPoints(const std::vector& x0, const std::vector& 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 xF(nDim, std::numeric_limits::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 data; data.nDim_ = nR; data.x_.resize(kept.size() * nR); data.w_.resize(kept.size()); if constexpr (KernelDensityData::hasAux) { data.aux_.reserve(kept.size()); } Eigen::VectorXd a(static_cast(nF)); // NOLINT(misc-include-cleaner) -- Eigen::VectorXd is provided by (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(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(r)); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) } data.w_[k] = w; // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) if constexpr (KernelDensityData::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(nF)); return {.data_ = std::move(data), .dims_ = std::move(dimsR), .metric_ = kernelMetric, .marginal_ = marginal}; } public: [[nodiscard]] auto conditional(const std::vector& x0, const std::vector& marginalDims, const double massTol, const std::size_t leafSize = 16) const -> ConditionalDensity { return conditional(x0, marginalDims, massTol, this->euclidean_, leafSize); } [[nodiscard]] auto pdf(const std::vector>& x, const double relTol, const double absTol, const std::vector& bandwidth) const -> std::vector { if (bandwidth.size() != x.size()) { throw std::invalid_argument("KernelDensity::pdf: x and bandwidth must have the same " "number of elements"); } return parallelEval(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>& x, const double relTol, const double absTol, const Bandwidth& bandwidth) const -> std::vector { const Bandwidth bw = this->sharedReduction(x, bandwidth); return parallelEval(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>& x, const double relTol, const double absTol) const -> std::vector { return pdf(x, relTol, absTol, this->euclidean_); } [[nodiscard]] auto pdf(const std::vector>& x, const std::vector& errDims, const std::vector& errCov, // NOLINT(misc-include-cleaner) -- Eigen::MatrixXd is provided by (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 { this->checkErrors(x, errDims, errCov, {}, "KernelDensity::pdf"); const Bandwidth bw = this->sharedReduction(x, bandwidth); return parallelEval(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>& x0, const std::vector& marginalDims, const double massTol, const Bandwidth& bandwidth, const std::size_t leafSize = 16) const -> std::vector> { return parallelEval>(x0.size(), [&](const std::size_t i) -> ConditionalDensity { return conditional(x0[i], marginalDims, massTol, bandwidth, leafSize); }); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) } [[nodiscard]] auto conditional(const std::vector>& x0, const std::vector& marginalDims, const double massTol, const std::size_t leafSize = 16) const -> std::vector> { return conditional(x0, marginalDims, massTol, this->euclidean_, leafSize); } [[nodiscard]] auto conditional(const std::vector>& x0, const std::vector& errDims, const std::vector& errCov, const std::vector& marginalDims, const double massTol, const Bandwidth& bandwidth, const std::size_t leafSize = 16) const -> std::vector> { this->checkErrors(x0, errDims, errCov, marginalDims, "KernelDensity::conditional"); return parallelEval>(x0.size(), [&](const std::size_t i) -> ConditionalDensity { 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>& x0, const std::vector& marginalDims, const double massTol, const Bandwidth& bandwidth) const -> std::vector { return parallelEval(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>& x0, const std::vector& marginalDims, const double massTol) const -> std::vector { return conditionalSample(x0, marginalDims, massTol, this->euclidean_); } [[nodiscard]] auto conditionalSample(const std::vector>& x0, const std::vector& errDims, const std::vector& errCov, const std::vector& marginalDims, const double massTol, const Bandwidth& bandwidth) const -> std::vector { this->checkErrors(x0, errDims, errCov, marginalDims, "KernelDensity::conditionalSample"); return parallelEval(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 [[nodiscard]] static auto parallelEval(const std::size_t n, const Eval& eval) -> std::vector { std::vector> 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 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& x0, const std::vector& marginalDims) const -> std::tuple, std::vector, std::vector, std::vector> { const std::size_t nDim = this->nDim_; std::vector 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 dimsF; std::vector dimsR; std::vector 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& dimsF, const std::vector& dimsR) -> std::pair // NOLINT(misc-include-cleaner) -- Eigen::MatrixXd is provided by (included via Bandwidth.hpp); clang-tidy's IWYU mapping doesn't know that { const auto nF = static_cast(dimsF.size()); const auto nR = static_cast(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(dimsR[static_cast(r)]); // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) for (Eigen::Index c = 0; c < nR; ++c) { mRR(r, c) = m(ri, static_cast(dimsR[static_cast(c)])); } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) for (Eigen::Index c = 0; c < nF; ++c) { mRF(r, c) = m(ri, static_cast(dimsF[static_cast(c)])); } // NOLINT(cppcoreguidelines-pro-bounds-avoid-unchecked-container-access) } const Eigen::LLT llt(mRR); // NOLINT(misc-include-cleaner) -- Eigen::LLT is provided by (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 (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& xF, const Bandwidth& weightMetric, const double massTol) const -> std::pair>, double> { const auto& pts = this->data_.get(); const auto bound = weightMetric.boxBounder(xF); std::vector scratch; RefinementList list; std::vector> 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(first)); double keptMass = 0.0; for (const auto& c : candidates) { keptMass += c.first; } return {std::move(candidates), keptMass}; } [[nodiscard]] auto evalPdf(const std::vector& 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(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 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& x, const Bandwidth& bandwidth, const Bandwidth::BoxBounder& bound, std::vector& scratch) const -> std::pair { 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& data) -> KernelDensityData& { data.validate(); normalizeWeightArray(data.w_); return data; } static void normalizeWeightArray(const std::span 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 nodeW_; }; template class ConditionalDensity { public: [[nodiscard]] auto pdf(const std::vector& y, const double relTol, const double absTol) const -> double { return kde_.pdf(y, relTol, absTol, bandwidth_); } [[nodiscard]] auto pdf(const std::vector>& y, const double relTol, const double absTol) const -> std::vector { 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& pct, const double relTol, const double absTol) const -> std::vector { return kde_.percentile(dim, pct, relTol, absTol, bandwidth_); } [[nodiscard]] auto dims() const -> const std::vector& { return dims_; } [[nodiscard]] auto marginal() const -> double { return marginal_; } [[nodiscard]] auto bandwidth() const -> const Bandwidth& { return bandwidth_; } [[nodiscard]] auto kde() const -> const KernelDensity& { return kde_; } [[nodiscard]] auto data() const -> const KernelDensityData& { return points_->view_; } private: friend class KernelDensity; struct Points { OwnedKernelDensityData owned_; KernelDensityData view_; }; static auto makePoints(OwnedKernelDensityData&& data) -> std::unique_ptr { auto p = std::make_unique(); p->owned_ = std::move(data); p->view_ = p->owned_.view(); return p; } ConditionalDensity(OwnedKernelDensityData&& data, Bandwidth bandwidth, std::vector 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_; KernelDensity kde_; Bandwidth bandwidth_; std::vector dims_; double marginal_; }; } // namespace kden #endif // KERNELDENSITY_HPP