Loading...
Searching...
No Matches
GaussianTwistedRestriction.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
3
4#include <Eigen/Eigenvalues>
5#include <Eigen/LU>
6#include <algorithm>
7#include <cmath>
8#include <iomanip>
9#include <limits>
10#include <numbers>
11#include <sstream>
12
13namespace gpr::quantum::gaussian {
14namespace {
15double magnitude(const Matrix &matrix)
16{
17 return matrix.size() ? matrix.cwiseAbs().maxCoeff() : 0;
18}
19} // namespace
20
22{
23 if (!(hbar > 0) || !std::isfinite(hbar))
24 throw std::invalid_argument("Expected finite positive hbar");
25 if (!logAbsNormalizedDet || !std::isfinite(*logAbsNormalizedDet) ||
26 inertia.negative || inertia.zero || unresolvedBorderEigenvalues ||
27 inertia.positive != static_cast<std::size_t>(dimension))
28 throw std::domain_error(
29 "Restricted twisted Gaussian is not resolved and positive");
30 return -.5 * *logAbsNormalizedDet -
31 .5 * codimension * std::log(2 * std::numbers::pi * hbar);
32}
33
35 const std::vector<Segment> &segments, const Matrix &twist,
36 const Vector &unitNormal)
37{
38 return restrictedTraceDeterminant(segments, twist, Matrix(unitNormal));
39}
40
42 const std::vector<Segment> &segments, const Matrix &twist,
43 const Matrix &orthonormalNormals)
44{
45 const Factorization open(segments);
46 const Eigen::Index d = open.blockDimension();
47 constexpr double eps = std::numeric_limits<double>::epsilon();
48 if (segments.size() >
49 static_cast<std::size_t>(std::numeric_limits<Eigen::Index>::max() / d))
50 throw std::overflow_error(
51 "Twisted restriction dimension exceeds index range");
52 const Eigen::Index total = static_cast<Eigen::Index>(segments.size()) * d;
53 const Eigen::Index k = orthonormalNormals.cols();
54 if (orthonormalNormals.rows() != total || k < 1 || k > total ||
55 !orthonormalNormals.allFinite() ||
56 (orthonormalNormals.transpose() * orthonormalNormals -
57 Matrix::Identity(k, k))
58 .norm() > 1e-10)
59 throw std::invalid_argument(
60 "Expected orthonormal constraints in the full cyclic nodal "
61 "measure");
62 if (twist.rows() != d || twist.cols() != d || !twist.allFinite())
63 throw std::invalid_argument(
64 "Twist must match the physical block dimension");
65 const Matrix gram = twist.transpose() * twist;
66 if (!gram.allFinite() || magnitude(gram - Matrix::Identity(d, d)) >
67 64 * eps * d * std::max(1.0, magnitude(gram)))
68 throw std::invalid_argument("Twist must be mass-metric orthogonal");
69 Matrix endpoint = Matrix::Zero(d + k, d + k);
70 endpoint.topLeftCorner(d, d) =
71 segments.front().A +
72 twist.transpose() * segments.back().rightEndpoint() * twist;
73 endpoint.topRightCorner(d, k) = orthonormalNormals.topRows(d);
74 endpoint.bottomLeftCorner(k, d) = orthonormalNormals.topRows(d).transpose();
75 Matrix correction = Matrix::Zero(d + k, d + k);
76 if (segments.size() == 1) {
77 correction.topLeftCorner(d, d) =
78 segments.front().L * twist +
79 twist.transpose() * segments.front().L.transpose();
80 } else {
81 Matrix coupling = Matrix::Zero(open.interiorDimension(), d + k);
82 coupling.topLeftCorner(d, d) -= segments.front().L.transpose();
83 coupling.bottomLeftCorner(d, d) -= segments.back().L * twist;
84 coupling.rightCols(k) =
85 orthonormalNormals.bottomRows(open.interiorDimension());
86 Matrix response(coupling.rows(), d + k);
87 for (Eigen::Index col = 0; col < d + k; ++col)
88 response.col(col) = open.solve(Vector(coupling.col(col)));
89 correction = coupling.transpose() * response;
90 }
91 Matrix schur = endpoint - correction;
92 const double reductionDimension =
93 static_cast<double>(open.interiorDimension() + d + k);
94 const double tolerance = 64 * eps * reductionDimension *
95 (magnitude(endpoint) + magnitude(correction));
96 const double asymmetry = magnitude(schur - schur.transpose());
97 if (!schur.allFinite() || !std::isfinite(tolerance) ||
98 asymmetry > tolerance) {
99 std::ostringstream message;
100 message << "Restricted twisted border exceeds arithmetic roundoff "
101 "(asymmetry="
102 << std::scientific << std::setprecision(17) << asymmetry
103 << ", tolerance=" << tolerance
104 << ", reduction_dimension=" << reductionDimension << ')';
105 throw std::runtime_error(message.str());
106 }
107 schur = (.5 * schur + .5 * schur.transpose()).eval();
108 Eigen::SelfAdjointEigenSolver<Matrix> eig(schur);
109 if (eig.info() != Eigen::Success || !eig.eigenvalues().allFinite())
110 throw std::runtime_error(
111 "Restricted twisted border eigendecomposition failed");
113 result.duration = open.duration();
114 result.dimension = total - k;
115 result.codimension = k;
116 result.inertia = open.inertia();
117 double logDet = open.logAbsD();
118 for (double value: eig.eigenvalues()) {
119 if (std::abs(value) <= tolerance) {
120 ++result.inertia.zero;
122 } else {
123 if (value > 0)
124 ++result.inertia.positive;
125 else
126 ++result.inertia.negative;
127 logDet += std::log(std::abs(value));
128 }
129 }
130 // Each orthonormal constraint contributes one positive and one negative
131 // direction to the border, independently of the restricted signed inertia.
132 if (result.inertia.positive < static_cast<std::size_t>(k) ||
133 result.inertia.negative < static_cast<std::size_t>(k))
134 throw std::runtime_error(
135 "Border inertia cannot resolve its constraint pair");
136 result.inertia.positive -= k;
137 result.inertia.negative -= k;
138 if (!result.unresolvedBorderEigenvalues) {
139 if (!std::isfinite(logDet))
140 throw std::overflow_error(
141 "Nonfinite restricted twisted determinant");
142 result.logAbsNormalizedDet = logDet;
143 }
144 return result;
145}
146
148 const std::vector<Segment> &segments, const Matrix &twist,
149 const Matrix &orthonormalNormals, const Matrix &features, double hbar,
150 bool positive, RestrictedKernelSolution *retained = nullptr)
151{
152 const auto qualification =
153 restrictedTraceDeterminant(segments, twist, orthonormalNormals);
154 if (positive)
155 qualification.logPositiveDensity(hbar);
156 else if (!qualification.logAbsNormalizedDet || qualification.inertia.zero ||
157 qualification.unresolvedBorderEigenvalues ||
158 !std::isfinite(*qualification.logAbsNormalizedDet))
159 throw std::domain_error(
160 "Restricted inverse requires a resolved nonsingular kernel");
161 const Factorization open(segments);
162 const Eigen::Index d = open.blockDimension(), k = orthonormalNormals.cols();
163 const Eigen::Index total = qualification.dimension + k;
164 if (features.rows() != total || !features.cols() || !features.allFinite())
165 throw std::invalid_argument(
166 "Invalid linear observables for the restricted Gaussian");
167 Matrix endpoint = Matrix::Zero(d + k, d + k);
168 endpoint.topLeftCorner(d, d) =
169 segments.front().A +
170 twist.transpose() * segments.back().rightEndpoint() * twist;
171 endpoint.topRightCorner(d, k) = orthonormalNormals.topRows(d);
172 endpoint.bottomLeftCorner(k, d) = orthonormalNormals.topRows(d).transpose();
173 Matrix coupling = Matrix::Zero(open.interiorDimension(), d + k);
174 Matrix response = Matrix::Zero(open.interiorDimension(), d + k);
175 Matrix interiorFeatures =
176 Matrix::Zero(open.interiorDimension(), features.cols());
177 if (segments.size() == 1) {
178 endpoint.topLeftCorner(d, d) -=
179 segments.front().L * twist +
180 twist.transpose() * segments.front().L.transpose();
181 } else {
182 coupling.topLeftCorner(d, d) -= segments.front().L.transpose();
183 coupling.bottomLeftCorner(d, d) -= segments.back().L * twist;
184 coupling.rightCols(k) =
185 orthonormalNormals.bottomRows(open.interiorDimension());
186 for (Eigen::Index col = 0; col < d + k; ++col)
187 response.col(col) = open.solve(Vector(coupling.col(col)));
188 for (Eigen::Index col = 0; col < features.cols(); ++col)
189 interiorFeatures.col(col) = open.solve(
190 Vector(features.col(col).tail(open.interiorDimension())));
191 endpoint -= coupling.transpose() * response;
192 }
193 Matrix right = Matrix::Zero(d + k, features.cols());
194 right.topRows(d) = features.topRows(d);
195 right -= coupling.transpose() * interiorFeatures;
196 Eigen::FullPivLU<Matrix> border(endpoint);
197 if (!border.isInvertible())
198 throw std::runtime_error("Restricted covariance border is unresolved");
199 const Matrix solved = border.solve(right);
200 Matrix physical(total, features.cols());
201 physical.topRows(d) = solved.topRows(d);
202 if (open.interiorDimension())
203 physical.bottomRows(open.interiorDimension()) =
204 interiorFeatures - response * solved;
205 if (!physical.allFinite())
206 throw std::runtime_error("Nonfinite restricted covariance response");
207 Matrix equation = orthonormalNormals * solved.bottomRows(k) - features;
208 for (std::size_t j = 0; j < segments.size(); ++j) {
209 const Matrix left = physical.middleRows(j * d, d);
210 const Matrix rightNode =
211 j + 1 < segments.size()
212 ? Matrix(physical.middleRows((j + 1) * d, d))
213 : Matrix(twist * physical.topRows(d));
214 equation.middleRows(j * d, d) +=
215 segments[j].A * left - segments[j].L * rightNode;
216 const Matrix endContribution = segments[j].rightEndpoint() * rightNode -
217 segments[j].L.transpose() * left;
218 if (j + 1 < segments.size())
219 equation.middleRows((j + 1) * d, d) += endContribution;
220 else
221 equation.topRows(d) += twist.transpose() * endContribution;
222 }
225 equation.norm() / std::max(1.0, features.norm());
227 (orthonormalNormals.transpose() * physical).norm() /
228 std::max(1.0, physical.norm());
229 if (!std::isfinite(result.relativeEquationResidual) ||
230 !std::isfinite(result.relativeConstraintResidual) ||
231 result.relativeEquationResidual > 1e-8 ||
232 result.relativeConstraintResidual > 1e-10)
233 throw std::runtime_error(
234 "Restricted covariance fails its original equation residual "
235 "checks");
236 if (retained) {
237 retained->values = physical;
238 retained->multipliers = solved.bottomRows(k);
239 retained->relativeEquationResidual = result.relativeEquationResidual;
240 retained->relativeConstraintResidual =
242 }
243 const Matrix raw = hbar * features.transpose() * physical;
245 64 * std::numeric_limits<double>::epsilon() * total * hbar *
246 features.norm() *
247 (physical.norm() + solved.norm() + interiorFeatures.norm() +
248 response.norm() * solved.norm());
249 if (!raw.allFinite() || !std::isfinite(result.symmetryRoundoffTolerance) ||
250 (raw - raw.transpose()).norm() > result.symmetryRoundoffTolerance)
251 throw std::runtime_error(
252 "Restricted covariance symmetry exceeds arithmetic roundoff");
253 result.covariance = (.5 * raw + .5 * raw.transpose()).eval();
254 return result;
255}
257 const std::vector<Segment> &segments, const Matrix &twist,
258 const Matrix &orthonormalNormals, const Matrix &sources)
259{
261 restrictedProjection(segments, twist, orthonormalNormals, sources, 1.,
262 false, &result);
263 return result;
264}
265
267 const std::vector<Segment> &segments, const Matrix &orthonormalNormals,
268 const Matrix &twist)
269{
270 const Factorization open(segments);
271 const Eigen::Index d = open.blockDimension();
272 const Eigen::Index k = orthonormalNormals.cols();
273 const Eigen::Index total = d * static_cast<Eigen::Index>(segments.size());
274 if (segments.size() < 2 || orthonormalNormals.rows() != total || k < 1 ||
275 k > total || !orthonormalNormals.allFinite() ||
276 (orthonormalNormals.transpose() * orthonormalNormals -
277 Matrix::Identity(k, k))
278 .norm() > 1e-10 ||
279 twist.rows() != d || twist.cols() != d || !twist.allFinite())
280 throw std::invalid_argument(
281 "Invalid cyclic inverse diagonal-block inputs");
282 const Matrix gram = twist.transpose() * twist;
283 if ((gram - Matrix::Identity(d, d)).norm() >
284 64 * std::numeric_limits<double>::epsilon() * d *
285 std::max(1.0, gram.norm()))
286 throw std::invalid_argument("Twist must be mass-metric orthogonal");
287
288 Matrix border = Matrix::Zero(d + k, d + k);
289 border.topLeftCorner(d, d) =
290 segments.front().A +
291 twist.transpose() * segments.back().rightEndpoint() * twist;
292 border.topRightCorner(d, k) = orthonormalNormals.topRows(d);
293 border.bottomLeftCorner(k, d) = orthonormalNormals.topRows(d).transpose();
294 Matrix coupling = Matrix::Zero(open.interiorDimension(), d + k);
295 coupling.topLeftCorner(d, d) = -segments.front().L.transpose();
296 coupling.bottomLeftCorner(d, d) = -segments.back().L * twist;
297 coupling.rightCols(k) =
298 orthonormalNormals.bottomRows(open.interiorDimension());
299 const Matrix response = open.solve(coupling);
300 border.noalias() -= coupling.transpose() * response;
301 border = (.5 * border + .5 * border.transpose()).eval();
302 Eigen::FullPivLU<Matrix> factor(border);
303 if (!factor.isInvertible())
304 throw std::runtime_error(
305 "Restricted inverse diagonal border is unresolved");
306 const Matrix borderInverse = factor.solve(Matrix::Identity(d + k, d + k));
307 const auto openDiagonal = open.inverseDiagonalBlocks();
308
310 result.blocks.reserve(segments.size());
311 result.blocks.push_back((.5 * borderInverse.topLeftCorner(d, d) +
312 .5 * borderInverse.topLeftCorner(d, d).transpose())
313 .eval());
314 for (std::size_t j = 0; j < openDiagonal.size(); ++j) {
315 const Matrix localResponse = response.middleRows(j * d, d);
316 Matrix block = openDiagonal[j] + localResponse * borderInverse *
317 localResponse.transpose();
318 result.blocks.push_back((.5 * block + .5 * block.transpose()).eval());
319 }
320
321 for (const auto &block: result.blocks)
322 if (!block.allFinite())
323 throw std::runtime_error(
324 "Restricted inverse diagonal blocks are nonfinite");
325 return result;
326}
327
329 const std::vector<Segment> &segments, const Matrix &twist,
330 const Matrix &orthonormalNormals, const Matrix &features)
331{
332 const auto value = restrictedProjection(segments, twist, orthonormalNormals,
333 features, 1., false);
334 return {value.covariance, value.relativeEquationResidual,
335 value.relativeConstraintResidual, value.symmetryRoundoffTolerance};
336}
337
339 const std::vector<Segment> &segments, const Matrix &twist,
340 const Matrix &orthonormalNormals, const Matrix &features, double hbar)
341{
342 return restrictedProjection(segments, twist, orthonormalNormals, features,
343 hbar, true);
344}
345
347 double duration,
348 const Matrix &measured)
349{
350 const auto d = green.rows(), r = measured.cols();
351 if (d < 1 || green.cols() != d || measured.rows() != d || r > d ||
352 !green.allFinite() || !measured.allFinite() || !(duration > 0) ||
353 !std::isfinite(duration) ||
354 (green - green.transpose()).norm() >
355 1e-10 * std::max(1., green.norm()) ||
356 (measured.transpose() * measured - Matrix::Identity(r, r)).norm() >
357 1e-10)
358 throw std::invalid_argument(
359 "Symmetric finite inverse and orthonormal measured basis required");
362 -duration * (green + green.transpose()) / 4;
363 result.unmeasuredDimension = d - r;
364 result.unmeasuredDirection = Vector::Zero(d);
365 result.unmeasuredGradient = Matrix::Zero(d, d);
366 if (r == d) return result;
367 const Matrix p = Matrix::Identity(d, d) - measured * measured.transpose();
368 result.unmeasuredGradient = p * result.logGaussianRateGradient * p;
369 result.unmeasuredGradient = (.5 * result.unmeasuredGradient +
370 .5 * result.unmeasuredGradient.transpose())
371 .eval();
372 const Eigen::SelfAdjointEigenSolver<Matrix> spectrum(
373 result.unmeasuredGradient);
374 if (spectrum.info() != Eigen::Success)
375 throw std::runtime_error(
376 "Unmeasured determinant response eigensystem failed");
377 Eigen::Index selected;
379 spectrum.eigenvalues().cwiseAbs().maxCoeff(&selected);
380 result.frobeniusInfluence = result.unmeasuredGradient.norm();
381 if (result.largestAbsoluteInfluence > 0) {
382 Vector direction = p * spectrum.eigenvectors().col(selected);
383 if (!(direction.norm() > 0))
384 throw std::runtime_error(
385 "Unmeasured influence direction is unresolved");
386 result.unmeasuredDirection = direction.normalized();
387 }
388 return result;
389}
390
391} // namespace gpr::quantum::gaussian
std::vector< Matrix > inverseDiagonalBlocks() const
Vector solve(const Vector &rhs) const
CurvatureRateInfluence nodalCurvatureRateInfluence(const Matrix &green, double duration, const Matrix &measured)
RestrictedInverseDiagonalBlocks restrictedTraceInverseDiagonalBlocks(const std::vector< Segment > &segments, const Matrix &orthonormalNormals, const Matrix &twist)
RestrictedInverseProjection restrictedTraceInverseProjection(const std::vector< Segment > &segments, const Matrix &twist, const Matrix &orthonormalNormals, const Matrix &features)
RestrictedKernelSolution solveRestrictedTraceKernel(const std::vector< Segment > &segments, const Matrix &twist, const Matrix &orthonormalNormals, const Matrix &sources)
TwistedRestrictedResult restrictedTraceDeterminant(const std::vector< Segment > &segments, const Matrix &twist, const Vector &unitNormal)
RestrictedCovarianceProjection restrictedTraceCovarianceProjection(const std::vector< Segment > &segments, const Matrix &twist, const Matrix &orthonormalNormals, const Matrix &features, double hbar)
static RestrictedCovarianceProjection restrictedProjection(const std::vector< Segment > &segments, const Matrix &twist, const Matrix &orthonormalNormals, const Matrix &features, double hbar, bool positive, RestrictedKernelSolution *retained=nullptr)