Loading...
Searching...
No Matches
SearchKktFactor.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
6#pragma once
7#include <Eigen/LU>
8#include <Eigen/SparseLU>
9#include <algorithm>
10#include <chrono>
11#include <cmath>
12#include <limits>
13#include <memory>
14#include <stdexcept>
15#include <string>
16#include <utility>
17#include <vector>
18
19namespace gpr::quantum {
20using SearchSparseMatrix = Eigen::SparseMatrix<double, Eigen::ColMajor, int>;
21
22// Both backends factor the identical matrix. Sparse conversion retains every
23// nonzero coefficient, including small entries and couplings outside a band.
24// The backend parameter permits another general sparse LU implementation with
25// the same compute/info/solve interface.
26template <class SparseBackend = Eigen::SparseLU<SearchSparseMatrix>>
28 using M = Eigen::MatrixXd;
29 using V = Eigen::VectorXd;
30 M matrix_;
31 SearchSparseMatrix sparse_;
32 std::unique_ptr<SparseBackend> sparseFactor_;
33 mutable Eigen::PartialPivLU<M> dense_;
34 mutable bool denseReady_{};
35 bool sparseEnabled_{}, sparseActive_{};
36 double tolerance_{1e-8};
37 std::size_t sparseFactorizations_{}, fallbacks_{};
38 mutable std::size_t residualChecks_{};
39 mutable double residualCheckSeconds_{};
40 std::string fallbackReason_;
41 void requireMatrix() const
42 {
43 if (matrix_.rows() == 0)
44 throw std::logic_error(
45 "A search matrix must be factored before solving");
46 }
47 void prepareDense() const
48 {
49 requireMatrix();
50 if (!denseReady_) {
51 dense_.compute(matrix_);
52 denseReady_ = true;
53 }
54 }
55 bool verified(const V& solution, const V& rhs) const
56 {
57 const auto begin = std::chrono::steady_clock::now();
58 bool accepted = false;
59 if (solution.size() == rhs.size() && solution.allFinite()) {
60 const V residual = matrix_ * solution - rhs;
61 accepted = residual.allFinite() &&
62 residual.stableNorm() <=
63 tolerance_ * std::max(1., rhs.stableNorm());
64 }
65 ++residualChecks_;
66 residualCheckSeconds_ += std::chrono::duration<double>(
67 std::chrono::steady_clock::now() - begin)
68 .count();
69 return accepted;
70 }
71 void fallback(const std::string& reason)
72 {
73 sparseActive_ = false;
74 ++fallbacks_;
75 fallbackReason_ = reason;
76 prepareDense();
77 }
78
79public:
80 explicit SearchKktFactor(bool sparseEnabled = false,
81 double tolerance = 1e-8)
82 : sparseEnabled_(sparseEnabled)
83 {
84 setTolerance(tolerance);
85 }
86 void clear()
87 {
88 matrix_.resize(0, 0);
89 sparse_.resize(0, 0);
90 sparseFactor_.reset();
91 denseReady_ = false;
92 sparseActive_ = false;
93 fallbackReason_.clear();
94 }
95 void setSparseEnabled(bool enabled)
96 {
97 if (enabled != sparseEnabled_) {
98 clear();
99 sparseEnabled_ = enabled;
100 }
101 }
102 void setTolerance(double tolerance)
103 {
104 if (!(tolerance > 0) || !std::isfinite(tolerance))
105 throw std::invalid_argument(
106 "A positive finite search equation tolerance is required");
107 tolerance_ = tolerance;
108 }
109 bool sparseEnabled() const noexcept
110 {
111 return sparseEnabled_;
112 }
113 bool usingSparse() const noexcept
114 {
115 return sparseActive_;
116 }
117 std::size_t sparseFactorizations() const noexcept
118 {
119 return sparseFactorizations_;
120 }
121 std::size_t denseFallbacks() const noexcept
122 {
123 return fallbacks_;
124 }
125 std::size_t residualChecks() const noexcept
126 {
127 return residualChecks_;
128 }
129 double residualCheckSeconds() const noexcept
130 {
131 return residualCheckSeconds_;
132 }
133 const std::string& fallbackReason() const noexcept
134 {
135 return fallbackReason_;
136 }
137 const M& matrix() const noexcept
138 {
139 return matrix_;
140 }
141 const SearchSparseMatrix& sparseMatrix() const noexcept
142 {
143 return sparse_;
144 }
145 const Eigen::PartialPivLU<M>& denseFactor() const
146 {
147 prepareDense();
148 return dense_;
149 }
151 {
152 if (matrix.rows() == 0 || matrix.rows() != matrix.cols() ||
153 !matrix.allFinite())
154 throw std::invalid_argument(
155 "A finite nonempty square search matrix is required");
156 clear();
157 matrix_ = std::move(matrix);
158 if (!sparseEnabled_) {
159 prepareDense();
160 return;
161 }
162 if (matrix_.rows() > std::numeric_limits<int>::max()) {
163 fallback("Search matrix exceeds sparse index capacity");
164 return;
165 }
166 std::vector<Eigen::Triplet<double, int>> entries;
167 for (Eigen::Index column = 0; column < matrix_.cols(); ++column)
168 for (Eigen::Index row = 0; row < matrix_.rows(); ++row)
169 if (matrix_(row, column) != 0.)
170 entries.emplace_back(static_cast<int>(row),
171 static_cast<int>(column),
172 matrix_(row, column));
173 sparse_.resize(matrix_.rows(), matrix_.cols());
174 sparse_.setFromTriplets(entries.begin(), entries.end());
175 sparse_.makeCompressed();
176 sparseFactor_ = std::make_unique<SparseBackend>();
177 sparseFactor_->compute(sparse_);
178 ++sparseFactorizations_;
179 if (sparseFactor_->info() != Eigen::Success) {
180 fallback("Sparse search factorization failed");
181 return;
182 }
183 sparseActive_ = true;
184 }
185 V solve(const V& rhs)
186 {
187 requireMatrix();
188 if (rhs.size() != matrix_.rows() || !rhs.allFinite())
189 throw std::invalid_argument(
190 "A finite matching search right-hand side is required");
191 if (sparseActive_) {
192 V result = sparseFactor_->solve(rhs);
193 if (sparseFactor_->info() == Eigen::Success &&
194 verified(result, rhs))
195 return result;
196 fallback(
197 "Sparse search solution failed its original-matrix residual");
198 }
199 prepareDense();
200 V result = dense_.solve(rhs);
201 if (sparseEnabled_ && !verified(result, rhs))
202 throw std::runtime_error(
203 "Dense search fallback failed its original-matrix residual");
204 return result;
205 }
206};
207} // namespace gpr::quantum
void setSparseEnabled(bool enabled)
const SearchSparseMatrix & sparseMatrix() const noexcept
const std::string & fallbackReason() const noexcept
std::size_t sparseFactorizations() const noexcept
bool usingSparse() const noexcept
SearchKktFactor(bool sparseEnabled=false, double tolerance=1e-8)
double residualCheckSeconds() const noexcept
const Eigen::PartialPivLU< M > & denseFactor() const
std::size_t denseFallbacks() const noexcept
std::size_t residualChecks() const noexcept
const M & matrix() const noexcept
void setTolerance(double tolerance)
bool sparseEnabled() const noexcept
Models for quantum-path (instanton) searches: arc and tail actions, amplitude continuation.
Eigen::SparseMatrix< double, Eigen::ColMajor, int > SearchSparseMatrix