72 const Eigen::MatrixXd& Cyy,
73 const Eigen::MatrixXd& Cya,
76 using namespace centroid_detail;
77 const auto n = Cyy.rows();
78 if (n <= 0 || Cyy.cols() != n || Caa.rows() != n || Caa.cols() != n ||
79 Cya.rows() != n || Cya.cols() != n || !Caa.allFinite() ||
80 !Cyy.allFinite() || !Cya.allFinite() || !std::isfinite(beta) ||
81 !(beta > 0.) || !std::isfinite(1. / beta) || !(1. / beta > 0.))
82 throw std::invalid_argument(
83 "Finite compatible centroid moments and positive beta required");
85 for (Eigen::Index i = 0; i < n; ++i) {
87 throw std::domain_error(
"Nonnegative centroid variance required");
88 if (Cyy(i, i) == 0. && ((Cyy.row(i).array() != 0.).any() ||
89 (Cyy.col(i).array() != 0.).any()))
90 throw std::domain_error(
91 "Zero centroid variance requires a zero covariance row");
92 scale[i] = Cyy(i, i) == 0. ? 1. : std::sqrt(Cyy(i, i));
94 Matrix aa(n, n), yy(n, n), ya(n, n);
95 for (Eigen::Index i = 0; i < n; ++i)
96 for (Eigen::Index j = 0; j < n; ++j) {
97 const long double si = scale[i], sj = scale[j];
98 aa(i, j) = checked(
static_cast<long double>(Caa(i, j)) * si * sj);
99 yy(i, j) = checked(
static_cast<long double>(Cyy(i, j)) / si / sj);
100 ya(i, j) = checked(
static_cast<long double>(Cya(i, j)) * sj / si);
103 const Matrix S = root(yy);
104 auto eig = spectrum(S * aa * S);
105 const double b = 1. / beta;
107 for (Eigen::Index i = 0; i < n; ++i) {
108 const double lambda = std::max(0., eig.eigenvalues()[i]);
109 weights[i] = 1. / (.5 * b + .5 * std::hypot(b, 2 * std::sqrt(lambda)));
111 Matrix response = S * eig.eigenvectors() * weights.asDiagonal() *
112 eig.eigenvectors().transpose() * S;
113 response = (.5 * response + .5 * response.transpose()).eval();
114 const Matrix meanResidual = ya + response * aa;
115 const Matrix quadratic = response * aa * response;
116 const Matrix scoreResidual = quadratic + b * response - yy;
119 ratio(meanResidual.stableNorm(),
120 std::max(ya.stableNorm(), (response * aa).stableNorm()));
122 ratio(scoreResidual.stableNorm(),
123 std::max({yy.stableNorm(), quadratic.stableNorm(),
124 (b * response).stableNorm()}));
129 for (Eigen::Index i = 0; i < n; ++i)
130 for (Eigen::Index j = 0; j < n; ++j) {
131 const long double si = scale[i], sj = scale[j];
132 const long double entry =
133 static_cast<long double>(response(i, j)) * si * sj;
134 result.
response(i, j) = checked(entry);
137 checked(
static_cast<long double>(meanResidual(i, j)) * si / sj);
139 static_cast<long double>(scoreResidual(i, j)) * si * sj);