20 #ifndef EIGEN_BDCSVD_H
21 #define EIGEN_BDCSVD_H
26 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
27 IOFormat bdcsvdfmt(8, 0,
", ",
"\n",
" [",
"]");
30 template<
typename _MatrixType>
class BDCSVD;
34 template<
typename _MatrixType>
35 struct traits<BDCSVD<_MatrixType> >
37 typedef _MatrixType MatrixType;
54 template<
typename _MatrixType>
55 class BDCSVD :
public SVDBase<BDCSVD<_MatrixType> >
57 typedef SVDBase<BDCSVD> Base;
65 typedef _MatrixType MatrixType;
66 typedef typename MatrixType::Scalar Scalar;
67 typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
69 RowsAtCompileTime = MatrixType::RowsAtCompileTime,
70 ColsAtCompileTime = MatrixType::ColsAtCompileTime,
71 DiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime, ColsAtCompileTime),
72 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
73 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
74 MaxDiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(MaxRowsAtCompileTime, MaxColsAtCompileTime),
75 MatrixOptions = MatrixType::Options
78 typedef typename Base::MatrixUType MatrixUType;
79 typedef typename Base::MatrixVType MatrixVType;
80 typedef typename Base::SingularValuesType SingularValuesType;
82 typedef Matrix<Scalar, Dynamic, Dynamic, ColMajor> MatrixX;
83 typedef Matrix<RealScalar, Dynamic, Dynamic, ColMajor> MatrixXr;
84 typedef Matrix<RealScalar, Dynamic, 1> VectorType;
85 typedef Array<RealScalar, Dynamic, 1> ArrayXr;
86 typedef Array<Index,1,Dynamic> ArrayXi;
87 typedef Ref<ArrayXr> ArrayRef;
88 typedef Ref<ArrayXi> IndicesRef;
95 BDCSVD() : m_algoswap(16), m_numIters(0)
106 : m_algoswap(16), m_numIters(0)
108 allocate(rows, cols, computationOptions);
121 BDCSVD(
const MatrixType& matrix,
unsigned int computationOptions = 0)
122 : m_algoswap(16), m_numIters(0)
124 compute(matrix, computationOptions);
141 BDCSVD&
compute(
const MatrixType& matrix,
unsigned int computationOptions);
151 return compute(matrix, this->m_computationOptions);
154 void setSwitchSize(
int s)
156 eigen_assert(s>3 &&
"BDCSVD the size of the algo switch has to be greater than 3");
161 void allocate(
Index rows,
Index cols,
unsigned int computationOptions);
163 void computeSVDofM(
Index firstCol,
Index n, MatrixXr& U, VectorType& singVals, MatrixXr& V);
164 void computeSingVals(
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef& perm, VectorType& singVals, ArrayRef shifts, ArrayRef mus);
165 void perturbCol0(
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef& perm,
const VectorType& singVals,
const ArrayRef& shifts,
const ArrayRef& mus, ArrayRef zhat);
166 void computeSingVecs(
const ArrayRef& zhat,
const ArrayRef& diag,
const IndicesRef& perm,
const VectorType& singVals,
const ArrayRef& shifts,
const ArrayRef& mus, MatrixXr& U, MatrixXr& V);
170 template<
typename HouseholderU,
typename HouseholderV,
typename NaiveU,
typename NaiveV>
171 void copyUV(
const HouseholderU &householderU,
const HouseholderV &householderV,
const NaiveU &naiveU,
const NaiveV &naivev);
172 void structured_update(Block<MatrixXr,Dynamic,Dynamic> A,
const MatrixXr &B,
Index n1);
173 static RealScalar secularEq(RealScalar x,
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef &perm,
const ArrayRef& diagShifted, RealScalar shift);
176 MatrixXr m_naiveU, m_naiveV;
180 ArrayXi m_workspaceI;
182 bool m_isTranspose, m_compU, m_compV;
184 using Base::m_singularValues;
185 using Base::m_diagSize;
186 using Base::m_computeFullU;
187 using Base::m_computeFullV;
188 using Base::m_computeThinU;
189 using Base::m_computeThinV;
190 using Base::m_matrixU;
191 using Base::m_matrixV;
192 using Base::m_isInitialized;
193 using Base::m_nonzeroSingularValues;
201 template<
typename MatrixType>
202 void BDCSVD<MatrixType>::allocate(Index rows, Index cols,
unsigned int computationOptions)
204 m_isTranspose = (cols > rows);
206 if (Base::allocate(rows, cols, computationOptions))
209 m_computed = MatrixXr::Zero(m_diagSize + 1, m_diagSize );
210 m_compU = computeV();
211 m_compV = computeU();
213 std::swap(m_compU, m_compV);
215 if (m_compU) m_naiveU = MatrixXr::Zero(m_diagSize + 1, m_diagSize + 1 );
216 else m_naiveU = MatrixXr::Zero(2, m_diagSize + 1 );
218 if (m_compV) m_naiveV = MatrixXr::Zero(m_diagSize, m_diagSize);
220 m_workspace.resize((m_diagSize+1)*(m_diagSize+1)*3);
221 m_workspaceI.resize(3*m_diagSize);
224 template<
typename MatrixType>
227 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
228 std::cout <<
"\n\n\n======================================================================================================================\n\n\n";
230 allocate(matrix.rows(), matrix.cols(), computationOptions);
234 if(matrix.cols() < m_algoswap)
238 if(computeU()) m_matrixU = jsvd.
matrixU();
239 if(computeV()) m_matrixV = jsvd.
matrixV();
242 m_isInitialized =
true;
247 RealScalar scale = matrix.cwiseAbs().maxCoeff();
248 if(scale==RealScalar(0)) scale = RealScalar(1);
250 if (m_isTranspose) copy = matrix.
adjoint()/scale;
251 else copy = matrix/scale;
255 internal::UpperBidiagonalization<MatrixX> bid(copy);
261 m_computed.topRows(m_diagSize) = bid.bidiagonal().toDenseMatrix().transpose();
262 m_computed.template bottomRows<1>().setZero();
263 divide(0, m_diagSize - 1, 0, 0, 0);
266 for (
int i=0; i<m_diagSize; i++)
268 RealScalar a = abs(m_computed.coeff(i, i));
269 m_singularValues.coeffRef(i) = a * scale;
272 m_nonzeroSingularValues = i;
273 m_singularValues.tail(m_diagSize - i - 1).setZero();
276 else if (i == m_diagSize - 1)
278 m_nonzeroSingularValues = i + 1;
283 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
287 if(m_isTranspose) copyUV(bid.householderV(), bid.householderU(), m_naiveV, m_naiveU);
288 else copyUV(bid.householderU(), bid.householderV(), m_naiveU, m_naiveV);
290 m_isInitialized =
true;
295 template<
typename MatrixType>
296 template<
typename HouseholderU,
typename HouseholderV,
typename NaiveU,
typename NaiveV>
297 void BDCSVD<MatrixType>::copyUV(
const HouseholderU &householderU,
const HouseholderV &householderV,
const NaiveU &naiveU,
const NaiveV &naiveV)
302 Index Ucols = m_computeThinU ? m_diagSize : householderU.cols();
303 m_matrixU = MatrixX::Identity(householderU.cols(), Ucols);
304 m_matrixU.topLeftCorner(m_diagSize, m_diagSize) = naiveV.template cast<Scalar>().topLeftCorner(m_diagSize, m_diagSize);
305 householderU.applyThisOnTheLeft(m_matrixU);
309 Index Vcols = m_computeThinV ? m_diagSize : householderV.cols();
310 m_matrixV = MatrixX::Identity(householderV.cols(), Vcols);
311 m_matrixV.topLeftCorner(m_diagSize, m_diagSize) = naiveU.template cast<Scalar>().topLeftCorner(m_diagSize, m_diagSize);
312 householderV.applyThisOnTheLeft(m_matrixV);
324 template<
typename MatrixType>
325 void BDCSVD<MatrixType>::structured_update(Block<MatrixXr,Dynamic,Dynamic> A,
const MatrixXr &B, Index n1)
333 Map<MatrixXr> A1(m_workspace.data() , n1, n);
334 Map<MatrixXr> A2(m_workspace.data()+ n1*n, n2, n);
335 Map<MatrixXr> B1(m_workspace.data()+ n*n, n, n);
336 Map<MatrixXr> B2(m_workspace.data()+2*n*n, n, n);
338 for(Index j=0; j<n; ++j)
340 if( (A.col(j).head(n1).array()!=0).any() )
342 A1.col(k1) = A.col(j).head(n1);
343 B1.row(k1) = B.row(j);
346 if( (A.col(j).tail(n2).array()!=0).any() )
348 A2.col(k2) = A.col(j).tail(n2);
349 B2.row(k2) = B.row(j);
354 A.topRows(n1).noalias() = A1.leftCols(k1) * B1.topRows(k1);
355 A.bottomRows(n2).noalias() = A2.leftCols(k2) * B2.topRows(k2);
359 Map<MatrixXr,Aligned> tmp(m_workspace.data(),n,n);
375 template<
typename MatrixType>
376 void BDCSVD<MatrixType>::divide (Index firstCol, Index lastCol, Index firstRowW, Index firstColW, Index shift)
382 const Index n = lastCol - firstCol + 1;
387 RealScalar lambda, phi, c0, s0;
396 m_naiveU.block(firstCol, firstCol, n + 1, n + 1).real() = b.matrixU();
399 m_naiveU.row(0).segment(firstCol, n + 1).real() = b.matrixU().row(0);
400 m_naiveU.row(1).segment(firstCol, n + 1).real() = b.matrixU().row(n);
402 if (m_compV) m_naiveV.block(firstRowW, firstColW, n, n).real() = b.matrixV();
403 m_computed.block(firstCol + shift, firstCol + shift, n + 1, n).setZero();
404 m_computed.diagonal().segment(firstCol + shift, n) = b.singularValues().head(n);
408 alphaK = m_computed(firstCol + k, firstCol + k);
409 betaK = m_computed(firstCol + k + 1, firstCol + k);
413 divide(k + 1 + firstCol, lastCol, k + 1 + firstRowW, k + 1 + firstColW, shift);
414 divide(firstCol, k - 1 + firstCol, firstRowW, firstColW + 1, shift + 1);
418 lambda = m_naiveU(firstCol + k, firstCol + k);
419 phi = m_naiveU(firstCol + k + 1, lastCol + 1);
423 lambda = m_naiveU(1, firstCol + k);
424 phi = m_naiveU(0, lastCol + 1);
426 r0 = sqrt((abs(alphaK * lambda) * abs(alphaK * lambda)) + abs(betaK * phi) * abs(betaK * phi));
429 l = m_naiveU.row(firstCol + k).segment(firstCol, k);
430 f = m_naiveU.row(firstCol + k + 1).segment(firstCol + k + 1, n - k - 1);
434 l = m_naiveU.row(1).segment(firstCol, k);
435 f = m_naiveU.row(0).segment(firstCol + k + 1, n - k - 1);
437 if (m_compV) m_naiveV(firstRowW+k, firstColW) = 1;
445 c0 = alphaK * lambda / r0;
446 s0 = betaK * phi / r0;
449 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
450 assert(m_naiveU.allFinite());
451 assert(m_naiveV.allFinite());
452 assert(m_computed.allFinite());
457 MatrixXr q1 (m_naiveU.col(firstCol + k).segment(firstCol, k + 1));
459 for (Index i = firstCol + k - 1; i >= firstCol; i--)
460 m_naiveU.col(i + 1).segment(firstCol, k + 1) = m_naiveU.col(i).segment(firstCol, k + 1);
462 m_naiveU.col(firstCol).segment( firstCol, k + 1) = (q1 * c0);
464 m_naiveU.col(lastCol + 1).segment(firstCol, k + 1) = (q1 * ( - s0));
466 m_naiveU.col(firstCol).segment(firstCol + k + 1, n - k) = m_naiveU.col(lastCol + 1).segment(firstCol + k + 1, n - k) * s0;
468 m_naiveU.col(lastCol + 1).segment(firstCol + k + 1, n - k) *= c0;
472 RealScalar q1 = m_naiveU(0, firstCol + k);
474 for (Index i = firstCol + k - 1; i >= firstCol; i--)
475 m_naiveU(0, i + 1) = m_naiveU(0, i);
477 m_naiveU(0, firstCol) = (q1 * c0);
479 m_naiveU(0, lastCol + 1) = (q1 * ( - s0));
481 m_naiveU(1, firstCol) = m_naiveU(1, lastCol + 1) *s0;
483 m_naiveU(1, lastCol + 1) *= c0;
484 m_naiveU.row(1).segment(firstCol + 1, k).setZero();
485 m_naiveU.row(0).segment(firstCol + k + 1, n - k - 1).setZero();
488 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
489 assert(m_naiveU.allFinite());
490 assert(m_naiveV.allFinite());
491 assert(m_computed.allFinite());
494 m_computed(firstCol + shift, firstCol + shift) = r0;
495 m_computed.col(firstCol + shift).segment(firstCol + shift + 1, k) = alphaK * l.transpose().real();
496 m_computed.col(firstCol + shift).segment(firstCol + shift + k + 1, n - k - 1) = betaK * f.transpose().real();
498 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
499 ArrayXr tmp1 = (m_computed.block(firstCol+shift, firstCol+shift, n, n)).jacobiSvd().singularValues();
502 deflation(firstCol, lastCol, k, firstRowW, firstColW, shift);
503 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
504 ArrayXr tmp2 = (m_computed.block(firstCol+shift, firstCol+shift, n, n)).jacobiSvd().singularValues();
505 std::cout <<
"\n\nj1 = " << tmp1.transpose().format(bdcsvdfmt) <<
"\n";
506 std::cout <<
"j2 = " << tmp2.transpose().format(bdcsvdfmt) <<
"\n\n";
507 std::cout <<
"err: " << ((tmp1-tmp2).abs()>1e-12*tmp2.abs()).transpose() <<
"\n";
508 static int count = 0;
509 std::cout <<
"# " << ++count <<
"\n\n";
510 assert((tmp1-tmp2).matrix().norm() < 1e-14*tmp2.matrix().norm());
516 MatrixXr UofSVD, VofSVD;
518 computeSVDofM(firstCol + shift, n, UofSVD, singVals, VofSVD);
520 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
521 assert(UofSVD.allFinite());
522 assert(VofSVD.allFinite());
526 structured_update(m_naiveU.block(firstCol, firstCol, n + 1, n + 1), UofSVD, (n+2)/2);
529 Map<Matrix<RealScalar,2,Dynamic>,
Aligned> tmp(m_workspace.data(),2,n+1);
530 tmp.noalias() = m_naiveU.middleCols(firstCol, n+1) * UofSVD;
531 m_naiveU.middleCols(firstCol, n + 1) = tmp;
534 if (m_compV) structured_update(m_naiveV.block(firstRowW, firstColW, n, n), VofSVD, (n+1)/2);
536 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
537 assert(m_naiveU.allFinite());
538 assert(m_naiveV.allFinite());
539 assert(m_computed.allFinite());
542 m_computed.block(firstCol + shift, firstCol + shift, n, n).setZero();
543 m_computed.block(firstCol + shift, firstCol + shift, n, n).diagonal() = singVals;
554 template <
typename MatrixType>
555 void BDCSVD<MatrixType>::computeSVDofM(Index firstCol, Index n, MatrixXr& U, VectorType& singVals, MatrixXr& V)
557 ArrayRef col0 = m_computed.col(firstCol).segment(firstCol, n);
558 m_workspace.head(n) = m_computed.block(firstCol, firstCol, n, n).diagonal();
559 ArrayRef diag = m_workspace.head(n);
565 if (m_compV) V.resize(n, n);
567 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
568 if (col0.hasNaN() || diag.hasNaN())
569 std::cout <<
"\n\nHAS NAN\n\n";
576 while(actual_n>1 && diag(actual_n-1)==0) --actual_n;
578 for(Index k=0;k<actual_n;++k)
580 m_workspaceI(m++) = k;
581 Map<ArrayXi> perm(m_workspaceI.data(),m);
583 Map<ArrayXr> shifts(m_workspace.data()+1*n, n);
584 Map<ArrayXr> mus(m_workspace.data()+2*n, n);
585 Map<ArrayXr> zhat(m_workspace.data()+3*n, n);
587 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
588 std::cout <<
"computeSVDofM using:\n";
589 std::cout <<
" z: " << col0.transpose() <<
"\n";
590 std::cout <<
" d: " << diag.transpose() <<
"\n";
594 computeSingVals(col0, diag, perm, singVals, shifts, mus);
596 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
597 std::cout <<
" j: " << (m_computed.block(firstCol, firstCol, n, n)).jacobiSvd().singularValues().transpose().reverse() <<
"\n\n";
598 std::cout <<
" sing-val: " << singVals.transpose() <<
"\n";
599 std::cout <<
" mu: " << mus.transpose() <<
"\n";
600 std::cout <<
" shift: " << shifts.transpose() <<
"\n";
604 while(actual_n>1 && col0(actual_n-1)==0) --actual_n;
605 std::cout <<
"\n\n mus: " << mus.head(actual_n).transpose() <<
"\n\n";
606 std::cout <<
" check1 (expect0) : " << ((singVals.array()-(shifts+mus)) / singVals.array()).head(actual_n).transpose() <<
"\n\n";
607 std::cout <<
" check2 (>0) : " << ((singVals.array()-diag) / singVals.array()).head(actual_n).transpose() <<
"\n\n";
608 std::cout <<
" check3 (>0) : " << ((diag.segment(1,actual_n-1)-singVals.head(actual_n-1).array()) / singVals.head(actual_n-1).array()).transpose() <<
"\n\n\n";
609 std::cout <<
" check4 (>0) : " << ((singVals.segment(1,actual_n-1)-singVals.head(actual_n-1))).transpose() <<
"\n\n\n";
613 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
614 assert(singVals.allFinite());
615 assert(mus.allFinite());
616 assert(shifts.allFinite());
620 perturbCol0(col0, diag, perm, singVals, shifts, mus, zhat);
621 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
622 std::cout <<
" zhat: " << zhat.transpose() <<
"\n";
625 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
626 assert(zhat.allFinite());
629 computeSingVecs(zhat, diag, perm, singVals, shifts, mus, U, V);
631 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
632 std::cout <<
"U^T U: " << (U.transpose() * U - MatrixXr(MatrixXr::Identity(U.cols(),U.cols()))).norm() <<
"\n";
633 std::cout <<
"V^T V: " << (V.transpose() * V - MatrixXr(MatrixXr::Identity(V.cols(),V.cols()))).norm() <<
"\n";
636 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
637 assert(U.allFinite());
638 assert(V.allFinite());
639 assert((U.transpose() * U - MatrixXr(MatrixXr::Identity(U.cols(),U.cols()))).norm() < 1e-14 * n);
640 assert((V.transpose() * V - MatrixXr(MatrixXr::Identity(V.cols(),V.cols()))).norm() < 1e-14 * n);
641 assert(m_naiveU.allFinite());
642 assert(m_naiveV.allFinite());
643 assert(m_computed.allFinite());
648 for(Index i=0; i<actual_n-1; ++i)
650 if(singVals(i)>singVals(i+1))
653 swap(singVals(i),singVals(i+1));
654 U.col(i).swap(U.col(i+1));
655 if(m_compV) V.col(i).swap(V.col(i+1));
661 singVals.head(actual_n).reverseInPlace();
662 U.leftCols(actual_n).rowwise().reverseInPlace();
663 if (m_compV) V.leftCols(actual_n).rowwise().reverseInPlace();
665 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
666 JacobiSVD<MatrixXr> jsvd(m_computed.block(firstCol, firstCol, n, n) );
667 std::cout <<
" * j: " << jsvd.singularValues().transpose() <<
"\n\n";
668 std::cout <<
" * sing-val: " << singVals.transpose() <<
"\n";
673 template <
typename MatrixType>
674 typename BDCSVD<MatrixType>::RealScalar BDCSVD<MatrixType>::secularEq(RealScalar mu,
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef &perm,
const ArrayRef& diagShifted, RealScalar shift)
676 Index m = perm.size();
678 for(Index i=0; i<m; ++i)
681 res += numext::abs2(col0(j)) / ((diagShifted(j) - mu) * (diag(j) + shift + mu));
686 template <
typename MatrixType>
687 void BDCSVD<MatrixType>::computeSingVals(
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef &perm,
688 VectorType& singVals, ArrayRef shifts, ArrayRef mus)
693 Index n = col0.size();
695 while(actual_n>1 && col0(actual_n-1)==0) --actual_n;
697 for (Index k = 0; k < n; ++k)
699 if (col0(k) == 0 || actual_n==1)
703 singVals(k) = k==0 ? col0(0) : diag(k);
705 shifts(k) = k==0 ? col0(0) : diag(k);
710 RealScalar left = diag(k);
713 right = (diag(actual_n-1) + col0.matrix().norm());
718 while(col0(l)==0) { ++l; eigen_internal_assert(l<actual_n); }
723 RealScalar mid = left + (right-left) / 2;
724 RealScalar fMid = secularEq(mid, col0, diag, perm, diag, 0);
725 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
726 std::cout << right-left <<
"\n";
727 std::cout <<
"fMid = " << fMid <<
" " << secularEq(mid-left, col0, diag, perm, diag-left, left) <<
" " << secularEq(mid-right, col0, diag, perm, diag-right, right) <<
"\n";
728 std::cout <<
" = " << secularEq(0.1*(left+right), col0, diag, perm, diag, 0)
729 <<
" " << secularEq(0.2*(left+right), col0, diag, perm, diag, 0)
730 <<
" " << secularEq(0.3*(left+right), col0, diag, perm, diag, 0)
731 <<
" " << secularEq(0.4*(left+right), col0, diag, perm, diag, 0)
732 <<
" " << secularEq(0.49*(left+right), col0, diag, perm, diag, 0)
733 <<
" " << secularEq(0.5*(left+right), col0, diag, perm, diag, 0)
734 <<
" " << secularEq(0.51*(left+right), col0, diag, perm, diag, 0)
735 <<
" " << secularEq(0.6*(left+right), col0, diag, perm, diag, 0)
736 <<
" " << secularEq(0.7*(left+right), col0, diag, perm, diag, 0)
737 <<
" " << secularEq(0.8*(left+right), col0, diag, perm, diag, 0)
738 <<
" " << secularEq(0.9*(left+right), col0, diag, perm, diag, 0) <<
"\n";
740 RealScalar shift = (k == actual_n-1 || fMid > 0) ? left : right;
743 Map<ArrayXr> diagShifted(m_workspace.data()+4*n, n);
744 diagShifted = diag - shift;
747 RealScalar muPrev, muCur;
750 muPrev = (right - left) * 0.1;
751 if (k == actual_n-1) muCur = right - left;
752 else muCur = (right - left) * 0.5;
756 muPrev = -(right - left) * 0.1;
757 muCur = -(right - left) * 0.5;
760 RealScalar fPrev = secularEq(muPrev, col0, diag, perm, diagShifted, shift);
761 RealScalar fCur = secularEq(muCur, col0, diag, perm, diagShifted, shift);
762 if (abs(fPrev) < abs(fCur))
770 bool useBisection = fPrev*fCur>0;
771 while (fCur!=0 && abs(muCur - muPrev) > 8 * NumTraits<RealScalar>::epsilon() * numext::maxi<RealScalar>(abs(muCur), abs(muPrev)) && abs(fCur - fPrev)>NumTraits<RealScalar>::epsilon() && !useBisection)
776 RealScalar a = (fCur - fPrev) / (1/muCur - 1/muPrev);
777 RealScalar b = fCur - a / muCur;
779 RealScalar muZero = -a/b;
780 RealScalar fZero = secularEq(muZero, col0, diag, perm, diagShifted, shift);
788 if (shift == left && (muCur < 0 || muCur > right - left)) useBisection =
true;
789 if (shift == right && (muCur < -(right - left) || muCur > 0)) useBisection =
true;
790 if (abs(fCur)>abs(fPrev)) useBisection =
true;
796 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
797 std::cout <<
"useBisection for k = " << k <<
", actual_n = " << actual_n <<
"\n";
799 RealScalar leftShifted, rightShifted;
802 leftShifted = RealScalar(1)/NumTraits<RealScalar>::highest();
805 rightShifted = (k==actual_n-1) ? right : ((right - left) * 0.6);
809 leftShifted = -(right - left) * 0.6;
810 rightShifted = -RealScalar(1)/NumTraits<RealScalar>::highest();
813 RealScalar fLeft = secularEq(leftShifted, col0, diag, perm, diagShifted, shift);
815 #if defined EIGEN_INTERNAL_DEBUGGING || defined EIGEN_BDCSVD_DEBUG_VERBOSE
816 RealScalar fRight = secularEq(rightShifted, col0, diag, perm, diagShifted, shift);
819 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
820 if(!(fLeft * fRight<0))
821 std::cout << k <<
" : " << fLeft <<
" * " << fRight <<
" == " << fLeft * fRight <<
" ; " << left <<
" - " << right <<
" -> " << leftShifted <<
" " << rightShifted <<
" shift=" << shift <<
"\n";
823 eigen_internal_assert(fLeft * fRight < 0);
825 while (rightShifted - leftShifted > 2 * NumTraits<RealScalar>::epsilon() * numext::maxi<RealScalar>(abs(leftShifted), abs(rightShifted)))
827 RealScalar midShifted = (leftShifted + rightShifted) / 2;
828 fMid = secularEq(midShifted, col0, diag, perm, diagShifted, shift);
829 if (fLeft * fMid < 0)
831 rightShifted = midShifted;
835 leftShifted = midShifted;
840 muCur = (leftShifted + rightShifted) / 2;
843 singVals[k] = shift + muCur;
857 template <
typename MatrixType>
858 void BDCSVD<MatrixType>::perturbCol0
859 (
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef &perm,
const VectorType& singVals,
860 const ArrayRef& shifts,
const ArrayRef& mus, ArrayRef zhat)
863 Index n = col0.size();
864 Index m = perm.size();
870 Index last = perm(m-1);
872 for (Index k = 0; k < n; ++k)
879 RealScalar dk = diag(k);
880 RealScalar prod = (singVals(last) + dk) * (mus(last) + (shifts(last) - dk));
882 for(Index l = 0; l<m; ++l)
887 Index j = i<k ? i : perm(l-1);
888 prod *= ((singVals(j)+dk) / ((diag(i)+dk))) * ((mus(j)+(shifts(j)-dk)) / ((diag(i)-dk)));
889 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
890 if(i!=k && std::abs(((singVals(j)+dk)*(mus(j)+(shifts(j)-dk)))/((diag(i)+dk)*(diag(i)-dk)) - 1) > 0.9 )
891 std::cout <<
" " << ((singVals(j)+dk)*(mus(j)+(shifts(j)-dk)))/((diag(i)+dk)*(diag(i)-dk)) <<
" == (" << (singVals(j)+dk) <<
" * " << (mus(j)+(shifts(j)-dk))
892 <<
") / (" << (diag(i)+dk) <<
" * " << (diag(i)-dk) <<
")\n";
896 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
897 std::cout <<
"zhat(" << k <<
") = sqrt( " << prod <<
") ; " << (singVals(last) + dk) <<
" * " << mus(last) + shifts(last) <<
" - " << dk <<
"\n";
899 RealScalar tmp = sqrt(prod);
900 zhat(k) = col0(k) > 0 ? tmp : -tmp;
906 template <
typename MatrixType>
907 void BDCSVD<MatrixType>::computeSingVecs
908 (
const ArrayRef& zhat,
const ArrayRef& diag,
const IndicesRef &perm,
const VectorType& singVals,
909 const ArrayRef& shifts,
const ArrayRef& mus, MatrixXr& U, MatrixXr& V)
911 Index n = zhat.size();
912 Index m = perm.size();
914 for (Index k = 0; k < n; ++k)
918 U.col(k) = VectorType::Unit(n+1, k);
919 if (m_compV) V.col(k) = VectorType::Unit(n, k);
924 for(Index l=0;l<m;++l)
927 U(i,k) = zhat(i)/(((diag(i) - shifts(k)) - mus(k)) )/( (diag(i) + singVals[k]));
930 U.col(k).normalize();
935 for(Index l=1;l<m;++l)
938 V(i,k) = diag(i) * zhat(i) / (((diag(i) - shifts(k)) - mus(k)) )/( (diag(i) + singVals[k]));
941 V.col(k).normalize();
945 U.col(n) = VectorType::Unit(n+1, n);
952 template <
typename MatrixType>
953 void BDCSVD<MatrixType>::deflation43(Index firstCol, Index shift, Index i, Index size)
958 Index start = firstCol + shift;
959 RealScalar c = m_computed(start, start);
960 RealScalar s = m_computed(start+i, start);
961 RealScalar r = sqrt(numext::abs2(c) + numext::abs2(s));
964 m_computed(start+i, start+i) = 0;
967 m_computed(start,start) = r;
968 m_computed(start+i, start) = 0;
969 m_computed(start+i, start+i) = 0;
971 JacobiRotation<RealScalar> J(c/r,-s/r);
972 if (m_compU) m_naiveU.middleRows(firstCol, size+1).applyOnTheRight(firstCol, firstCol+i, J);
973 else m_naiveU.applyOnTheRight(firstCol, firstCol+i, J);
981 template <
typename MatrixType>
982 void BDCSVD<MatrixType>::deflation44(Index firstColu , Index firstColm, Index firstRowW, Index firstColW, Index i, Index j, Index size)
988 RealScalar c = m_computed(firstColm+i, firstColm);
989 RealScalar s = m_computed(firstColm+j, firstColm);
990 RealScalar r = sqrt(numext::abs2(c) + numext::abs2(s));
991 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
992 std::cout <<
"deflation 4.4: " << i <<
"," << j <<
" -> " << c <<
" " << s <<
" " << r <<
" ; "
993 << m_computed(firstColm + i-1, firstColm) <<
" "
994 << m_computed(firstColm + i, firstColm) <<
" "
995 << m_computed(firstColm + i+1, firstColm) <<
" "
996 << m_computed(firstColm + i+2, firstColm) <<
"\n";
997 std::cout << m_computed(firstColm + i-1, firstColm + i-1) <<
" "
998 << m_computed(firstColm + i, firstColm+i) <<
" "
999 << m_computed(firstColm + i+1, firstColm+i+1) <<
" "
1000 << m_computed(firstColm + i+2, firstColm+i+2) <<
"\n";
1004 m_computed(firstColm + i, firstColm + i) = m_computed(firstColm + j, firstColm + j);
1009 m_computed(firstColm + i, firstColm) = r;
1010 m_computed(firstColm + j, firstColm + j) = m_computed(firstColm + i, firstColm + i);
1011 m_computed(firstColm + j, firstColm) = 0;
1013 JacobiRotation<RealScalar> J(c,-s);
1014 if (m_compU) m_naiveU.middleRows(firstColu, size+1).applyOnTheRight(firstColu + i, firstColu + j, J);
1015 else m_naiveU.applyOnTheRight(firstColu+i, firstColu+j, J);
1016 if (m_compV) m_naiveV.middleRows(firstRowW, size).applyOnTheRight(firstColW + i, firstColW + j, J);
1021 template <
typename MatrixType>
1022 void BDCSVD<MatrixType>::deflation(Index firstCol, Index lastCol, Index k, Index firstRowW, Index firstColW, Index shift)
1026 const Index length = lastCol + 1 - firstCol;
1028 Block<MatrixXr,Dynamic,1> col0(m_computed, firstCol+shift, firstCol+shift, length, 1);
1029 Diagonal<MatrixXr> fulldiag(m_computed);
1030 VectorBlock<Diagonal<MatrixXr>,Dynamic> diag(fulldiag, firstCol+shift, length);
1032 RealScalar maxDiag = diag.tail((std::max)(Index(1),length-1)).cwiseAbs().maxCoeff();
1033 RealScalar epsilon_strict = NumTraits<RealScalar>::epsilon() * maxDiag;
1034 RealScalar epsilon_coarse = 8 * NumTraits<RealScalar>::epsilon() * numext::maxi<RealScalar>(col0.cwiseAbs().maxCoeff(), maxDiag);
1036 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
1037 assert(m_naiveU.allFinite());
1038 assert(m_naiveV.allFinite());
1039 assert(m_computed.allFinite());
1042 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1043 std::cout <<
"\ndeflate:" << diag.head(k+1).transpose() <<
" | " << diag.segment(k+1,length-k-1).transpose() <<
"\n";
1047 if (diag(0) < epsilon_coarse)
1049 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1050 std::cout <<
"deflation 4.1, because " << diag(0) <<
" < " << epsilon_coarse <<
"\n";
1052 diag(0) = epsilon_coarse;
1056 for (Index i=1;i<length;++i)
1057 if (abs(col0(i)) < epsilon_strict)
1059 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1060 std::cout <<
"deflation 4.2, set z(" << i <<
") to zero because " << abs(col0(i)) <<
" < " << epsilon_strict <<
" (diag(" << i <<
")=" << diag(i) <<
")\n";
1066 for (Index i=1;i<length; i++)
1067 if (diag(i) < epsilon_coarse)
1069 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1070 std::cout <<
"deflation 4.3, cancel z(" << i <<
")=" << col0(i) <<
" because diag(" << i <<
")=" << diag(i) <<
" < " << epsilon_coarse <<
"\n";
1072 deflation43(firstCol, shift, i, length);
1075 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
1076 assert(m_naiveU.allFinite());
1077 assert(m_naiveV.allFinite());
1078 assert(m_computed.allFinite());
1080 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1081 std::cout <<
"to be sorted: " << diag.transpose() <<
"\n\n";
1086 bool total_deflation = (col0.tail(length-1).array()==RealScalar(0)).all();
1090 Index *permutation = m_workspaceI.data();
1096 for(Index i=1; i<length; ++i)
1098 permutation[p++] = i;
1101 for( ; p < length; ++p)
1103 if (i > k) permutation[p] = j++;
1104 else if (j >= length) permutation[p] = i++;
1105 else if (diag(i) < diag(j)) permutation[p] = j++;
1106 else permutation[p] = i++;
1113 for(Index i=1; i<length; ++i)
1115 Index pi = permutation[i];
1116 if(diag(pi)==0 || diag(0)<diag(pi))
1117 permutation[i-1] = permutation[i];
1120 permutation[i-1] = 0;
1127 Index *realInd = m_workspaceI.data()+length;
1128 Index *realCol = m_workspaceI.data()+2*length;
1130 for(
int pos = 0; pos< length; pos++)
1136 for(Index i = total_deflation?0:1; i < length; i++)
1138 const Index pi = permutation[length - (total_deflation ? i+1 : i)];
1139 const Index J = realCol[pi];
1143 swap(diag(i), diag(J));
1144 if(i!=0 && J!=0) swap(col0(i), col0(J));
1147 if (m_compU) m_naiveU.col(firstCol+i).segment(firstCol, length + 1).swap(m_naiveU.col(firstCol+J).segment(firstCol, length + 1));
1148 else m_naiveU.col(firstCol+i).segment(0, 2) .swap(m_naiveU.col(firstCol+J).segment(0, 2));
1149 if (m_compV) m_naiveV.col(firstColW + i).segment(firstRowW, length).swap(m_naiveV.col(firstColW + J).segment(firstRowW, length));
1152 const Index realI = realInd[i];
1159 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1160 std::cout <<
"sorted: " << diag.transpose().format(bdcsvdfmt) <<
"\n";
1161 std::cout <<
" : " << col0.transpose() <<
"\n\n";
1167 while(i>0 && (diag(i)==0 || col0(i)==0)) --i;
1169 if( (diag(i) - diag(i-1)) < NumTraits<RealScalar>::epsilon()*maxDiag )
1171 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1172 std::cout <<
"deflation 4.4 with i = " << i <<
" because " << (diag(i) - diag(i-1)) <<
" < " << NumTraits<RealScalar>::epsilon()*diag(i) <<
"\n";
1174 eigen_internal_assert(abs(diag(i) - diag(i-1))<epsilon_coarse &&
" diagonal entries are not properly sorted");
1175 deflation44(firstCol, firstCol + shift, firstRowW, firstColW, i-1, i, length);
1179 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
1180 for(Index j=2;j<length;++j)
1181 assert(diag(j-1)<=diag(j) || diag(j)==0);
1184 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
1185 assert(m_naiveU.allFinite());
1186 assert(m_naiveV.allFinite());
1187 assert(m_computed.allFinite());
1198 template<
typename Derived>
1199 BDCSVD<typename MatrixBase<Derived>::PlainObject>
BDCSVD & compute(const MatrixType &matrix)
Method performing the decomposition of given matrix using current options.
Definition: BDCSVD.h:149
Definition: Constants.h:383
const SingularValuesType & singularValues() const
Definition: SVDBase.h:111
Eigen::Index Index
Definition: SVDBase.h:56
bool computeV() const
Definition: SVDBase.h:191
BDCSVD< PlainObject > bdcSvd(unsigned int computationOptions=0) const
Definition: BDCSVD.h:1200
BDCSVD(Index rows, Index cols, unsigned int computationOptions=0)
Default Constructor with memory preallocation.
Definition: BDCSVD.h:105
BDCSVD & compute(const MatrixType &matrix, unsigned int computationOptions)
Method performing the decomposition of given matrix using custom options.
Definition: BDCSVD.h:225
const MatrixVType & matrixV() const
Definition: SVDBase.h:99
BDCSVD(const MatrixType &matrix, unsigned int computationOptions=0)
Constructor performing the decomposition of given matrix.
Definition: BDCSVD.h:121
const MatrixUType & matrixU() const
Definition: SVDBase.h:83
bool computeU() const
Definition: SVDBase.h:189
class Bidiagonal Divide and Conquer SVD
Definition: ForwardDeclarations.h:256
Index nonzeroSingularValues() const
Definition: SVDBase.h:118
Definition: Eigen_Colamd.h:54
BDCSVD()
Default Constructor.
Definition: BDCSVD.h:95
Two-sided Jacobi SVD decomposition of a rectangular matrix.
Definition: ForwardDeclarations.h:255
Definition: Constants.h:235
Definition: Constants.h:387
The matrix class, also used for vectors and row-vectors.
Definition: Matrix.h:178
const AdjointReturnType adjoint() const
Definition: Transpose.h:204