12#ifndef EIGEN_JACOBISVD_H
13#define EIGEN_JACOBISVD_H
16#include "./InternalHeaderCheck.h"
24template <typename MatrixType, int Options, bool IsComplex = NumTraits<typename MatrixType::Scalar>::IsComplex>
25struct svd_precondition_2x2_block_to_be_real {};
34enum { PreconditionIfMoreColsThanRows, PreconditionIfMoreRowsThanCols };
37constexpr bool svd_precondition_more_rows(
int options, Index rows, Index cols) {
38 return rows > cols || (should_svd_precondition_square_matrix(options) && rows == cols);
41template <
typename MatrixType,
int QRPreconditioner,
int Case,
bool PreconditionSquare>
42struct qr_preconditioner_should_do_anything
43 : bool_constant<!((QRPreconditioner == NoQRPreconditioner) ||
44 (Case == PreconditionIfMoreColsThanRows && MatrixType::RowsAtCompileTime != Dynamic &&
45 MatrixType::ColsAtCompileTime != Dynamic &&
46 MatrixType::ColsAtCompileTime <= MatrixType::RowsAtCompileTime) ||
47 (Case == PreconditionIfMoreRowsThanCols && MatrixType::RowsAtCompileTime != Dynamic &&
48 MatrixType::ColsAtCompileTime != Dynamic &&
49 (PreconditionSquare ? MatrixType::RowsAtCompileTime < MatrixType::ColsAtCompileTime
50 : MatrixType::RowsAtCompileTime <= MatrixType::ColsAtCompileTime)))> {};
52template <typename MatrixType, int Options, int QRPreconditioner, int Case,
53 bool DoAnything = qr_preconditioner_should_do_anything<MatrixType, QRPreconditioner, Case,
54 should_svd_precondition_square_matrix(Options)>::value>
55struct qr_preconditioner_impl {};
57template <typename MatrixType, int Options, int QRPreconditioner, int Case>
58class qr_preconditioner_impl<MatrixType, Options, QRPreconditioner, Case, false> {
60 void allocate(const JacobiSVD<MatrixType, Options>&) {}
61 template <typename Xpr>
62 bool run(JacobiSVD<MatrixType, Options>&, const Xpr&) {
69template <typename MatrixType, int Options>
70class qr_preconditioner_impl<MatrixType, Options, FullPivHouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols,
73 using Scalar = typename MatrixType::Scalar;
74 using SVDType = JacobiSVD<MatrixType, Options>;
76 enum { WorkspaceSize = MatrixType::RowsAtCompileTime, MaxWorkspaceSize = MatrixType::MaxRowsAtCompileTime };
78 using WorkspaceType = Matrix<Scalar, 1, WorkspaceSize, RowMajor, 1, MaxWorkspaceSize>;
80 void allocate(const SVDType& svd) {
81 if (svd.rows() != m_qr.rows() || svd.cols() != m_qr.cols()) {
82 internal::destroy_at(&m_qr);
83 internal::construct_at(&m_qr, svd.rows(), svd.cols());
85 if (svd.m_computeFullU) m_workspace.resize(svd.rows());
87 template <typename Xpr>
88 bool run(SVDType& svd, const Xpr& matrix) {
89 if (svd_precondition_more_rows(Options, matrix.rows(), matrix.cols())) {
91 svd.m_workMatrix = m_qr.matrixQR().block(0, 0, matrix.cols(), matrix.cols()).template triangularView<Upper>();
92 if (svd.m_computeFullU) m_qr.matrixQ().evalTo(svd.m_matrixU, m_workspace);
93 if (svd.computeV()) svd.m_matrixV = m_qr.colsPermutation();
100 using QRType = FullPivHouseholderQR<MatrixType>;
102 WorkspaceType m_workspace;
105template <typename MatrixType, int Options>
106class qr_preconditioner_impl<MatrixType, Options, FullPivHouseholderQRPreconditioner, PreconditionIfMoreColsThanRows,
109 using Scalar = typename MatrixType::Scalar;
110 using SVDType = JacobiSVD<MatrixType, Options>;
113 RowsAtCompileTime = MatrixType::RowsAtCompileTime,
114 ColsAtCompileTime = MatrixType::ColsAtCompileTime,
115 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
116 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
117 MatrixOptions = traits<MatrixType>::Options
120 using TransposeTypeWithSameStorageOrder =
121 typename internal::make_proper_matrix_type<Scalar, ColsAtCompileTime, RowsAtCompileTime, MatrixOptions,
122 MaxColsAtCompileTime, MaxRowsAtCompileTime>::type;
124 void allocate(const SVDType& svd) {
125 if (svd.cols() != m_qr.rows() || svd.rows() != m_qr.cols()) {
126 internal::destroy_at(&m_qr);
127 internal::construct_at(&m_qr, svd.cols(), svd.rows());
129 if (svd.m_computeFullV) m_workspace.resize(svd.cols());
131 template <typename Xpr>
132 bool run(SVDType& svd, const Xpr& matrix) {
133 if (matrix.cols() > matrix.rows()) {
134 m_qr.compute(matrix.adjoint());
136 m_qr.matrixQR().block(0, 0, matrix.rows(), matrix.rows()).template triangularView<Upper>().adjoint();
137 if (svd.m_computeFullV) m_qr.matrixQ().evalTo(svd.m_matrixV, m_workspace);
138 if (svd.computeU()) svd.m_matrixU = m_qr.colsPermutation();
145 using QRType = FullPivHouseholderQR<TransposeTypeWithSameStorageOrder>;
147 typename plain_row_type<MatrixType>::type m_workspace;
152template <typename MatrixType, int Options>
153class qr_preconditioner_impl<MatrixType, Options, ColPivHouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols,
156 using Scalar = typename MatrixType::Scalar;
157 using SVDType = JacobiSVD<MatrixType, Options>;
160 WorkspaceSize = internal::traits<SVDType>::MatrixUColsAtCompileTime,
161 MaxWorkspaceSize = internal::traits<SVDType>::MatrixUMaxColsAtCompileTime
164 using WorkspaceType = Matrix<Scalar, 1, WorkspaceSize, RowMajor, 1, MaxWorkspaceSize>;
166 void allocate(const SVDType& svd) {
167 if (svd.rows() != m_qr.rows() || svd.cols() != m_qr.cols()) {
168 internal::destroy_at(&m_qr);
169 internal::construct_at(&m_qr, svd.rows(), svd.cols());
171 if (svd.m_computeFullU)
172 m_workspace.resize(svd.rows());
173 else if (svd.m_computeThinU)
174 m_workspace.resize(svd.cols());
176 template <typename Xpr>
177 bool run(SVDType& svd, const Xpr& matrix) {
178 if (svd_precondition_more_rows(Options, matrix.rows(), matrix.cols())) {
179 m_qr.compute(matrix);
180 svd.m_workMatrix = m_qr.matrixQR().block(0, 0, matrix.cols(), matrix.cols()).template triangularView<Upper>();
181 if (svd.m_computeFullU)
182 m_qr.householderQ().evalTo(svd.m_matrixU, m_workspace);
183 else if (svd.m_computeThinU) {
184 svd.m_matrixU.setIdentity(matrix.rows(), matrix.cols());
185 m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixU, m_workspace);
187 if (svd.computeV()) svd.m_matrixV = m_qr.colsPermutation();
194 using QRType = ColPivHouseholderQR<MatrixType>;
196 WorkspaceType m_workspace;
199template <typename MatrixType, int Options>
200class qr_preconditioner_impl<MatrixType, Options, ColPivHouseholderQRPreconditioner, PreconditionIfMoreColsThanRows,
203 using Scalar = typename MatrixType::Scalar;
204 using SVDType = JacobiSVD<MatrixType, Options>;
207 RowsAtCompileTime = MatrixType::RowsAtCompileTime,
208 ColsAtCompileTime = MatrixType::ColsAtCompileTime,
209 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
210 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
211 MatrixOptions = internal::traits<MatrixType>::Options,
212 WorkspaceSize = internal::traits<SVDType>::MatrixVColsAtCompileTime,
213 MaxWorkspaceSize = internal::traits<SVDType>::MatrixVMaxColsAtCompileTime
216 using WorkspaceType = Matrix<Scalar, WorkspaceSize, 1, ColMajor, MaxWorkspaceSize, 1>;
218 using TransposeTypeWithSameStorageOrder =
219 typename internal::make_proper_matrix_type<Scalar, ColsAtCompileTime, RowsAtCompileTime, MatrixOptions,
220 MaxColsAtCompileTime, MaxRowsAtCompileTime>::type;
222 void allocate(const SVDType& svd) {
223 if (svd.cols() != m_qr.rows() || svd.rows() != m_qr.cols()) {
224 internal::destroy_at(&m_qr);
225 internal::construct_at(&m_qr, svd.cols(), svd.rows());
227 if (svd.m_computeFullV)
228 m_workspace.resize(svd.cols());
229 else if (svd.m_computeThinV)
230 m_workspace.resize(svd.rows());
232 template <typename Xpr>
233 bool run(SVDType& svd, const Xpr& matrix) {
234 if (matrix.cols() > matrix.rows()) {
235 m_qr.compute(matrix.adjoint());
238 m_qr.matrixQR().block(0, 0, matrix.rows(), matrix.rows()).template triangularView<Upper>().adjoint();
239 if (svd.m_computeFullV)
240 m_qr.householderQ().evalTo(svd.m_matrixV, m_workspace);
241 else if (svd.m_computeThinV) {
242 svd.m_matrixV.setIdentity(matrix.cols(), matrix.rows());
243 m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixV, m_workspace);
245 if (svd.computeU()) svd.m_matrixU = m_qr.colsPermutation();
252 using QRType = ColPivHouseholderQR<TransposeTypeWithSameStorageOrder>;
254 WorkspaceType m_workspace;
259template <typename MatrixType, int Options>
260class qr_preconditioner_impl<MatrixType, Options, HouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true> {
262 using Scalar = typename MatrixType::Scalar;
263 using SVDType = JacobiSVD<MatrixType, Options>;
266 WorkspaceSize = internal::traits<SVDType>::MatrixUColsAtCompileTime,
267 MaxWorkspaceSize = internal::traits<SVDType>::MatrixUMaxColsAtCompileTime
270 using WorkspaceType = Matrix<Scalar, 1, WorkspaceSize, RowMajor, 1, MaxWorkspaceSize>;
272 void allocate(const SVDType& svd) {
273 if (svd.rows() != m_qr.rows() || svd.cols() != m_qr.cols()) {
274 internal::destroy_at(&m_qr);
275 internal::construct_at(&m_qr, svd.rows(), svd.cols());
277 if (svd.m_computeFullU)
278 m_workspace.resize(svd.rows());
279 else if (svd.m_computeThinU)
280 m_workspace.resize(svd.cols());
282 template <typename Xpr>
283 bool run(SVDType& svd, const Xpr& matrix) {
284 if (svd_precondition_more_rows(Options, matrix.rows(), matrix.cols())) {
285 m_qr.compute(matrix);
286 svd.m_workMatrix = m_qr.matrixQR().block(0, 0, matrix.cols(), matrix.cols()).template triangularView<Upper>();
287 if (svd.m_computeFullU)
288 m_qr.householderQ().evalTo(svd.m_matrixU, m_workspace);
289 else if (svd.m_computeThinU) {
290 svd.m_matrixU.setIdentity(matrix.rows(), matrix.cols());
291 m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixU, m_workspace);
293 if (svd.computeV()) svd.m_matrixV.setIdentity(matrix.cols(), matrix.cols());
300 using QRType = HouseholderQR<MatrixType>;
302 WorkspaceType m_workspace;
305template <typename MatrixType, int Options>
306class qr_preconditioner_impl<MatrixType, Options, HouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true> {
308 using Scalar = typename MatrixType::Scalar;
309 using SVDType = JacobiSVD<MatrixType, Options>;
312 RowsAtCompileTime = MatrixType::RowsAtCompileTime,
313 ColsAtCompileTime = MatrixType::ColsAtCompileTime,
314 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
315 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
316 MatrixOptions = internal::traits<MatrixType>::Options,
317 WorkspaceSize = internal::traits<SVDType>::MatrixVColsAtCompileTime,
318 MaxWorkspaceSize = internal::traits<SVDType>::MatrixVMaxColsAtCompileTime
321 using WorkspaceType = Matrix<Scalar, WorkspaceSize, 1, ColMajor, MaxWorkspaceSize, 1>;
323 using TransposeTypeWithSameStorageOrder =
324 typename internal::make_proper_matrix_type<Scalar, ColsAtCompileTime, RowsAtCompileTime, MatrixOptions,
325 MaxColsAtCompileTime, MaxRowsAtCompileTime>::type;
327 void allocate(const SVDType& svd) {
328 if (svd.cols() != m_qr.rows() || svd.rows() != m_qr.cols()) {
329 internal::destroy_at(&m_qr);
330 internal::construct_at(&m_qr, svd.cols(), svd.rows());
332 if (svd.m_computeFullV)
333 m_workspace.resize(svd.cols());
334 else if (svd.m_computeThinV)
335 m_workspace.resize(svd.rows());
338 template <typename Xpr>
339 bool run(SVDType& svd, const Xpr& matrix) {
340 if (matrix.cols() > matrix.rows()) {
341 m_qr.compute(matrix.adjoint());
344 m_qr.matrixQR().block(0, 0, matrix.rows(), matrix.rows()).template triangularView<Upper>().adjoint();
345 if (svd.m_computeFullV)
346 m_qr.householderQ().evalTo(svd.m_matrixV, m_workspace);
347 else if (svd.m_computeThinV) {
348 svd.m_matrixV.setIdentity(matrix.cols(), matrix.rows());
349 m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixV, m_workspace);
351 if (svd.computeU()) svd.m_matrixU.setIdentity(matrix.rows(), matrix.rows());
360 WorkspaceType m_workspace;
371template <
typename Scalar>
372EIGEN_DONT_INLINE
typename NumTraits<Scalar>::Real jacobi_pivot_norm_scaled(
373 const Scalar& a,
const Scalar& b, Scalar& a_scaled, Scalar& b_scaled,
typename NumTraits<Scalar>::Real sumSquares) {
374 using RealScalar =
typename NumTraits<Scalar>::Real;
375 const RealScalar m = numext::maxi(numext::maxi(numext::abs(numext::real(a)), numext::abs(numext::imag(a))),
376 numext::maxi(numext::abs(numext::real(b)), numext::abs(numext::imag(b))));
378 if (!(m > RealScalar(0)))
return numext::sqrt(sumSquares);
381 const RealScalar scaledSumSquares = numext::abs2(a_scaled) + numext::abs2(b_scaled);
382 return numext::sqrt(scaledSumSquares);
390template <
typename Scalar>
391EIGEN_STRONG_INLINE
typename NumTraits<Scalar>::Real jacobi_pivot_norm(
const Scalar& a,
const Scalar& b,
392 Scalar& a_scaled, Scalar& b_scaled) {
393 using RealScalar =
typename NumTraits<Scalar>::Real;
394 const RealScalar sumSquares = numext::abs2(a) + numext::abs2(b);
397 const RealScalar bound = RealScalar(4) * (std::numeric_limits<RealScalar>::min)() / NumTraits<RealScalar>::epsilon();
398 if (EIGEN_PREDICT_TRUE(sumSquares >= bound))
return numext::sqrt(sumSquares);
399 return jacobi_pivot_norm_scaled(a, b, a_scaled, b_scaled, sumSquares);
407template <
typename MatrixType,
int Options>
408struct svd_precondition_2x2_block_to_be_real<MatrixType, Options, false> {
409 using SVD = JacobiSVD<MatrixType, Options>;
410 using RealScalar =
typename MatrixType::RealScalar;
411 static bool run(
typename SVD::WorkMatrixType&, SVD&, Index, Index, RealScalar&) {
return true; }
414template <
typename MatrixType,
int Options>
415struct svd_precondition_2x2_block_to_be_real<MatrixType, Options, true> {
416 using SVD = JacobiSVD<MatrixType, Options>;
417 using Scalar =
typename MatrixType::Scalar;
418 using RealScalar =
typename MatrixType::RealScalar;
419 static bool run(
typename SVD::WorkMatrixType& work_matrix, SVD& svd, Index p, Index q, RealScalar& maxDiagEntry) {
421 JacobiRotation<Scalar> rot;
423 RealScalar n = jacobi_pivot_norm(work_matrix.coeff(p, p), work_matrix.coeff(q, p), w_pp, w_qp);
425 const RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)();
426 const RealScalar precision = NumTraits<Scalar>::epsilon();
428 if (numext::is_exactly_zero(n)) {
430 work_matrix.coeffRef(p, p) = work_matrix.coeffRef(q, p) = Scalar(0);
432 if (numext::abs(numext::imag(work_matrix.coeff(p, q))) > considerAsZero) {
434 z = numext::abs(work_matrix.coeff(p, q)) / work_matrix.coeff(p, q);
435 work_matrix.row(p) *= z;
436 if (svd.computeU()) svd.m_matrixU.col(p) *= numext::conj(z);
438 if (numext::abs(numext::imag(work_matrix.coeff(q, q))) > considerAsZero) {
439 z = numext::abs(work_matrix.coeff(q, q)) / work_matrix.coeff(q, q);
440 work_matrix.row(q) *= z;
441 if (svd.computeU()) svd.m_matrixU.col(q) *= numext::conj(z);
445 rot.c() = numext::conj(w_pp) / n;
447 work_matrix.applyOnTheLeft(p, q, rot);
448 if (svd.computeU()) svd.m_matrixU.applyOnTheRight(p, q, rot.adjoint());
449 if (numext::abs(numext::imag(work_matrix.coeff(p, q))) > considerAsZero) {
450 z = numext::abs(work_matrix.coeff(p, q)) / work_matrix.coeff(p, q);
451 work_matrix.col(q) *= z;
452 if (svd.computeV()) svd.m_matrixV.col(q) *= z;
454 if (numext::abs(numext::imag(work_matrix.coeff(q, q))) > considerAsZero) {
455 z = numext::abs(work_matrix.coeff(q, q)) / work_matrix.coeff(q, q);
456 work_matrix.row(q) *= z;
457 if (svd.computeU()) svd.m_matrixU.col(q) *= numext::conj(z);
462 maxDiagEntry = numext::maxi<RealScalar>(
464 numext::maxi<RealScalar>(numext::abs(work_matrix.coeff(p, p)), numext::abs(work_matrix.coeff(q, q))));
466 RealScalar threshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry);
467 return numext::abs(work_matrix.coeff(p, q)) > threshold || numext::abs(work_matrix.coeff(q, p)) > threshold;
471template <
typename WorkMatrixType,
typename MatrixUType,
typename MatrixVType>
472EIGEN_DONT_INLINE
bool jacobi_svd_nonblocking_sweep(WorkMatrixType& work_matrix, MatrixUType& matrix_u,
473 MatrixVType& matrix_v,
bool compute_u,
bool compute_v,
474 typename WorkMatrixType::RealScalar considerAsZero,
475 typename WorkMatrixType::RealScalar precision,
476 typename WorkMatrixType::RealScalar& maxDiagEntry) {
477 using Scalar =
typename WorkMatrixType::Scalar;
478 using RealScalar =
typename WorkMatrixType::RealScalar;
479 const Index n = work_matrix.rows();
480 bool notFinished =
false;
482 EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsComplex) {
484 for (Index p = 1; p < n; ++p) {
485 for (Index q = 0; q < p; ++q) {
486 RealScalar threshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry);
487 if (numext::abs(work_matrix.coeff(p, q)) > threshold || numext::abs(work_matrix.coeff(q, p)) > threshold) {
490 bool doRealSvd =
true;
492 RealScalar nn = jacobi_pivot_norm(work_matrix.coeff(p, p), work_matrix.coeff(q, p), w_pp, w_qp);
494 if (numext::is_exactly_zero(nn)) {
496 work_matrix.coeffRef(p, p) = work_matrix.coeffRef(q, p) = Scalar(0);
498 if (numext::abs(numext::imag(work_matrix.coeff(p, q))) > considerAsZero) {
500 z = numext::abs(work_matrix.coeff(p, q)) / work_matrix.coeff(p, q);
501 work_matrix.row(p) *= z;
502 if (compute_u) matrix_u.col(p) *= numext::conj(z);
504 if (numext::abs(numext::imag(work_matrix.coeff(q, q))) > considerAsZero) {
505 z = numext::abs(work_matrix.coeff(q, q)) / work_matrix.coeff(q, q);
506 work_matrix.row(q) *= z;
507 if (compute_u) matrix_u.col(q) *= numext::conj(z);
510 JacobiRotation<Scalar> rot;
511 rot.c() = numext::conj(w_pp) / nn;
513 work_matrix.applyOnTheLeft(p, q, rot);
514 if (compute_u) matrix_u.applyOnTheRight(p, q, rot.adjoint());
515 if (numext::abs(numext::imag(work_matrix.coeff(p, q))) > considerAsZero) {
516 z = numext::abs(work_matrix.coeff(p, q)) / work_matrix.coeff(p, q);
517 work_matrix.col(q) *= z;
518 if (compute_v) matrix_v.col(q) *= z;
520 if (numext::abs(numext::imag(work_matrix.coeff(q, q))) > considerAsZero) {
521 z = numext::abs(work_matrix.coeff(q, q)) / work_matrix.coeff(q, q);
522 work_matrix.row(q) *= z;
523 if (compute_u) matrix_u.col(q) *= numext::conj(z);
527 maxDiagEntry = numext::maxi<RealScalar>(
529 numext::maxi<RealScalar>(numext::abs(work_matrix.coeff(p, p)), numext::abs(work_matrix.coeff(q, q))));
530 threshold = numext::maxi<RealScalar>(considerAsZero, NumTraits<Scalar>::epsilon() * maxDiagEntry);
532 numext::abs(work_matrix.coeff(p, q)) > threshold || numext::abs(work_matrix.coeff(q, p)) > threshold;
535 JacobiRotation<RealScalar> j_left, j_right;
536 internal::real_2x2_jacobi_svd(work_matrix, p, q, &j_left, &j_right);
537 work_matrix.applyOnTheLeft(p, q, j_left);
538 if (compute_u) matrix_u.applyOnTheRight(p, q, j_left.transpose());
539 work_matrix.applyOnTheRight(p, q, j_right);
540 if (compute_v) matrix_v.applyOnTheRight(p, q, j_right);
541 maxDiagEntry = numext::maxi<RealScalar>(
543 numext::maxi<RealScalar>(numext::abs(work_matrix.coeff(p, p)), numext::abs(work_matrix.coeff(q, q))));
550 RealScalar threshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry);
551 for (Index p = 1; p < n; ++p) {
552 for (Index q = 0; q < p; ++q) {
553 if (numext::abs(work_matrix.coeff(p, q)) > threshold || numext::abs(work_matrix.coeff(q, p)) > threshold) {
555 JacobiRotation<RealScalar> j_left, j_right;
556 internal::real_2x2_jacobi_svd(work_matrix, p, q, &j_left, &j_right);
557 work_matrix.applyOnTheLeft(p, q, j_left);
558 if (compute_u) matrix_u.applyOnTheRight(p, q, j_left.transpose());
559 work_matrix.applyOnTheRight(p, q, j_right);
560 if (compute_v) matrix_v.applyOnTheRight(p, q, j_right);
561 maxDiagEntry = numext::maxi<RealScalar>(
563 numext::maxi<RealScalar>(numext::abs(work_matrix.coeff(p, p)), numext::abs(work_matrix.coeff(q, q))));
564 threshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry);
573template <
typename MatrixType_,
int Options>
574struct traits<JacobiSVD<MatrixType_, Options>> : svd_traits<MatrixType_, Options> {
575 using MatrixType = MatrixType_;
652template <
typename MatrixType_,
int Options_>
657 using MatrixType = MatrixType_;
658 using Scalar =
typename Base::Scalar;
659 using RealScalar =
typename Base::RealScalar;
662 QRPreconditioner = internal::get_qr_preconditioner(Options),
663 RowsAtCompileTime = Base::RowsAtCompileTime,
664 ColsAtCompileTime = Base::ColsAtCompileTime,
665 DiagSizeAtCompileTime = Base::DiagSizeAtCompileTime,
666 MaxRowsAtCompileTime = Base::MaxRowsAtCompileTime,
667 MaxColsAtCompileTime = Base::MaxColsAtCompileTime,
668 MaxDiagSizeAtCompileTime = Base::MaxDiagSizeAtCompileTime,
669 MatrixOptions = Base::MatrixOptions
672 using MatrixUType =
typename Base::MatrixUType;
673 using MatrixVType =
typename Base::MatrixVType;
674 using SingularValuesType =
typename Base::SingularValuesType;
675 using WorkMatrixType =
Matrix<Scalar, DiagSizeAtCompileTime, DiagSizeAtCompileTime, MatrixOptions,
676 MaxDiagSizeAtCompileTime, MaxDiagSizeAtCompileTime>;
692 JacobiSVD(Index rows, Index cols) { allocate(rows, cols, internal::get_computation_options(Options)); }
710 EIGEN_DEPRECATED_WITH_REASON(
"Options should be specified using the class template parameter.")
711 JacobiSVD(Index rows, Index cols,
unsigned int computationOptions) {
712 internal::check_svd_options_assertions<MatrixType, Options>(computationOptions, rows, cols);
713 allocate(rows, cols, computationOptions);
721 template <
typename Derived>
723 compute_impl(matrix, internal::get_computation_options(Options));
726 template <
typename Derived>
728 compute_impl(matrix, internal::get_computation_options(Options));
744 template <
typename Derived>
746 internal::check_svd_options_assertions<MatrixType, Options>(computationOptions, matrix.rows(), matrix.cols());
747 compute_impl(matrix, computationOptions);
755 template <
typename Derived>
757 return compute_impl(matrix, m_computationOptions);
760 template <
typename Derived>
762 return compute_impl(matrix, m_computationOptions);
774 template <
typename Derived>
775 EIGEN_DEPRECATED_WITH_REASON(
"Options should be specified using the class template parameter.")
777 internal::check_svd_options_assertions<MatrixType, Options>(m_computationOptions, matrix.rows(), matrix.cols());
778 return compute_impl(matrix, computationOptions);
782 using Base::computeU;
783 using Base::computeV;
784 using Base::diagSize;
788 void allocate(Index rows_, Index cols_,
unsigned int computationOptions) {
789 if (Base::allocate(rows_, cols_, computationOptions))
return;
792 "JacobiSVD: can't compute thin U or thin V with the FullPivHouseholderQR preconditioner. "
793 "Use the ColPivHouseholderQR preconditioner instead.");
795 m_workMatrix.resize(diagSize(), diagSize());
796 if (cols() > rows()) m_qr_precond_morecols.allocate(*
this);
797 if (internal::svd_precondition_more_rows(Options, rows(), cols())) m_qr_precond_morerows.allocate(*
this);
801 template <
typename Derived>
802 JacobiSVD& compute_impl(
const TriangularBase<Derived>& matrix,
unsigned int computationOptions);
803 template <
typename Derived>
804 JacobiSVD& compute_impl(
const MatrixBase<Derived>& matrix,
unsigned int computationOptions);
810 EIGEN_DONT_INLINE
bool blocked_sweep(RealScalar considerAsZero, RealScalar precision, RealScalar& maxDiagEntry);
813 using Base::m_computationOptions;
814 using Base::m_computeFullU;
815 using Base::m_computeFullV;
816 using Base::m_computeThinU;
817 using Base::m_computeThinV;
819 using Base::m_isAllocated;
820 using Base::m_isInitialized;
821 using Base::m_matrixU;
822 using Base::m_matrixV;
823 using Base::m_nonzeroSingularValues;
824 using Base::m_prescribedThreshold;
825 using Base::m_singularValues;
826 using Base::m_usePrescribedThreshold;
827 using Base::ShouldComputeThinU;
828 using Base::ShouldComputeThinV;
830 EIGEN_STATIC_ASSERT(!(ShouldComputeThinU &&
int(QRPreconditioner) ==
int(FullPivHouseholderQRPreconditioner)) &&
831 !(ShouldComputeThinV &&
int(QRPreconditioner) ==
int(FullPivHouseholderQRPreconditioner)),
832 "JacobiSVD: can't compute thin U or thin V with the FullPivHouseholderQR preconditioner. "
833 "Use the ColPivHouseholderQR preconditioner instead.")
834 EIGEN_STATIC_ASSERT(!(internal::should_svd_precondition_square_matrix(Options) &&
835 int(QRPreconditioner) ==
int(NoQRPreconditioner)),
836 "JacobiSVD: PreconditionSquareMatrix requires a QR preconditioner other than NoQRPreconditioner.")
838 template <typename MatrixType__,
int Options__,
bool IsComplex_>
839 friend struct internal::svd_precondition_2x2_block_to_be_real;
840 template <typename MatrixType__,
int Options__,
int QRPreconditioner_,
int Case_,
bool DoAnything_>
841 friend struct internal::qr_preconditioner_impl;
843 internal::qr_preconditioner_impl<MatrixType, Options, QRPreconditioner, internal::PreconditionIfMoreColsThanRows>
844 m_qr_precond_morecols;
845 internal::qr_preconditioner_impl<MatrixType, Options, QRPreconditioner, internal::PreconditionIfMoreRowsThanCols>
846 m_qr_precond_morerows;
847 WorkMatrixType m_workMatrix;
850#ifdef EIGEN_JACOBI_SVD_BLOCK_SIZE
851 static constexpr Index kDefaultBlockSize = EIGEN_JACOBI_SVD_BLOCK_SIZE;
853 static constexpr Index kDefaultBlockSize = 32;
857 static constexpr Index kBlockSize = internal::min_size_prefer_fixed(kDefaultBlockSize, MaxDiagSizeAtCompileTime);
860template <
typename MatrixType,
int Options>
861template <
typename Derived>
862JacobiSVD<MatrixType, Options>& JacobiSVD<MatrixType, Options>::compute_impl(
const TriangularBase<Derived>& matrix,
863 unsigned int computationOptions) {
864 return compute_impl(matrix.toDenseMatrix(), computationOptions);
867template <
typename MatrixType,
int Options>
868template <
typename Derived>
869JacobiSVD<MatrixType, Options>& JacobiSVD<MatrixType, Options>::compute_impl(
const MatrixBase<Derived>& matrix,
870 unsigned int computationOptions) {
871 EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Derived, MatrixType);
872 EIGEN_STATIC_ASSERT((std::is_same<typename Derived::Scalar, typename MatrixType::Scalar>::value),
873 Input matrix must have the same Scalar type as the JacobiSVD
object.);
875 allocate(matrix.rows(), matrix.cols(), computationOptions);
879 const RealScalar precision = RealScalar(2) * NumTraits<Scalar>::epsilon();
882 const RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)();
886 const RealScalar maxCoeff = internal::safe_scaling<RealScalar>::max_abs_component(matrix.derived());
887 if (!(numext::isfinite)(maxCoeff)) {
888 m_isInitialized =
true;
890 m_nonzeroSingularValues = 0;
891 m_singularValues.setZero();
894 internal::safe_scaling_factors<RealScalar> factors;
898 if (rows() != cols() || internal::should_svd_precondition_square_matrix(Options)) {
900 internal::safe_scaling<RealScalar>::with_scaled(matrix.derived(), maxCoeff, [&](
const auto& scaledMatrix) {
901 m_qr_precond_morecols.run(*this, scaledMatrix);
902 m_qr_precond_morerows.run(*this, scaledMatrix);
905 factors = internal::safe_scaling<RealScalar>::scale_to(
907 matrix.template topLeftCorner<DiagSizeAtCompileTime, DiagSizeAtCompileTime>(diagSize(), diagSize()), maxCoeff);
908 if (m_computeFullU) m_matrixU.setIdentity(rows(), rows());
909 if (m_computeThinU) m_matrixU.setIdentity(rows(), diagSize());
910 if (m_computeFullV) m_matrixV.setIdentity(cols(), cols());
911 if (m_computeThinV) m_matrixV.setIdentity(cols(), diagSize());
915 RealScalar maxDiagEntry = diagSize() == 0 ? RealScalar(0) : m_workMatrix.cwiseAbs().diagonal().maxCoeff();
917 bool finished =
false;
921 EIGEN_IF_CONSTEXPR (MaxDiagSizeAtCompileTime == Dynamic || MaxDiagSizeAtCompileTime > kBlockSize) {
930 const Index n = diagSize();
931#ifdef EIGEN_JACOBI_SVD_BLOCKING_THRESHOLD
932 const Index blockingThreshold = EIGEN_JACOBI_SVD_BLOCKING_THRESHOLD;
934 const Index blockingThreshold =
935 static_cast<Index
>(numext::sqrt(
static_cast<double>(l2CacheSize() /
sizeof(
float))));
938 if (n >= blockingThreshold) {
942 finished = !blocked_sweep(considerAsZero, precision, maxDiagEntry);
946 finished = !internal::jacobi_svd_nonblocking_sweep(m_workMatrix, m_matrixU, m_matrixV, computeU(), computeV(),
947 considerAsZero, precision, maxDiagEntry);
953 for (Index i = 0; i < diagSize(); ++i) {
957 bool diagonal_has_imaginary_part =
false;
958 EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsComplex) {
959 diagonal_has_imaginary_part = numext::abs(numext::imag(m_workMatrix.coeff(i, i))) > considerAsZero;
961 if (diagonal_has_imaginary_part) {
962 RealScalar a = numext::abs(m_workMatrix.coeff(i, i));
963 m_singularValues.coeffRef(i) = numext::abs(a);
964 if (computeU()) m_matrixU.col(i) *= m_workMatrix.coeff(i, i) / a;
968 RealScalar a = numext::real(m_workMatrix.coeff(i, i));
969 m_singularValues.coeffRef(i) = internal::abs_preserving_subnormals(a);
970 if (computeU() && internal::is_negative_preserving_subnormals(a)) m_matrixU.col(i) = -m_matrixU.col(i);
978 for (Index i = 0; i < diagSize(); i++) {
980 RealScalar maxRemainingSingularValue = m_singularValues.tail(diagSize() - i).maxCoeff(&pos);
981 if (internal::is_zero_or_subnormal_magnitude(maxRemainingSingularValue)) {
982 pos = internal::safe_scaling<RealScalar>::recover_flushed_max_coeff_index(m_singularValues.tail(diagSize() - i),
984 if (numext::is_exactly_zero_no_flush(m_singularValues.coeff(i + pos)))
break;
988 std::swap(m_singularValues.coeffRef(i), m_singularValues.coeffRef(pos));
989 if (computeU()) m_matrixU.col(pos).swap(m_matrixU.col(i));
990 if (computeV()) m_matrixV.col(pos).swap(m_matrixV.col(i));
995 internal::safe_scaling<RealScalar>::unscale_in_place(m_singularValues, maxCoeff, factors);
996 m_nonzeroSingularValues = diagSize();
997 for (Index i = 0; i < diagSize(); i++) {
998 if (numext::is_exactly_zero_no_flush(m_singularValues.coeff(i))) {
999 m_nonzeroSingularValues = i;
1004 m_isInitialized =
true;
1025template <
typename MatrixType,
int Options>
1026EIGEN_DONT_INLINE
bool JacobiSVD<MatrixType, Options>::blocked_sweep(RealScalar considerAsZero, RealScalar precision,
1027 RealScalar& maxDiagEntry) {
1028 const Index n = diagSize();
1029 RealScalar threshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry);
1030 bool notFinished =
false;
1031 static constexpr Index kBlockBufferSize = (kBlockSize + 1) * (kBlockSize + 1);
1032 ei_declare_aligned_stack_constructed_variable(Scalar, blockBufferPtr, kBlockBufferSize, 0);
1033 Map<Matrix<Scalar, kBlockSize + 1, kBlockSize + 1, MatrixOptions>, AlignedMax> blockBuffer(
1034 blockBufferPtr, kBlockSize + 1, kBlockSize + 1);
1036 ei_declare_aligned_stack_constructed_variable(Scalar, accumPtr, kBlockBufferSize, 0);
1037 Map<Matrix<Scalar, kBlockSize + 1, kBlockSize + 1, MatrixOptions>, AlignedMax> accum(accumPtr, kBlockSize + 1,
1039 Matrix<Scalar, 1, Dynamic, RowMajor, 1, MaxDiagSizeAtCompileTime> Mp_save;
1041 for (Index p = 1; p < n; ++p) {
1048 for (; q + kBlockSize <= p; q += kBlockSize) {
1051 blockBuffer.template topLeftCorner<kBlockSize, kBlockSize>() =
1052 m_workMatrix.template block<kBlockSize, kBlockSize>(q, q);
1053 blockBuffer.col(kBlockSize).template head<kBlockSize>() = m_workMatrix.col(p).template segment<kBlockSize>(q);
1054 blockBuffer.row(kBlockSize).template head<kBlockSize>() = m_workMatrix.row(p).template segment<kBlockSize>(q);
1055 blockBuffer(kBlockSize, kBlockSize) = m_workMatrix(p, p);
1061 accum.setIdentity(kBlockSize + 1, kBlockSize + 1);
1062 bool blockDirty =
false;
1064 for (Index qq = 0; qq < kBlockSize; ++qq) {
1065 if (numext::abs(blockBuffer.coeff(kBlockSize, qq)) > threshold ||
1066 numext::abs(blockBuffer.coeff(qq, kBlockSize)) > threshold) {
1080 bool doRealSvd =
true;
1081 EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsComplex) {
1085 RealScalar nn = internal::jacobi_pivot_norm(blockBuffer.coeff(kBlockSize, kBlockSize),
1086 blockBuffer.coeff(qq, kBlockSize), w_pp, w_qp);
1088 if (numext::is_exactly_zero(nn)) {
1090 blockBuffer.coeffRef(kBlockSize, kBlockSize) = Scalar(0);
1091 blockBuffer.coeffRef(qq, kBlockSize) = Scalar(0);
1094 if (numext::abs(numext::imag(blockBuffer.coeff(kBlockSize, qq))) > considerAsZero) {
1095 z = numext::abs(blockBuffer.coeff(kBlockSize, qq)) / blockBuffer.coeff(kBlockSize, qq);
1096 blockBuffer.row(kBlockSize) *= z;
1097 accum.row(kBlockSize) *= z;
1098 if (computeU()) m_matrixU.col(p) *= numext::conj(z);
1100 if (numext::abs(numext::imag(blockBuffer.coeff(qq, qq))) > considerAsZero) {
1101 z = numext::abs(blockBuffer.coeff(qq, qq)) / blockBuffer.coeff(qq, qq);
1102 blockBuffer.row(qq) *= z;
1104 if (computeU()) m_matrixU.col(q + qq) *= numext::conj(z);
1111 JacobiRotation<Scalar> rot;
1112 rot.c() = numext::conj(w_pp) / nn;
1113 rot.s() = w_qp / nn;
1114 blockBuffer.applyOnTheLeft(kBlockSize, qq, rot);
1115 accum.applyOnTheLeft(kBlockSize, qq, rot);
1116 if (computeU()) m_matrixU.applyOnTheRight(p, q + qq, rot.adjoint());
1119 if (numext::abs(numext::imag(blockBuffer.coeff(kBlockSize, qq))) > considerAsZero) {
1120 z = numext::abs(blockBuffer.coeff(kBlockSize, qq)) / blockBuffer.coeff(kBlockSize, qq);
1121 blockBuffer.col(qq) *= z;
1122 m_workMatrix.col(q + qq) *= z;
1123 if (computeV()) m_matrixV.col(q + qq) *= z;
1126 if (numext::abs(numext::imag(blockBuffer.coeff(qq, qq))) > considerAsZero) {
1127 z = numext::abs(blockBuffer.coeff(qq, qq)) / blockBuffer.coeff(qq, qq);
1128 blockBuffer.row(qq) *= z;
1130 if (computeU()) m_matrixU.col(q + qq) *= numext::conj(z);
1134 maxDiagEntry = numext::maxi<RealScalar>(
1135 maxDiagEntry, numext::maxi<RealScalar>(numext::abs(blockBuffer.coeff(kBlockSize, kBlockSize)),
1136 numext::abs(blockBuffer.coeff(qq, qq))));
1138 RealScalar precondThreshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry);
1139 doRealSvd = numext::abs(blockBuffer.coeff(kBlockSize, qq)) > precondThreshold ||
1140 numext::abs(blockBuffer.coeff(qq, kBlockSize)) > precondThreshold;
1145 JacobiRotation<RealScalar> j_left, j_right;
1146 internal::real_2x2_jacobi_svd(blockBuffer, kBlockSize, qq, &j_left, &j_right);
1147 blockBuffer.applyOnTheLeft(kBlockSize, qq, j_left);
1148 blockBuffer.applyOnTheRight(kBlockSize, qq, j_right);
1151 accum.applyOnTheLeft(kBlockSize, qq, j_left);
1154 m_workMatrix.applyOnTheRight(p, q + qq, j_right);
1155 if (computeU()) m_matrixU.applyOnTheRight(p, q + qq, j_left.transpose());
1156 if (computeV()) m_matrixV.applyOnTheRight(p, q + qq, j_right);
1158 maxDiagEntry = numext::maxi<RealScalar>(
1159 maxDiagEntry, numext::maxi<RealScalar>(numext::abs(blockBuffer.coeff(kBlockSize, kBlockSize)),
1160 numext::abs(blockBuffer.coeff(qq, qq))));
1162 threshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry);
1173 if (p == q + kBlockSize) {
1174 m_workMatrix.template middleRows<kBlockSize + 1>(q) =
1175 accum * m_workMatrix.template middleRows<kBlockSize + 1>(q);
1177 const auto L11 = accum.template topLeftCorner<kBlockSize, kBlockSize>();
1178 const auto l12 = accum.col(kBlockSize).template head<kBlockSize>();
1179 const auto l21 = accum.row(kBlockSize).template head<kBlockSize>();
1180 const Scalar l22 = accum(kBlockSize, kBlockSize);
1181 auto Mq = m_workMatrix.template middleRows<kBlockSize>(q);
1182 auto Mp = m_workMatrix.row(p);
1184 Mp.noalias() = l21 * Mq + l22 * Mp_save;
1185 Mq = L11.template triangularView<Lower>() * Mq + l12 * Mp_save;
1191 for (; q < p; ++q) {
1192 if (numext::abs(m_workMatrix.coeff(p, q)) > threshold || numext::abs(m_workMatrix.coeff(q, p)) > threshold) {
1195 bool doRealSvd =
true;
1196 EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsComplex) {
1197 doRealSvd = internal::svd_precondition_2x2_block_to_be_real<MatrixType, Options>::run(m_workMatrix, *
this, p,
1202 JacobiRotation<RealScalar> j_left, j_right;
1203 internal::real_2x2_jacobi_svd(m_workMatrix, p, q, &j_left, &j_right);
1204 m_workMatrix.applyOnTheLeft(p, q, j_left);
1205 if (computeU()) m_matrixU.applyOnTheRight(p, q, j_left.transpose());
1206 m_workMatrix.applyOnTheRight(p, q, j_right);
1207 if (computeV()) m_matrixV.applyOnTheRight(p, q, j_right);
1208 maxDiagEntry = numext::maxi<RealScalar>(
1210 numext::maxi<RealScalar>(numext::abs(m_workMatrix.coeff(p, p)), numext::abs(m_workMatrix.coeff(q, q))));
1212 threshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry);
1227template <
typename Derived>
1228template <
int Options>
1233template <
typename Derived>
1234template <
int Options>
1236 unsigned int computationOptions)
const {
Householder QR decomposition of a matrix.
Definition HouseholderQR.h:77
Two-sided Jacobi SVD decomposition of a rectangular matrix.
Definition JacobiSVD.h:653
JacobiSVD()
Default Constructor.
Definition JacobiSVD.h:683
JacobiSVD & compute(const MatrixBase< Derived > &matrix)
Method performing the decomposition of given matrix. Computes Thin/Full unitaries U/V if specified us...
Definition JacobiSVD.h:756
JacobiSVD(Index rows, Index cols)
Default Constructor with memory preallocation.
Definition JacobiSVD.h:692
JacobiSVD(const MatrixBase< Derived > &matrix)
Constructor performing the decomposition of given matrix, using the custom options specified with the...
Definition JacobiSVD.h:722
JacobiSVD(const MatrixBase< Derived > &matrix, unsigned int computationOptions)
Constructor performing the decomposition of given matrix using specified options for computing unitar...
Definition JacobiSVD.h:745
Base class for all dense matrices, vectors, and expressions.
Definition MatrixBase.h:53
The matrix class, also used for vectors and row-vectors.
Definition Matrix.h:188
SVDBase()
Definition SVDBase.h:359
Base class for triangular part in a matrix.
Definition TriangularMatrix.h:68
@ FullPivHouseholderQRPreconditioner
Definition Constants.h:432
@ InvalidInput
Definition Constants.h:464