Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
JacobiSVD.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2009-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
5// Copyright (C) 2013-2014 Gael Guennebaud <gael.guennebaud@inria.fr>
6//
7// This Source Code Form is subject to the terms of the Mozilla
8// Public License v. 2.0. If a copy of the MPL was not distributed
9// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10// SPDX-License-Identifier: MPL-2.0
11
12#ifndef EIGEN_JACOBISVD_H
13#define EIGEN_JACOBISVD_H
14
15// IWYU pragma: private
16#include "./InternalHeaderCheck.h"
17
18namespace Eigen {
19
20namespace internal {
21
22// forward declaration (needed by ICC)
23// the empty body is required by MSVC
24template <typename MatrixType, int Options, bool IsComplex = NumTraits<typename MatrixType::Scalar>::IsComplex>
25struct svd_precondition_2x2_block_to_be_real {};
26
27/*** QR preconditioners (R-SVD)
28 ***
29 *** Their role is to reduce the problem of computing the SVD to the case of a square matrix.
30 *** This approach, known as R-SVD, is an optimization for rectangular-enough matrices, and is a requirement for
31 *** JacobiSVD which by itself is only able to work on square matrices.
32 ***/
33
34enum { PreconditionIfMoreColsThanRows, PreconditionIfMoreRowsThanCols };
35
36// If option PreconditionSquareMatrix is set, square matrices take the PreconditionIfMoreRowsThanCols path: A = Q R P^*.
37constexpr bool svd_precondition_more_rows(int options, Index rows, Index cols) {
38 return rows > cols || (should_svd_precondition_square_matrix(options) && rows == cols);
39}
40
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)))> {};
51
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 {};
56
57template <typename MatrixType, int Options, int QRPreconditioner, int Case>
58class qr_preconditioner_impl<MatrixType, Options, QRPreconditioner, Case, false> {
59 public:
60 void allocate(const JacobiSVD<MatrixType, Options>&) {}
61 template <typename Xpr>
62 bool run(JacobiSVD<MatrixType, Options>&, const Xpr&) {
63 return false;
64 }
65};
66
67/*** preconditioner using FullPivHouseholderQR ***/
68
69template <typename MatrixType, int Options>
70class qr_preconditioner_impl<MatrixType, Options, FullPivHouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols,
71 true> {
72 public:
73 using Scalar = typename MatrixType::Scalar;
74 using SVDType = JacobiSVD<MatrixType, Options>;
75
76 enum { WorkspaceSize = MatrixType::RowsAtCompileTime, MaxWorkspaceSize = MatrixType::MaxRowsAtCompileTime };
77
78 using WorkspaceType = Matrix<Scalar, 1, WorkspaceSize, RowMajor, 1, MaxWorkspaceSize>;
79
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());
84 }
85 if (svd.m_computeFullU) m_workspace.resize(svd.rows());
86 }
87 template <typename Xpr>
88 bool run(SVDType& svd, const Xpr& matrix) {
89 if (svd_precondition_more_rows(Options, matrix.rows(), matrix.cols())) {
90 m_qr.compute(matrix);
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();
94 return true;
95 }
96 return false;
97 }
98
99 private:
100 using QRType = FullPivHouseholderQR<MatrixType>;
101 QRType m_qr;
102 WorkspaceType m_workspace;
103};
104
105template <typename MatrixType, int Options>
106class qr_preconditioner_impl<MatrixType, Options, FullPivHouseholderQRPreconditioner, PreconditionIfMoreColsThanRows,
107 true> {
108 public:
109 using Scalar = typename MatrixType::Scalar;
110 using SVDType = JacobiSVD<MatrixType, Options>;
111
112 enum {
113 RowsAtCompileTime = MatrixType::RowsAtCompileTime,
114 ColsAtCompileTime = MatrixType::ColsAtCompileTime,
115 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
116 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
117 MatrixOptions = traits<MatrixType>::Options
118 };
119
120 using TransposeTypeWithSameStorageOrder =
121 typename internal::make_proper_matrix_type<Scalar, ColsAtCompileTime, RowsAtCompileTime, MatrixOptions,
122 MaxColsAtCompileTime, MaxRowsAtCompileTime>::type;
123
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());
128 }
129 if (svd.m_computeFullV) m_workspace.resize(svd.cols());
130 }
131 template <typename Xpr>
132 bool run(SVDType& svd, const Xpr& matrix) {
133 if (matrix.cols() > matrix.rows()) {
134 m_qr.compute(matrix.adjoint());
135 svd.m_workMatrix =
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();
139 return true;
140 } else
141 return false;
142 }
143
144 private:
145 using QRType = FullPivHouseholderQR<TransposeTypeWithSameStorageOrder>;
146 QRType m_qr;
147 typename plain_row_type<MatrixType>::type m_workspace;
148};
149
150/*** preconditioner using ColPivHouseholderQR ***/
151
152template <typename MatrixType, int Options>
153class qr_preconditioner_impl<MatrixType, Options, ColPivHouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols,
154 true> {
155 public:
156 using Scalar = typename MatrixType::Scalar;
157 using SVDType = JacobiSVD<MatrixType, Options>;
158
159 enum {
160 WorkspaceSize = internal::traits<SVDType>::MatrixUColsAtCompileTime,
161 MaxWorkspaceSize = internal::traits<SVDType>::MatrixUMaxColsAtCompileTime
162 };
163
164 using WorkspaceType = Matrix<Scalar, 1, WorkspaceSize, RowMajor, 1, MaxWorkspaceSize>;
165
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());
170 }
171 if (svd.m_computeFullU)
172 m_workspace.resize(svd.rows());
173 else if (svd.m_computeThinU)
174 m_workspace.resize(svd.cols());
175 }
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);
186 }
187 if (svd.computeV()) svd.m_matrixV = m_qr.colsPermutation();
188 return true;
189 }
190 return false;
191 }
192
193 private:
194 using QRType = ColPivHouseholderQR<MatrixType>;
195 QRType m_qr;
196 WorkspaceType m_workspace;
197};
198
199template <typename MatrixType, int Options>
200class qr_preconditioner_impl<MatrixType, Options, ColPivHouseholderQRPreconditioner, PreconditionIfMoreColsThanRows,
201 true> {
202 public:
203 using Scalar = typename MatrixType::Scalar;
204 using SVDType = JacobiSVD<MatrixType, Options>;
205
206 enum {
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
214 };
215
216 using WorkspaceType = Matrix<Scalar, WorkspaceSize, 1, ColMajor, MaxWorkspaceSize, 1>;
217
218 using TransposeTypeWithSameStorageOrder =
219 typename internal::make_proper_matrix_type<Scalar, ColsAtCompileTime, RowsAtCompileTime, MatrixOptions,
220 MaxColsAtCompileTime, MaxRowsAtCompileTime>::type;
221
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());
226 }
227 if (svd.m_computeFullV)
228 m_workspace.resize(svd.cols());
229 else if (svd.m_computeThinV)
230 m_workspace.resize(svd.rows());
231 }
232 template <typename Xpr>
233 bool run(SVDType& svd, const Xpr& matrix) {
234 if (matrix.cols() > matrix.rows()) {
235 m_qr.compute(matrix.adjoint());
236
237 svd.m_workMatrix =
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);
244 }
245 if (svd.computeU()) svd.m_matrixU = m_qr.colsPermutation();
246 return true;
247 } else
248 return false;
249 }
250
251 private:
252 using QRType = ColPivHouseholderQR<TransposeTypeWithSameStorageOrder>;
253 QRType m_qr;
254 WorkspaceType m_workspace;
255};
256
257/*** preconditioner using HouseholderQR ***/
258
259template <typename MatrixType, int Options>
260class qr_preconditioner_impl<MatrixType, Options, HouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true> {
261 public:
262 using Scalar = typename MatrixType::Scalar;
263 using SVDType = JacobiSVD<MatrixType, Options>;
264
265 enum {
266 WorkspaceSize = internal::traits<SVDType>::MatrixUColsAtCompileTime,
267 MaxWorkspaceSize = internal::traits<SVDType>::MatrixUMaxColsAtCompileTime
268 };
269
270 using WorkspaceType = Matrix<Scalar, 1, WorkspaceSize, RowMajor, 1, MaxWorkspaceSize>;
271
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());
276 }
277 if (svd.m_computeFullU)
278 m_workspace.resize(svd.rows());
279 else if (svd.m_computeThinU)
280 m_workspace.resize(svd.cols());
281 }
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);
292 }
293 if (svd.computeV()) svd.m_matrixV.setIdentity(matrix.cols(), matrix.cols());
294 return true;
295 }
296 return false;
297 }
298
299 private:
300 using QRType = HouseholderQR<MatrixType>;
301 QRType m_qr;
302 WorkspaceType m_workspace;
303};
304
305template <typename MatrixType, int Options>
306class qr_preconditioner_impl<MatrixType, Options, HouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true> {
307 public:
308 using Scalar = typename MatrixType::Scalar;
309 using SVDType = JacobiSVD<MatrixType, Options>;
310
311 enum {
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
319 };
320
321 using WorkspaceType = Matrix<Scalar, WorkspaceSize, 1, ColMajor, MaxWorkspaceSize, 1>;
322
323 using TransposeTypeWithSameStorageOrder =
324 typename internal::make_proper_matrix_type<Scalar, ColsAtCompileTime, RowsAtCompileTime, MatrixOptions,
325 MaxColsAtCompileTime, MaxRowsAtCompileTime>::type;
326
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());
331 }
332 if (svd.m_computeFullV)
333 m_workspace.resize(svd.cols());
334 else if (svd.m_computeThinV)
335 m_workspace.resize(svd.rows());
336 }
337
338 template <typename Xpr>
339 bool run(SVDType& svd, const Xpr& matrix) {
340 if (matrix.cols() > matrix.rows()) {
341 m_qr.compute(matrix.adjoint());
342
343 svd.m_workMatrix =
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);
350 }
351 if (svd.computeU()) svd.m_matrixU.setIdentity(matrix.rows(), matrix.rows());
352 return true;
353 } else
354 return false;
355 }
356
357 private:
359 QRType m_qr;
360 WorkspaceType m_workspace;
361};
362
363// The complex preconditioning rotates by c = conj(a) / n, s = b / n with n = |(a, b)|_2, the norm of the first column
364// of a 2x2 pivot block. The rotation is unitary to rounding only if n is accurate to a few eps in the relative sense.
365
366// Cold path of jacobi_pivot_norm: returns the norm, in [1, 2], of (a_s, b_s) = (a, b) / m with m the largest of the
367// four real components, so no square underflows or overflows. Division by m, not by a power of two via frexp/ldexp
368// (which a custom scalar need not provide), rounds each component to relative error <= eps / 2, or absolute error
369// <= min against a norm >= 1, so the rotation built from (a_s, b_s) is unitary to rounding and within O(eps) of the
370// exact one.
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))));
377 // A zero pair, which FTZ/DAZ hardware may also read from subnormal entries, or NaN: nothing to scale.
378 if (!(m > RealScalar(0))) return numext::sqrt(sumSquares);
379 a_scaled = a / m;
380 b_scaled = b / m;
381 const RealScalar scaledSumSquares = numext::abs2(a_scaled) + numext::abs2(b_scaled);
382 return numext::sqrt(scaledSumSquares);
383}
384
385// Returns n = |(a_s, b_s)|_2, where (a_s, b_s) is (a, b) itself or, below the bound, the scaled pair of the cold path,
386// so that c = conj(a_s) / n, s = b_s / n is the rotation for (a, b), unitary to rounding. For S = |a|^2 + |b|^2 >=
387// 4 min / eps the largest real component m has m^2 >= S / 4 >= min / eps, so m^2 is normal. A subnormal square is off
388// by at most min eps / 2, or by at most min if FTZ flushes it, and three such terms total <= 3 min <= 0.75 eps S: S
389// stays accurate to eps. Below that bound the squares lose their accuracy, so the pair is scaled first.
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);
395 a_scaled = a;
396 b_scaled = 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);
400}
401
402/*** 2x2 SVD implementation
403 ***
404 *** JacobiSVD consists in performing a series of 2x2 SVD subproblems
405 ***/
406
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; }
412};
413
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) {
420 Scalar z;
421 JacobiRotation<Scalar> rot;
422 Scalar w_pp, w_qp;
423 RealScalar n = jacobi_pivot_norm(work_matrix.coeff(p, p), work_matrix.coeff(q, p), w_pp, w_qp);
424
425 const RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)();
426 const RealScalar precision = NumTraits<Scalar>::epsilon();
427
428 if (numext::is_exactly_zero(n)) {
429 // make sure first column is zero
430 work_matrix.coeffRef(p, p) = work_matrix.coeffRef(q, p) = Scalar(0);
431
432 if (numext::abs(numext::imag(work_matrix.coeff(p, q))) > considerAsZero) {
433 // n is zero only if both entries are zero, or are subnormal and flushed by FTZ/DAZ.
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);
437 }
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);
442 }
443 // otherwise the second row is already zero, so we have nothing to do.
444 } else {
445 rot.c() = numext::conj(w_pp) / n;
446 rot.s() = w_qp / 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;
453 }
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);
458 }
459 }
460
461 // update largest diagonal entry
462 maxDiagEntry = numext::maxi<RealScalar>(
463 maxDiagEntry,
464 numext::maxi<RealScalar>(numext::abs(work_matrix.coeff(p, p)), numext::abs(work_matrix.coeff(q, q))));
465 // and check whether the 2x2 block is already diagonal
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;
468 }
469};
470
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;
481
482 EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsComplex) {
483 // Complex non-blocking sweep: condition each 2x2 block to be real before diagonalizing.
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) {
488 notFinished = true;
489 Scalar z;
490 bool doRealSvd = true;
491 Scalar w_pp, w_qp;
492 RealScalar nn = jacobi_pivot_norm(work_matrix.coeff(p, p), work_matrix.coeff(q, p), w_pp, w_qp);
493
494 if (numext::is_exactly_zero(nn)) {
495 // Make sure first column is zero.
496 work_matrix.coeffRef(p, p) = work_matrix.coeffRef(q, p) = Scalar(0);
497
498 if (numext::abs(numext::imag(work_matrix.coeff(p, q))) > considerAsZero) {
499 // nn is zero only if both entries are zero, or are subnormal and flushed by FTZ/DAZ.
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);
503 }
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);
508 }
509 } else {
510 JacobiRotation<Scalar> rot;
511 rot.c() = numext::conj(w_pp) / nn;
512 rot.s() = w_qp / 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;
519 }
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);
524 }
525 }
526
527 maxDiagEntry = numext::maxi<RealScalar>(
528 maxDiagEntry,
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);
531 doRealSvd =
532 numext::abs(work_matrix.coeff(p, q)) > threshold || numext::abs(work_matrix.coeff(q, p)) > threshold;
533
534 if (doRealSvd) {
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>(
542 maxDiagEntry,
543 numext::maxi<RealScalar>(numext::abs(work_matrix.coeff(p, p)), numext::abs(work_matrix.coeff(q, q))));
544 }
545 }
546 }
547 }
548 } else {
549 // Real non-blocking sweep: diagonalize each 2x2 block directly.
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) {
554 notFinished = true;
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>(
562 maxDiagEntry,
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);
565 }
566 }
567 }
568 }
569
570 return notFinished;
571}
572
573template <typename MatrixType_, int Options>
574struct traits<JacobiSVD<MatrixType_, Options>> : svd_traits<MatrixType_, Options> {
575 using MatrixType = MatrixType_;
576};
577
578} // end namespace internal
579
652template <typename MatrixType_, int Options_>
653class JacobiSVD : public SVDBase<JacobiSVD<MatrixType_, Options_>> {
654 using Base = SVDBase<JacobiSVD>;
655
656 public:
657 using MatrixType = MatrixType_;
658 using Scalar = typename Base::Scalar;
659 using RealScalar = typename Base::RealScalar;
660 enum : int {
661 Options = Options_,
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
670 };
671
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>;
677
684
692 JacobiSVD(Index rows, Index cols) { allocate(rows, cols, internal::get_computation_options(Options)); }
693
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);
714 }
715
721 template <typename Derived>
722 explicit JacobiSVD(const MatrixBase<Derived>& matrix) {
723 compute_impl(matrix, internal::get_computation_options(Options));
724 }
725
726 template <typename Derived>
727 explicit JacobiSVD(const TriangularBase<Derived>& matrix) {
728 compute_impl(matrix, internal::get_computation_options(Options));
729 }
730
743 // EIGEN_DEPRECATED // TODO(cantonios): re-enable after fixing a few 3p libraries that error on deprecation warnings.
744 template <typename Derived>
745 JacobiSVD(const MatrixBase<Derived>& matrix, unsigned int computationOptions) {
746 internal::check_svd_options_assertions<MatrixType, Options>(computationOptions, matrix.rows(), matrix.cols());
747 compute_impl(matrix, computationOptions);
748 }
749
755 template <typename Derived>
757 return compute_impl(matrix, m_computationOptions);
758 }
759
760 template <typename Derived>
761 JacobiSVD& compute(const TriangularBase<Derived>& matrix) {
762 return compute_impl(matrix, m_computationOptions);
763 }
764
774 template <typename Derived>
775 EIGEN_DEPRECATED_WITH_REASON("Options should be specified using the class template parameter.")
776 JacobiSVD& compute(const MatrixBase<Derived>& matrix, unsigned int computationOptions) {
777 internal::check_svd_options_assertions<MatrixType, Options>(m_computationOptions, matrix.rows(), matrix.cols());
778 return compute_impl(matrix, computationOptions);
779 }
780
781 using Base::cols;
782 using Base::computeU;
783 using Base::computeV;
784 using Base::diagSize;
785 using Base::rank;
786 using Base::rows;
787
788 void allocate(Index rows_, Index cols_, unsigned int computationOptions) {
789 if (Base::allocate(rows_, cols_, computationOptions)) return;
790 eigen_assert(
791 !((m_computeThinU || m_computeThinV) && int(QRPreconditioner) == int(FullPivHouseholderQRPreconditioner)) &&
792 "JacobiSVD: can't compute thin U or thin V with the FullPivHouseholderQR preconditioner. "
793 "Use the ColPivHouseholderQR preconditioner instead.");
794
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);
798 }
799
800 private:
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);
805
806 // Blocked sweep for the Jacobi SVD (works for both real and complex scalars).
807 // Extracted into a separate EIGEN_DONT_INLINE method to prevent the blocking
808 // code from interfering with the compiler's optimization of the non-blocking
809 // scalar sweep.
810 EIGEN_DONT_INLINE bool blocked_sweep(RealScalar considerAsZero, RealScalar precision, RealScalar& maxDiagEntry);
811
812 protected:
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;
818 using Base::m_info;
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;
829
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.")
837
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;
842
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;
848
849 // Blocking parameters for the Jacobi SVD sweep.
850#ifdef EIGEN_JACOBI_SVD_BLOCK_SIZE
851 static constexpr Index kDefaultBlockSize = EIGEN_JACOBI_SVD_BLOCK_SIZE;
852#else
853 static constexpr Index kDefaultBlockSize = 32;
854#endif
855
856 // Use the lower of the default block size and static maximum matrix dimensions.
857 static constexpr Index kBlockSize = internal::min_size_prefer_fixed(kDefaultBlockSize, MaxDiagSizeAtCompileTime);
858};
859
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);
865}
866
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.);
874
875 allocate(matrix.rows(), matrix.cols(), computationOptions);
876
877 // currently we stop when we reach precision 2*epsilon as the last bit of precision can require an unreasonable number
878 // of iterations, only worsening the precision of U and V as we accumulate more rotations
879 const RealScalar precision = RealScalar(2) * NumTraits<Scalar>::epsilon();
880
881 // limit for denormal numbers to be considered zero in order to avoid infinite loops (see bug 286)
882 const RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)();
883
884 // Scaling factor to reduce over/under-flows. A SIMD unit that flushes subnormal inputs reads an all-subnormal matrix
885 // as zero; recover its maximum from the representation so that the scaling still brings it into the normal range.
886 const RealScalar maxCoeff = internal::safe_scaling<RealScalar>::max_abs_component(matrix.derived());
887 if (!(numext::isfinite)(maxCoeff)) {
888 m_isInitialized = true;
889 m_info = InvalidInput;
890 m_nonzeroSingularValues = 0;
891 m_singularValues.setZero();
892 return *this;
893 }
894 internal::safe_scaling_factors<RealScalar> factors;
895
896 /*** step 1. The R-SVD step: we use a QR decomposition to reduce to the case of a square matrix */
897
898 if (rows() != cols() || internal::should_svd_precondition_square_matrix(Options)) {
899 factors =
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);
903 });
904 } else {
905 factors = internal::safe_scaling<RealScalar>::scale_to(
906 m_workMatrix,
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());
912 }
913
914 /*** step 2. The main Jacobi SVD iteration. ***/
915 RealScalar maxDiagEntry = diagSize() == 0 ? RealScalar(0) : m_workMatrix.cwiseAbs().diagonal().maxCoeff();
916
917 bool finished = false;
918 while (!finished) {
919 finished = true;
920
921 EIGEN_IF_CONSTEXPR (MaxDiagSizeAtCompileTime == Dynamic || MaxDiagSizeAtCompileTime > kBlockSize) {
922 // Sweep with optional blocking for large matrices.
923 // Use blocking when the matrix is large enough that individual left rotations
924 // (strided row operations on column-major data) cause significant cache misses.
925 // The threshold is derived from the L2 cache size: blocking becomes worthwhile
926 // when n exceeds sqrt(L2 / 4). We divide by sizeof(float) rather than sizeof(RealScalar)
927 // because the cache miss pattern depends on the number of columns accessed (one cache
928 // line per column), not the scalar size. This also makes the threshold appropriately
929 // more conservative for larger types where GEMM overhead is higher.
930 const Index n = diagSize();
931#ifdef EIGEN_JACOBI_SVD_BLOCKING_THRESHOLD
932 const Index blockingThreshold = EIGEN_JACOBI_SVD_BLOCKING_THRESHOLD;
933#else
934 const Index blockingThreshold =
935 static_cast<Index>(numext::sqrt(static_cast<double>(l2CacheSize() / sizeof(float))));
936#endif
937
938 if (n >= blockingThreshold) {
939 // The blocked sweep is in a separate EIGEN_DONT_INLINE method to prevent
940 // the blocking code from interfering with the compiler's optimization of
941 // the non-blocking scalar sweep below.
942 finished = !blocked_sweep(considerAsZero, precision, maxDiagEntry);
943 continue;
944 }
945 }
946 finished = !internal::jacobi_svd_nonblocking_sweep(m_workMatrix, m_matrixU, m_matrixV, computeU(), computeV(),
947 considerAsZero, precision, maxDiagEntry);
948 }
949
950 /*** step 3. The work matrix is now diagonal, so ensure it's positive so its diagonal entries are the singular values
951 * ***/
952
953 for (Index i = 0; i < diagSize(); ++i) {
954 // For a complex matrix, some diagonal coefficients might not have been
955 // treated by svd_precondition_2x2_block_to_be_real, and the imaginary part
956 // of some diagonal entry might not be null.
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;
960 }
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;
965 } else {
966 // m_workMatrix.coeff(i,i) is already real. Its magnitude and sign are read from the representation for float
967 // and double: a subnormal entry compares as zero under DAZ, and an abs() that widens flushes it under FTZ.
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);
971 }
972 }
973
974 /*** step 4. Sort singular values in descending order and compute the number of nonzero singular values ***/
975
976 // Sort in the scaled frame, where the largest values are normal. A tail whose maximum reads zero or subnormal
977 // holds zeros and subnormals, which FTZ/DAZ hardware compares as zero: order it from the representation.
978 for (Index i = 0; i < diagSize(); i++) {
979 Index pos;
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),
983 pos);
984 if (numext::is_exactly_zero_no_flush(m_singularValues.coeff(i + pos))) break;
985 }
986 if (pos) {
987 pos += i;
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));
991 }
992 }
993 // Unscaling with maxCoeff keeps singular values that land in the subnormal range under FTZ; the count then reads
994 // them from the representation.
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;
1000 break;
1001 }
1002 }
1003
1004 m_isInitialized = true;
1005 return *this;
1006}
1007
1008// Blocked Jacobi SVD sweep for both real and complex scalar types. For large n,
1009// applying left rotations (row operations on column-major data) causes cache
1010// misses due to strided access. To mitigate this, we accumulate kBlockSize left
1011// rotations into a small dense matrix and apply them via a single GEMM to the
1012// contiguous row block q..q+kBlockSize-1 and the (possibly distant) row p.
1013// Right rotations and column scalings act on columns (contiguous in column-major)
1014// and are applied individually.
1015//
1016// For complex types, the 2x2 preconditioning (making the block real) involves
1017// complex left rotations and row scalings, which are also accumulated into the
1018// block matrix. Column scalings from preconditioning are applied directly.
1019//
1020// The accumulated rotation matrix has lower-triangular structure in its top-left
1021// kBlockSize x kBlockSize corner, which we exploit with triangularView.
1022//
1023// Returns true if any off-diagonal element exceeded the threshold (i.e. sweep
1024// is not yet converged).
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);
1035
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,
1038 kBlockSize + 1);
1039 Matrix<Scalar, 1, Dynamic, RowMajor, 1, MaxDiagSizeAtCompileTime> Mp_save;
1040
1041 for (Index p = 1; p < n; ++p) {
1042 Index q = 0;
1043
1044 // Blocked loop: process kBlockSize pairs (p,q+qq) for qq=0..kBlockSize-1.
1045 // We extract the relevant (kBlockSize+1) x (kBlockSize+1) submatrix of W
1046 // into a small buffer, compute all rotations on the buffer, accumulate the
1047 // left transformations into `accum`, and apply them in one GEMM at the end.
1048 for (; q + kBlockSize <= p; q += kBlockSize) {
1049 // Buffer = [ W(q:q+k, q:q+k) W(q:q+k, p) ]
1050 // [ W(p, q:q+k) W(p, p) ]
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);
1056
1057 // Accumulator for left transformations: W <- accum * W.
1058 // After processing qq pairs, accum's top-left kBlockSize x kBlockSize
1059 // block is lower-triangular (each rotation only mixes row qq with row
1060 // kBlockSize, so rows 0..qq-1 are unchanged).
1061 accum.setIdentity(kBlockSize + 1, kBlockSize + 1);
1062 bool blockDirty = false;
1063
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) {
1067 notFinished = true;
1068 blockDirty = true;
1069
1070 // Complex preconditioning: transform the 2x2 block
1071 // [w_pp w_pq] = [buffer(kBlockSize, kBlockSize) buffer(kBlockSize, qq)]
1072 // [w_qp w_qq] [buffer(qq, kBlockSize) buffer(qq, qq) ]
1073 // to have real entries via unitary row/column operations, so
1074 // real_2x2_jacobi_svd can be applied.
1075 //
1076 // Left operations (complex rotation, row scaling by e^{i*theta}) are
1077 // accumulated into `accum` for deferred GEMM application.
1078 // Right operations (column scaling) are applied directly since column
1079 // ops are contiguous in column-major layout.
1080 bool doRealSvd = true;
1081 EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsComplex) {
1082 Scalar z;
1083 // nn = ||(w_pp, w_qp)||_2, the norm of the first column of the 2x2 block.
1084 Scalar w_pp, w_qp;
1085 RealScalar nn = internal::jacobi_pivot_norm(blockBuffer.coeff(kBlockSize, kBlockSize),
1086 blockBuffer.coeff(qq, kBlockSize), w_pp, w_qp);
1087
1088 if (numext::is_exactly_zero(nn)) {
1089 // First column is zero => block is already upper triangular.
1090 blockBuffer.coeffRef(kBlockSize, kBlockSize) = Scalar(0);
1091 blockBuffer.coeffRef(qq, kBlockSize) = Scalar(0);
1092
1093 // Scale rows by z = e^{-i*arg(w)} to make remaining entries real.
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; // accumulate left op
1098 if (computeU()) m_matrixU.col(p) *= numext::conj(z);
1099 }
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;
1103 accum.row(qq) *= z; // accumulate left op
1104 if (computeU()) m_matrixU.col(q + qq) *= numext::conj(z);
1105 }
1106 } else {
1107 // Apply complex Givens rotation to zero out w_qp:
1108 // [c s] [w_pp] [nn] conj(w_pp) w_qp
1109 // [-s c] [w_qp] = [0 ] c = ----------, s = ------
1110 // nn nn
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); // accumulate left op
1116 if (computeU()) m_matrixU.applyOnTheRight(p, q + qq, rot.adjoint());
1117
1118 // Scale column qq by z = e^{-i*arg(w_pq)} to make w_pq real.
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; // right op: apply directly
1123 if (computeV()) m_matrixV.col(q + qq) *= z;
1124 }
1125 // Scale row qq by z = e^{-i*arg(w_qq)} to make w_qq real.
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;
1129 accum.row(qq) *= z; // accumulate left op
1130 if (computeU()) m_matrixU.col(q + qq) *= numext::conj(z);
1131 }
1132 }
1133 // Update maxDiagEntry from preconditioning.
1134 maxDiagEntry = numext::maxi<RealScalar>(
1135 maxDiagEntry, numext::maxi<RealScalar>(numext::abs(blockBuffer.coeff(kBlockSize, kBlockSize)),
1136 numext::abs(blockBuffer.coeff(qq, qq))));
1137 // Check if 2x2 block still needs diagonalizing.
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;
1141 }
1142
1143 if (doRealSvd) {
1144 // Compute real 2x2 SVD: buffer_2x2 = j_left * diag * j_right^T.
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);
1149
1150 // Accumulate left rotation for deferred GEMM.
1151 accum.applyOnTheLeft(kBlockSize, qq, j_left);
1152
1153 // Right rotation is a column op (contiguous): apply directly.
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);
1157
1158 maxDiagEntry = numext::maxi<RealScalar>(
1159 maxDiagEntry, numext::maxi<RealScalar>(numext::abs(blockBuffer.coeff(kBlockSize, kBlockSize)),
1160 numext::abs(blockBuffer.coeff(qq, qq))));
1161 }
1162 threshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry);
1163 }
1164 }
1165
1166 // Apply accumulated left rotations: W <- accum * W, via GEMM.
1167 // When p == q + kBlockSize, all kBlockSize+1 rows are contiguous.
1168 // Otherwise, rows q..q+k-1 and row p are non-adjacent; we split:
1169 // [Mq] [L11 l12] [Mq]
1170 // [Mp] <- [l21 l22] [Mp]
1171 // L11 is lower-triangular (exploited via triangularView).
1172 if (blockDirty) {
1173 if (p == q + kBlockSize) {
1174 m_workMatrix.template middleRows<kBlockSize + 1>(q) =
1175 accum * m_workMatrix.template middleRows<kBlockSize + 1>(q);
1176 } else {
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);
1183 Mp_save = Mp;
1184 Mp.noalias() = l21 * Mq + l22 * Mp_save;
1185 Mq = L11.template triangularView<Lower>() * Mq + l12 * Mp_save;
1186 }
1187 }
1188 }
1189
1190 // Scalar loop for remaining pairs after blocked processing.
1191 for (; q < p; ++q) {
1192 if (numext::abs(m_workMatrix.coeff(p, q)) > threshold || numext::abs(m_workMatrix.coeff(q, p)) > threshold) {
1193 notFinished = true;
1194
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,
1198 q, maxDiagEntry);
1199 }
1200
1201 if (doRealSvd) {
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>(
1209 maxDiagEntry,
1210 numext::maxi<RealScalar>(numext::abs(m_workMatrix.coeff(p, p)), numext::abs(m_workMatrix.coeff(q, q))));
1211 }
1212 threshold = numext::maxi<RealScalar>(considerAsZero, precision * maxDiagEntry);
1213 }
1214 }
1215 }
1216
1217 return notFinished;
1218}
1219
1227template <typename Derived>
1228template <int Options>
1229JacobiSVD<typename MatrixBase<Derived>::PlainObject, Options> MatrixBase<Derived>::jacobiSvd() const {
1230 return JacobiSVD<PlainObject, Options>(*this);
1231}
1232
1233template <typename Derived>
1234template <int Options>
1235JacobiSVD<typename MatrixBase<Derived>::PlainObject, Options> MatrixBase<Derived>::jacobiSvd(
1236 unsigned int computationOptions) const {
1237 return JacobiSVD<PlainObject, Options>(*this, computationOptions);
1238}
1239
1240} // end namespace Eigen
1241
1242#endif // EIGEN_JACOBISVD_H
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
Base class for triangular part in a matrix.
Definition TriangularMatrix.h:68
@ FullPivHouseholderQRPreconditioner
Definition Constants.h:432
@ InvalidInput
Definition Constants.h:464