20 #ifndef EIGEN_BDCSVD_H
21 #define EIGEN_BDCSVD_H
27 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
28 IOFormat bdcsvdfmt(8, 0,
", ",
"\n",
" [",
"]");
31 template<
typename _MatrixType>
class BDCSVD;
35 template<
typename _MatrixType>
36 struct traits<BDCSVD<_MatrixType> >
38 typedef _MatrixType MatrixType;
66 template<
typename _MatrixType>
67 class BDCSVD :
public SVDBase<BDCSVD<_MatrixType> >
69 typedef SVDBase<BDCSVD> Base;
77 typedef _MatrixType MatrixType;
78 typedef typename MatrixType::Scalar Scalar;
79 typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
80 typedef typename NumTraits<RealScalar>::Literal Literal;
82 RowsAtCompileTime = MatrixType::RowsAtCompileTime,
83 ColsAtCompileTime = MatrixType::ColsAtCompileTime,
84 DiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime, ColsAtCompileTime),
85 MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
86 MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
87 MaxDiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(MaxRowsAtCompileTime, MaxColsAtCompileTime),
88 MatrixOptions = MatrixType::Options
91 typedef typename Base::MatrixUType MatrixUType;
92 typedef typename Base::MatrixVType MatrixVType;
93 typedef typename Base::SingularValuesType SingularValuesType;
95 typedef Matrix<Scalar, Dynamic, Dynamic, ColMajor> MatrixX;
96 typedef Matrix<RealScalar, Dynamic, Dynamic, ColMajor> MatrixXr;
97 typedef Matrix<RealScalar, Dynamic, 1> VectorType;
98 typedef Array<RealScalar, Dynamic, 1> ArrayXr;
99 typedef Array<Index,1,Dynamic> ArrayXi;
100 typedef Ref<ArrayXr> ArrayRef;
101 typedef Ref<ArrayXi> IndicesRef;
119 : m_algoswap(16), m_numIters(0)
121 allocate(rows, cols, computationOptions);
134 BDCSVD(
const MatrixType& matrix,
unsigned int computationOptions = 0)
135 : m_algoswap(16), m_numIters(0)
137 compute(matrix, computationOptions);
154 BDCSVD&
compute(
const MatrixType& matrix,
unsigned int computationOptions);
164 return compute(matrix, this->m_computationOptions);
167 void setSwitchSize(
int s)
169 eigen_assert(s>3 &&
"BDCSVD the size of the algo switch has to be greater than 3");
174 void allocate(
Index rows,
Index cols,
unsigned int computationOptions);
176 void computeSVDofM(
Index firstCol,
Index n, MatrixXr& U, VectorType& singVals, MatrixXr& V);
177 void computeSingVals(
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef& perm, VectorType& singVals, ArrayRef shifts, ArrayRef mus);
178 void perturbCol0(
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef& perm,
const VectorType& singVals,
const ArrayRef& shifts,
const ArrayRef& mus, ArrayRef zhat);
179 void computeSingVecs(
const ArrayRef& zhat,
const ArrayRef& diag,
const IndicesRef& perm,
const VectorType& singVals,
const ArrayRef& shifts,
const ArrayRef& mus, MatrixXr& U, MatrixXr& V);
183 template<
typename HouseholderU,
typename HouseholderV,
typename NaiveU,
typename NaiveV>
184 void copyUV(
const HouseholderU &householderU,
const HouseholderV &householderV,
const NaiveU &naiveU,
const NaiveV &naivev);
185 void structured_update(Block<MatrixXr,Dynamic,Dynamic> A,
const MatrixXr &B,
Index n1);
186 static RealScalar secularEq(RealScalar x,
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef &perm,
const ArrayRef& diagShifted, RealScalar shift);
189 MatrixXr m_naiveU, m_naiveV;
193 ArrayXi m_workspaceI;
195 bool m_isTranspose, m_compU, m_compV;
197 using Base::m_singularValues;
198 using Base::m_diagSize;
199 using Base::m_computeFullU;
200 using Base::m_computeFullV;
201 using Base::m_computeThinU;
202 using Base::m_computeThinV;
203 using Base::m_matrixU;
204 using Base::m_matrixV;
205 using Base::m_isInitialized;
206 using Base::m_nonzeroSingularValues;
214 template<
typename MatrixType>
215 void BDCSVD<MatrixType>::allocate(
Index rows,
Index cols,
unsigned int computationOptions)
217 m_isTranspose = (cols > rows);
219 if (Base::allocate(rows, cols, computationOptions))
222 m_computed = MatrixXr::Zero(m_diagSize + 1, m_diagSize );
223 m_compU = computeV();
224 m_compV = computeU();
226 std::swap(m_compU, m_compV);
228 if (m_compU) m_naiveU = MatrixXr::Zero(m_diagSize + 1, m_diagSize + 1 );
229 else m_naiveU = MatrixXr::Zero(2, m_diagSize + 1 );
231 if (m_compV) m_naiveV = MatrixXr::Zero(m_diagSize, m_diagSize);
233 m_workspace.resize((m_diagSize+1)*(m_diagSize+1)*3);
234 m_workspaceI.resize(3*m_diagSize);
237 template<
typename MatrixType>
240 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
241 std::cout <<
"\n\n\n======================================================================================================================\n\n\n";
243 allocate(matrix.rows(), matrix.cols(), computationOptions);
246 const RealScalar considerZero = (std::numeric_limits<RealScalar>::min)();
249 if(matrix.cols() < m_algoswap)
253 if(computeU()) m_matrixU = jsvd.matrixU();
254 if(computeV()) m_matrixV = jsvd.matrixV();
255 m_singularValues = jsvd.singularValues();
256 m_nonzeroSingularValues = jsvd.nonzeroSingularValues();
257 m_isInitialized =
true;
262 RealScalar scale = matrix.cwiseAbs().maxCoeff();
263 if(scale==Literal(0)) scale = Literal(1);
265 if (m_isTranspose) copy = matrix.
adjoint()/scale;
266 else copy = matrix/scale;
270 internal::UpperBidiagonalization<MatrixX> bid(copy);
276 m_computed.topRows(m_diagSize) = bid.bidiagonal().toDenseMatrix().transpose();
277 m_computed.template bottomRows<1>().setZero();
278 divide(0, m_diagSize - 1, 0, 0, 0);
281 for (
int i=0; i<m_diagSize; i++)
283 RealScalar a =
abs(m_computed.coeff(i, i));
284 m_singularValues.coeffRef(i) = a * scale;
287 m_nonzeroSingularValues = i;
288 m_singularValues.tail(m_diagSize - i - 1).setZero();
291 else if (i == m_diagSize - 1)
293 m_nonzeroSingularValues = i + 1;
298 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
302 if(m_isTranspose) copyUV(bid.householderV(), bid.householderU(), m_naiveV, m_naiveU);
303 else copyUV(bid.householderU(), bid.householderV(), m_naiveU, m_naiveV);
305 m_isInitialized =
true;
310 template<
typename MatrixType>
311 template<
typename HouseholderU,
typename HouseholderV,
typename NaiveU,
typename NaiveV>
312 void BDCSVD<MatrixType>::copyUV(
const HouseholderU &householderU,
const HouseholderV &householderV,
const NaiveU &naiveU,
const NaiveV &naiveV)
317 Index Ucols = m_computeThinU ? m_diagSize : householderU.cols();
318 m_matrixU = MatrixX::Identity(householderU.cols(), Ucols);
319 m_matrixU.topLeftCorner(m_diagSize, m_diagSize) = naiveV.template cast<Scalar>().topLeftCorner(m_diagSize, m_diagSize);
320 householderU.applyThisOnTheLeft(m_matrixU);
324 Index Vcols = m_computeThinV ? m_diagSize : householderV.cols();
325 m_matrixV = MatrixX::Identity(householderV.cols(), Vcols);
326 m_matrixV.topLeftCorner(m_diagSize, m_diagSize) = naiveU.template cast<Scalar>().topLeftCorner(m_diagSize, m_diagSize);
327 householderV.applyThisOnTheLeft(m_matrixV);
339 template<
typename MatrixType>
340 void BDCSVD<MatrixType>::structured_update(Block<MatrixXr,Dynamic,Dynamic> A,
const MatrixXr &B,
Index n1)
348 Map<MatrixXr> A1(m_workspace.data() , n1, n);
349 Map<MatrixXr> A2(m_workspace.data()+ n1*n, n2, n);
350 Map<MatrixXr> B1(m_workspace.data()+ n*n, n, n);
351 Map<MatrixXr> B2(m_workspace.data()+2*n*n, n, n);
353 for(
Index j=0; j<n; ++j)
355 if( (A.col(j).head(n1).array()!=Literal(0)).any() )
357 A1.col(k1) = A.col(j).head(n1);
358 B1.row(k1) = B.row(j);
361 if( (A.col(j).tail(n2).array()!=Literal(0)).any() )
363 A2.col(k2) = A.col(j).tail(n2);
364 B2.row(k2) = B.row(j);
369 A.topRows(n1).noalias() = A1.leftCols(k1) * B1.topRows(k1);
370 A.bottomRows(n2).noalias() = A2.leftCols(k2) * B2.topRows(k2);
374 Map<MatrixXr,Aligned> tmp(m_workspace.data(),n,n);
390 template<
typename MatrixType>
397 const Index n = lastCol - firstCol + 1;
399 const RealScalar considerZero = (std::numeric_limits<RealScalar>::min)();
403 RealScalar lambda, phi, c0, s0;
412 m_naiveU.block(firstCol, firstCol, n + 1, n + 1).real() = b.matrixU();
415 m_naiveU.row(0).segment(firstCol, n + 1).real() = b.matrixU().row(0);
416 m_naiveU.row(1).segment(firstCol, n + 1).real() = b.matrixU().row(n);
418 if (m_compV) m_naiveV.block(firstRowW, firstColW, n, n).real() = b.matrixV();
419 m_computed.block(firstCol + shift, firstCol + shift, n + 1, n).setZero();
420 m_computed.diagonal().segment(firstCol + shift, n) = b.singularValues().head(n);
424 alphaK = m_computed(firstCol + k, firstCol + k);
425 betaK = m_computed(firstCol + k + 1, firstCol + k);
429 divide(k + 1 + firstCol, lastCol, k + 1 + firstRowW, k + 1 + firstColW, shift);
430 divide(firstCol, k - 1 + firstCol, firstRowW, firstColW + 1, shift + 1);
434 lambda = m_naiveU(firstCol + k, firstCol + k);
435 phi = m_naiveU(firstCol + k + 1, lastCol + 1);
439 lambda = m_naiveU(1, firstCol + k);
440 phi = m_naiveU(0, lastCol + 1);
442 r0 =
sqrt((
abs(alphaK * lambda) *
abs(alphaK * lambda)) +
abs(betaK * phi) *
abs(betaK * phi));
445 l = m_naiveU.row(firstCol + k).segment(firstCol, k);
446 f = m_naiveU.row(firstCol + k + 1).segment(firstCol + k + 1, n - k - 1);
450 l = m_naiveU.row(1).segment(firstCol, k);
451 f = m_naiveU.row(0).segment(firstCol + k + 1, n - k - 1);
453 if (m_compV) m_naiveV(firstRowW+k, firstColW) = Literal(1);
461 c0 = alphaK * lambda / r0;
462 s0 = betaK * phi / r0;
465 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
466 assert(m_naiveU.allFinite());
467 assert(m_naiveV.allFinite());
468 assert(m_computed.allFinite());
473 MatrixXr q1 (m_naiveU.col(firstCol + k).segment(firstCol, k + 1));
475 for (
Index i = firstCol + k - 1; i >= firstCol; i--)
476 m_naiveU.col(i + 1).segment(firstCol, k + 1) = m_naiveU.col(i).segment(firstCol, k + 1);
478 m_naiveU.col(firstCol).segment( firstCol, k + 1) = (q1 * c0);
480 m_naiveU.col(lastCol + 1).segment(firstCol, k + 1) = (q1 * ( - s0));
482 m_naiveU.col(firstCol).segment(firstCol + k + 1, n - k) = m_naiveU.col(lastCol + 1).segment(firstCol + k + 1, n - k) * s0;
484 m_naiveU.col(lastCol + 1).segment(firstCol + k + 1, n - k) *= c0;
488 RealScalar q1 = m_naiveU(0, firstCol + k);
490 for (
Index i = firstCol + k - 1; i >= firstCol; i--)
491 m_naiveU(0, i + 1) = m_naiveU(0, i);
493 m_naiveU(0, firstCol) = (q1 * c0);
495 m_naiveU(0, lastCol + 1) = (q1 * ( - s0));
497 m_naiveU(1, firstCol) = m_naiveU(1, lastCol + 1) *s0;
499 m_naiveU(1, lastCol + 1) *= c0;
500 m_naiveU.row(1).segment(firstCol + 1, k).setZero();
501 m_naiveU.row(0).segment(firstCol + k + 1, n - k - 1).setZero();
504 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
505 assert(m_naiveU.allFinite());
506 assert(m_naiveV.allFinite());
507 assert(m_computed.allFinite());
510 m_computed(firstCol + shift, firstCol + shift) = r0;
511 m_computed.col(firstCol + shift).segment(firstCol + shift + 1, k) = alphaK * l.transpose().real();
512 m_computed.col(firstCol + shift).segment(firstCol + shift + k + 1, n - k - 1) = betaK * f.transpose().real();
514 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
515 ArrayXr tmp1 = (m_computed.block(firstCol+shift, firstCol+shift, n, n)).jacobiSvd().singularValues();
518 deflation(firstCol, lastCol, k, firstRowW, firstColW, shift);
519 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
520 ArrayXr tmp2 = (m_computed.block(firstCol+shift, firstCol+shift, n, n)).jacobiSvd().singularValues();
521 std::cout <<
"\n\nj1 = " << tmp1.transpose().format(bdcsvdfmt) <<
"\n";
522 std::cout <<
"j2 = " << tmp2.transpose().format(bdcsvdfmt) <<
"\n\n";
523 std::cout <<
"err: " << ((tmp1-tmp2).
abs()>1e-12*tmp2.abs()).transpose() <<
"\n";
524 static int count = 0;
525 std::cout <<
"# " << ++count <<
"\n\n";
526 assert((tmp1-tmp2).matrix().norm() < 1e-14*tmp2.matrix().norm());
532 MatrixXr UofSVD, VofSVD;
534 computeSVDofM(firstCol + shift, n, UofSVD, singVals, VofSVD);
536 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
537 assert(UofSVD.allFinite());
538 assert(VofSVD.allFinite());
542 structured_update(m_naiveU.block(firstCol, firstCol, n + 1, n + 1), UofSVD, (n+2)/2);
545 Map<Matrix<RealScalar,2,Dynamic>,
Aligned> tmp(m_workspace.data(),2,n+1);
546 tmp.noalias() = m_naiveU.middleCols(firstCol, n+1) * UofSVD;
547 m_naiveU.middleCols(firstCol, n + 1) = tmp;
550 if (m_compV) structured_update(m_naiveV.block(firstRowW, firstColW, n, n), VofSVD, (n+1)/2);
552 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
553 assert(m_naiveU.allFinite());
554 assert(m_naiveV.allFinite());
555 assert(m_computed.allFinite());
558 m_computed.block(firstCol + shift, firstCol + shift, n, n).setZero();
559 m_computed.block(firstCol + shift, firstCol + shift, n, n).diagonal() = singVals;
570 template <
typename MatrixType>
571 void BDCSVD<MatrixType>::computeSVDofM(
Index firstCol,
Index n, MatrixXr& U, VectorType& singVals, MatrixXr& V)
573 const RealScalar considerZero = (std::numeric_limits<RealScalar>::min)();
575 ArrayRef col0 = m_computed.col(firstCol).segment(firstCol, n);
576 m_workspace.head(n) = m_computed.block(firstCol, firstCol, n, n).diagonal();
577 ArrayRef diag = m_workspace.head(n);
578 diag(0) = Literal(0);
583 if (m_compV) V.resize(n, n);
585 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
586 if (col0.hasNaN() || diag.hasNaN())
587 std::cout <<
"\n\nHAS NAN\n\n";
594 while(actual_n>1 && diag(actual_n-1)==Literal(0)) --actual_n;
596 for(
Index k=0;k<actual_n;++k)
597 if(
abs(col0(k))>considerZero)
598 m_workspaceI(m++) = k;
599 Map<ArrayXi> perm(m_workspaceI.data(),m);
601 Map<ArrayXr> shifts(m_workspace.data()+1*n, n);
602 Map<ArrayXr> mus(m_workspace.data()+2*n, n);
603 Map<ArrayXr> zhat(m_workspace.data()+3*n, n);
605 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
606 std::cout <<
"computeSVDofM using:\n";
607 std::cout <<
" z: " << col0.transpose() <<
"\n";
608 std::cout <<
" d: " << diag.transpose() <<
"\n";
612 computeSingVals(col0, diag, perm, singVals, shifts, mus);
614 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
615 std::cout <<
" j: " << (m_computed.block(firstCol, firstCol, n, n)).jacobiSvd().singularValues().transpose().reverse() <<
"\n\n";
616 std::cout <<
" sing-val: " << singVals.transpose() <<
"\n";
617 std::cout <<
" mu: " << mus.transpose() <<
"\n";
618 std::cout <<
" shift: " << shifts.transpose() <<
"\n";
622 while(actual_n>1 &&
abs(col0(actual_n-1))<considerZero) --actual_n;
623 std::cout <<
"\n\n mus: " << mus.head(actual_n).transpose() <<
"\n\n";
624 std::cout <<
" check1 (expect0) : " << ((singVals.array()-(shifts+mus)) / singVals.array()).head(actual_n).transpose() <<
"\n\n";
625 std::cout <<
" check2 (>0) : " << ((singVals.array()-diag) / singVals.array()).head(actual_n).transpose() <<
"\n\n";
626 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";
627 std::cout <<
" check4 (>0) : " << ((singVals.segment(1,actual_n-1)-singVals.head(actual_n-1))).transpose() <<
"\n\n\n";
631 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
632 assert(singVals.allFinite());
633 assert(mus.allFinite());
634 assert(shifts.allFinite());
638 perturbCol0(col0, diag, perm, singVals, shifts, mus, zhat);
639 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
640 std::cout <<
" zhat: " << zhat.transpose() <<
"\n";
643 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
644 assert(zhat.allFinite());
647 computeSingVecs(zhat, diag, perm, singVals, shifts, mus, U, V);
649 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
650 std::cout <<
"U^T U: " << (U.transpose() * U - MatrixXr(MatrixXr::Identity(U.cols(),U.cols()))).norm() <<
"\n";
651 std::cout <<
"V^T V: " << (V.transpose() * V - MatrixXr(MatrixXr::Identity(V.cols(),V.cols()))).norm() <<
"\n";
654 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
655 assert(U.allFinite());
656 assert(V.allFinite());
657 assert((U.transpose() * U - MatrixXr(MatrixXr::Identity(U.cols(),U.cols()))).norm() < 1e-14 * n);
658 assert((V.transpose() * V - MatrixXr(MatrixXr::Identity(V.cols(),V.cols()))).norm() < 1e-14 * n);
659 assert(m_naiveU.allFinite());
660 assert(m_naiveV.allFinite());
661 assert(m_computed.allFinite());
666 for(
Index i=0; i<actual_n-1; ++i)
668 if(singVals(i)>singVals(i+1))
671 swap(singVals(i),singVals(i+1));
672 U.col(i).swap(U.col(i+1));
673 if(m_compV) V.col(i).swap(V.col(i+1));
679 singVals.head(actual_n).reverseInPlace();
680 U.leftCols(actual_n).rowwise().reverseInPlace();
681 if (m_compV) V.leftCols(actual_n).rowwise().reverseInPlace();
683 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
684 JacobiSVD<MatrixXr> jsvd(m_computed.block(firstCol, firstCol, n, n) );
685 std::cout <<
" * j: " << jsvd.singularValues().transpose() <<
"\n\n";
686 std::cout <<
" * sing-val: " << singVals.transpose() <<
"\n";
691 template <
typename MatrixType>
692 typename BDCSVD<MatrixType>::RealScalar BDCSVD<MatrixType>::secularEq(RealScalar mu,
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef &perm,
const ArrayRef& diagShifted, RealScalar shift)
694 Index m = perm.size();
695 RealScalar res = Literal(1);
696 for(
Index i=0; i<m; ++i)
701 res += (col0(j) / (diagShifted(j) - mu)) * (col0(j) / (diag(j) + shift + mu));
707 template <
typename MatrixType>
708 void BDCSVD<MatrixType>::computeSingVals(
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef &perm,
709 VectorType& singVals, ArrayRef shifts, ArrayRef mus)
715 Index n = col0.size();
719 while(actual_n>1 && col0(actual_n-1)==Literal(0)) --actual_n;
721 for (
Index k = 0; k < n; ++k)
723 if (col0(k) == Literal(0) || actual_n==1)
727 singVals(k) = k==0 ? col0(0) : diag(k);
729 shifts(k) = k==0 ? col0(0) : diag(k);
734 RealScalar left = diag(k);
737 right = (diag(actual_n-1) + col0.matrix().norm());
744 while(col0(l)==Literal(0)) { ++l; eigen_internal_assert(l<actual_n); }
749 RealScalar mid = left + (right-left) / Literal(2);
750 RealScalar fMid = secularEq(mid, col0, diag, perm, diag, Literal(0));
751 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
752 std::cout << right-left <<
"\n";
753 std::cout <<
"fMid = " << fMid <<
" " << secularEq(mid-left, col0, diag, perm, diag-left, left) <<
" " << secularEq(mid-right, col0, diag, perm, diag-right, right) <<
"\n";
754 std::cout <<
" = " << secularEq(0.1*(left+right), col0, diag, perm, diag, 0)
755 <<
" " << secularEq(0.2*(left+right), col0, diag, perm, diag, 0)
756 <<
" " << secularEq(0.3*(left+right), col0, diag, perm, diag, 0)
757 <<
" " << secularEq(0.4*(left+right), col0, diag, perm, diag, 0)
758 <<
" " << secularEq(0.49*(left+right), col0, diag, perm, diag, 0)
759 <<
" " << secularEq(0.5*(left+right), col0, diag, perm, diag, 0)
760 <<
" " << secularEq(0.51*(left+right), col0, diag, perm, diag, 0)
761 <<
" " << secularEq(0.6*(left+right), col0, diag, perm, diag, 0)
762 <<
" " << secularEq(0.7*(left+right), col0, diag, perm, diag, 0)
763 <<
" " << secularEq(0.8*(left+right), col0, diag, perm, diag, 0)
764 <<
" " << secularEq(0.9*(left+right), col0, diag, perm, diag, 0) <<
"\n";
766 RealScalar shift = (k == actual_n-1 || fMid > Literal(0)) ? left : right;
769 Map<ArrayXr> diagShifted(m_workspace.data()+4*n, n);
770 diagShifted = diag - shift;
775 RealScalar midShifted = (right - left) / RealScalar(2);
777 midShifted = -midShifted;
778 RealScalar fMidShifted = secularEq(midShifted, col0, diag, perm, diagShifted, shift);
782 shift = fMidShifted > Literal(0) ? left : right;
783 diagShifted = diag - shift;
788 RealScalar muPrev, muCur;
791 muPrev = (right - left) * RealScalar(0.1);
792 if (k == actual_n-1) muCur = right - left;
793 else muCur = (right - left) * RealScalar(0.5);
797 muPrev = -(right - left) * RealScalar(0.1);
798 muCur = -(right - left) * RealScalar(0.5);
801 RealScalar fPrev = secularEq(muPrev, col0, diag, perm, diagShifted, shift);
802 RealScalar fCur = secularEq(muCur, col0, diag, perm, diagShifted, shift);
803 if (
abs(fPrev) <
abs(fCur))
811 bool useBisection = fPrev*fCur>Literal(0);
812 while (fCur!=Literal(0) &&
abs(muCur - muPrev) > Literal(8) * NumTraits<RealScalar>::epsilon() * numext::maxi<RealScalar>(
abs(muCur),
abs(muPrev)) &&
abs(fCur - fPrev)>NumTraits<RealScalar>::epsilon() && !useBisection)
817 RealScalar a = (fCur - fPrev) / (Literal(1)/muCur - Literal(1)/muPrev);
818 RealScalar b = fCur - a / muCur;
820 RealScalar muZero = -a/b;
821 RealScalar fZero = secularEq(muZero, col0, diag, perm, diagShifted, shift);
829 if (shift == left && (muCur < Literal(0) || muCur > right - left)) useBisection =
true;
830 if (shift == right && (muCur < -(right - left) || muCur > Literal(0))) useBisection =
true;
831 if (
abs(fCur)>
abs(fPrev)) useBisection =
true;
837 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
838 std::cout <<
"useBisection for k = " << k <<
", actual_n = " << actual_n <<
"\n";
840 RealScalar leftShifted, rightShifted;
845 leftShifted = numext::maxi<RealScalar>( (std::numeric_limits<RealScalar>::min)(), Literal(2) *
abs(col0(k)) /
sqrt((std::numeric_limits<RealScalar>::max)()) );
848 eigen_internal_assert( (numext::isfinite)( (col0(k)/leftShifted)*(col0(k)/(diag(k)+shift+leftShifted)) ) );
851 rightShifted = (k==actual_n-1) ? right : ((right - left) * RealScalar(0.51));
855 leftShifted = -(right - left) * RealScalar(0.51);
857 rightShifted = -numext::maxi<RealScalar>( (std::numeric_limits<RealScalar>::min)(),
abs(col0(k+1)) /
sqrt((std::numeric_limits<RealScalar>::max)()) );
859 rightShifted = -(std::numeric_limits<RealScalar>::min)();
862 RealScalar fLeft = secularEq(leftShifted, col0, diag, perm, diagShifted, shift);
863 eigen_internal_assert(fLeft<Literal(0));
865 #if defined EIGEN_INTERNAL_DEBUGGING || defined EIGEN_BDCSVD_DEBUG_VERBOSE
866 RealScalar fRight = secularEq(rightShifted, col0, diag, perm, diagShifted, shift);
870 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
871 if(!(fLeft * fRight<0))
873 std::cout <<
"fLeft: " << leftShifted <<
" - " << diagShifted.head(10).transpose() <<
"\n ; " << bool(left==shift) <<
" " << (left-shift) <<
"\n";
874 std::cout << k <<
" : " << fLeft <<
" * " << fRight <<
" == " << fLeft * fRight <<
" ; " << left <<
" - " << right <<
" -> " << leftShifted <<
" " << rightShifted <<
" shift=" << shift <<
"\n";
877 eigen_internal_assert(fLeft * fRight < Literal(0));
881 while (rightShifted - leftShifted > Literal(2) * NumTraits<RealScalar>::epsilon() * numext::maxi<RealScalar>(
abs(leftShifted),
abs(rightShifted)))
883 RealScalar midShifted = (leftShifted + rightShifted) / Literal(2);
884 fMid = secularEq(midShifted, col0, diag, perm, diagShifted, shift);
885 eigen_internal_assert((numext::isfinite)(fMid));
887 if (fLeft * fMid < Literal(0))
889 rightShifted = midShifted;
893 leftShifted = midShifted;
897 muCur = (leftShifted + rightShifted) / Literal(2);
905 muCur = (right - left) * RealScalar(0.5);
911 singVals[k] = shift + muCur;
925 template <
typename MatrixType>
926 void BDCSVD<MatrixType>::perturbCol0
927 (
const ArrayRef& col0,
const ArrayRef& diag,
const IndicesRef &perm,
const VectorType& singVals,
928 const ArrayRef& shifts,
const ArrayRef& mus, ArrayRef zhat)
931 Index n = col0.size();
932 Index m = perm.size();
938 Index last = perm(m-1);
940 for (
Index k = 0; k < n; ++k)
942 if (col0(k) == Literal(0))
943 zhat(k) = Literal(0);
947 RealScalar dk = diag(k);
948 RealScalar prod = (singVals(last) + dk) * (mus(last) + (shifts(last) - dk));
950 for(
Index l = 0; l<m; ++l)
955 Index j = i<k ? i : perm(l-1);
956 prod *= ((singVals(j)+dk) / ((diag(i)+dk))) * ((mus(j)+(shifts(j)-dk)) / ((diag(i)-dk)));
957 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
958 if(i!=k && numext::abs(((singVals(j)+dk)*(mus(j)+(shifts(j)-dk)))/((diag(i)+dk)*(diag(i)-dk)) - 1) > 0.9 )
959 std::cout <<
" " << ((singVals(j)+dk)*(mus(j)+(shifts(j)-dk)))/((diag(i)+dk)*(diag(i)-dk)) <<
" == (" << (singVals(j)+dk) <<
" * " << (mus(j)+(shifts(j)-dk))
960 <<
") / (" << (diag(i)+dk) <<
" * " << (diag(i)-dk) <<
")\n";
964 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
965 std::cout <<
"zhat(" << k <<
") = sqrt( " << prod <<
") ; " << (singVals(last) + dk) <<
" * " << mus(last) + shifts(last) <<
" - " << dk <<
"\n";
967 RealScalar tmp =
sqrt(prod);
968 zhat(k) = col0(k) > Literal(0) ? RealScalar(tmp) : RealScalar(-tmp);
974 template <
typename MatrixType>
975 void BDCSVD<MatrixType>::computeSingVecs
976 (
const ArrayRef& zhat,
const ArrayRef& diag,
const IndicesRef &perm,
const VectorType& singVals,
977 const ArrayRef& shifts,
const ArrayRef& mus, MatrixXr& U, MatrixXr& V)
979 Index n = zhat.size();
980 Index m = perm.size();
982 for (
Index k = 0; k < n; ++k)
984 if (zhat(k) == Literal(0))
986 U.col(k) = VectorType::Unit(n+1, k);
987 if (m_compV) V.col(k) = VectorType::Unit(n, k);
992 for(
Index l=0;l<m;++l)
995 U(i,k) = zhat(i)/(((diag(i) - shifts(k)) - mus(k)) )/( (diag(i) + singVals[k]));
998 U.col(k).normalize();
1003 for(
Index l=1;l<m;++l)
1006 V(i,k) = diag(i) * zhat(i) / (((diag(i) - shifts(k)) - mus(k)) )/( (diag(i) + singVals[k]));
1008 V(0,k) = Literal(-1);
1009 V.col(k).normalize();
1013 U.col(n) = VectorType::Unit(n+1, n);
1020 template <
typename MatrixType>
1026 Index start = firstCol + shift;
1027 RealScalar c = m_computed(start, start);
1028 RealScalar s = m_computed(start+i, start);
1029 RealScalar r = numext::hypot(c,s);
1030 if (r == Literal(0))
1032 m_computed(start+i, start+i) = Literal(0);
1035 m_computed(start,start) = r;
1036 m_computed(start+i, start) = Literal(0);
1037 m_computed(start+i, start+i) = Literal(0);
1039 JacobiRotation<RealScalar> J(c/r,-s/r);
1040 if (m_compU) m_naiveU.middleRows(firstCol, size+1).applyOnTheRight(firstCol, firstCol+i, J);
1041 else m_naiveU.applyOnTheRight(firstCol, firstCol+i, J);
1049 template <
typename MatrixType>
1056 RealScalar c = m_computed(firstColm+i, firstColm);
1057 RealScalar s = m_computed(firstColm+j, firstColm);
1058 RealScalar r =
sqrt(numext::abs2(c) + numext::abs2(s));
1059 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1060 std::cout <<
"deflation 4.4: " << i <<
"," << j <<
" -> " << c <<
" " << s <<
" " << r <<
" ; "
1061 << m_computed(firstColm + i-1, firstColm) <<
" "
1062 << m_computed(firstColm + i, firstColm) <<
" "
1063 << m_computed(firstColm + i+1, firstColm) <<
" "
1064 << m_computed(firstColm + i+2, firstColm) <<
"\n";
1065 std::cout << m_computed(firstColm + i-1, firstColm + i-1) <<
" "
1066 << m_computed(firstColm + i, firstColm+i) <<
" "
1067 << m_computed(firstColm + i+1, firstColm+i+1) <<
" "
1068 << m_computed(firstColm + i+2, firstColm+i+2) <<
"\n";
1072 m_computed(firstColm + i, firstColm + i) = m_computed(firstColm + j, firstColm + j);
1077 m_computed(firstColm + i, firstColm) = r;
1078 m_computed(firstColm + j, firstColm + j) = m_computed(firstColm + i, firstColm + i);
1079 m_computed(firstColm + j, firstColm) = Literal(0);
1081 JacobiRotation<RealScalar> J(c,-s);
1082 if (m_compU) m_naiveU.middleRows(firstColu, size+1).applyOnTheRight(firstColu + i, firstColu + j, J);
1083 else m_naiveU.applyOnTheRight(firstColu+i, firstColu+j, J);
1084 if (m_compV) m_naiveV.middleRows(firstRowW, size).applyOnTheRight(firstColW + i, firstColW + j, J);
1089 template <
typename MatrixType>
1094 const Index length = lastCol + 1 - firstCol;
1096 Block<MatrixXr,Dynamic,1> col0(m_computed, firstCol+shift, firstCol+shift, length, 1);
1097 Diagonal<MatrixXr> fulldiag(m_computed);
1098 VectorBlock<Diagonal<MatrixXr>,
Dynamic> diag(fulldiag, firstCol+shift, length);
1100 const RealScalar considerZero = (std::numeric_limits<RealScalar>::min)();
1101 RealScalar maxDiag = diag.tail((std::max)(
Index(1),length-1)).cwiseAbs().maxCoeff();
1102 RealScalar epsilon_strict = numext::maxi<RealScalar>(considerZero,NumTraits<RealScalar>::epsilon() * maxDiag);
1103 RealScalar epsilon_coarse = Literal(8) * NumTraits<RealScalar>::epsilon() * numext::maxi<RealScalar>(col0.cwiseAbs().maxCoeff(), maxDiag);
1105 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
1106 assert(m_naiveU.allFinite());
1107 assert(m_naiveV.allFinite());
1108 assert(m_computed.allFinite());
1111 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1112 std::cout <<
"\ndeflate:" << diag.head(k+1).transpose() <<
" | " << diag.segment(k+1,length-k-1).transpose() <<
"\n";
1116 if (diag(0) < epsilon_coarse)
1118 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1119 std::cout <<
"deflation 4.1, because " << diag(0) <<
" < " << epsilon_coarse <<
"\n";
1121 diag(0) = epsilon_coarse;
1125 for (
Index i=1;i<length;++i)
1126 if (
abs(col0(i)) < epsilon_strict)
1128 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1129 std::cout <<
"deflation 4.2, set z(" << i <<
") to zero because " <<
abs(col0(i)) <<
" < " << epsilon_strict <<
" (diag(" << i <<
")=" << diag(i) <<
")\n";
1131 col0(i) = Literal(0);
1135 for (
Index i=1;i<length; i++)
1136 if (diag(i) < epsilon_coarse)
1138 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1139 std::cout <<
"deflation 4.3, cancel z(" << i <<
")=" << col0(i) <<
" because diag(" << i <<
")=" << diag(i) <<
" < " << epsilon_coarse <<
"\n";
1141 deflation43(firstCol, shift, i, length);
1144 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
1145 assert(m_naiveU.allFinite());
1146 assert(m_naiveV.allFinite());
1147 assert(m_computed.allFinite());
1149 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1150 std::cout <<
"to be sorted: " << diag.transpose() <<
"\n\n";
1155 bool total_deflation = (col0.tail(length-1).array()<considerZero).all();
1159 Index *permutation = m_workspaceI.data();
1165 for(
Index i=1; i<length; ++i)
1166 if(
abs(diag(i))<considerZero)
1167 permutation[p++] = i;
1170 for( ; p < length; ++p)
1172 if (i > k) permutation[p] = j++;
1173 else if (j >= length) permutation[p] = i++;
1174 else if (diag(i) < diag(j)) permutation[p] = j++;
1175 else permutation[p] = i++;
1182 for(
Index i=1; i<length; ++i)
1184 Index pi = permutation[i];
1185 if(
abs(diag(pi))<considerZero || diag(0)<diag(pi))
1186 permutation[i-1] = permutation[i];
1189 permutation[i-1] = 0;
1196 Index *realInd = m_workspaceI.data()+length;
1197 Index *realCol = m_workspaceI.data()+2*length;
1199 for(
int pos = 0; pos< length; pos++)
1205 for(
Index i = total_deflation?0:1; i < length; i++)
1207 const Index pi = permutation[length - (total_deflation ? i+1 : i)];
1208 const Index J = realCol[pi];
1212 swap(diag(i), diag(J));
1213 if(i!=0 && J!=0) swap(col0(i), col0(J));
1216 if (m_compU) m_naiveU.col(firstCol+i).segment(firstCol, length + 1).swap(m_naiveU.col(firstCol+J).segment(firstCol, length + 1));
1217 else m_naiveU.col(firstCol+i).segment(0, 2) .swap(m_naiveU.col(firstCol+J).segment(0, 2));
1218 if (m_compV) m_naiveV.col(firstColW + i).segment(firstRowW, length).swap(m_naiveV.col(firstColW + J).segment(firstRowW, length));
1221 const Index realI = realInd[i];
1228 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1229 std::cout <<
"sorted: " << diag.transpose().format(bdcsvdfmt) <<
"\n";
1230 std::cout <<
" : " << col0.transpose() <<
"\n\n";
1236 while(i>0 && (
abs(diag(i))<considerZero ||
abs(col0(i))<considerZero)) --i;
1238 if( (diag(i) - diag(i-1)) < NumTraits<RealScalar>::epsilon()*maxDiag )
1240 #ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
1241 std::cout <<
"deflation 4.4 with i = " << i <<
" because " << (diag(i) - diag(i-1)) <<
" < " << NumTraits<RealScalar>::epsilon()*diag(i) <<
"\n";
1243 eigen_internal_assert(
abs(diag(i) - diag(i-1))<epsilon_coarse &&
" diagonal entries are not properly sorted");
1244 deflation44(firstCol, firstCol + shift, firstRowW, firstColW, i-1, i, length);
1248 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
1249 for(
Index j=2;j<length;++j)
1250 assert(diag(j-1)<=diag(j) ||
abs(diag(j))<considerZero);
1253 #ifdef EIGEN_BDCSVD_SANITY_CHECKS
1254 assert(m_naiveU.allFinite());
1255 assert(m_naiveV.allFinite());
1256 assert(m_computed.allFinite());
1267 template<
typename Derived>
1268 BDCSVD<typename MatrixBase<Derived>::PlainObject>