csr_to_simple.cc 2.05 KB
Newer Older
1
2
/*!
 *  Copyright (c) 2020 by Contributors
3
4
 * @file array/cpu/csr_to_simple.cc
 * @brief CSR sorting
5
6
 */
#include <dgl/array.h>
7

8
#include <algorithm>
9
#include <numeric>
10
11
12
13
14
15
#include <vector>

namespace dgl {
namespace aten {
namespace impl {

16
template <DGLDeviceType XPU, typename IdType>
17
std::tuple<CSRMatrix, IdArray, IdArray> CSRToSimple(CSRMatrix csr) {
18
  if (!csr.sorted) csr = CSRSort(csr);
19

20
21
  const IdType *indptr_data = static_cast<IdType *>(csr.indptr->data);
  const IdType *indices_data = static_cast<IdType *>(csr.indices->data);
22
23
24
25
26
27
28
29

  std::vector<IdType> indptr;
  std::vector<IdType> indices;
  std::vector<IdType> count;
  indptr.resize(csr.indptr->shape[0]);
  indptr[0] = 0;

  for (int64_t i = 1; i < csr.indptr->shape[0]; ++i) {
30
31
    if (indptr_data[i - 1] == indptr_data[i]) {
      indptr[i] = indptr[i - 1];
32
33
34
35
36
      continue;
    }

    int64_t cnt = 1;
    int64_t dup_cnt = 1;
37
38
39
    indices.push_back(indices_data[indptr_data[i - 1]]);
    for (int64_t j = indptr_data[i - 1] + 1; j < indptr_data[i]; ++j) {
      if (indices_data[j - 1] == indices_data[j]) {
40
41
42
43
44
45
46
47
48
        ++dup_cnt;
        continue;
      }
      count.push_back(dup_cnt);
      dup_cnt = 1;
      indices.push_back(indices_data[j]);
      ++cnt;
    }
    count.push_back(dup_cnt);
49
    indptr[i] = indptr[i - 1] + cnt;
50
51
52
  }

  CSRMatrix res_csr = CSRMatrix(
53
54
      csr.num_rows, csr.num_cols, IdArray::FromVector(indptr),
      IdArray::FromVector(indices), NullArray(), true);
55
56

  const IdArray &edge_count = IdArray::FromVector(count);
57
58
59
60
61
  const IdArray new_eids =
      Range(0, res_csr.indices->shape[0], sizeof(IdType) * 8, csr.indptr->ctx);
  const IdArray eids_remapped =
      CSRHasData(csr) ? Scatter(Repeat(new_eids, edge_count), csr.data)
                      : Repeat(new_eids, edge_count);
62
63
64
65

  return std::make_tuple(res_csr, edge_count, eids_remapped);
}

66
67
68
69
template std::tuple<CSRMatrix, IdArray, IdArray> CSRToSimple<kDGLCPU, int32_t>(
    CSRMatrix);
template std::tuple<CSRMatrix, IdArray, IdArray> CSRToSimple<kDGLCPU, int64_t>(
    CSRMatrix);
70
71
72
73

}  // namespace impl
}  // namespace aten
}  // namespace dgl