spop_sum_meat.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
  2. // Copyright 2008-2016 National ICT Australia (NICTA)
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // ------------------------------------------------------------------------
  15. //! \addtogroup spop_sum
  16. //! @{
  17. template<typename T1>
  18. arma_hot
  19. inline
  20. void
  21. spop_sum::apply(SpMat<typename T1::elem_type>& out, const SpOp<T1,spop_sum>& in)
  22. {
  23. arma_extra_debug_sigprint();
  24. typedef typename T1::elem_type eT;
  25. const uword dim = in.aux_uword_a;
  26. arma_debug_check( (dim > 1), "sum(): parameter 'dim' must be 0 or 1" );
  27. const SpProxy<T1> p(in.m);
  28. const uword p_n_rows = p.get_n_rows();
  29. const uword p_n_cols = p.get_n_cols();
  30. if(p.get_n_nonzero() == 0)
  31. {
  32. if(dim == 0) { out.zeros(1,p_n_cols); }
  33. if(dim == 1) { out.zeros(p_n_rows,1); }
  34. return;
  35. }
  36. if(dim == 0) // find the sum in each column
  37. {
  38. Row<eT> acc(p_n_cols, fill::zeros);
  39. eT* acc_mem = acc.memptr();
  40. if(SpProxy<T1>::use_iterator)
  41. {
  42. typename SpProxy<T1>::const_iterator_type it = p.begin();
  43. const uword N = p.get_n_nonzero();
  44. for(uword i=0; i < N; ++i)
  45. {
  46. acc_mem[it.col()] += (*it);
  47. ++it;
  48. }
  49. }
  50. else
  51. {
  52. for(uword col = 0; col < p_n_cols; ++col)
  53. {
  54. acc_mem[col] = arrayops::accumulate
  55. (
  56. &p.get_values()[p.get_col_ptrs()[col]],
  57. p.get_col_ptrs()[col + 1] - p.get_col_ptrs()[col]
  58. );
  59. }
  60. }
  61. out = acc;
  62. }
  63. else
  64. if(dim == 1) // find the sum in each row
  65. {
  66. Col<eT> acc(p_n_rows, fill::zeros);
  67. eT* acc_mem = acc.memptr();
  68. typename SpProxy<T1>::const_iterator_type it = p.begin();
  69. const uword N = p.get_n_nonzero();
  70. for(uword i=0; i < N; ++i)
  71. {
  72. acc_mem[it.row()] += (*it);
  73. ++it;
  74. }
  75. out = acc;
  76. }
  77. }
  78. //! @}