slope 6.6.0
Loading...
Searching...
No Matches
observation_weights.h
1#pragma once
2
3#include <Eigen/Core>
4#include <stdexcept>
5
6namespace slope::detail {
7
8inline bool
9uniformObservationWeights(const Eigen::VectorXd& weights)
10{
11 return weights.size() == 0 ||
12 (weights(0) > 0.0 && (weights.array() == weights(0)).all());
13}
14
16inline Eigen::VectorXd
17normalizeObservationWeights(const Eigen::VectorXd& weights, Eigen::Index n)
18{
19 if (n <= 0) {
20 throw std::invalid_argument("Observation weights require at least one row");
21 }
22 if (weights.size() == 0) {
23 return Eigen::VectorXd::Ones(n);
24 }
25 if (weights.size() != n) {
26 throw std::invalid_argument(
27 "Observation weights must have one entry per row");
28 }
29 if (!weights.allFinite() || (weights.array() < 0.0).any()) {
30 throw std::invalid_argument(
31 "Observation weights must be finite and nonnegative");
32 }
33 if (weights.maxCoeff() == 0.0) {
34 throw std::invalid_argument(
35 "Observation weights must have positive total weight");
36 }
37 if (uniformObservationWeights(weights)) {
38 return Eigen::VectorXd::Ones(n);
39 }
40 // Scaling first avoids overflow when finite weights have a very large sum.
41 Eigen::VectorXd normalized = weights / weights.maxCoeff();
42 normalized *= static_cast<double>(n) / normalized.sum();
43 return normalized;
44}
45
46inline Eigen::Index
47positiveWeightCount(const Eigen::VectorXd& weights)
48{
49 return (weights.array() > 0.0).count();
50}
51
52inline void
53maskZeroWeightRows(Eigen::MatrixXd& values, const Eigen::VectorXd& weights)
54{
55 for (Eigen::Index i = 0; i < weights.size(); ++i) {
56 if (weights(i) == 0.0) {
57 values.row(i).setZero();
58 }
59 }
60}
61
62inline Eigen::RowVectorXd
63weightedMean(const Eigen::MatrixXd& values, const Eigen::VectorXd& weights)
64{
65 Eigen::RowVectorXd mean = Eigen::RowVectorXd::Zero(values.cols());
66 const double total = weights.sum();
67 for (Eigen::Index i = 0; i < values.rows(); ++i) {
68 if (weights(i) > 0.0) {
69 mean += (weights(i) / total) * values.row(i);
70 }
71 }
72 return mean;
73}
74
75} // namespace slope::detail