sum.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2016 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "sum.h"
  9. #include "redux.h"
  10. template <typename T>
  11. IGL_INLINE void igl::sum(
  12. const Eigen::SparseMatrix<T>& X,
  13. const int dim,
  14. Eigen::SparseVector<T>& S)
  15. {
  16. assert((dim == 1 || dim == 2) && "dim must be 2 or 1");
  17. // Get size of input
  18. int m = X.rows();
  19. int n = X.cols();
  20. // resize output
  21. if(dim==1)
  22. {
  23. S = Eigen::SparseVector<T>(n);
  24. }else
  25. {
  26. S = Eigen::SparseVector<T>(m);
  27. }
  28. // Iterate over outside
  29. for(int k=0; k<X.outerSize(); ++k)
  30. {
  31. // Iterate over inside
  32. for(typename Eigen::SparseMatrix<T>::InnerIterator it (X,k); it; ++it)
  33. {
  34. if(dim == 1)
  35. {
  36. S.coeffRef(it.col()) += it.value();
  37. }else
  38. {
  39. S.coeffRef(it.row()) += it.value();
  40. }
  41. }
  42. }
  43. }
  44. template <typename AType, typename DerivedB>
  45. IGL_INLINE void igl::sum(
  46. const Eigen::SparseMatrix<AType> & A,
  47. const int dim,
  48. Eigen::PlainObjectBase<DerivedB>& B)
  49. {
  50. typedef typename DerivedB::Scalar Scalar;
  51. igl::redux(A,dim,[](Scalar a, Scalar b){ return a+b;},B);
  52. }
  53. #ifdef IGL_STATIC_LIBRARY
  54. // Explicit template instantiation
  55. // generated by autoexplicit.sh
  56. template void igl::sum<double, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(Eigen::SparseMatrix<double, 0, int> const&, int, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
  57. // generated by autoexplicit.sh
  58. template void igl::sum<bool, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::SparseMatrix<bool, 0, int> const&, int, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
  59. template void igl::sum<double>(Eigen::SparseMatrix<double, 0, int> const&, int, Eigen::SparseVector<double, 0, int>&);
  60. #endif