Loading...
Searching...
No Matches
ArrowheadEigen.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "ArrowheadEigen.h"
6
7#include <Eigen/Dense>
8#include <algorithm>
9#include <cmath>
10#include <limits>
11#include <numeric>
12#include <vector>
13
14namespace gpr::linalg {
15
16namespace {
17
23struct Secular {
24 const double* d;
25 const double* z2;
26 int p;
27 double alpha;
28 double origin;
29
30 double operator()(double delta) const
31 {
32 double s = alpha - origin - delta;
33 for (int i = 0; i < p; ++i) {
34 const double den = (d[i] - origin) - delta;
35 s -= z2[i] / den;
36 }
37 return s;
38 }
39
40 double derivative(double delta) const
41 {
42 double s = -1.0;
43 for (int i = 0; i < p; ++i) {
44 const double den = (d[i] - origin) - delta;
45 s -= z2[i] / (den * den);
46 }
47 return s;
48 }
49};
50
63double solveShifted(const Secular& f, double lo, double hi)
64{
65 double a = lo, b = hi;
66 for (int i = 0; i < 6; ++i) {
67 const double mid = 0.5 * (a + b);
68 const double fm = f(mid);
69 if (!std::isfinite(fm)) {
70 b = mid;
71 continue;
72 }
73 if (fm > 0.0)
74 a = mid;
75 else
76 b = mid;
77 }
78 double x = 0.5 * (a + b);
79 for (int it = 0; it < 50; ++it) {
80 const double fx = f(x);
81 if (!std::isfinite(fx)) {
82 x = 0.5 * (a + b);
83 continue;
84 }
85 if (fx == 0.0) break;
86 if (fx > 0.0)
87 a = x;
88 else
89 b = x;
90 const double dfx = f.derivative(x);
91 double nx = (std::isfinite(dfx) && dfx != 0.0) ? x - fx / dfx : x;
92 if (!(nx > a && nx < b) || !std::isfinite(nx)) nx = 0.5 * (a + b);
93 const double step = std::abs(nx - x);
94 x = nx;
95 if (step <= 4.0 * std::numeric_limits<double>::epsilon() *
96 std::max(1.0, std::abs(x)))
97 break;
98 if (b - a <= 4.0 * std::numeric_limits<double>::epsilon() *
99 std::max(1.0, std::abs(x)))
100 break;
101 }
102 return x;
103}
104
105} // namespace
106
107bool arrowheadEigenRankOne(const Eigen::VectorXd& d_in,
108 const Eigen::VectorXd& z_in, double alpha,
109 Eigen::VectorXd& evals_asc, Eigen::MatrixXd& evecs)
110{
111 const Eigen::Index p = d_in.size();
112 if (z_in.size() != p || p < 0) return false;
113 const Eigen::Index n = p + 1;
114 if (!std::isfinite(alpha) || !d_in.allFinite() || !z_in.allFinite())
115 return false;
116
117 if (p == 0) {
118 evals_asc.resize(1);
119 evals_asc(0) = alpha;
120 evecs = Eigen::MatrixXd::Identity(1, 1);
121 return true;
122 }
123
124 // Ascending diagonal; the interlacing the root search relies on is
125 // stated for sorted poles.
126 std::vector<Eigen::Index> perm(static_cast<std::size_t>(p));
127 std::iota(perm.begin(), perm.end(), Eigen::Index{0});
128 std::sort(perm.begin(), perm.end(), [&](Eigen::Index a, Eigen::Index b) {
129 return d_in(a) < d_in(b);
130 });
131 Eigen::VectorXd d(p), z(p);
132 for (Eigen::Index i = 0; i < p; ++i) {
133 d(i) = d_in(perm[static_cast<std::size_t>(i)]);
134 z(i) = z_in(perm[static_cast<std::size_t>(i)]);
135 }
136
137 const double scale =
138 std::max({d.cwiseAbs().maxCoeff(), z.cwiseAbs().maxCoeff(),
139 std::abs(alpha), 1.0});
140 const double eps = std::numeric_limits<double>::epsilon();
141 // Coupling is judged against the overall scale, but a gap between two
142 // diagonal entries is judged against those entries. These spectra span
143 // eight decades: one absolute gap tolerance either deflates everything
144 // at the small end or nothing at the large end.
145 const double z_tol = 8.0 * eps * scale;
146 const auto close = [&](double x, double y) {
147 return std::abs(x - y) <=
148 8.0 * eps * std::max({std::abs(x), std::abs(y), 1e-300});
149 };
150
151 // Deflation. A negligible coupling entry leaves its diagonal entry an
152 // eigenvalue outright, and two diagonal entries closer than tol are
153 // rotated so one coupling entry vanishes and joins that case. Without
154 // this the secular equation has a zero-width bracket and the
155 // eigenvectors it produces are not orthogonal.
156 std::vector<Eigen::Index> keep;
157 std::vector<std::pair<Eigen::Index, double>> deflated; // index, eigenvalue
158 std::vector<std::array<Eigen::Index, 2>> rotations;
159 std::vector<double> rot_c, rot_s;
160 for (Eigen::Index i = 0; i < p; ++i) {
161 if (std::abs(z(i)) <= z_tol) {
162 deflated.emplace_back(i, d(i));
163 continue;
164 }
165 if (!keep.empty()) {
166 const Eigen::Index j = keep.back();
167 if (close(d(i), d(j))) {
168 // Rotate (j, i) so the coupling concentrates on one of
169 // them; the other deflates at the shared diagonal value.
170 const double r = std::hypot(z(j), z(i));
171 const double c = z(j) / r, s = z(i) / r;
172 rotations.push_back({j, i});
173 rot_c.push_back(c);
174 rot_s.push_back(s);
175 z(j) = r;
176 z(i) = 0.0;
177 deflated.emplace_back(i, d(i));
178 continue;
179 }
180 }
181 keep.push_back(i);
182 }
183
184 const auto m = static_cast<Eigen::Index>(keep.size());
185 Eigen::VectorXd dk(m), zk(m), z2k(m);
186 for (Eigen::Index i = 0; i < m; ++i) {
187 dk(i) = d(keep[static_cast<std::size_t>(i)]);
188 zk(i) = z(keep[static_cast<std::size_t>(i)]);
189 z2k(i) = zk(i) * zk(i);
190 }
191
192 // Roots. Interlacing for an arrowhead is
193 // lam_0 <= d_0 <= lam_1 <= d_1 <= ... <= d_{m-1} <= lam_m,
194 // so there is one below the first pole, one in each gap, and one above
195 // the last: m + 1 in total.
196 //
197 // Each root is KEPT as the pole it was shifted from plus its offset,
198 // never as a reconstructed absolute value. Everything downstream needs
199 // differences lam_j - d_i, and forming those by subtracting a
200 // reconstructed eigenvalue from a nearby pole throws away exactly the
201 // digits the eigenvector depends on. Written as
202 // (d_{origin(j)} - d_i) + delta_j the cancellation happens between two
203 // input poles instead, which is as good as the data allows.
204 std::vector<Eigen::Index> root_org(static_cast<std::size_t>(m + 1));
205 Eigen::VectorXd root_del(m + 1);
206 Secular f{dk.data(), z2k.data(), static_cast<int>(m), alpha, 0.0};
207 const double zsum = z2k.sum();
208 const double span = std::abs(alpha) + zsum + dk.cwiseAbs().maxCoeff() + 1.0;
209 {
210 Secular fs = f;
211 fs.origin = dk(0);
212 root_org[0] = 0;
213 root_del(0) = solveShifted(fs, -span, 0.0);
214 }
215 for (Eigen::Index k = 0; k + 1 < m; ++k) {
216 Secular fs = f;
217 fs.origin = dk(k);
218 root_org[static_cast<std::size_t>(k + 1)] = k;
219 root_del(k + 1) = solveShifted(fs, 0.0, dk(k + 1) - dk(k));
220 }
221 {
222 Secular fs = f;
223 fs.origin = dk(m - 1);
224 root_org[static_cast<std::size_t>(m)] = m - 1;
225 root_del(m) = solveShifted(fs, 0.0, span);
226 }
227
229 const auto lam_minus_d = [&](Eigen::Index j, Eigen::Index i) {
230 return (dk(root_org[static_cast<std::size_t>(j)]) - dk(i)) +
231 root_del(j);
232 };
233
234 Eigen::VectorXd lam(m + 1);
235 for (Eigen::Index j = 0; j <= m; ++j)
236 lam(j) = dk(root_org[static_cast<std::size_t>(j)]) + root_del(j);
237
238 // Lowner reconstruction: the coupling that makes the COMPUTED
239 // eigenvalues exact. Eigenvectors built from this are orthogonal to
240 // working precision; built from the original coupling they are not,
241 // once eigenvalues cluster.
242 Eigen::VectorXd zhat(m);
243 for (Eigen::Index i = 0; i < m; ++i) {
244 // zhat_i^2 = -prod_j (lam_j - d_i) / prod_{j != i} (d_j - d_i),
245 // as paired ratios so nothing over- or underflows across eight
246 // decades, and with every numerator taken from the shifts.
247 double acc = -lam_minus_d(i, i) * lam_minus_d(m, i);
248 for (Eigen::Index j = 0; j < m; ++j) {
249 if (j == i) continue;
250 const double den = dk(j) - dk(i);
251 if (den == 0.0) {
252 acc = 0.0;
253 break;
254 }
255 acc *= lam_minus_d(j, i) / den;
256 }
257 zhat(i) = std::sqrt(std::max(acc, 0.0));
258 if (zk(i) < 0.0) zhat(i) = -zhat(i);
259 }
260
261 Eigen::MatrixXd Vk(m + 1, m + 1);
262 for (Eigen::Index j = 0; j <= m; ++j) {
263 Eigen::VectorXd x(m + 1);
264 // d_i - lam_j through the shift, for the same reason as above:
265 // this denominator is what the eigenvector is made of, and it is
266 // smallest exactly where subtracting reconstructed values is worst.
267 for (Eigen::Index i = 0; i < m; ++i)
268 x(i) = -zhat(i) / lam_minus_d(j, i);
269 x(m) = -1.0;
270 Vk.col(j) = x.normalized();
271 }
272
273 // Reassemble: deflated directions are unit vectors at their own
274 // diagonal value, then the rotations are undone, then the sort is.
275 evals_asc.resize(n);
276 evecs = Eigen::MatrixXd::Zero(n, n);
277 Eigen::Index col = 0;
278 for (Eigen::Index j = 0; j <= m; ++j) {
279 for (Eigen::Index i = 0; i < m; ++i)
280 evecs(keep[static_cast<std::size_t>(i)], col) = Vk(i, j);
281 evecs(p, col) = Vk(m, j);
282 evals_asc(col) = lam(j);
283 ++col;
284 }
285 for (const auto& [idx, val]: deflated) {
286 evecs(idx, col) = 1.0;
287 evals_asc(col) = val;
288 ++col;
289 }
290 for (Eigen::Index r = static_cast<Eigen::Index>(rotations.size()) - 1;
291 r >= 0; --r) {
292 const Eigen::Index j = rotations[static_cast<std::size_t>(r)][0];
293 const Eigen::Index i = rotations[static_cast<std::size_t>(r)][1];
294 const double c = rot_c[static_cast<std::size_t>(r)];
295 const double s = rot_s[static_cast<std::size_t>(r)];
296 for (Eigen::Index k = 0; k < n; ++k) {
297 const double vj = evecs(j, k), vi = evecs(i, k);
298 evecs(j, k) = c * vj - s * vi;
299 evecs(i, k) = s * vj + c * vi;
300 }
301 }
302 // Undo the diagonal sort on the leading block.
303 Eigen::MatrixXd out = Eigen::MatrixXd::Zero(n, n);
304 for (Eigen::Index i = 0; i < p; ++i)
305 out.row(perm[static_cast<std::size_t>(i)]) = evecs.row(i);
306 out.row(p) = evecs.row(p);
307 evecs = out;
308
309 // Ascending order, which every caller assumes.
310 std::vector<Eigen::Index> order(static_cast<std::size_t>(n));
311 std::iota(order.begin(), order.end(), Eigen::Index{0});
312 std::sort(order.begin(), order.end(), [&](Eigen::Index a, Eigen::Index b) {
313 return evals_asc(a) < evals_asc(b);
314 });
315 Eigen::VectorXd ev_sorted(n);
316 Eigen::MatrixXd V_sorted(n, n);
317 for (Eigen::Index i = 0; i < n; ++i) {
318 ev_sorted(i) = evals_asc(order[static_cast<std::size_t>(i)]);
319 V_sorted.col(i) = evecs.col(order[static_cast<std::size_t>(i)]);
320 }
321 evals_asc = ev_sorted;
322 evecs = V_sorted;
323 return evals_asc.allFinite() && evecs.allFinite();
324}
325
326bool arrowheadEigen(const Eigen::VectorXd& d, const Eigen::MatrixXd& B,
327 const Eigen::MatrixXd& A, Eigen::VectorXd& evals_asc,
328 Eigen::MatrixXd& evecs)
329{
330 const Eigen::Index p = d.size();
331 const Eigen::Index k = A.rows();
332 if (B.rows() != p || B.cols() != k || A.cols() != k || k < 1) return false;
333 if (!d.allFinite() || !B.allFinite() || !A.allFinite()) return false;
334
335 // Diagonalise the trailing block first. That is what makes each pass
336 // below a genuine arrowhead: once A is diagonal the appended rows do
337 // not couple to each other, so a border column meets a diagonal and
338 // nothing else. A is k x k with k the number of rows an acquisition
339 // added, so this eigendecomposition is free.
340 const Eigen::MatrixXd As = 0.5 * (A + A.transpose());
341 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> aes(As);
342 if (aes.info() != Eigen::Success) return false;
343 const Eigen::VectorXd a_ev = aes.eigenvalues();
344 const Eigen::MatrixXd Bq = B * aes.eigenvectors();
345
346 // Absorb one border column per pass. After a pass the leading part is
347 // diagonal again in the accumulated basis, so the next column meets an
348 // arrowhead too: k passes at O((p+k)^2) instead of one at O((p+k)^3).
349 Eigen::VectorXd cur_d = d;
350 Eigen::MatrixXd basis = Eigen::MatrixXd::Identity(p, p);
351
352 for (Eigen::Index c = 0; c < k; ++c) {
353 const Eigen::Index cur = cur_d.size(); // p + c
354
355 // Border in the ORIGINAL coordinates: the coupling to the leading
356 // block, then zero against every previously absorbed row, since
357 // diagonalising A removed those couplings.
358 Eigen::VectorXd raw = Eigen::VectorXd::Zero(cur);
359 raw.head(p) = Bq.col(c);
360
361 // Same border expressed in the basis the previous passes produced.
362 const Eigen::VectorXd zc = basis.transpose() * raw;
363
364 Eigen::VectorXd ev;
365 Eigen::MatrixXd V; // (cur + 1) x (cur + 1)
366 if (!arrowheadEigenRankOne(cur_d, zc, a_ev(c), ev, V)) return false;
367
368 // Extend the accumulated basis by the coordinate this pass added,
369 // then rotate it into the new eigenvectors.
370 Eigen::MatrixXd grown =
371 Eigen::MatrixXd::Zero(basis.rows() + 1, cur + 1);
372 grown.topLeftCorner(basis.rows(), cur) = basis;
373 grown(basis.rows(), cur) = 1.0;
374 basis = grown * V;
375 cur_d = ev;
376 }
377
378 // Back out of the basis A was diagonalised in. Everything above works
379 // in coordinates where the trailing block is diagonal, so the trailing
380 // rows of the accumulated eigenvectors are expressed in Qa's columns
381 // and have to be rotated back before a caller can use them against the
382 // original matrix. For k = 1 this is a sign and hides itself.
383 evecs = basis;
384 evecs.bottomRows(k) = aes.eigenvectors() * basis.bottomRows(k);
385 evals_asc = cur_d;
386 return evals_asc.allFinite() && evecs.allFinite() &&
387 evals_asc.size() == p + k && evecs.rows() == p + k;
388}
389
390} // namespace gpr::linalg
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
bool arrowheadEigenRankOne(const Eigen::VectorXd &d_in, const Eigen::VectorXd &z_in, double alpha, Eigen::VectorXd &evals_asc, Eigen::MatrixXd &evecs)
bool arrowheadEigen(const Eigen::VectorXd &d, const Eigen::MatrixXd &B, const Eigen::MatrixXd &A, Eigen::VectorXd &evals_asc, Eigen::MatrixXd &evecs)