Loading...
Searching...
No Matches
ElementFluctuation.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
6#pragma once
7#include <Eigen/Dense>
8#include <Eigen/SparseCholesky>
9#include <Eigen/SparseCore>
10#include <Eigen/SparseLU>
11#include <algorithm>
12#include <cmath>
13#include <functional>
14#include <numbers>
15#include <stdexcept>
16#include <utility>
17#include <vector>
18
19// Spectral-element discretisation of the periodic fluctuation operator
20//
21// J = -d^2/dtau^2 + H(tau) on [0, period), mass-weighted, hbar = 1,
22//
23// in continuous Lagrange bases on the Gauss-Lobatto-Legendre nodes of each
24// element. Collocated Gauss-Lobatto quadrature makes the mass and potential
25// blocks diagonal in the node index, so H is needed only at the nodes. The
26// element boundaries are free: put a few long elements where H is flat (the
27// dwell near a well) and short ones on the kinks, and the number of native
28// Hessians follows the kink width rather than the period.
29//
30// The discrete pencil (J, M) converges to the continuum operator, and the
31// ratio of two pencils on one mesh converges to the ratio of functional
32// determinants, the mesh cancelling. A time-translation zero mode u of J is
33// removed by bordering:
34//
35// det [[J, M u], [u^T M, 0]] = -det(M) (u^T M u) det'(J, M),
36//
37// with det' the product of the remaining generalised eigenvalues.
39using Matrix = Eigen::MatrixXd;
40using Vector = Eigen::VectorXd;
41using Sparse = Eigen::SparseMatrix<double>;
42
43// Gauss-Lobatto-Legendre nodes, weights and the nodal derivative matrix on [-1,
44// 1].
45struct Lobatto {
47 Matrix derivative; // derivative(i, j) = l_j'(x_i)
48};
49
50inline void legendre(int order, double x, double& p, double& dp)
51{
52 double p0 = 1, p1 = x;
53 if (order == 0) {
54 p = 1;
55 dp = 0;
56 return;
57 }
58 for (int n = 2; n <= order; ++n) {
59 const double pn = ((2 * n - 1) * x * p1 - (n - 1) * p0) / n;
60 p0 = p1;
61 p1 = pn;
62 }
63 p = p1;
64 dp = order * (x * p1 - p0) / (x * x - 1);
65}
66
67inline Lobatto lobatto(int order)
68{
69 if (order < 1)
70 throw std::invalid_argument("Element order must be at least 1");
71 Lobatto rule;
72 rule.nodes.resize(order + 1);
73 rule.weights.resize(order + 1);
74 rule.nodes(0) = -1;
75 rule.nodes(order) = 1;
76 Vector value(order + 1);
77 for (int i = 1; i < order; ++i) {
78 // Interior nodes are the roots of P_order'; Newton from the Chebyshev
79 // guess with P'' from the Legendre equation.
80 double x = -std::cos(std::numbers::pi * i / order);
81 for (int it = 0; it < 100; ++it) {
82 double p, dp;
83 legendre(order, x, p, dp);
84 const double d2p =
85 (2 * x * dp - order * (order + 1) * p) / (1 - x * x);
86 const double step = dp / d2p;
87 x -= step;
88 if (std::abs(step) < 1e-15) break;
89 }
90 rule.nodes(i) = x;
91 }
92 for (int i = 0; i <= order; ++i) {
93 double p, dp;
94 if (i == 0 || i == order)
95 p = (i == 0 && order % 2 == 1) ? -1. : 1.;
96 else
97 legendre(order, rule.nodes(i), p, dp);
98 value(i) = p;
99 rule.weights(i) = 2. / (order * (order + 1) * p * p);
100 }
101 rule.derivative = Matrix::Zero(order + 1, order + 1);
102 for (int i = 0; i <= order; ++i)
103 for (int j = 0; j <= order; ++j)
104 if (i != j)
105 rule.derivative(i, j) =
106 value(i) / (value(j) * (rule.nodes(i) - rule.nodes(j)));
107 rule.derivative(0, 0) = -order * (order + 1) / 4.;
108 rule.derivative(order, order) = order * (order + 1) / 4.;
109 return rule;
110}
111
112// A periodic mesh: element boundaries 0 = t_0 < ... < t_E = period, one order.
113struct Mesh {
114 std::vector<double> boundaries;
115 int order = 8;
116 double period() const
117 {
118 return boundaries.back();
119 }
120 Eigen::Index elements() const
121 {
122 return static_cast<Eigen::Index>(boundaries.size()) - 1;
123 }
124 Eigen::Index nodes() const
125 {
126 return elements() * order;
127 }
128};
129
130inline Mesh uniformMesh(double period, Eigen::Index elements, int order)
131{
132 if (!(period > 0) || elements < 1)
133 throw std::invalid_argument("Positive period and elements required");
134 Mesh mesh;
135 mesh.order = order;
136 for (Eigen::Index e = 0; e <= elements; ++e)
137 mesh.boundaries.push_back(period * static_cast<double>(e) / elements);
138 return mesh;
139}
140
141// Element boundaries graded towards the given kink centres: inside each window
142// of half-width `window` around a centre the elements have length `fine`, and
143// the rest of the period is covered by elements no longer than `coarse`.
144inline Mesh kinkMesh(double period, const std::vector<double>& centres,
145 double window, double fine, double coarse, int order)
146{
147 if (!(period > 0) || !(window > 0) || !(fine > 0) || !(coarse >= fine) ||
148 centres.empty())
149 throw std::invalid_argument(
150 "Positive period, window and element lengths required");
151 std::vector<std::pair<double, double>>
152 intervals; // fine windows, sorted, unwrapped
153 for (double c: centres) {
154 double a = std::fmod(c - window, period), b;
155 if (a < 0) a += period;
156 b = a + 2 * window;
157 if (b > period) {
158 intervals.push_back({a, period});
159 intervals.push_back({0, b - period});
160 } else {
161 intervals.push_back({a, b});
162 }
163 }
164 std::sort(intervals.begin(), intervals.end());
165 std::vector<double> cuts{0};
166 double cursor = 0;
167 const auto fill = [&](double to, double length) {
168 const double span = to - cursor;
169 if (span <= 0) return;
170 const auto n =
171 static_cast<Eigen::Index>(std::ceil(span / length - 1e-12));
172 for (Eigen::Index i = 1; i <= n; ++i)
173 cuts.push_back(cursor + span * static_cast<double>(i) / n);
174 cursor = to;
175 };
176 for (const auto& [a, b]: intervals) {
177 if (b <= cursor) continue;
178 fill(std::max(a, cursor), coarse);
179 fill(b, fine);
180 }
181 fill(period, coarse);
182 Mesh mesh;
183 mesh.order = order;
184 mesh.boundaries = cuts;
185 return mesh;
186}
187
188// Node times and lumped masses of a mesh, global node g = e * order + i (mod
189// nodes).
190struct Nodes {
192};
193
194inline Nodes meshNodes(const Mesh& mesh)
195{
196 const Lobatto rule = lobatto(mesh.order);
197 const Eigen::Index n = mesh.nodes();
198 Nodes out{Vector::Zero(n), Vector::Zero(n)};
199 for (Eigen::Index e = 0; e < mesh.elements(); ++e) {
200 const double a = mesh.boundaries[e], b = mesh.boundaries[e + 1],
201 jac = (b - a) / 2;
202 for (int i = 0; i <= mesh.order; ++i) {
203 const Eigen::Index g = (e * mesh.order + i) % n;
204 if (i < mesh.order) out.tau(g) = a + jac * (rule.nodes(i) + 1);
205 out.mass(g) += rule.weights(i) * jac;
206 }
207 }
208 return out;
209}
210
211// The pencil (J, M) of dimension nodes * d. curvature(g) is H at node g (d x d,
212// symmetric).
213struct Pencil {
215 Eigen::Index dimension = 0;
216};
217
218inline Pencil assemble(const Mesh& mesh, Eigen::Index d,
219 const std::function<Matrix(Eigen::Index)>& curvature)
220{
221 if (d < 1 || mesh.elements() < 1 || mesh.order < 1)
222 throw std::invalid_argument("Invalid mesh or dimension");
223 const Lobatto rule = lobatto(mesh.order);
224 const Eigen::Index n = mesh.nodes(), N = n * d;
225 const Nodes nodes = meshNodes(mesh);
226 std::vector<Eigen::Triplet<double>> jt, mt;
227 for (Eigen::Index e = 0; e < mesh.elements(); ++e) {
228 const double jac = (mesh.boundaries[e + 1] - mesh.boundaries[e]) / 2;
229 if (!(jac > 0))
230 throw std::invalid_argument("Element boundaries must increase");
231 // Stiffness: sum_q w_q l_i'(x_q) l_j'(x_q) / jac.
232 const Matrix stiffness = rule.derivative.transpose() *
233 rule.weights.asDiagonal() * rule.derivative /
234 jac;
235 for (int i = 0; i <= mesh.order; ++i)
236 for (int j = 0; j <= mesh.order; ++j) {
237 const Eigen::Index gi = (e * mesh.order + i) % n,
238 gj = (e * mesh.order + j) % n;
239 for (Eigen::Index a = 0; a < d; ++a)
240 jt.emplace_back(gi * d + a, gj * d + a, stiffness(i, j));
241 }
242 }
243 for (Eigen::Index g = 0; g < n; ++g) {
244 const Matrix h = curvature(g);
245 if (h.rows() != d || h.cols() != d || !h.allFinite())
246 throw std::invalid_argument("Finite d x d curvature required");
247 for (Eigen::Index a = 0; a < d; ++a) {
248 mt.emplace_back(g * d + a, g * d + a, nodes.mass(g));
249 for (Eigen::Index b = 0; b < d; ++b)
250 jt.emplace_back(g * d + a, g * d + b,
251 nodes.mass(g) * .5 * (h(a, b) + h(b, a)));
252 }
253 }
254 Pencil p;
255 p.dimension = N;
256 p.operatorMatrix.resize(N, N);
257 p.operatorMatrix.setFromTriplets(jt.begin(), jt.end());
258 p.mass.resize(N, N);
259 p.mass.setFromTriplets(mt.begin(), mt.end());
260 return p;
261}
262
263struct LogDet {
264 double logAbs = 0;
265 Eigen::Index negative = 0; // count of negative generalised eigenvalues
266};
267
268// log |det J| and the inertia of J; M is positive diagonal so the pencil has
269// the same inertia.
271{
272 Eigen::SimplicialLDLT<Sparse> ldlt(J);
273 if (ldlt.info() != Eigen::Success)
274 throw std::runtime_error("Fluctuation factorisation failed");
275 LogDet out;
276 const Vector D = ldlt.vectorD();
277 for (Eigen::Index i = 0; i < D.size(); ++i) {
278 if (!(D(i) != 0) || !std::isfinite(D(i)))
279 throw std::domain_error("Singular fluctuation operator");
280 out.logAbs += std::log(std::abs(D(i)));
281 if (D(i) < 0) ++out.negative;
282 }
283 return out;
284}
285
286// The discrete spectrum has finitely many modes and its high ones sit away from
287// the continuum, so a ratio of discrete determinants differs from the
288// functional ratio by a tail. To first order in dH = H - H_R the ratio is
289// tr(J_R^-1 M dH); its continuum value uses the exact periodic Green's
290// function of a constant positive H_R, diagonal coth(beta w / 2) / (2 w) in
291// each eigenmode of H_R. This returns that continuum term minus the discrete
292// one, so adding it to a discrete log ratio leaves an error second order in dH
293// and confined to the unresolved modes.
294inline double tailCorrection(
295 const Mesh& mesh, const Matrix& reference,
296 const std::function<Matrix(Eigen::Index)>& curvature)
297{
298 const Eigen::Index d = reference.rows();
299 if (d < 1 || reference.cols() != d || !reference.allFinite())
300 throw std::invalid_argument(
301 "Finite square reference curvature required");
302 Eigen::SelfAdjointEigenSolver<Matrix> modes(
303 .5 * (reference + reference.transpose()));
304 if (modes.info() != Eigen::Success || !(modes.eigenvalues().minCoeff() > 0))
305 throw std::domain_error("A positive reference curvature is required");
306 const Nodes nodes = meshNodes(mesh);
307 const Eigen::Index n = nodes.tau.size();
308 std::vector<Matrix> delta(n);
309 for (Eigen::Index g = 0; g < n; ++g)
310 delta[g] = curvature(g) - reference;
311 double correction = 0;
312 for (Eigen::Index a = 0; a < d; ++a) {
313 const double w2 = modes.eigenvalues()(a), w = std::sqrt(w2);
314 const Vector v = modes.eigenvectors().col(a);
315 const double continuum = 1 / (2 * w * std::tanh(mesh.period() * w / 2));
316 const Pencil scalar = assemble(
317 mesh, 1, [&](Eigen::Index) { return Matrix::Constant(1, 1, w2); });
318 Eigen::SimplicialLDLT<Sparse> ldlt(scalar.operatorMatrix);
319 if (ldlt.info() != Eigen::Success)
320 throw std::runtime_error("Reference factorisation failed");
321 Vector unit = Vector::Zero(n);
322 for (Eigen::Index g = 0; g < n; ++g) {
323 unit(g) = 1;
324 const double discrete = ldlt.solve(unit)(g);
325 unit(g) = 0;
326 correction +=
327 nodes.mass(g) * (continuum - discrete) * v.dot(delta[g] * v);
328 }
329 }
330 return correction;
331}
332
333// log det(J) / det(J_R) on one mesh with the first-order tail restored.
334inline double logRatio(const Mesh& mesh, Eigen::Index d,
335 const std::function<Matrix(Eigen::Index)>& curvature,
336 const Matrix& reference)
337{
338 const Pencil p = assemble(mesh, d, curvature);
339 const Pencil r = assemble(mesh, d, [&](Eigen::Index) { return reference; });
342 tailCorrection(mesh, reference, curvature);
343}
344
345// log |det'(J, M)| with the zero mode u removed by bordering, minus log det(M),
346// and B = u^T M u, the mass-weighted norm the zero-mode factor needs.
348 double logAbs =
349 0; // log |det'(J, M)| + log det(M) (det M cancels in a ratio)
350 double norm = 0; // u^T M u
351};
352
354{
355 if (u.size() != p.dimension || !(u.norm() > 0))
356 throw std::invalid_argument("Zero mode of the pencil's size required");
357 const Vector mu = p.mass * u;
358 const Eigen::Index N = p.dimension;
359 std::vector<Eigen::Triplet<double>> t;
360 t.reserve(p.operatorMatrix.nonZeros() + 2 * N);
361 for (Eigen::Index k = 0; k < p.operatorMatrix.outerSize(); ++k)
362 for (Sparse::InnerIterator it(p.operatorMatrix, k); it; ++it)
363 t.emplace_back(it.row(), it.col(), it.value());
364 for (Eigen::Index i = 0; i < N; ++i)
365 if (mu(i) != 0) {
366 t.emplace_back(i, N, mu(i));
367 t.emplace_back(N, i, mu(i));
368 }
369 Sparse bordered(N + 1, N + 1);
370 bordered.setFromTriplets(t.begin(), t.end());
371 Eigen::SparseLU<Sparse> lu;
372 lu.analyzePattern(bordered);
373 lu.factorize(bordered);
374 if (lu.info() != Eigen::Success)
375 throw std::runtime_error("Bordered fluctuation factorisation failed");
377 out.norm = u.dot(mu);
378 out.logAbs = lu.logAbsDeterminant() - std::log(out.norm);
379 return out;
380}
381
382// Fredholm form of the same ratio. With dH = H - H_R and the pencil of a
383// constant positive reference H_R,
384//
385// det J / det J_R = det(I + J_R^-1 M dH),
386//
387// an identity for the discrete matrices. The columns where dH vanishes are the
388// identity, so the determinant reduces to the support of dH: the native
389// Hessian is needed only where the orbit leaves the reference, and the ratio
390// is computed directly instead of as a difference of two large logarithms.
391// In the eigenbasis of H_R the pencil splits into scalar pencils, and J_R^-1 is
392// needed only between support nodes, from one sparse solve per node and mode.
393// The first-order tail of tailCorrection restores the continuum as for the
394// pencil. periodicKernel is the continuum Green's function of one mode,
395//
396// g(t) = [exp(-w t) + exp(-w (beta - t))] / (2 w (1 - exp(-beta w))),
397//
398// t the periodic separation; its diagonal is the tail correction's continuum
399// term. Used directly as a Nystrom kernel it converges only at second order,
400// from its corner at t = 0.
401inline double periodicKernel(double w, double period, double separation)
402{
403 double t = std::fmod(std::abs(separation), period);
404 return (std::exp(-w * t) + std::exp(-w * (period - t))) /
405 (2 * w * -std::expm1(-period * w));
406}
407
409 double logAbs =
410 0; // log |det J / det J_R|, or log |det' J / det J_R| with a zero mode
411 int sign = 1;
412 double norm = 0; // u^T M u when a zero mode is bordered
413};
414
415// support lists the nodes where dH is nonzero; curvature(g) is H at those
416// nodes. With a zero mode u over every node (d per node), the mode is removed
417// by the bordering of primedLogDeterminant, carried through the factor J_R.
419 const Mesh& mesh, Eigen::Index d, const std::vector<Eigen::Index>& support,
420 const std::function<Matrix(Eigen::Index)>& curvature,
421 const Matrix& reference, const Vector& zeroMode = Vector())
422{
423 if (d < 1 || reference.rows() != d || reference.cols() != d ||
424 support.empty())
425 throw std::invalid_argument(
426 "A d x d reference and a nonempty support are required");
427 Eigen::SelfAdjointEigenSolver<Matrix> modes(
428 .5 * (reference + reference.transpose()));
429 if (modes.info() != Eigen::Success || !(modes.eigenvalues().minCoeff() > 0))
430 throw std::domain_error("A positive reference curvature is required");
431 const Matrix& R = modes.eigenvectors();
432 const Nodes nodes = meshNodes(mesh);
433 const Eigen::Index n = nodes.tau.size(),
434 s = static_cast<Eigen::Index>(support.size()), S = s * d;
435 const bool primed = zeroMode.size() != 0;
436 if (primed && zeroMode.size() != n * d)
437 throw std::invalid_argument("A zero mode over every node is required");
438 std::vector<char> inSupport(n, 0);
439 for (Eigen::Index g: support) {
440 if (g < 0 || g >= n || inSupport[g])
441 throw std::invalid_argument(
442 "Support nodes must be distinct mesh nodes");
443 inSupport[g] = 1;
444 }
445 // Scaled perturbation m_g R^T dH_g R on the support, in reference modes.
446 std::vector<Matrix> weighted(s);
447 for (Eigen::Index i = 0; i < s; ++i) {
448 const Matrix h = curvature(support[i]);
449 if (h.rows() != d || h.cols() != d || !h.allFinite())
450 throw std::invalid_argument("Finite d x d curvature required");
451 weighted[i] =
452 nodes.mass(support[i]) *
453 (R.transpose() * (.5 * (h + h.transpose()) - reference) * R);
454 }
455 // columns[a] holds J_a^-1 e_g for every support node g, scalar pencil of
456 // mode a.
457 std::vector<Matrix> columns(d, Matrix(n, s));
458 std::vector<Eigen::SimplicialLDLT<Sparse>> scalar(d);
459 for (Eigen::Index a = 0; a < d; ++a) {
460 const double w2 = modes.eigenvalues()(a);
461 scalar[a].compute(assemble(mesh, 1, [&](Eigen::Index) {
462 return Matrix::Constant(1, 1, w2);
463 }).operatorMatrix);
464 if (scalar[a].info() != Eigen::Success)
465 throw std::runtime_error("Reference factorisation failed");
466 Vector unit = Vector::Zero(n);
467 for (Eigen::Index j = 0; j < s; ++j) {
468 unit(support[j]) = 1;
469 columns[a].col(j) = scalar[a].solve(unit);
470 unit(support[j]) = 0;
471 }
472 }
473 const Eigen::Index N = primed ? S + 1 : S;
474 Matrix A = Matrix::Identity(N, N);
475 for (Eigen::Index i = 0; i < s; ++i)
476 for (Eigen::Index j = 0; j < s; ++j)
477 for (Eigen::Index a = 0; a < d; ++a)
478 A.block(i * d + a, j * d, 1, d) +=
479 columns[a](support[i], j) * weighted[j].row(a);
481 if (primed) {
482 // Bordered [[I + G M dH, G M u], [u^T M, 0]] with G = J_R^-1 and the
483 // off-support identity rows eliminated: the last row gains
484 // -u_o^T M_o (G M dH)_oS and the corner becomes -u_o^T M_o (G M u)_o.
485 std::vector<Vector> modeU(d, Vector(n)), gmu(d);
486 for (Eigen::Index g = 0; g < n; ++g) {
487 const Vector r = R.transpose() * zeroMode.segment(g * d, d);
488 for (Eigen::Index a = 0; a < d; ++a)
489 modeU[a](g) = r(a);
490 }
491 for (Eigen::Index a = 0; a < d; ++a)
492 gmu[a] = scalar[a].solve(Vector(nodes.mass.cwiseProduct(modeU[a])));
493 A(N - 1, N - 1) = 0;
494 for (Eigen::Index i = 0; i < s; ++i)
495 for (Eigen::Index a = 0; a < d; ++a) {
496 A(i * d + a, N - 1) = gmu[a](support[i]);
497 A(N - 1, i * d + a) =
498 nodes.mass(support[i]) * modeU[a](support[i]);
499 }
500 for (Eigen::Index a = 0; a < d; ++a) {
501 Vector offMass = nodes.mass.cwiseProduct(modeU[a]);
502 for (Eigen::Index g: support)
503 offMass(g) = 0;
504 // (u_o^T M_o G) restricted to the support columns, mode a.
505 const Vector reach = columns[a].transpose() * offMass;
506 for (Eigen::Index j = 0; j < s; ++j)
507 A.block(N - 1, j * d, 1, d) -= reach(j) * weighted[j].row(a);
508 A(N - 1, N - 1) -= offMass.dot(gmu[a]);
509 }
510 for (Eigen::Index g = 0; g < n; ++g)
511 out.norm +=
512 nodes.mass(g) * zeroMode.segment(g * d, d).squaredNorm();
513 }
514 Eigen::PartialPivLU<Matrix> lu(A);
515 const Matrix& U = lu.matrixLU();
516 out.sign = lu.permutationP().determinant() > 0 ? 1 : -1;
517 for (Eigen::Index i = 0; i < N; ++i) {
518 if (!(U(i, i) != 0))
519 throw std::domain_error("Singular Fredholm matrix");
520 out.logAbs += std::log(std::abs(U(i, i)));
521 if (U(i, i) < 0) out.sign = -out.sign;
522 }
523 if (primed) {
524 out.logAbs -= std::log(out.norm);
525 out.sign = -out.sign;
526 }
527 return out;
528}
529} // namespace gpr::quantum::elementfluct
@ x
Definition Enums.h:28
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
double logRatio(const Mesh &mesh, Eigen::Index d, const std::function< Matrix(Eigen::Index)> &curvature, const Matrix &reference)
PrimedLogDet primedLogDeterminant(const Pencil &p, const Vector &u)
LogDet logDeterminant(const Sparse &J)
Mesh uniformMesh(double period, Eigen::Index elements, int order)
Pencil assemble(const Mesh &mesh, Eigen::Index d, const std::function< Matrix(Eigen::Index)> &curvature)
double periodicKernel(double w, double period, double separation)
FredholmRatio fredholmLogRatio(const Mesh &mesh, Eigen::Index d, const std::vector< Eigen::Index > &support, const std::function< Matrix(Eigen::Index)> &curvature, const Matrix &reference, const Vector &zeroMode=Vector())
Mesh kinkMesh(double period, const std::vector< double > &centres, double window, double fine, double coarse, int order)
void legendre(int order, double x, double &p, double &dp)
double tailCorrection(const Mesh &mesh, const Matrix &reference, const std::function< Matrix(Eigen::Index)> &curvature)
Nodes meshNodes(const Mesh &mesh)
Eigen::SparseMatrix< double > Sparse