Loading...
Searching...
No Matches
GaussianSegments.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2#include "GaussianSegments.h"
3
4#include <Eigen/Eigenvalues>
5#include <algorithm>
6#include <cmath>
7#include <limits>
8#include <numbers>
9#include <string>
10
12namespace {
13constexpr double eps = std::numeric_limits<double>::epsilon();
14double magnitude(const Matrix &matrix)
15{
16 return matrix.size() ? matrix.cwiseAbs().maxCoeff() : 0;
17}
18void requireSymmetric(const Matrix &matrix)
19{
20 if (!matrix.rows() || matrix.rows() != matrix.cols() || !matrix.allFinite())
21 throw std::invalid_argument("Expected a finite nonempty square matrix");
22 const double tolerance = 64 * eps * matrix.rows() * magnitude(matrix);
23 if (magnitude(matrix - matrix.transpose()) > tolerance)
24 throw std::invalid_argument(
25 "Matrix asymmetry exceeds floating-point roundoff");
26}
27void requireHbar(double hbar)
28{
29 if (!(hbar > 0) || !std::isfinite(hbar))
30 throw std::invalid_argument("Expected finite positive hbar");
31}
32} // namespace
33
34Segment exactSegment(const Matrix &hessian, double duration)
35{
36 requireSymmetric(hessian);
37 if (!(duration > 0) || !std::isfinite(duration))
38 throw std::invalid_argument(
39 "Expected finite positive segment duration");
40 Eigen::SelfAdjointEigenSolver<Matrix> eig(.5 * hessian +
41 .5 * hessian.transpose());
42 if (eig.info() != Eigen::Success || !eig.eigenvalues().allFinite())
43 throw std::runtime_error("Segment Hessian eigendecomposition failed");
44 Vector a(hessian.rows()), l(hessian.rows());
46 out.duration = duration;
47 out.minimumCausticDistance = std::numeric_limits<double>::infinity();
48 for (Eigen::Index i = 0; i < hessian.rows(); ++i) {
49 const double lambda = eig.eigenvalues()[i];
50 const double frequency = std::sqrt(std::abs(lambda));
51 const double x = duration * frequency;
52 if (!std::isfinite(x))
53 throw std::overflow_error(
54 "Unrepresentable segment frequency-duration product");
55 double logL;
56 if (lambda < 0) {
57 const double distance = std::numbers::pi - x;
58 out.minimumCausticDistance =
59 std::min(out.minimumCausticDistance, distance);
60 if (!(distance > 32 * eps * std::numbers::pi))
61 throw std::domain_error(
62 "Segment reaches or cannot resolve its first Dirichlet "
63 "caustic");
64 }
65 if (x < 1e-3) {
66 const double z = std::copysign(x * x, lambda);
67 a[i] = (1 + z / 3 - z * z / 45 + 2 * z * z * z / 945) / duration;
68 logL = -std::log(duration) - z / 6 + z * z / 180 - z * z * z / 2835;
69 l[i] = std::exp(logL);
70 } else if (lambda > 0) {
71 const double denominator = -std::expm1(-2 * x);
72 a[i] = frequency * (1 + std::exp(-2 * x)) / denominator;
73 logL = std::log(2 * frequency) - x - std::log(denominator);
74 l[i] = std::exp(logL);
75 } else {
76 a[i] = frequency * std::cos(x) / std::sin(x);
77 logL = std::log(frequency) - std::log(std::sin(x));
78 l[i] = std::exp(logL);
79 }
80 if (!std::isfinite(a[i]) || !std::isfinite(logL) ||
81 !std::isfinite(l[i]))
82 throw std::overflow_error("Nonfinite exact segment coefficient");
83 out.logDetL += logL;
84 }
85 out.A =
86 eig.eigenvectors() * a.asDiagonal() * eig.eigenvectors().transpose();
87 out.L =
88 eig.eigenvectors() * l.asDiagonal() * eig.eigenvectors().transpose();
89 if (!out.A.allFinite() || !out.L.allFinite() || !std::isfinite(out.logDetL))
90 throw std::overflow_error("Nonfinite exact segment matrix");
91 return out;
92}
93
95 double roundoffTolerance)
96 : std::runtime_error("Singular or unresolved unpivoted Schur block " +
97 std::to_string(index) +
98 "; this is not a global zero-mode classification"),
99 block(index),
100 tolerance(roundoffTolerance)
101{
102}
103
104Matrix Factorization::Pivot::solve(const Matrix &rhs) const
105{
106 return eigenvectors * ((eigenvectors.transpose() * rhs).array().colwise() /
107 eigenvalues.array())
108 .matrix();
109}
110
111Factorization::Factorization(const std::vector<Segment> &segments)
112{
113 if (segments.empty())
114 throw std::invalid_argument("At least one segment is required");
115 segments_ = segments.size();
116 dimension_ = segments.front().A.rows();
117 for (const auto &segment: segments) {
118 requireSymmetric(segment.A);
119 requireSymmetric(segment.rightEndpoint());
120 requireSymmetric(segment.L);
121 if (segment.A.rows() != dimension_ ||
122 segment.rightEndpoint().rows() != dimension_ ||
123 segment.L.rows() != dimension_ || !std::isfinite(segment.logDetL) ||
124 !(segment.duration > 0) || !std::isfinite(segment.duration))
125 throw std::invalid_argument(
126 "Inconsistent segment dimensions or normalization");
127 logDetL_ += segment.logDetL;
128 duration_ += segment.duration;
129 }
130 for (std::size_t i = 0; i + 1 < segments.size(); ++i) {
131 Matrix pivot = segments[i].rightEndpoint() + segments[i + 1].A;
132 double arithmeticScale = magnitude(segments[i].rightEndpoint()) +
133 magnitude(segments[i + 1].A) +
134 magnitude(segments[i].L) +
135 magnitude(segments[i + 1].L);
136 if (i) {
137 const Matrix correction =
138 segments[i].L.transpose() * pivots_.back().solve(segments[i].L);
139 pivot -= correction;
140 arithmeticScale += magnitude(correction);
141 }
142 if (!pivot.allFinite() || magnitude(pivot - pivot.transpose()) >
143 64 * eps * dimension_ * arithmeticScale)
144 throw std::runtime_error(
145 "Computed Schur block asymmetry exceeds arithmetic roundoff");
146 Eigen::SelfAdjointEigenSolver<Matrix> eig(.5 * pivot +
147 .5 * pivot.transpose());
148 if (eig.info() != Eigen::Success || !eig.eigenvalues().allFinite())
149 throw std::runtime_error("Schur pivot eigendecomposition failed");
150 const double tolerance = 64 * eps * dimension_ * arithmeticScale;
151 for (double value: eig.eigenvalues()) {
152 if (std::abs(value) <= tolerance)
153 throw SingularBlockPivot(i, tolerance);
154 value < 0 ? ++inertia_.negative : ++inertia_.positive;
155 logAbsDetK_ += std::log(std::abs(value));
156 }
157 pivots_.push_back({eig.eigenvectors(), eig.eigenvalues()});
158 if (i + 2 < segments.size()) offDiagonal_.push_back(-segments[i + 1].L);
159 }
160 if (!std::isfinite(duration_) || !std::isfinite(logDetL_) ||
161 !std::isfinite(logAbsDetK_) || !std::isfinite(logAbsD()))
162 throw std::overflow_error("Nonfinite composed determinant");
163}
164
166{
167 return dimension_ * static_cast<Eigen::Index>(pivots_.size());
168}
169
171{
172 if (rhs.size() != interiorDimension() || !rhs.allFinite())
173 throw std::invalid_argument("Invalid nodal right-hand side");
174 Vector result = rhs;
175 for (std::size_t i = 1; i < pivots_.size(); ++i)
176 result.segment(i * dimension_, dimension_) -=
177 offDiagonal_[i - 1].transpose() *
178 pivots_[i - 1].solve(
179 result.segment((i - 1) * dimension_, dimension_));
180 for (std::size_t k = pivots_.size(); k > 0; --k) {
181 const std::size_t i = k - 1;
182 Vector block = result.segment(i * dimension_, dimension_);
183 if (i + 1 < pivots_.size())
184 block -= offDiagonal_[i] *
185 result.segment((i + 1) * dimension_, dimension_);
186 result.segment(i * dimension_, dimension_) = pivots_[i].solve(block);
187 }
188 if (!result.allFinite()) throw std::overflow_error("Nonfinite Schur solve");
189 return result;
190}
191
193{
194 if (rhs.rows() != interiorDimension() || !rhs.cols() || !rhs.allFinite())
195 throw std::invalid_argument("Invalid block-nodal right-hand side");
196 Matrix result = rhs;
197 for (std::size_t i = 1; i < pivots_.size(); ++i)
198 result.middleRows(i * dimension_, dimension_) -=
199 offDiagonal_[i - 1].transpose() *
200 pivots_[i - 1].solve(
201 result.middleRows((i - 1) * dimension_, dimension_));
202 for (std::size_t k = pivots_.size(); k > 0; --k) {
203 const std::size_t i = k - 1;
204 Matrix block = result.middleRows(i * dimension_, dimension_);
205 if (i + 1 < pivots_.size())
206 block -= offDiagonal_[i] *
207 result.middleRows((i + 1) * dimension_, dimension_);
208 result.middleRows(i * dimension_, dimension_) = pivots_[i].solve(block);
209 }
210 if (!result.allFinite())
211 throw std::overflow_error("Nonfinite block Schur solve");
212 return result;
213}
214
215std::vector<Matrix> Factorization::inverseDiagonalBlocks() const
216{
217 if (pivots_.empty()) return {};
218 const Matrix identity = Matrix::Identity(dimension_, dimension_);
219 std::vector<Matrix> diagonal(pivots_.size());
220 diagonal.back() = pivots_.back().solve(identity);
221 for (std::size_t k = pivots_.size() - 1; k > 0; --k) {
222 const std::size_t i = k - 1;
223 const Matrix inversePivot = pivots_[i].solve(identity);
224 const Matrix response = inversePivot * offDiagonal_[i];
225 diagonal[i] =
226 inversePivot + response * diagonal[i + 1] * response.transpose();
227 diagonal[i] = (.5 * diagonal[i] + .5 * diagonal[i].transpose()).eval();
228 }
229 return diagonal;
230}
231
233 const Vector &normal) const
234{
235 if (!normal.size() || normal.size() != interiorDimension() ||
236 !normal.allFinite() ||
237 std::abs(normal.squaredNorm() - 1) > 128 * eps * normal.size())
238 throw std::invalid_argument(
239 "Restriction requires a Euclidean-unit nodal normal");
240 const Vector inverseNormal = solve(normal);
241 long double quadratic = 0, absoluteSum = 0;
242 for (Eigen::Index i = 0; i < normal.size(); ++i) {
243 const long double term =
244 static_cast<long double>(normal[i]) * inverseNormal[i];
245 quadratic += term;
246 absoluteSum += std::abs(term);
247 }
248 if (std::abs(quadratic) <= 128 * eps * normal.size() * absoluteSum)
249 throw std::runtime_error(
250 "Restricted cofactor quadratic is singular or unresolved");
252 out.inverseQuadratic = static_cast<double>(quadratic);
253 if (!std::isfinite(out.inverseQuadratic))
254 throw std::overflow_error("Nonfinite restriction quadratic");
255 out.logAbsD =
256 logAbsD() + static_cast<double>(std::log(std::abs(quadratic)));
257 out.sign = determinantSign() * (quadratic < 0 ? -1 : 1);
258 out.inertia = inertia_;
259 if (quadratic > 0) {
260 if (!out.inertia.positive)
261 throw std::runtime_error(
262 "Inconsistent positive restriction inertia");
263 --out.inertia.positive;
264 } else {
265 if (!out.inertia.negative)
266 throw std::runtime_error(
267 "Inconsistent negative restriction inertia");
268 --out.inertia.negative;
269 }
270 out.physicalDimension = dimension_;
271 out.duration = duration_;
272 out.segments = segments_;
273 return out;
274}
275
277{
278 requireHbar(hbar);
279 if (inertia_.negative || inertia_.zero)
280 throw std::domain_error(
281 "Indefinite fixed-end Gaussian requires a contour prescription");
282 return -.5 * dimension_ *
283 (std::log(2 * std::numbers::pi) + std::log(hbar)) -
284 .5 * logAbsD();
285}
286
288 const RestrictedDeterminant &restricted,
289 double action, double hbar)
290{
291 requireHbar(hbar);
292 if (!std::isfinite(action) || !std::isfinite(restricted.logAbsD))
293 throw std::invalid_argument(
294 "Nonfinite action or restricted determinant");
295 if (restricted.physicalDimension != reference.blockDimension() ||
296 !(restricted.duration > 0) || !std::isfinite(restricted.duration) ||
297 std::abs(restricted.duration - reference.duration()) >
298 128 * eps * (restricted.segments + reference.segmentCount()) *
299 std::max(restricted.duration, reference.duration()))
300 throw std::invalid_argument(
301 "Reference and restricted operators require identical physical "
302 "dimension and duration");
303 if (reference.inertia().negative || reference.inertia().zero ||
304 restricted.inertia.negative || restricted.inertia.zero ||
305 restricted.sign != 1)
306 throw std::domain_error(
307 "A real Gaussian density requires positive restricted/reference "
308 "operators");
309 const double result =
310 .5 * (reference.logAbsD() - restricted.logAbsD) -
311 .5 * (std::log(2 * std::numbers::pi) + std::log(hbar)) - action / hbar;
312 if (!std::isfinite(result))
313 throw std::overflow_error("Nonfinite restricted log density");
314 return result;
315}
316} // namespace gpr::quantum::gaussian
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
Factorization(const std::vector< Segment > &segments)
std::vector< Matrix > inverseDiagonalBlocks() const
Vector solve(const Vector &rhs) const
RestrictedDeterminant restrictUnitNormal(const Vector &normal) const
double logFixedEndpointKernel(double hbar) const
SingularBlockPivot(std::size_t index, double roundoffTolerance)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
double logRestrictedDensityRatio(const Factorization &reference, const RestrictedDeterminant &restricted, double action, double hbar)
Segment exactSegment(const Matrix &hessian, double duration)
STL namespace.