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
37constexpr bool should_svd_precondition_square_matrix(int options) { return (options & PreconditionSquareMatrix) != 0; }
38
39constexpr bool should_svd_compute_thin_u(int options) { return (options & ComputeThinU) != 0; }
40constexpr bool should_svd_compute_full_u(int options) { return (options & ComputeFullU) != 0; }
41constexpr bool should_svd_compute_thin_v(int options) { return (options & ComputeThinV) != 0; }
42constexpr bool should_svd_compute_full_v(int options) { return (options & ComputeFullV) != 0; }
43
44template <typename MatrixType, int Options>
45void check_svd_options_assertions(unsigned int computationOptions, Index rows, Index cols) {
46 EIGEN_STATIC_ASSERT((Options & ComputationOptionsBits) == 0,
47 "SVDBase: Cannot request U or V using both static and runtime options, even if they match. "
48 "Requesting unitaries at runtime is DEPRECATED: "
49 "Prefer requesting unitaries statically, using the Options template parameter.");
50 eigen_assert(
51 !(should_svd_compute_thin_u(computationOptions) && cols < rows && MatrixType::RowsAtCompileTime != Dynamic) &&
52 !(should_svd_compute_thin_v(computationOptions) && rows < cols && MatrixType::ColsAtCompileTime != Dynamic) &&
53 "SVDBase: If thin U is requested at runtime, your matrix must have more rows than columns or a dynamic number of "
54 "rows."
55 "Similarly, if thin V is requested at runtime, you matrix must have more columns than rows or a dynamic number "
56 "of columns.");
57 (void)computationOptions;
58 (void)rows;
59 (void)cols;
60}
61
62template <typename Derived>
63struct traits<SVDBase<Derived> > : traits<Derived> {
64 using XprKind = MatrixXpr;
65 using StorageKind = SolverStorage;
66 using StorageIndex = int;
67 enum { Flags = 0 };
68};
69
70template <typename MatrixType, int Options_>
71struct svd_traits : traits<MatrixType> {
72 static constexpr int Options = Options_;
73 static constexpr bool ShouldComputeFullU = internal::should_svd_compute_full_u(Options);
74 static constexpr bool ShouldComputeThinU = internal::should_svd_compute_thin_u(Options);
75 static constexpr bool ShouldComputeFullV = internal::should_svd_compute_full_v(Options);
76 static constexpr bool ShouldComputeThinV = internal::should_svd_compute_thin_v(Options);
77 enum {
78 DiagSizeAtCompileTime =
79 internal::min_size_prefer_dynamic(MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime),
80 MaxDiagSizeAtCompileTime =
81 internal::min_size_prefer_dynamic(MatrixType::MaxRowsAtCompileTime, MatrixType::MaxColsAtCompileTime),
82 MatrixUColsAtCompileTime = ShouldComputeThinU ? DiagSizeAtCompileTime : MatrixType::RowsAtCompileTime,
83 MatrixVColsAtCompileTime = ShouldComputeThinV ? DiagSizeAtCompileTime : MatrixType::ColsAtCompileTime,
84 MatrixUMaxColsAtCompileTime = ShouldComputeThinU ? MaxDiagSizeAtCompileTime : MatrixType::MaxRowsAtCompileTime,
85 MatrixVMaxColsAtCompileTime = ShouldComputeThinV ? MaxDiagSizeAtCompileTime : MatrixType::MaxColsAtCompileTime
86 };
87};
88} // namespace internal
89
121template <typename Derived>
122class SVDBase : public SolverBase<SVDBase<Derived> > {
123 public:
124 template <typename Derived_>
125 friend struct internal::solve_assertion;
126
127 using MatrixType = typename internal::traits<Derived>::MatrixType;
128 using Scalar = typename MatrixType::Scalar;
129 using RealScalar = typename NumTraits<typename MatrixType::Scalar>::Real;
130 using StorageIndex = typename Eigen::internal::traits<SVDBase>::StorageIndex;
131
132 static constexpr bool ShouldComputeFullU = internal::traits<Derived>::ShouldComputeFullU;
133 static constexpr bool ShouldComputeThinU = internal::traits<Derived>::ShouldComputeThinU;
134 static constexpr bool ShouldComputeFullV = internal::traits<Derived>::ShouldComputeFullV;
135 static constexpr bool ShouldComputeThinV = internal::traits<Derived>::ShouldComputeThinV;
136
137 enum {
138 RowsAtCompileTime = MatrixType::RowsAtCompileTime,
139 ColsAtCompileTime = MatrixType::ColsAtCompileTime,
140 DiagSizeAtCompileTime = internal::min_size_prefer_dynamic(RowsAtCompileTime, ColsAtCompileTime),
141 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
142 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
143 MaxDiagSizeAtCompileTime = internal::min_size_prefer_fixed(MaxRowsAtCompileTime, MaxColsAtCompileTime),
144 MatrixOptions = internal::traits<MatrixType>::Options,
145 MatrixUColsAtCompileTime = internal::traits<Derived>::MatrixUColsAtCompileTime,
146 MatrixVColsAtCompileTime = internal::traits<Derived>::MatrixVColsAtCompileTime,
147 MatrixUMaxColsAtCompileTime = internal::traits<Derived>::MatrixUMaxColsAtCompileTime,
148 MatrixVMaxColsAtCompileTime = internal::traits<Derived>::MatrixVMaxColsAtCompileTime
149 };
150
151 EIGEN_STATIC_ASSERT(!(ShouldComputeFullU && ShouldComputeThinU), "SVDBase: Cannot request both full and thin U")
152 EIGEN_STATIC_ASSERT(!(ShouldComputeFullV && ShouldComputeThinV), "SVDBase: Cannot request both full and thin V")
153
154 using MatrixUType =
155 typename internal::make_proper_matrix_type<Scalar, RowsAtCompileTime, MatrixUColsAtCompileTime, MatrixOptions,
156 MaxRowsAtCompileTime, MatrixUMaxColsAtCompileTime>::type;
157 using MatrixVType =
158 typename internal::make_proper_matrix_type<Scalar, ColsAtCompileTime, MatrixVColsAtCompileTime, MatrixOptions,
159 MaxColsAtCompileTime, MatrixVMaxColsAtCompileTime>::type;
160
161 using SingularValuesType = typename internal::plain_diag_type<MatrixType, RealScalar>::type;
162
163 Derived& derived() { return *static_cast<Derived*>(this); }
164 const Derived& derived() const { return *static_cast<const Derived*>(this); }
165
176 const MatrixUType& matrixU() const {
177 _check_compute_assertions();
178 eigen_assert(computeU() && "This SVD decomposition didn't compute U. Did you ask for it?");
179 return m_matrixU;
180 }
181
192 const MatrixVType& matrixV() const {
193 _check_compute_assertions();
194 eigen_assert(computeV() && "This SVD decomposition didn't compute V. Did you ask for it?");
195 return m_matrixV;
196 }
197
203 const SingularValuesType& singularValues() const {
204 _check_compute_assertions();
205 return m_singularValues;
206 }
207
210 _check_compute_assertions();
211 return m_nonzeroSingularValues;
212 }
213
220 inline Index rank() const {
221 _check_compute_assertions();
222 if (m_singularValues.size() == 0) return 0;
223 RealScalar premultiplied_threshold =
224 numext::maxi<RealScalar>(m_singularValues.coeff(0) * threshold(), (std::numeric_limits<RealScalar>::min)());
225 Index i = m_nonzeroSingularValues - 1;
226 while (i >= 0 && m_singularValues.coeff(i) < premultiplied_threshold) --i;
227 return i + 1;
228 }
229
244 Derived& setThreshold(const RealScalar& threshold) {
245 m_usePrescribedThreshold = true;
246 m_prescribedThreshold = threshold;
247 return derived();
248 }
249
258 Derived& setThreshold(Default_t) {
259 m_usePrescribedThreshold = false;
260 return derived();
261 }
262
267 RealScalar threshold() const {
268 eigen_assert(m_isInitialized || m_usePrescribedThreshold);
269 // this temporary is needed to workaround a MSVC issue
270 Index diagSize = (std::max<Index>)(1, m_diagSize);
271 return m_usePrescribedThreshold ? m_prescribedThreshold : RealScalar(diagSize) * NumTraits<Scalar>::epsilon();
272 }
273
275 inline bool computeU() const { return m_computeFullU || m_computeThinU; }
277 inline bool computeV() const { return m_computeFullV || m_computeThinV; }
278
279 inline Index rows() const { return m_rows.value(); }
280 inline Index cols() const { return m_cols.value(); }
281 inline Index diagSize() const { return m_diagSize.value(); }
282
283#ifdef EIGEN_PARSED_BY_DOXYGEN
294 template <typename Rhs>
296#endif
297
302 EIGEN_DEVICE_FUNC ComputationInfo info() const {
303 eigen_assert(m_isInitialized && "SVD is not initialized.");
304 return m_info;
305 }
306
307#ifndef EIGEN_PARSED_BY_DOXYGEN
308 template <typename RhsType, typename DstType>
309 void _solve_impl(const RhsType& rhs, DstType& dst) const;
310
311 template <bool Conjugate, typename RhsType, typename DstType>
312 void _solve_impl_transposed(const RhsType& rhs, DstType& dst) const;
313#endif
314
315 protected:
316 EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar)
317
318 void _check_compute_assertions() const { eigen_assert(m_isInitialized && "SVD is not initialized."); }
319
320 template <bool Transpose_, typename Rhs>
321 void _check_solve_assertion(const Rhs& b) const {
322 _check_compute_assertions();
323 eigen_assert(computeU() && computeV() &&
324 "SVDBase::solve(): Both unitaries U and V are required to be computed (thin unitaries suffice).");
325 EIGEN_INTERNAL_ASSERT_SOLVER_RHS_MSG(derived(), b, Transpose_,
326 "SVDBase::solve(): invalid number of rows of the right hand side matrix b");
327 }
328
329 // return true if already allocated
330 bool allocate(Index rows, Index cols, unsigned int computationOptions);
331
332 MatrixUType m_matrixU;
333 MatrixVType m_matrixV;
334 SingularValuesType m_singularValues;
335 ComputationInfo m_info;
336 bool m_isInitialized, m_isAllocated, m_usePrescribedThreshold;
337 bool m_computeFullU, m_computeThinU;
338 bool m_computeFullV, m_computeThinV;
339 unsigned int m_computationOptions;
340 Index m_nonzeroSingularValues;
341 internal::variable_if_dynamic<Index, RowsAtCompileTime> m_rows;
342 internal::variable_if_dynamic<Index, ColsAtCompileTime> m_cols;
343 internal::variable_if_dynamic<Index, DiagSizeAtCompileTime> m_diagSize;
344 RealScalar m_prescribedThreshold;
345
351 : m_matrixU(MatrixUType()),
352 m_matrixV(MatrixVType()),
353 m_singularValues(SingularValuesType()),
354 m_info(Success),
355 m_isInitialized(false),
356 m_isAllocated(false),
357 m_usePrescribedThreshold(false),
358 m_computeFullU(ShouldComputeFullU),
359 m_computeThinU(ShouldComputeThinU),
360 m_computeFullV(ShouldComputeFullV),
361 m_computeThinV(ShouldComputeThinV),
362 m_computationOptions(internal::traits<Derived>::Options),
363 m_nonzeroSingularValues(0),
364 m_rows(RowsAtCompileTime),
365 m_cols(ColsAtCompileTime),
366 m_diagSize(DiagSizeAtCompileTime),
367 m_prescribedThreshold(0) {}
368};
369
370#ifndef EIGEN_PARSED_BY_DOXYGEN
371template <typename Derived>
372template <typename RhsType, typename DstType>
373void SVDBase<Derived>::_solve_impl(const RhsType& rhs, DstType& dst) const {
374 // A = U S V^*
375 // So A^{-1} = V S^{-1} U^*
376
377 Matrix<typename RhsType::Scalar, Dynamic, RhsType::ColsAtCompileTime, 0, MatrixType::MaxRowsAtCompileTime,
378 RhsType::MaxColsAtCompileTime>
379 tmp;
380 Index l_rank = rank();
381 tmp.noalias() = m_matrixU.leftCols(l_rank).adjoint() * rhs;
382 tmp = m_singularValues.head(l_rank).asDiagonal().inverse() * tmp;
383 dst.noalias() = m_matrixV.leftCols(l_rank) * tmp;
384}
385
386template <typename Derived>
387template <bool Conjugate, typename RhsType, typename DstType>
388void SVDBase<Derived>::_solve_impl_transposed(const RhsType& rhs, DstType& dst) const {
389 // A = U S V^*
390 // So A^{-*} = U S^{-1} V^*
391 // And A^{-T} = U_conj S^{-1} V^T
392 Matrix<typename RhsType::Scalar, Dynamic, RhsType::ColsAtCompileTime, 0, MatrixType::MaxRowsAtCompileTime,
393 RhsType::MaxColsAtCompileTime>
394 tmp;
395 Index l_rank = rank();
396
397 tmp.noalias() = m_matrixV.leftCols(l_rank).transpose().template conjugateIf<Conjugate>() * rhs;
398 tmp = m_singularValues.head(l_rank).asDiagonal().inverse() * tmp;
399 dst = m_matrixU.template conjugateIf<!Conjugate>().leftCols(l_rank) * tmp;
400}
401#endif
402
403template <typename Derived>
404bool SVDBase<Derived>::allocate(Index rows, Index cols, unsigned int computationOptions) {
405 eigen_assert(rows >= 0 && cols >= 0);
406
407 // Reset the status on every call: a recompute of the same shape must not keep the InvalidInput of a previous one.
408 m_info = Success;
409 if (m_isAllocated && rows == m_rows.value() && cols == m_cols.value() && computationOptions == m_computationOptions) {
410 return true;
411 }
412
413 m_rows.setValue(rows);
414 m_cols.setValue(cols);
415 m_isInitialized = false;
416 m_isAllocated = true;
417 m_computationOptions = computationOptions;
418 m_computeFullU = ShouldComputeFullU || internal::should_svd_compute_full_u(computationOptions);
419 m_computeThinU = ShouldComputeThinU || internal::should_svd_compute_thin_u(computationOptions);
420 m_computeFullV = ShouldComputeFullV || internal::should_svd_compute_full_v(computationOptions);
421 m_computeThinV = ShouldComputeThinV || internal::should_svd_compute_thin_v(computationOptions);
422
423 eigen_assert(!(m_computeFullU && m_computeThinU) && "SVDBase: you can't ask for both full and thin U");
424 eigen_assert(!(m_computeFullV && m_computeThinV) && "SVDBase: you can't ask for both full and thin V");
425
426 m_diagSize.setValue(numext::mini(m_rows.value(), m_cols.value()));
427 m_singularValues.resize(m_diagSize.value());
428 EIGEN_IF_CONSTEXPR (RowsAtCompileTime == Dynamic) {
429 m_matrixU.resize(m_rows.value(), m_computeFullU ? m_rows.value() : m_computeThinU ? m_diagSize.value() : 0);
430 }
431 EIGEN_IF_CONSTEXPR (ColsAtCompileTime == Dynamic) {
432 m_matrixV.resize(m_cols.value(), m_computeFullV ? m_cols.value() : m_computeThinV ? m_diagSize.value() : 0);
433 }
434
435 return false;
436}
437
438} // namespace Eigen
439
440#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:122
ComputationInfo info() const
Reports whether previous computation was successful.
Definition SVDBase.h:302
Derived & setThreshold(const RealScalar &threshold)
Definition SVDBase.h:244
Index rank() const
Definition SVDBase.h:220
bool computeV() const
Definition SVDBase.h:277
Solve< Derived, Rhs > solve(const MatrixBase< Rhs > &b) const
bool computeU() const
Definition SVDBase.h:275
Derived & setThreshold(Default_t)
Definition SVDBase.h:258
RealScalar threshold() const
Definition SVDBase.h:267
SVDBase()
Default Constructor.
Definition SVDBase.h:350
const SingularValuesType & singularValues() const
Definition SVDBase.h:203
const MatrixUType & matrixU() const
Definition SVDBase.h:176
const MatrixVType & matrixV() const
Definition SVDBase.h:192
Index nonzeroSingularValues() const
Definition SVDBase.h:209
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