18#ifndef itkBridgeMathSVD_h
19#define itkBridgeMathSVD_h
23#include "vnl/vnl_matrix.h"
24#include "vnl/vnl_matrix_fixed.h"
25#include "vnl/vnl_vector.h"
26#include "vnl/vnl_vector_fixed.h"
29#include ITK_EIGEN(Dense)
40template <
typename T,
unsigned int VRows,
unsigned int VColumns>
52template <
typename TReal>
56 return rcond < TReal{ 0 } ?
static_cast<TReal
>(n) * std::numeric_limits<TReal>::epsilon() : rcond;
61template <
typename TMatrixU,
typename TVector,
typename TMatrixV,
typename TReal>
63PseudoInverse(
const TMatrixU & U,
const TVector & W,
const TMatrixV & V, TReal rcond)
65 const unsigned int k = W.size();
69 for (
unsigned int col = 0; col < k; ++col)
71 const TReal s = (W[col] > tol) ? TReal{ 1 } / W[col] : TReal{ 0 };
72 for (
unsigned int i = 0; i < scaledV.rows(); ++i)
77 return scaledV * U.transpose();
81template <
typename TMatrixU,
typename TVector,
typename TMatrixV,
typename TVectorB,
typename TReal>
83SolveLinear(
const TMatrixU & U,
const TVector & W,
const TMatrixV & V,
const TVectorB & b, TReal rcond)
85 const unsigned int n = W.size();
87 auto utb = U.transpose() * b;
88 for (
unsigned int k = 0; k < n; ++k)
90 utb[k] = (W[k] > tol) ? utb[k] / W[k] : TReal{ 0 };
95template <
typename TVector,
typename TReal>
99 const unsigned int n = W.size();
101 unsigned int count = 0;
102 for (
unsigned int k = 0; k < n; ++k)
114template <
typename TMatrixU,
typename TVector,
typename TMatrixV,
typename TReal>
116Recompose(
const TMatrixU & U,
const TVector & W,
const TMatrixV & V, TReal rcond)
118 const unsigned int k = W.size();
120 TMatrixU scaledU = U;
121 for (
unsigned int col = 0; col < k; ++col)
123 const TReal s = (W[col] > tol) ? W[col] : TReal{ 0 };
124 for (
unsigned int i = 0; i < scaledU.rows(); ++i)
126 scaledU(i, col) *= s;
129 return scaledU * V.transpose();
134template <
typename TMatrixU,
typename TVector,
typename TMatrixV>
136RecomposeWith(
const TMatrixU & U,
const TVector & modifiedW,
const TMatrixV & V)
138 TMatrixU scaledU = U;
139 for (
unsigned int col = 0; col < modifiedW.size(); ++col)
141 for (
unsigned int i = 0; i < scaledU.rows(); ++i)
143 scaledU(i, col) *= modifiedW[col];
146 return scaledU * V.transpose();
150template <
typename TVector>
154 const unsigned int k = W.size();
155 if (k == 0 || W[0] == 0)
159 return W[k - 1] / W[0];
163template <
typename TVector>
167 std::decay_t<
decltype(W[0])> product{ 1 };
168 for (
unsigned int k = 0; k < W.size(); ++k)
178template <
typename TReal,
unsigned int VDim>
181 vnl_matrix_fixed<TReal, VDim, VDim>
U{};
182 vnl_vector_fixed<TReal, VDim>
W{};
183 vnl_matrix_fixed<TReal, VDim, VDim>
V{};
186 vnl_matrix_fixed<TReal, VDim, VDim>
193 vnl_vector_fixed<TReal, VDim>
194 Solve(
const vnl_vector_fixed<TReal, VDim> & b, TReal rcond = TReal{ -1 })
const
201 Rank(TReal rcond = TReal{ -1 })
const
207 vnl_matrix_fixed<TReal, VDim, VDim>
214 vnl_matrix_fixed<TReal, VDim, VDim>
222 vnl_vector_fixed<TReal, VDim>
225 return V.get_column(VDim - 1);
246template <
typename TReal>
249 vnl_matrix<TReal>
U{};
250 vnl_vector<TReal>
W{};
251 vnl_matrix<TReal>
V{};
262 Solve(
const vnl_vector<TReal> & b, TReal rcond = TReal{ -1 })
const
269 Rank(TReal rcond = TReal{ -1 })
const
295 if (
U.rows() <
V.rows())
297 itkGenericExceptionMacro(
298 "NullVector() requires rows >= cols; the thin V of an underdetermined input does not span the nullspace.");
300 return V.get_column(
V.cols() - 1);
321template <
typename TReal,
unsigned int VRows,
unsigned int VCols>
324 static constexpr unsigned int K = (VRows < VCols) ? VRows : VCols;
326 vnl_matrix_fixed<TReal, VRows, K>
U{};
327 vnl_vector_fixed<TReal, K>
W{};
328 vnl_matrix_fixed<TReal, VCols, K>
V{};
331 vnl_matrix_fixed<TReal, VCols, VRows>
338 vnl_vector_fixed<TReal, VCols>
339 Solve(
const vnl_vector_fixed<TReal, VRows> & b, TReal rcond = TReal{ -1 })
const
346 Rank(TReal rcond = TReal{ -1 })
const
352 vnl_matrix_fixed<TReal, VRows, VCols>
359 vnl_matrix_fixed<TReal, VRows, VCols>
368 vnl_vector_fixed<TReal, VCols>
371 static_assert(VRows >= VCols,
"NullVector() requires VRows >= VCols (thin V cannot span the nullspace).");
372 return V.get_column(
K - 1);
402template <
typename TReal>
406 using RowMajor = Eigen::Matrix<TReal, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
407 using ColMajor = Eigen::Matrix<TReal, Eigen::Dynamic, Eigen::Dynamic>;
408 constexpr int full = Eigen::ComputeFullU | Eigen::ComputeFullV;
410 const Eigen::Map<const RowMajor> inMap(inData, n, n);
411 Eigen::Map<RowMajor> uMap(uData, n, n);
412 Eigen::Map<RowMajor> vMap(vData, n, n);
414 const auto extract = [&](
const auto & svd) {
415 if (svd.info() != Eigen::Success)
417 itkGenericExceptionMacro(
"itk::bridge::Math::SVD failed; input is likely non-finite (NaN/Inf).");
419 uMap = svd.matrixU();
420 vMap = svd.matrixV();
421 for (
unsigned int i = 0; i < n; ++i)
423 wData[i] = svd.singularValues()[i];
429 extract(Eigen::JacobiSVD < ColMajor, full | Eigen::NoQRPreconditioner > (inMap));
433 extract(Eigen::BDCSVD<ColMajor, full>(inMap));
439template <
unsigned int VDim,
typename TReal>
452 using RowMajor = Eigen::Matrix<TReal, VDim, VDim, Eigen::RowMajor>;
453 using ColMajor = Eigen::Matrix<TReal, VDim, VDim>;
454 constexpr int options = Eigen::ComputeFullU | Eigen::ComputeFullV | Eigen::NoQRPreconditioner;
456 const Eigen::Map<const RowMajor> inMap(inData);
457 const Eigen::JacobiSVD<ColMajor, options> svd(inMap);
458 if (svd.info() != Eigen::Success)
460 itkGenericExceptionMacro(
"itk::bridge::Math::SVD failed; input is likely non-finite (NaN/Inf).");
463 Eigen::Map<RowMajor> uMap(uData);
464 Eigen::Map<RowMajor> vMap(vData);
465 uMap = svd.matrixU();
466 vMap = svd.matrixV();
467 for (
unsigned int i = 0; i < VDim; ++i)
469 wData[i] = svd.singularValues()[i];
477template <
typename TReal>
486 using RowMajor = Eigen::Matrix<TReal, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
487 using ColMajor = Eigen::Matrix<TReal, Eigen::Dynamic, Eigen::Dynamic>;
488 constexpr int thin = Eigen::ComputeThinU | Eigen::ComputeThinV;
489 const unsigned int k = (rows < cols) ? rows : cols;
491 const Eigen::Map<const RowMajor> inMap(inData, rows, cols);
492 const Eigen::BDCSVD<ColMajor, thin> svd(inMap);
493 if (svd.info() != Eigen::Success)
495 itkGenericExceptionMacro(
"itk::bridge::Math::SVD failed; input is likely non-finite (NaN/Inf).");
497 Eigen::Map<RowMajor> uMap(uData, rows, k);
498 Eigen::Map<RowMajor> vMap(vData, cols, k);
499 uMap = svd.matrixU();
500 vMap = svd.matrixV();
501 for (
unsigned int i = 0; i < k; ++i)
503 wData[i] = svd.singularValues()[i];
515template <
typename TComplex>
519 using TReal =
typename TComplex::value_type;
520 using RowMajor = Eigen::Matrix<TComplex, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
521 using ColMajor = Eigen::Matrix<TComplex, Eigen::Dynamic, Eigen::Dynamic>;
522 constexpr int thin = Eigen::ComputeThinU | Eigen::ComputeThinV;
524 const unsigned int rows = A.rows();
525 const unsigned int cols = A.cols();
526 if (rows == 0 || cols == 0)
528 itkGenericExceptionMacro(
"itk::bridge::Math::PseudoInverse requires a non-empty matrix.");
530 const Eigen::Map<const RowMajor> inMap(A.data_block(), rows, cols);
531 const Eigen::BDCSVD<ColMajor, thin> svd(inMap);
532 if (svd.info() != Eigen::Success)
534 itkGenericExceptionMacro(
"itk::bridge::Math::PseudoInverse failed; input is likely non-finite (NaN/Inf).");
537 const unsigned int k = svd.singularValues().size();
538 const TReal tol =
ResolveRcond(TReal{ -1 }, k) * svd.singularValues()[0];
539 ColMajor scaledV = svd.matrixV();
540 for (
unsigned int col = 0; col < k; ++col)
542 const TReal w = svd.singularValues()[col];
543 scaledV.col(col) *= (w > tol) ? TReal{ 1 } / w : TReal{ 0 };
545 vnl_matrix<TComplex> result(cols, rows);
546 Eigen::Map<RowMajor> resultMap(result.data_block(), cols, rows);
547 resultMap = scaledV * svd.matrixU().adjoint();
556#if defined(ITKCommon_EXPORTS)
557# define ITKCommon_EXPORT_EXPLICIT ITK_TEMPLATE_EXPORT
559# define ITKCommon_EXPORT_EXPLICIT ITKCommon_EXPORT
562#define ITK_MATH_SVD_FIXED_DIMS(F) F(1) F(2) F(3) F(4) F(5) F(6)
566ITK_GCC_PRAGMA_DIAG_PUSH()
567ITK_GCC_PRAGMA_DIAG(ignored
"-Wattributes")
569#define ITK_MATH_SVD_EXTERN_FIXED(D) \
570 extern template ITKCommon_EXPORT_EXPLICIT void SquareSVDEigen<D, float>(const float *, float *, float *, float *); \
571 extern template ITKCommon_EXPORT_EXPLICIT void SquareSVDEigen<D, double>( \
572 const double *, double *, double *, double *);
574#undef ITK_MATH_SVD_EXTERN_FIXED
589ITK_GCC_PRAGMA_DIAG_POP()
592#undef ITKCommon_EXPORT_EXPLICIT
624template <
typename TReal,
unsigned int VDim>
626SVD(
const vnl_matrix_fixed<TReal, VDim, VDim> & A,
bool canonicalizeSigns =
true)
630 if (canonicalizeSigns)
638template <
typename TReal,
unsigned int VDim>
639FixedSquareSVDResult<TReal, VDim>
648template <
typename TReal,
unsigned int VRows,
unsigned int VCols,
typename = std::enable_if_t<VRows != VCols>>
649FixedRectangularSVDResult<TReal, VRows, VCols>
650SVD(
const vnl_matrix_fixed<TReal, VRows, VCols> & A,
bool canonicalizeSigns =
true)
654 A.data_block(), VRows, VCols, result.
U.data_block(), result.
W.data_block(), result.
V.data_block());
655 if (canonicalizeSigns)
663template <
typename TReal,
unsigned int VRows,
unsigned int VCols,
typename = std::enable_if_t<VRows != VCols>>
664FixedRectangularSVDResult<TReal, VRows, VCols>
673template <
typename TReal>
675SVD(
const vnl_matrix<TReal> & A,
bool canonicalizeSigns =
true)
677 const unsigned int rows = A.rows();
678 const unsigned int cols = A.cols();
679 if (rows == 0 || cols == 0)
681 itkGenericExceptionMacro(
"itk::bridge::Math::SVD requires a non-empty matrix.");
683 const unsigned int k = (rows < cols) ? rows : cols;
685 result.
U.set_size(rows, k);
686 result.
V.set_size(cols, k);
687 result.
W.set_size(k);
691 A.data_block(), rows, result.
U.data_block(), result.
W.data_block(), result.
V.data_block());
696 A.data_block(), rows, cols, result.
U.data_block(), result.
W.data_block(), result.
V.data_block());
698 if (canonicalizeSigns)
708template <
typename TScalar>
718 return SVD(A).PseudoInverse();
A templated class holding a M x N size Matrix.
InternalMatrixType & GetVnlMatrix()
FixedSquareSVDResult< TReal, VDim > SVD(const vnl_matrix_fixed< TReal, VDim, VDim > &A, bool canonicalizeSigns=true)
Singular value decomposition A = U diag(W) V^T, backed by Eigen.
#define ITKCommon_EXPORT_EXPLICIT
#define ITK_MATH_SVD_EXTERN_FIXED(D)
#define ITK_MATH_SVD_FIXED_DIMS(F)
Cholesky-based linear algebra for symmetric matrices, backed by Eigen.
template void DynamicSquareSVDEigen< float >(const float *, unsigned int, float *, float *, float *)
TReal ResolveRcond(TReal rcond, unsigned int n)
auto Recompose(const TMatrixU &U, const TVector &W, const TMatrixV &V, TReal rcond)
void RectangularSVDEigen(const TReal *inData, unsigned int rows, unsigned int cols, TReal *uData, TReal *wData, TReal *vData)
auto DeterminantMagnitude(const TVector &W) -> std::decay_t< decltype(W[0])>
auto WellCondition(const TVector &W) -> std::decay_t< decltype(W[0])>
constexpr unsigned int kFixedSVDMaxDim
vnl_matrix< TComplex > ComplexPseudoInverse(const vnl_matrix< TComplex > &A)
auto SolveLinear(const TMatrixU &U, const TVector &W, const TMatrixV &V, const TVectorB &b, TReal rcond)
unsigned int NumericalRank(const TVector &W, TReal rcond)
constexpr unsigned int kJacobiMaxDim
void SquareSVDEigen(const TReal *inData, TReal *uData, TReal *wData, TReal *vData)
template void DynamicSquareSVDEigen< double >(const double *, unsigned int, double *, double *, double *)
void DynamicSquareSVDEigen(const TReal *inData, unsigned int n, TReal *uData, TReal *wData, TReal *vData)
auto RecomposeWith(const TMatrixU &U, const TVector &modifiedW, const TMatrixV &V)
auto PseudoInverse(const TMatrixU &U, const TVector &W, const TMatrixV &V, TReal rcond)
template void RectangularSVDEigen< double >(const double *, unsigned int, unsigned int, double *, double *, double *)
template void RectangularSVDEigen< float >(const float *, unsigned int, unsigned int, float *, float *, float *)
vnl_matrix< TScalar > PseudoInverse(const vnl_matrix< TScalar > &A)
void CanonicalizeColumnSignsPaired(TMatrixU &u, TMatrixV &paired)
Convenience wrappers over third-party numerical backends, provided as a migration aid rather than as ...
The "itk" namespace contains all Insight Segmentation and Registration Toolkit (ITK) classes....
TReal WellCondition() const
vnl_vector_fixed< TReal, VCols > NullVector() const
TReal DeterminantMagnitude() const
vnl_matrix_fixed< TReal, VRows, K > U
vnl_vector_fixed< TReal, VCols > Solve(const vnl_vector_fixed< TReal, VRows > &b, TReal rcond=TReal{ -1 }) const
static constexpr unsigned int K
vnl_matrix_fixed< TReal, VRows, VCols > Recompose(TReal rcond=TReal{ -1 }) const
unsigned int Rank(TReal rcond=TReal{ -1 }) const
vnl_matrix_fixed< TReal, VCols, VRows > PseudoInverse(TReal rcond=TReal{ -1 }) const
vnl_matrix_fixed< TReal, VRows, VCols > RecomposeWith(const vnl_vector_fixed< TReal, K > &modifiedW) const
vnl_vector_fixed< TReal, K > W
vnl_matrix_fixed< TReal, VCols, K > V
vnl_vector_fixed< TReal, VDim > Solve(const vnl_vector_fixed< TReal, VDim > &b, TReal rcond=TReal{ -1 }) const
vnl_matrix_fixed< TReal, VDim, VDim > RecomposeWith(const vnl_vector_fixed< TReal, VDim > &modifiedW) const
vnl_matrix_fixed< TReal, VDim, VDim > Recompose(TReal rcond=TReal{ -1 }) const
vnl_matrix_fixed< TReal, VDim, VDim > U
vnl_matrix_fixed< TReal, VDim, VDim > V
TReal DeterminantMagnitude() const
unsigned int Rank(TReal rcond=TReal{ -1 }) const
vnl_vector_fixed< TReal, VDim > W
vnl_matrix_fixed< TReal, VDim, VDim > PseudoInverse(TReal rcond=TReal{ -1 }) const
vnl_vector_fixed< TReal, VDim > NullVector() const
TReal WellCondition() const
unsigned int Rank(TReal rcond=TReal{ -1 }) const
vnl_vector< TReal > NullVector() const
vnl_matrix< TReal > RecomposeWith(const vnl_vector< TReal > &modifiedW) const
TReal WellCondition() const
vnl_matrix< TReal > Recompose(TReal rcond=TReal{ -1 }) const
TReal DeterminantMagnitude() const
vnl_matrix< TReal > PseudoInverse(TReal rcond=TReal{ -1 }) const
vnl_vector< TReal > Solve(const vnl_vector< TReal > &b, TReal rcond=TReal{ -1 }) const