spqr_support.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // This file is part of Eigen, a lightweight C++ template library
  2. // for linear algebra.
  3. //
  4. // Copyright (C) 2012 Desire Nuentsa Wakam <desire.nuentsa_wakam@inria.fr>
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla
  7. // Public License v. 2.0. If a copy of the MPL was not distributed
  8. #define EIGEN_NO_DEBUG_SMALL_PRODUCT_BLOCKS
  9. #include "sparse.h"
  10. #include <Eigen/SPQRSupport>
  11. template<typename MatrixType,typename DenseMat>
  12. int generate_sparse_rectangular_problem(MatrixType& A, DenseMat& dA, int maxRows = 300, int maxCols = 300)
  13. {
  14. eigen_assert(maxRows >= maxCols);
  15. typedef typename MatrixType::Scalar Scalar;
  16. int rows = internal::random<int>(1,maxRows);
  17. int cols = internal::random<int>(1,rows);
  18. double density = (std::max)(8./(rows*cols), 0.01);
  19. A.resize(rows,cols);
  20. dA.resize(rows,cols);
  21. initSparse<Scalar>(density, dA, A,ForceNonZeroDiag);
  22. A.makeCompressed();
  23. return rows;
  24. }
  25. template<typename Scalar> void test_spqr_scalar()
  26. {
  27. typedef SparseMatrix<Scalar,ColMajor> MatrixType;
  28. MatrixType A;
  29. Matrix<Scalar,Dynamic,Dynamic> dA;
  30. typedef Matrix<Scalar,Dynamic,1> DenseVector;
  31. DenseVector refX,x,b;
  32. SPQR<MatrixType> solver;
  33. generate_sparse_rectangular_problem(A,dA);
  34. Index m = A.rows();
  35. b = DenseVector::Random(m);
  36. solver.compute(A);
  37. if (solver.info() != Success)
  38. {
  39. std::cerr << "sparse QR factorization failed\n";
  40. exit(0);
  41. return;
  42. }
  43. x = solver.solve(b);
  44. if (solver.info() != Success)
  45. {
  46. std::cerr << "sparse QR factorization failed\n";
  47. exit(0);
  48. return;
  49. }
  50. //Compare with a dense solver
  51. refX = dA.colPivHouseholderQr().solve(b);
  52. VERIFY(x.isApprox(refX,test_precision<Scalar>()));
  53. }
  54. void test_spqr_support()
  55. {
  56. CALL_SUBTEST_1(test_spqr_scalar<double>());
  57. CALL_SUBTEST_2(test_spqr_scalar<std::complex<double> >());
  58. }