Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
SVDBase.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) 2014 Gael Guennebaud <gael.guennebaud@inria.fr>
6//
7// Copyright (C) 2013 Gauthier Brun <brun.gauthier@gmail.com>
8// Copyright (C) 2013 Nicolas Carre <nicolas.carre@ensimag.fr>
9// Copyright (C) 2013 Jean Ceccato <jean.ceccato@ensimag.fr>
10// Copyright (C) 2013 Pierre Zoppitelli <pierre.zoppitelli@ensimag.fr>
11//
12// This Source Code Form is subject to the terms of the Mozilla
13// Public License v. 2.0. If a copy of the MPL was not distributed
14// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
15// SPDX-License-Identifier: MPL-2.0
16
17#ifndef EIGEN_SVDBASE_H
18#define EIGEN_SVDBASE_H
19
20// IWYU pragma: private
21#include "./InternalHeaderCheck.h"
22
23namespace Eigen {
24
25namespace internal {
26
27enum OptionsMasks {
30 ComputationOptionsBits = ComputeThinU | ComputeFullU | ComputeThinV | ComputeFullV
31};
32
33constexpr int get_qr_preconditioner(int options) { return options & QRPreconditionerBits; }
34
35constexpr int get_computation_options(int options) { return options & ComputationOptionsBits; }
36
37// The number of leading entries of the descending singular values that are not exactly 0 (a subnormal counts as nonzero
38// also under FTZ/DAZ).
39template <typename ValuesType>
40Index count_nonzero_singular_values(const ValuesType& values) {
41 Index i = 0;
42 while (i < values.size() && !numext::is_exactly_zero_no_flush(values.coeff(i))) ++i;
43 return i;
44}
45
46constexpr bool should_svd_precondition_square_matrix(int options) { return (options & PreconditionSquareMatrix) != 0; }
47
48constexpr bool should_svd_compute_thin_u(int options) { return (options & ComputeThinU) != 0; }
49constexpr bool should_svd_compute_full_u(int options) { return (options & ComputeFullU) != 0; }
50constexpr bool should_svd_compute_thin_v(int options) { return (options & ComputeThinV) != 0; }
51constexpr bool should_svd_compute_full_v(int options) { return (options & ComputeFullV) != 0; }
52
53template <typename MatrixType, int Options>
54void check_svd_options_assertions(unsigned int computationOptions, Index rows, Index cols) {
55 EIGEN_STATIC_ASSERT((Options & ComputationOptionsBits) == 0,
56 "SVDBase: Cannot request U or V using both static and runtime options, even if they match. "
57 "Requesting unitaries at runtime is DEPRECATED: "
58 "Prefer requesting unitaries statically, using the Options template parameter.");
59 eigen_assert(
60 !(should_svd_compute_thin_u(computationOptions) && cols < rows && MatrixType::RowsAtCompileTime != Dynamic) &&
61 !(should_svd_compute_thin_v(computationOptions) && rows < cols && MatrixType::ColsAtCompileTime != Dynamic) &&
62 "SVDBase: If thin U is requested at runtime, your matrix must have more rows than columns or a dynamic number of "
63 "rows."
64 "Similarly, if thin V is requested at runtime, you matrix must have more columns than rows or a dynamic number "
65 "of columns.");
66 (void)computationOptions;
67 (void)rows;
68 (void)cols;
69}
70
71template <typename Derived>
72struct traits<SVDBase<Derived> > : traits<Derived> {
73 using XprKind = MatrixXpr;
74 using StorageKind = SolverStorage;
75 using StorageIndex = int;
76 enum { Flags = 0 };
77};
78
79template <typename MatrixType, int Options_>
80struct svd_traits : traits<MatrixType> {
81 static constexpr int Options = Options_;
82 static constexpr bool ShouldComputeFullU = internal::should_svd_compute_full_u(Options);
83 static constexpr bool ShouldComputeThinU = internal::should_svd_compute_thin_u(Options);
84 static constexpr bool ShouldComputeFullV = internal::should_svd_compute_full_v(Options);
85 static constexpr bool ShouldComputeThinV = internal::should_svd_compute_thin_v(Options);
86 enum {
87 DiagSizeAtCompileTime =
88 internal::min_size_prefer_dynamic(MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime),
89 MaxDiagSizeAtCompileTime =
90 internal::min_size_prefer_dynamic(MatrixType::MaxRowsAtCompileTime, MatrixType::MaxColsAtCompileTime),
91 MatrixUColsAtCompileTime = ShouldComputeThinU ? DiagSizeAtCompileTime : MatrixType::RowsAtCompileTime,
92 MatrixVColsAtCompileTime = ShouldComputeThinV ? DiagSizeAtCompileTime : MatrixType::ColsAtCompileTime,
93 MatrixUMaxColsAtCompileTime = ShouldComputeThinU ? MaxDiagSizeAtCompileTime : MatrixType::MaxRowsAtCompileTime,
94 MatrixVMaxColsAtCompileTime = ShouldComputeThinV ? MaxDiagSizeAtCompileTime : MatrixType::MaxColsAtCompileTime
95 };
96};
97} // namespace internal
98
130template <typename Derived>
131class SVDBase : public SolverBase<SVDBase<Derived> > {
132 public:
133 template <typename Derived_>
134 friend struct internal::solve_assertion;
135
136 using MatrixType = typename internal::traits<Derived>::MatrixType;
137 using Scalar = typename MatrixType::Scalar;
138 using RealScalar = typename NumTraits<typename MatrixType::Scalar>::Real;
139 using StorageIndex = typename Eigen::internal::traits<SVDBase>::StorageIndex;
140
141 static constexpr bool ShouldComputeFullU = internal::traits<Derived>::ShouldComputeFullU;
142 static constexpr bool ShouldComputeThinU = internal::traits<Derived>::ShouldComputeThinU;
143 static constexpr bool ShouldComputeFullV = internal::traits<Derived>::ShouldComputeFullV;
144 static constexpr bool ShouldComputeThinV = internal::traits<Derived>::ShouldComputeThinV;
145
146 enum {
147 RowsAtCompileTime = MatrixType::RowsAtCompileTime,
148 ColsAtCompileTime = MatrixType::ColsAtCompileTime,
149 DiagSizeAtCompileTime = internal::min_size_prefer_dynamic(RowsAtCompileTime, ColsAtCompileTime),
150 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
151 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
152 MaxDiagSizeAtCompileTime = internal::min_size_prefer_fixed(MaxRowsAtCompileTime, MaxColsAtCompileTime),
153 MatrixOptions = internal::traits<MatrixType>::Options,
154 MatrixUColsAtCompileTime = internal::traits<Derived>::MatrixUColsAtCompileTime,
155 MatrixVColsAtCompileTime = internal::traits<Derived>::MatrixVColsAtCompileTime,
156 MatrixUMaxColsAtCompileTime = internal::traits<Derived>::MatrixUMaxColsAtCompileTime,
157 MatrixVMaxColsAtCompileTime = internal::traits<Derived>::MatrixVMaxColsAtCompileTime
158 };
159
160 EIGEN_STATIC_ASSERT(!(ShouldComputeFullU && ShouldComputeThinU), "SVDBase: Cannot request both full and thin U")
161 EIGEN_STATIC_ASSERT(!(ShouldComputeFullV && ShouldComputeThinV), "SVDBase: Cannot request both full and thin V")
162
163 using MatrixUType =
164 typename internal::make_proper_matrix_type<Scalar, RowsAtCompileTime, MatrixUColsAtCompileTime, MatrixOptions,
165 MaxRowsAtCompileTime, MatrixUMaxColsAtCompileTime>::type;
166 using MatrixVType =
167 typename internal::make_proper_matrix_type<Scalar, ColsAtCompileTime, MatrixVColsAtCompileTime, MatrixOptions,
168 MaxColsAtCompileTime, MatrixVMaxColsAtCompileTime>::type;
169
170 using SingularValuesType = typename internal::plain_diag_type<MatrixType, RealScalar>::type;
171
172 Derived& derived() { return *static_cast<Derived*>(this); }
173 const Derived& derived() const { return *static_cast<const Derived*>(this); }
174
185 const MatrixUType& matrixU() const {
186 _check_compute_assertions();
187 eigen_assert(computeU() && "This SVD decomposition didn't compute U. Did you ask for it?");
188 return m_matrixU;
189 }
190
201 const MatrixVType& matrixV() const {
202 _check_compute_assertions();
203 eigen_assert(computeV() && "This SVD decomposition didn't compute V. Did you ask for it?");
204 return m_matrixV;
205 }
206
212 const SingularValuesType& singularValues() const {
213 _check_compute_assertions();
214 return m_singularValues;
215 }
216
219 _check_compute_assertions();
220 return m_nonzeroSingularValues;
221 }
222
229 inline Index rank() const {
230 _check_compute_assertions();
231 if (m_singularValues.size() == 0) return 0;
232 RealScalar premultiplied_threshold =
233 numext::maxi<RealScalar>(m_singularValues.coeff(0) * threshold(), (std::numeric_limits<RealScalar>::min)());
234 Index i = m_nonzeroSingularValues - 1;
235 while (i >= 0 && m_singularValues.coeff(i) < premultiplied_threshold) --i;
236 return i + 1;
237 }
238
253 Derived& setThreshold(const RealScalar& threshold) {
254 m_usePrescribedThreshold = true;
255 m_prescribedThreshold = threshold;
256 return derived();
257 }
258
267 Derived& setThreshold(Default_t) {
268 m_usePrescribedThreshold = false;
269 return derived();
270 }
271
276 RealScalar threshold() const {
277 eigen_assert(m_isInitialized || m_usePrescribedThreshold);
278 // this temporary is needed to workaround a MSVC issue
279 Index diagSize = (std::max<Index>)(1, m_diagSize);
280 return m_usePrescribedThreshold ? m_prescribedThreshold : RealScalar(diagSize) * NumTraits<Scalar>::epsilon();
281 }
282
284 inline bool computeU() const { return m_computeFullU || m_computeThinU; }
286 inline bool computeV() const { return m_computeFullV || m_computeThinV; }
287
288 inline Index rows() const { return m_rows.value(); }
289 inline Index cols() const { return m_cols.value(); }
290 inline Index diagSize() const { return m_diagSize.value(); }
291
292#ifdef EIGEN_PARSED_BY_DOXYGEN
303 template <typename Rhs>
305#endif
306
311 EIGEN_DEVICE_FUNC ComputationInfo info() const {
312 eigen_assert(m_isInitialized && "SVD is not initialized.");
313 return m_info;
314 }
315
316#ifndef EIGEN_PARSED_BY_DOXYGEN
317 template <typename RhsType, typename DstType>
318 void _solve_impl(const RhsType& rhs, DstType& dst) const;
319
320 template <bool Conjugate, typename RhsType, typename DstType>
321 void _solve_impl_transposed(const RhsType& rhs, DstType& dst) const;
322#endif
323
324 protected:
325 EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar)
326
327 void _check_compute_assertions() const { eigen_assert(m_isInitialized && "SVD is not initialized."); }
328
329 template <bool Transpose_, typename Rhs>
330 void _check_solve_assertion(const Rhs& b) const {
331 _check_compute_assertions();
332 eigen_assert(computeU() && computeV() &&
333 "SVDBase::solve(): Both unitaries U and V are required to be computed (thin unitaries suffice).");
334 EIGEN_INTERNAL_ASSERT_SOLVER_RHS_MSG(derived(), b, Transpose_,
335 "SVDBase::solve(): invalid number of rows of the right hand side matrix b");
336 }
337
338 // return true if already allocated
339 bool allocate(Index rows, Index cols, unsigned int computationOptions);
340
341 MatrixUType m_matrixU;
342 MatrixVType m_matrixV;
343 SingularValuesType m_singularValues;
344 ComputationInfo m_info;
345 bool m_isInitialized, m_isAllocated, m_usePrescribedThreshold;
346 bool m_computeFullU, m_computeThinU;
347 bool m_computeFullV, m_computeThinV;
348 unsigned int m_computationOptions;
349 Index m_nonzeroSingularValues;
350 internal::variable_if_dynamic<Index, RowsAtCompileTime> m_rows;
351 internal::variable_if_dynamic<Index, ColsAtCompileTime> m_cols;
352 internal::variable_if_dynamic<Index, DiagSizeAtCompileTime> m_diagSize;
353 RealScalar m_prescribedThreshold;
354
360 : m_matrixU(MatrixUType()),
361 m_matrixV(MatrixVType()),
362 m_singularValues(SingularValuesType()),
363 m_info(Success),
364 m_isInitialized(false),
365 m_isAllocated(false),
366 m_usePrescribedThreshold(false),
367 m_computeFullU(ShouldComputeFullU),
368 m_computeThinU(ShouldComputeThinU),
369 m_computeFullV(ShouldComputeFullV),
370 m_computeThinV(ShouldComputeThinV),
371 m_computationOptions(internal::traits<Derived>::Options),
372 m_nonzeroSingularValues(0),
373 m_rows(RowsAtCompileTime),
374 m_cols(ColsAtCompileTime),
375 m_diagSize(DiagSizeAtCompileTime),
376 m_prescribedThreshold(0) {}
377};
378
379#ifndef EIGEN_PARSED_BY_DOXYGEN
380template <typename Derived>
381template <typename RhsType, typename DstType>
382void SVDBase<Derived>::_solve_impl(const RhsType& rhs, DstType& dst) const {
383 // A = U S V^*
384 // So A^{-1} = V S^{-1} U^*
385
386 Matrix<typename RhsType::Scalar, Dynamic, RhsType::ColsAtCompileTime, 0, MatrixType::MaxRowsAtCompileTime,
387 RhsType::MaxColsAtCompileTime>
388 tmp;
389 Index l_rank = rank();
390 tmp.noalias() = m_matrixU.leftCols(l_rank).adjoint() * rhs;
391 tmp = m_singularValues.head(l_rank).asDiagonal().inverse() * tmp;
392 dst.noalias() = m_matrixV.leftCols(l_rank) * tmp;
393}
394
395template <typename Derived>
396template <bool Conjugate, typename RhsType, typename DstType>
397void SVDBase<Derived>::_solve_impl_transposed(const RhsType& rhs, DstType& dst) const {
398 // A = U S V^*
399 // So A^{-*} = U S^{-1} V^*
400 // And A^{-T} = U_conj S^{-1} V^T
401 Matrix<typename RhsType::Scalar, Dynamic, RhsType::ColsAtCompileTime, 0, MatrixType::MaxRowsAtCompileTime,
402 RhsType::MaxColsAtCompileTime>
403 tmp;
404 Index l_rank = rank();
405
406 tmp.noalias() = m_matrixV.leftCols(l_rank).transpose().template conjugateIf<Conjugate>() * rhs;
407 tmp = m_singularValues.head(l_rank).asDiagonal().inverse() * tmp;
408 dst = m_matrixU.template conjugateIf<!Conjugate>().leftCols(l_rank) * tmp;
409}
410#endif
411
412template <typename Derived>
413bool SVDBase<Derived>::allocate(Index rows, Index cols, unsigned int computationOptions) {
414 eigen_assert(rows >= 0 && cols >= 0);
415
416 // Reset the status on every call: a recompute of the same shape must not keep the InvalidInput of a previous one.
417 m_info = Success;
418 if (m_isAllocated && rows == m_rows.value() && cols == m_cols.value() && computationOptions == m_computationOptions) {
419 return true;
420 }
421
422 m_rows.setValue(rows);
423 m_cols.setValue(cols);
424 m_isInitialized = false;
425 m_isAllocated = true;
426 m_computationOptions = computationOptions;
427 m_computeFullU = ShouldComputeFullU || internal::should_svd_compute_full_u(computationOptions);
428 m_computeThinU = ShouldComputeThinU || internal::should_svd_compute_thin_u(computationOptions);
429 m_computeFullV = ShouldComputeFullV || internal::should_svd_compute_full_v(computationOptions);
430 m_computeThinV = ShouldComputeThinV || internal::should_svd_compute_thin_v(computationOptions);
431
432 eigen_assert(!(m_computeFullU && m_computeThinU) && "SVDBase: you can't ask for both full and thin U");
433 eigen_assert(!(m_computeFullV && m_computeThinV) && "SVDBase: you can't ask for both full and thin V");
434
435 m_diagSize.setValue(numext::mini(m_rows.value(), m_cols.value()));
436 m_singularValues.resize(m_diagSize.value());
437 EIGEN_IF_CONSTEXPR (RowsAtCompileTime == Dynamic) {
438 m_matrixU.resize(m_rows.value(), m_computeFullU ? m_rows.value() : m_computeThinU ? m_diagSize.value() : 0);
439 }
440 EIGEN_IF_CONSTEXPR (ColsAtCompileTime == Dynamic) {
441 m_matrixV.resize(m_cols.value(), m_computeFullV ? m_cols.value() : m_computeThinV ? m_diagSize.value() : 0);
442 }
443
444 return false;
445}
446
447} // namespace Eigen
448
449#endif // EIGEN_SVDBASE_H
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 of SVD algorithms.
Definition SVDBase.h:131
ComputationInfo info() const
Reports whether previous computation was successful.
Definition SVDBase.h:311
Derived & setThreshold(const RealScalar &threshold)
Definition SVDBase.h:253
Index rank() const
Definition SVDBase.h:229
bool computeV() const
Definition SVDBase.h:286
Solve< Derived, Rhs > solve(const MatrixBase< Rhs > &b) const
bool computeU() const
Definition SVDBase.h:284
Derived & setThreshold(Default_t)
Definition SVDBase.h:267
RealScalar threshold() const
Definition SVDBase.h:276
SVDBase()
Default Constructor.
Definition SVDBase.h:359
const SingularValuesType & singularValues() const
Definition SVDBase.h:212
const MatrixUType & matrixU() const
Definition SVDBase.h:185
const MatrixVType & matrixV() const
Definition SVDBase.h:201
Index nonzeroSingularValues() const
Definition SVDBase.h:218
Pseudo expression representing a solving operation.
Definition Solve.h:63
ComputationInfo
Definition Constants.h:455
@ NoQRPreconditioner
Definition Constants.h:428
@ HouseholderQRPreconditioner
Definition Constants.h:430
@ ColPivHouseholderQRPreconditioner
Definition Constants.h:426
@ FullPivHouseholderQRPreconditioner
Definition Constants.h:432
@ PreconditionSquareMatrix
Definition Constants.h:437
@ Success
Definition Constants.h:457
@ ComputeFullV
Definition Constants.h:398
@ ComputeThinV
Definition Constants.h:400
@ ComputeFullU
Definition Constants.h:394
@ ComputeThinU
Definition Constants.h:396
Eigen::Index Index
The interface type of indices.
Definition EigenBase.h:44