unit_graph.cc 43.6 KB
Newer Older
1
2
/*!
 *  Copyright (c) 2019 by Contributors
Minjie Wang's avatar
Minjie Wang committed
3
4
 * \file graph/unit_graph.cc
 * \brief UnitGraph graph implementation
5
6
 */
#include <dgl/array.h>
7
#include <dgl/base_heterograph.h>
8
9
#include <dgl/immutable_graph.h>
#include <dgl/lazy.h>
10
11

#include "../c_api_common.h"
12
#include "./unit_graph.h"
13
14

namespace dgl {
15

16
namespace {
17
18
19

using namespace dgl::aten;

Minjie Wang's avatar
Minjie Wang committed
20
21
22
23
24
25
26
27
28
29
// create metagraph of one node type
inline GraphPtr CreateUnitGraphMetaGraph1() {
  // a self-loop edge 0->0
  std::vector<int64_t> row_vec(1, 0);
  std::vector<int64_t> col_vec(1, 0);
  IdArray row = aten::VecToIdArray(row_vec);
  IdArray col = aten::VecToIdArray(col_vec);
  GraphPtr g = ImmutableGraph::CreateFromCOO(1, row, col);
  return g;
}
30

Minjie Wang's avatar
Minjie Wang committed
31
32
33
34
35
// create metagraph of two node types
inline GraphPtr CreateUnitGraphMetaGraph2() {
  // an edge 0->1
  std::vector<int64_t> row_vec(1, 0);
  std::vector<int64_t> col_vec(1, 1);
36
37
38
39
40
  IdArray row = aten::VecToIdArray(row_vec);
  IdArray col = aten::VecToIdArray(col_vec);
  GraphPtr g = ImmutableGraph::CreateFromCOO(2, row, col);
  return g;
}
Minjie Wang's avatar
Minjie Wang committed
41
42
43
44
45
46
47
48
49
50
51
52

inline GraphPtr CreateUnitGraphMetaGraph(int num_vtypes) {
  static GraphPtr mg1 = CreateUnitGraphMetaGraph1();
  static GraphPtr mg2 = CreateUnitGraphMetaGraph2();
  if (num_vtypes == 1)
    return mg1;
  else if (num_vtypes == 2)
    return mg2;
  else
    LOG(FATAL) << "Invalid number of vertex types. Must be 1 or 2.";
  return {};
}
53
54

};  // namespace
55
56
57
58
59
60
61

//////////////////////////////////////////////////////////
//
// COO graph implementation
//
//////////////////////////////////////////////////////////

Minjie Wang's avatar
Minjie Wang committed
62
class UnitGraph::COO : public BaseHeteroGraph {
63
 public:
Minjie Wang's avatar
Minjie Wang committed
64
65
  COO(GraphPtr metagraph, int64_t num_src, int64_t num_dst, IdArray src, IdArray dst)
    : BaseHeteroGraph(metagraph) {
66
67
68
    CHECK(aten::IsValidIdArray(src));
    CHECK(aten::IsValidIdArray(dst));
    CHECK_EQ(src->shape[0], dst->shape[0]) << "Input arrays should have the same length.";
69
70
    adj_ = aten::COOMatrix{num_src, num_dst, src, dst};
  }
71

Minjie Wang's avatar
Minjie Wang committed
72
73
74
  COO(GraphPtr metagraph, int64_t num_src, int64_t num_dst,
      IdArray src, IdArray dst, bool is_multigraph)
    : BaseHeteroGraph(metagraph),
75
      is_multigraph_(is_multigraph) {
76
77
78
    CHECK(aten::IsValidIdArray(src));
    CHECK(aten::IsValidIdArray(dst));
    CHECK_EQ(src->shape[0], dst->shape[0]) << "Input arrays should have the same length.";
79
80
    adj_ = aten::COOMatrix{num_src, num_dst, src, dst};
  }
81

82
83
84
85
  COO(GraphPtr metagraph, const aten::COOMatrix& coo)
    : BaseHeteroGraph(metagraph), adj_(coo) {
    // Data index should not be inherited. Edges in COO format are always
    // assigned ids from 0 to num_edges - 1.
86
    CHECK(!COOHasData(coo)) << "[BUG] COO should not contain data.";
87
    adj_.data = aten::NullArray();
88
  }
89

Minjie Wang's avatar
Minjie Wang committed
90
91
  inline dgl_type_t SrcType() const {
    return 0;
92
  }
Minjie Wang's avatar
Minjie Wang committed
93
94
95
96
97
98
99

  inline dgl_type_t DstType() const {
    return NumVertexTypes() == 1? 0 : 1;
  }

  inline dgl_type_t EdgeType() const {
    return 0;
100
101
102
  }

  HeteroGraphPtr GetRelationGraph(dgl_type_t etype) const override {
Minjie Wang's avatar
Minjie Wang committed
103
    LOG(FATAL) << "The method shouldn't be called for UnitGraph graph. "
104
105
106
107
108
      << "The relation graph is simply this graph itself.";
    return {};
  }

  void AddVertices(dgl_type_t vtype, uint64_t num_vertices) override {
Minjie Wang's avatar
Minjie Wang committed
109
    LOG(FATAL) << "UnitGraph graph is not mutable.";
110
111
112
  }

  void AddEdge(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) override {
Minjie Wang's avatar
Minjie Wang committed
113
    LOG(FATAL) << "UnitGraph graph is not mutable.";
114
115
116
  }

  void AddEdges(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) override {
Minjie Wang's avatar
Minjie Wang committed
117
    LOG(FATAL) << "UnitGraph graph is not mutable.";
118
119
120
  }

  void Clear() override {
Minjie Wang's avatar
Minjie Wang committed
121
    LOG(FATAL) << "UnitGraph graph is not mutable.";
122
123
  }

124
125
126
127
  DLDataType DataType() const override {
    return adj_.row->dtype;
  }

128
129
130
131
132
133
134
135
  DLContext Context() const override {
    return adj_.row->ctx;
  }

  uint8_t NumBits() const override {
    return adj_.row->dtype.bits;
  }

136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
  COO AsNumBits(uint8_t bits) const {
    if (NumBits() == bits)
      return *this;

    COO ret(
        meta_graph_,
        adj_.num_rows, adj_.num_cols,
        aten::AsNumBits(adj_.row, bits),
        aten::AsNumBits(adj_.col, bits));
    ret.is_multigraph_ = is_multigraph_;
    return ret;
  }

  COO CopyTo(const DLContext& ctx) const {
    if (Context() == ctx)
      return *this;

    COO ret(
        meta_graph_,
        adj_.num_rows, adj_.num_cols,
        adj_.row.CopyTo(ctx),
        adj_.col.CopyTo(ctx));
    ret.is_multigraph_ = is_multigraph_;
    return ret;
  }

162
163
164
165
166
167
168
169
170
171
172
  bool IsMultigraph() const override {
    return const_cast<COO*>(this)->is_multigraph_.Get([this] () {
        return aten::COOHasDuplicate(adj_);
      });
  }

  bool IsReadonly() const override {
    return true;
  }

  uint64_t NumVertices(dgl_type_t vtype) const override {
Minjie Wang's avatar
Minjie Wang committed
173
    if (vtype == SrcType()) {
174
      return adj_.num_rows;
Minjie Wang's avatar
Minjie Wang committed
175
    } else if (vtype == DstType()) {
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
      return adj_.num_cols;
    } else {
      LOG(FATAL) << "Invalid vertex type: " << vtype;
      return 0;
    }
  }

  uint64_t NumEdges(dgl_type_t etype) const override {
    return adj_.row->shape[0];
  }

  bool HasVertex(dgl_type_t vtype, dgl_id_t vid) const override {
    return vid < NumVertices(vtype);
  }

  BoolArray HasVertices(dgl_type_t vtype, IdArray vids) const override {
    LOG(FATAL) << "Not enabled for COO graph";
    return {};
  }

  bool HasEdgeBetween(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const override {
197
198
199
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
    return aten::COOIsNonZero(adj_, src, dst);
200
201
202
  }

  BoolArray HasEdgesBetween(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) const override {
203
204
205
    CHECK(aten::IsValidIdArray(src_ids)) << "Invalid vertex id array.";
    CHECK(aten::IsValidIdArray(dst_ids)) << "Invalid vertex id array.";
    return aten::COOIsNonZero(adj_, src_ids, dst_ids);
206
207
208
  }

  IdArray Predecessors(dgl_type_t etype, dgl_id_t dst) const override {
209
210
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
    return aten::COOGetRowDataAndIndices(aten::COOTranspose(adj_), dst).second;
211
212
213
  }

  IdArray Successors(dgl_type_t etype, dgl_id_t src) const override {
214
215
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    return aten::COOGetRowDataAndIndices(adj_, src).second;
216
217
218
  }

  IdArray EdgeId(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const override {
219
220
221
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
    return aten::COOGetData(adj_, src, dst);
222
223
224
  }

  EdgeArray EdgeIds(dgl_type_t etype, IdArray src, IdArray dst) const override {
225
226
227
228
    CHECK(aten::IsValidIdArray(src)) << "Invalid vertex id array.";
    CHECK(aten::IsValidIdArray(dst)) << "Invalid vertex id array.";
    const auto& arrs = aten::COOGetDataAndIndices(adj_, src, dst);
    return EdgeArray{arrs[0], arrs[1], arrs[2]};
229
230
231
232
  }

  std::pair<dgl_id_t, dgl_id_t> FindEdge(dgl_type_t etype, dgl_id_t eid) const override {
    CHECK(eid < NumEdges(etype)) << "Invalid edge id: " << eid;
233
234
    const dgl_id_t src = aten::IndexSelect<int64_t>(adj_.row, eid);
    const dgl_id_t dst = aten::IndexSelect<int64_t>(adj_.col, eid);
235
236
237
238
    return std::pair<dgl_id_t, dgl_id_t>(src, dst);
  }

  EdgeArray FindEdges(dgl_type_t etype, IdArray eids) const override {
239
    CHECK(aten::IsValidIdArray(eids)) << "Invalid edge id array";
240
241
242
243
244
245
    return EdgeArray{aten::IndexSelect(adj_.row, eids),
                     aten::IndexSelect(adj_.col, eids),
                     eids};
  }

  EdgeArray InEdges(dgl_type_t etype, dgl_id_t vid) const override {
246
247
248
249
250
    IdArray ret_src, ret_eid;
    std::tie(ret_eid, ret_src) = aten::COOGetRowDataAndIndices(
        aten::COOTranspose(adj_), vid);
    IdArray ret_dst = aten::Full(vid, ret_src->shape[0], NumBits(), ret_src->ctx);
    return EdgeArray{ret_src, ret_dst, ret_eid};
251
252
253
  }

  EdgeArray InEdges(dgl_type_t etype, IdArray vids) const override {
254
255
256
257
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
    auto coosubmat = aten::COOSliceRows(aten::COOTranspose(adj_), vids);
    auto row = aten::IndexSelect(vids, coosubmat.row);
    return EdgeArray{coosubmat.col, row, coosubmat.data};
258
259
260
  }

  EdgeArray OutEdges(dgl_type_t etype, dgl_id_t vid) const override {
261
262
263
264
    IdArray ret_dst, ret_eid;
    std::tie(ret_eid, ret_dst) = aten::COOGetRowDataAndIndices(adj_, vid);
    IdArray ret_src = aten::Full(vid, ret_dst->shape[0], NumBits(), ret_dst->ctx);
    return EdgeArray{ret_src, ret_dst, ret_eid};
265
266
267
  }

  EdgeArray OutEdges(dgl_type_t etype, IdArray vids) const override {
268
269
270
271
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
    auto coosubmat = aten::COOSliceRows(adj_, vids);
    auto row = aten::IndexSelect(vids, coosubmat.row);
    return EdgeArray{row, coosubmat.col, coosubmat.data};
272
273
274
275
276
277
278
279
280
281
282
  }

  EdgeArray Edges(dgl_type_t etype, const std::string &order = "") const override {
    CHECK(order.empty() || order == std::string("eid"))
      << "COO only support Edges of order \"eid\", but got \""
      << order << "\".";
    IdArray rst_eid = aten::Range(0, NumEdges(etype), NumBits(), Context());
    return EdgeArray{adj_.row, adj_.col, rst_eid};
  }

  uint64_t InDegree(dgl_type_t etype, dgl_id_t vid) const override {
283
284
    CHECK(HasVertex(DstType(), vid)) << "Invalid dst vertex id: " << vid;
    return aten::COOGetRowNNZ(aten::COOTranspose(adj_), vid);
285
286
287
  }

  DegreeArray InDegrees(dgl_type_t etype, IdArray vids) const override {
288
289
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
    return aten::COOGetRowNNZ(aten::COOTranspose(adj_), vids);
290
291
292
  }

  uint64_t OutDegree(dgl_type_t etype, dgl_id_t vid) const override {
293
294
    CHECK(HasVertex(SrcType(), vid)) << "Invalid src vertex id: " << vid;
    return aten::COOGetRowNNZ(adj_, vid);
295
296
297
  }

  DegreeArray OutDegrees(dgl_type_t etype, IdArray vids) const override {
298
299
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
    return aten::COOGetRowNNZ(adj_, vids);
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
  }

  DGLIdIters SuccVec(dgl_type_t etype, dgl_id_t vid) const override {
    LOG(INFO) << "Not enabled for COO graph.";
    return {};
  }

  DGLIdIters OutEdgeVec(dgl_type_t etype, dgl_id_t vid) const override {
    LOG(INFO) << "Not enabled for COO graph.";
    return {};
  }

  DGLIdIters PredVec(dgl_type_t etype, dgl_id_t vid) const override {
    LOG(INFO) << "Not enabled for COO graph.";
    return {};
  }

  DGLIdIters InEdgeVec(dgl_type_t etype, dgl_id_t vid) const override {
    LOG(INFO) << "Not enabled for COO graph.";
    return {};
  }

  std::vector<IdArray> GetAdj(
      dgl_type_t etype, bool transpose, const std::string &fmt) const override {
    CHECK(fmt == "coo") << "Not valid adj format request.";
    if (transpose) {
      return {aten::HStack(adj_.col, adj_.row)};
    } else {
      return {aten::HStack(adj_.row, adj_.col)};
    }
  }

332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
  aten::COOMatrix GetCOOMatrix(dgl_type_t etype) const override {
    return adj_;
  }

  aten::CSRMatrix GetCSCMatrix(dgl_type_t etype) const override {
    LOG(FATAL) << "Not enabled for COO graph";
    return aten::CSRMatrix();
  }

  aten::CSRMatrix GetCSRMatrix(dgl_type_t etype) const override {
    LOG(FATAL) << "Not enabled for COO graph";
    return aten::CSRMatrix();
  }

  SparseFormat SelectFormat(dgl_type_t etype, SparseFormat preferred_format) const override {
    LOG(FATAL) << "Not enabled for COO graph";
348
    return SparseFormat::kAny;
349
350
  }

351
  HeteroSubgraph VertexSubgraph(const std::vector<IdArray>& vids) const override {
352
353
354
355
356
357
358
359
360
361
362
363
    CHECK_EQ(vids.size(), NumVertexTypes()) << "Number of vertex types mismatch";
    auto srcvids = vids[SrcType()], dstvids = vids[DstType()];
    CHECK(aten::IsValidIdArray(srcvids)) << "Invalid vertex id array.";
    CHECK(aten::IsValidIdArray(dstvids)) << "Invalid vertex id array.";
    HeteroSubgraph subg;
    const auto& submat = aten::COOSliceMatrix(adj_, srcvids, dstvids);
    IdArray sub_eids = aten::Range(0, submat.data->shape[0], NumBits(), Context());
    subg.graph = std::make_shared<COO>(meta_graph(), submat.num_rows, submat.num_cols,
        submat.row, submat.col);
    subg.induced_vertices = vids;
    subg.induced_edges.emplace_back(submat.data);
    return subg;
364
365
366
367
368
369
370
371
372
373
374
375
376
377
  }

  HeteroSubgraph EdgeSubgraph(
      const std::vector<IdArray>& eids, bool preserve_nodes = false) const override {
    CHECK_EQ(eids.size(), 1) << "Edge type number mismatch.";
    HeteroSubgraph subg;
    if (!preserve_nodes) {
      IdArray new_src = aten::IndexSelect(adj_.row, eids[0]);
      IdArray new_dst = aten::IndexSelect(adj_.col, eids[0]);
      subg.induced_vertices.emplace_back(aten::Relabel_({new_src}));
      subg.induced_vertices.emplace_back(aten::Relabel_({new_dst}));
      const auto new_nsrc = subg.induced_vertices[0]->shape[0];
      const auto new_ndst = subg.induced_vertices[1]->shape[0];
      subg.graph = std::make_shared<COO>(
Minjie Wang's avatar
Minjie Wang committed
378
          meta_graph(), new_nsrc, new_ndst, new_src, new_dst);
379
380
381
382
383
384
385
      subg.induced_edges = eids;
    } else {
      IdArray new_src = aten::IndexSelect(adj_.row, eids[0]);
      IdArray new_dst = aten::IndexSelect(adj_.col, eids[0]);
      subg.induced_vertices.emplace_back(aten::Range(0, NumVertices(0), NumBits(), Context()));
      subg.induced_vertices.emplace_back(aten::Range(0, NumVertices(1), NumBits(), Context()));
      subg.graph = std::make_shared<COO>(
Minjie Wang's avatar
Minjie Wang committed
386
          meta_graph(), NumVertices(0), NumVertices(1), new_src, new_dst);
387
388
389
390
391
392
393
394
395
      subg.induced_edges = eids;
    }
    return subg;
  }

  aten::COOMatrix adj() const {
    return adj_;
  }

396
397
398
399
400
401
402
403
404
  /*!
   * \brief Determines whether the graph is "hypersparse", i.e. having significantly more
   * nodes than edges.
   */
  bool IsHypersparse() const {
    return (NumVertices(SrcType()) / 8 > NumEdges(EdgeType())) &&
           (NumVertices(SrcType()) > 1000000);
  }

405
406
407
408
409
410
411
412
413
414
415
416
417
  bool Load(dmlc::Stream* fs) {
    auto meta_imgraph = Serializer::make_shared<ImmutableGraph>();
    CHECK(fs->Read(&meta_imgraph)) << "Invalid meta graph";
    meta_graph_ = meta_imgraph;
    CHECK(fs->Read(&adj_)) << "Invalid adj matrix";
    return true;
  }
  void Save(dmlc::Stream* fs) const {
    auto meta_graph_ptr = ImmutableGraph::ToImmutable(meta_graph());
    fs->Write(meta_graph_ptr);
    fs->Write(adj_);
  }

418
 private:
419
420
421
422
  friend class Serializer;

  COO() {}

423
424
425
426
427
428
429
430
431
432
433
434
435
436
  /*! \brief internal adjacency matrix. Data array is empty */
  aten::COOMatrix adj_;

  /*! \brief multi-graph flag */
  Lazy<bool> is_multigraph_;
};

//////////////////////////////////////////////////////////
//
// CSR graph implementation
//
//////////////////////////////////////////////////////////

/*! \brief CSR graph */
Minjie Wang's avatar
Minjie Wang committed
437
class UnitGraph::CSR : public BaseHeteroGraph {
438
 public:
Minjie Wang's avatar
Minjie Wang committed
439
  CSR(GraphPtr metagraph, int64_t num_src, int64_t num_dst,
440
      IdArray indptr, IdArray indices, IdArray edge_ids)
Minjie Wang's avatar
Minjie Wang committed
441
    : BaseHeteroGraph(metagraph) {
442
443
444
445
446
    CHECK(aten::IsValidIdArray(indptr));
    CHECK(aten::IsValidIdArray(indices));
    CHECK(aten::IsValidIdArray(edge_ids));
    CHECK_EQ(indices->shape[0], edge_ids->shape[0])
      << "indices and edge id arrays should have the same length";
447

448
449
450
    adj_ = aten::CSRMatrix{num_src, num_dst, indptr, indices, edge_ids};
  }

Minjie Wang's avatar
Minjie Wang committed
451
  CSR(GraphPtr metagraph, int64_t num_src, int64_t num_dst,
452
      IdArray indptr, IdArray indices, IdArray edge_ids, bool is_multigraph)
Minjie Wang's avatar
Minjie Wang committed
453
    : BaseHeteroGraph(metagraph), is_multigraph_(is_multigraph) {
454
455
456
457
458
    CHECK(aten::IsValidIdArray(indptr));
    CHECK(aten::IsValidIdArray(indices));
    CHECK(aten::IsValidIdArray(edge_ids));
    CHECK_EQ(indices->shape[0], edge_ids->shape[0])
      << "indices and edge id arrays should have the same length";
459
460
461
    adj_ = aten::CSRMatrix{num_src, num_dst, indptr, indices, edge_ids};
  }

462
  CSR(GraphPtr metagraph, const aten::CSRMatrix& csr)
Da Zheng's avatar
Da Zheng committed
463
464
    : BaseHeteroGraph(metagraph), adj_(csr) {
  }
465

Minjie Wang's avatar
Minjie Wang committed
466
467
  inline dgl_type_t SrcType() const {
    return 0;
468
  }
Minjie Wang's avatar
Minjie Wang committed
469
470
471
472
473
474
475

  inline dgl_type_t DstType() const {
    return NumVertexTypes() == 1? 0 : 1;
  }

  inline dgl_type_t EdgeType() const {
    return 0;
476
477
478
  }

  HeteroGraphPtr GetRelationGraph(dgl_type_t etype) const override {
Minjie Wang's avatar
Minjie Wang committed
479
    LOG(FATAL) << "The method shouldn't be called for UnitGraph graph. "
480
481
482
483
484
      << "The relation graph is simply this graph itself.";
    return {};
  }

  void AddVertices(dgl_type_t vtype, uint64_t num_vertices) override {
Minjie Wang's avatar
Minjie Wang committed
485
    LOG(FATAL) << "UnitGraph graph is not mutable.";
486
487
488
  }

  void AddEdge(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) override {
Minjie Wang's avatar
Minjie Wang committed
489
    LOG(FATAL) << "UnitGraph graph is not mutable.";
490
491
492
  }

  void AddEdges(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) override {
Minjie Wang's avatar
Minjie Wang committed
493
    LOG(FATAL) << "UnitGraph graph is not mutable.";
494
495
496
  }

  void Clear() override {
Minjie Wang's avatar
Minjie Wang committed
497
    LOG(FATAL) << "UnitGraph graph is not mutable.";
498
499
  }

500
501
502
503
  DLDataType DataType() const override {
    return adj_.indices->dtype;
  }

504
505
506
507
508
509
510
511
  DLContext Context() const override {
    return adj_.indices->ctx;
  }

  uint8_t NumBits() const override {
    return adj_.indices->dtype.bits;
  }

512
513
514
515
516
  CSR AsNumBits(uint8_t bits) const {
    if (NumBits() == bits) {
      return *this;
    } else {
      CSR ret(
Minjie Wang's avatar
Minjie Wang committed
517
          meta_graph_,
518
519
520
521
522
523
524
525
526
527
528
529
530
531
          adj_.num_rows, adj_.num_cols,
          aten::AsNumBits(adj_.indptr, bits),
          aten::AsNumBits(adj_.indices, bits),
          aten::AsNumBits(adj_.data, bits));
      ret.is_multigraph_ = is_multigraph_;
      return ret;
    }
  }

  CSR CopyTo(const DLContext& ctx) const {
    if (Context() == ctx) {
      return *this;
    } else {
      CSR ret(
Minjie Wang's avatar
Minjie Wang committed
532
          meta_graph_,
533
534
535
536
537
538
539
540
541
          adj_.num_rows, adj_.num_cols,
          adj_.indptr.CopyTo(ctx),
          adj_.indices.CopyTo(ctx),
          adj_.data.CopyTo(ctx));
      ret.is_multigraph_ = is_multigraph_;
      return ret;
    }
  }

542
543
544
545
546
547
548
549
550
551
552
  bool IsMultigraph() const override {
    return const_cast<CSR*>(this)->is_multigraph_.Get([this] () {
        return aten::CSRHasDuplicate(adj_);
      });
  }

  bool IsReadonly() const override {
    return true;
  }

  uint64_t NumVertices(dgl_type_t vtype) const override {
Minjie Wang's avatar
Minjie Wang committed
553
    if (vtype == SrcType()) {
554
      return adj_.num_rows;
Minjie Wang's avatar
Minjie Wang committed
555
    } else if (vtype == DstType()) {
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
      return adj_.num_cols;
    } else {
      LOG(FATAL) << "Invalid vertex type: " << vtype;
      return 0;
    }
  }

  uint64_t NumEdges(dgl_type_t etype) const override {
    return adj_.indices->shape[0];
  }

  bool HasVertex(dgl_type_t vtype, dgl_id_t vid) const override {
    return vid < NumVertices(vtype);
  }

  BoolArray HasVertices(dgl_type_t vtype, IdArray vids) const override {
    LOG(FATAL) << "Not enabled for COO graph";
    return {};
  }

  bool HasEdgeBetween(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const override {
Minjie Wang's avatar
Minjie Wang committed
577
578
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
579
580
581
582
    return aten::CSRIsNonZero(adj_, src, dst);
  }

  BoolArray HasEdgesBetween(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) const override {
583
584
    CHECK(aten::IsValidIdArray(src_ids)) << "Invalid vertex id array.";
    CHECK(aten::IsValidIdArray(dst_ids)) << "Invalid vertex id array.";
585
586
587
588
589
590
591
592
593
    return aten::CSRIsNonZero(adj_, src_ids, dst_ids);
  }

  IdArray Predecessors(dgl_type_t etype, dgl_id_t dst) const override {
    LOG(INFO) << "Not enabled for CSR graph.";
    return {};
  }

  IdArray Successors(dgl_type_t etype, dgl_id_t src) const override {
Minjie Wang's avatar
Minjie Wang committed
594
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
595
596
597
598
    return aten::CSRGetRowColumnIndices(adj_, src);
  }

  IdArray EdgeId(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const override {
Minjie Wang's avatar
Minjie Wang committed
599
600
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
601
602
603
604
    return aten::CSRGetData(adj_, src, dst);
  }

  EdgeArray EdgeIds(dgl_type_t etype, IdArray src, IdArray dst) const override {
605
606
    CHECK(aten::IsValidIdArray(src)) << "Invalid vertex id array.";
    CHECK(aten::IsValidIdArray(dst)) << "Invalid vertex id array.";
607
608
609
610
611
    const auto& arrs = aten::CSRGetDataAndIndices(adj_, src, dst);
    return EdgeArray{arrs[0], arrs[1], arrs[2]};
  }

  std::pair<dgl_id_t, dgl_id_t> FindEdge(dgl_type_t etype, dgl_id_t eid) const override {
612
    LOG(FATAL) << "Not enabled for CSR graph.";
613
614
615
616
    return {};
  }

  EdgeArray FindEdges(dgl_type_t etype, IdArray eids) const override {
617
    LOG(FATAL) << "Not enabled for CSR graph.";
618
619
620
621
    return {};
  }

  EdgeArray InEdges(dgl_type_t etype, dgl_id_t vid) const override {
622
    LOG(FATAL) << "Not enabled for CSR graph.";
623
624
625
626
    return {};
  }

  EdgeArray InEdges(dgl_type_t etype, IdArray vids) const override {
627
    LOG(FATAL) << "Not enabled for CSR graph.";
628
629
630
631
    return {};
  }

  EdgeArray OutEdges(dgl_type_t etype, dgl_id_t vid) const override {
Minjie Wang's avatar
Minjie Wang committed
632
    CHECK(HasVertex(SrcType(), vid)) << "Invalid src vertex id: " << vid;
633
634
635
636
637
638
639
    IdArray ret_dst = aten::CSRGetRowColumnIndices(adj_, vid);
    IdArray ret_eid = aten::CSRGetRowData(adj_, vid);
    IdArray ret_src = aten::Full(vid, ret_dst->shape[0], NumBits(), ret_dst->ctx);
    return EdgeArray{ret_src, ret_dst, ret_eid};
  }

  EdgeArray OutEdges(dgl_type_t etype, IdArray vids) const override {
640
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
    auto csrsubmat = aten::CSRSliceRows(adj_, vids);
    auto coosubmat = aten::CSRToCOO(csrsubmat, false);
    // Note that the row id in the csr submat is relabled, so
    // we need to recover it using an index select.
    auto row = aten::IndexSelect(vids, coosubmat.row);
    return EdgeArray{row, coosubmat.col, coosubmat.data};
  }

  EdgeArray Edges(dgl_type_t etype, const std::string &order = "") const override {
    CHECK(order.empty() || order == std::string("srcdst"))
      << "CSR only support Edges of order \"srcdst\","
      << " but got \"" << order << "\".";
    const auto& coo = aten::CSRToCOO(adj_, false);
    return EdgeArray{coo.row, coo.col, coo.data};
  }

  uint64_t InDegree(dgl_type_t etype, dgl_id_t vid) const override {
658
    LOG(FATAL) << "Not enabled for CSR graph.";
659
660
661
662
    return {};
  }

  DegreeArray InDegrees(dgl_type_t etype, IdArray vids) const override {
663
    LOG(FATAL) << "Not enabled for CSR graph.";
664
665
666
667
    return {};
  }

  uint64_t OutDegree(dgl_type_t etype, dgl_id_t vid) const override {
Minjie Wang's avatar
Minjie Wang committed
668
    CHECK(HasVertex(SrcType(), vid)) << "Invalid src vertex id: " << vid;
669
670
671
672
    return aten::CSRGetRowNNZ(adj_, vid);
  }

  DegreeArray OutDegrees(dgl_type_t etype, IdArray vids) const override {
673
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
    return aten::CSRGetRowNNZ(adj_, vids);
  }

  DGLIdIters SuccVec(dgl_type_t etype, dgl_id_t vid) const override {
    // TODO(minjie): This still assumes the data type and device context
    //   of this graph. Should fix later.
    const dgl_id_t* indptr_data = static_cast<dgl_id_t*>(adj_.indptr->data);
    const dgl_id_t* indices_data = static_cast<dgl_id_t*>(adj_.indices->data);
    const dgl_id_t start = indptr_data[vid];
    const dgl_id_t end = indptr_data[vid + 1];
    return DGLIdIters(indices_data + start, indices_data + end);
  }

  DGLIdIters OutEdgeVec(dgl_type_t etype, dgl_id_t vid) const override {
    // TODO(minjie): This still assumes the data type and device context
    //   of this graph. Should fix later.
    const dgl_id_t* indptr_data = static_cast<dgl_id_t*>(adj_.indptr->data);
    const dgl_id_t* eid_data = static_cast<dgl_id_t*>(adj_.data->data);
    const dgl_id_t start = indptr_data[vid];
    const dgl_id_t end = indptr_data[vid + 1];
    return DGLIdIters(eid_data + start, eid_data + end);
  }

  DGLIdIters PredVec(dgl_type_t etype, dgl_id_t vid) const override {
698
    LOG(FATAL) << "Not enabled for CSR graph.";
699
700
701
702
    return {};
  }

  DGLIdIters InEdgeVec(dgl_type_t etype, dgl_id_t vid) const override {
703
    LOG(FATAL) << "Not enabled for CSR graph.";
704
705
706
707
708
709
710
711
712
    return {};
  }

  std::vector<IdArray> GetAdj(
      dgl_type_t etype, bool transpose, const std::string &fmt) const override {
    CHECK(!transpose && fmt == "csr") << "Not valid adj format request.";
    return {adj_.indptr, adj_.indices, adj_.data};
  }

713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
  aten::COOMatrix GetCOOMatrix(dgl_type_t etype) const override {
    LOG(FATAL) << "Not enabled for CSR graph";
    return aten::COOMatrix();
  }

  aten::CSRMatrix GetCSCMatrix(dgl_type_t etype) const override {
    LOG(FATAL) << "Not enabled for CSR graph";
    return aten::CSRMatrix();
  }

  aten::CSRMatrix GetCSRMatrix(dgl_type_t etype) const override {
    return adj_;
  }

  SparseFormat SelectFormat(dgl_type_t etype, SparseFormat preferred_format) const override {
    LOG(FATAL) << "Not enabled for CSR graph";
729
    return SparseFormat::kAny;
730
731
  }

732
  HeteroSubgraph VertexSubgraph(const std::vector<IdArray>& vids) const override {
Minjie Wang's avatar
Minjie Wang committed
733
734
735
736
    CHECK_EQ(vids.size(), NumVertexTypes()) << "Number of vertex types mismatch";
    auto srcvids = vids[SrcType()], dstvids = vids[DstType()];
    CHECK(aten::IsValidIdArray(srcvids)) << "Invalid vertex id array.";
    CHECK(aten::IsValidIdArray(dstvids)) << "Invalid vertex id array.";
737
    HeteroSubgraph subg;
Minjie Wang's avatar
Minjie Wang committed
738
    const auto& submat = aten::CSRSliceMatrix(adj_, srcvids, dstvids);
739
    IdArray sub_eids = aten::Range(0, submat.data->shape[0], NumBits(), Context());
Minjie Wang's avatar
Minjie Wang committed
740
    subg.graph = std::make_shared<CSR>(meta_graph(), submat.num_rows, submat.num_cols,
741
742
743
744
745
746
747
748
        submat.indptr, submat.indices, sub_eids);
    subg.induced_vertices = vids;
    subg.induced_edges.emplace_back(submat.data);
    return subg;
  }

  HeteroSubgraph EdgeSubgraph(
      const std::vector<IdArray>& eids, bool preserve_nodes = false) const override {
749
    LOG(FATAL) << "Not enabled for CSR graph.";
750
751
752
753
754
755
756
    return {};
  }

  aten::CSRMatrix adj() const {
    return adj_;
  }

757
758
759
760
761
762
763
764
765
766
767
768
769
770
  bool Load(dmlc::Stream* fs) {
    auto meta_imgraph = Serializer::make_shared<ImmutableGraph>();
    CHECK(fs->Read(&meta_imgraph)) << "Invalid meta graph";
    meta_graph_ = meta_imgraph;
    CHECK(fs->Read(&adj_)) << "Invalid adj matrix";
    return true;
  }
  void Save(dmlc::Stream* fs) const {
    auto meta_graph_ptr = ImmutableGraph::ToImmutable(meta_graph());
    fs->Write(meta_graph_ptr);
    fs->Write(adj_);
  }


771
 private:
772
773
774
775
  friend class Serializer;

  CSR() {};

776
777
778
779
780
781
782
783
784
  /*! \brief internal adjacency matrix. Data array stores edge ids */
  aten::CSRMatrix adj_;

  /*! \brief multi-graph flag */
  Lazy<bool> is_multigraph_;
};

//////////////////////////////////////////////////////////
//
Minjie Wang's avatar
Minjie Wang committed
785
// unit graph implementation
786
787
788
//
//////////////////////////////////////////////////////////

789
790
791
792
DLDataType UnitGraph::DataType() const {
  return GetAny()->DataType();
}

Minjie Wang's avatar
Minjie Wang committed
793
DLContext UnitGraph::Context() const {
794
795
796
  return GetAny()->Context();
}

Minjie Wang's avatar
Minjie Wang committed
797
uint8_t UnitGraph::NumBits() const {
798
799
800
  return GetAny()->NumBits();
}

Minjie Wang's avatar
Minjie Wang committed
801
bool UnitGraph::IsMultigraph() const {
802
803
804
  return GetAny()->IsMultigraph();
}

Minjie Wang's avatar
Minjie Wang committed
805
uint64_t UnitGraph::NumVertices(dgl_type_t vtype) const {
806
  const SparseFormat fmt = SelectFormat(SparseFormat::kAny);
807
808
809
  const auto ptr = GetFormat(fmt);
  // TODO(BarclayII): we have a lot of special handling for CSC.
  // Need to have a UnitGraph::CSC backend instead.
810
  if (fmt == SparseFormat::kCSC)
Minjie Wang's avatar
Minjie Wang committed
811
    vtype = (vtype == SrcType()) ? DstType() : SrcType();
812
  return ptr->NumVertices(vtype);
813
814
}

Minjie Wang's avatar
Minjie Wang committed
815
uint64_t UnitGraph::NumEdges(dgl_type_t etype) const {
816
817
818
  return GetAny()->NumEdges(etype);
}

Minjie Wang's avatar
Minjie Wang committed
819
bool UnitGraph::HasVertex(dgl_type_t vtype, dgl_id_t vid) const {
820
  const SparseFormat fmt = SelectFormat(SparseFormat::kAny);
821
  const auto ptr = GetFormat(fmt);
822
  if (fmt == SparseFormat::kCSC)
Minjie Wang's avatar
Minjie Wang committed
823
    vtype = (vtype == SrcType()) ? DstType() : SrcType();
824
  return ptr->HasVertex(vtype, vid);
825
826
}

Minjie Wang's avatar
Minjie Wang committed
827
BoolArray UnitGraph::HasVertices(dgl_type_t vtype, IdArray vids) const {
828
  CHECK(aten::IsValidIdArray(vids)) << "Invalid id array input";
829
830
831
  return aten::LT(vids, NumVertices(vtype));
}

Minjie Wang's avatar
Minjie Wang committed
832
bool UnitGraph::HasEdgeBetween(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const {
833
  const SparseFormat fmt = SelectFormat(SparseFormat::kAny);
834
  const auto ptr = GetFormat(fmt);
835
  if (fmt == SparseFormat::kCSC)
836
837
838
    return ptr->HasEdgeBetween(etype, dst, src);
  else
    return ptr->HasEdgeBetween(etype, src, dst);
839
840
}

Minjie Wang's avatar
Minjie Wang committed
841
BoolArray UnitGraph::HasEdgesBetween(
842
    dgl_type_t etype, IdArray src, IdArray dst) const {
843
  const SparseFormat fmt = SelectFormat(SparseFormat::kAny);
844
  const auto ptr = GetFormat(fmt);
845
  if (fmt == SparseFormat::kCSC)
846
847
848
    return ptr->HasEdgesBetween(etype, dst, src);
  else
    return ptr->HasEdgesBetween(etype, src, dst);
849
850
}

Minjie Wang's avatar
Minjie Wang committed
851
IdArray UnitGraph::Predecessors(dgl_type_t etype, dgl_id_t dst) const {
852
  const SparseFormat fmt = SelectFormat(SparseFormat::kCSC);
853
  const auto ptr = GetFormat(fmt);
854
  if (fmt == SparseFormat::kCSC)
855
856
857
    return ptr->Successors(etype, dst);
  else
    return ptr->Predecessors(etype, dst);
858
859
}

Minjie Wang's avatar
Minjie Wang committed
860
IdArray UnitGraph::Successors(dgl_type_t etype, dgl_id_t src) const {
861
  const SparseFormat fmt = SelectFormat(SparseFormat::kCSR);
862
863
  const auto ptr = GetFormat(fmt);
  return ptr->Successors(etype, src);
864
865
}

Minjie Wang's avatar
Minjie Wang committed
866
IdArray UnitGraph::EdgeId(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const {
867
  const SparseFormat fmt = SelectFormat(SparseFormat::kAny);
868
  const auto ptr = GetFormat(fmt);
869
  if (fmt == SparseFormat::kCSC)
870
871
872
    return ptr->EdgeId(etype, dst, src);
  else
    return ptr->EdgeId(etype, src, dst);
873
874
}

Minjie Wang's avatar
Minjie Wang committed
875
EdgeArray UnitGraph::EdgeIds(dgl_type_t etype, IdArray src, IdArray dst) const {
876
  const SparseFormat fmt = SelectFormat(SparseFormat::kAny);
877
  const auto ptr = GetFormat(fmt);
878
  if (fmt == SparseFormat::kCSC) {
879
    EdgeArray edges = ptr->EdgeIds(etype, dst, src);
880
881
    return EdgeArray{edges.dst, edges.src, edges.id};
  } else {
882
    return ptr->EdgeIds(etype, src, dst);
883
884
885
  }
}

Minjie Wang's avatar
Minjie Wang committed
886
std::pair<dgl_id_t, dgl_id_t> UnitGraph::FindEdge(dgl_type_t etype, dgl_id_t eid) const {
887
  const SparseFormat fmt = SelectFormat(SparseFormat::kCOO);
888
889
  const auto ptr = GetFormat(fmt);
  return ptr->FindEdge(etype, eid);
890
891
}

Minjie Wang's avatar
Minjie Wang committed
892
EdgeArray UnitGraph::FindEdges(dgl_type_t etype, IdArray eids) const {
893
  const SparseFormat fmt = SelectFormat(SparseFormat::kCOO);
894
895
  const auto ptr = GetFormat(fmt);
  return ptr->FindEdges(etype, eids);
896
897
}

Minjie Wang's avatar
Minjie Wang committed
898
EdgeArray UnitGraph::InEdges(dgl_type_t etype, dgl_id_t vid) const {
899
  const SparseFormat fmt = SelectFormat(SparseFormat::kCSC);
900
  const auto ptr = GetFormat(fmt);
901
  if (fmt == SparseFormat::kCSC) {
902
903
904
905
906
    const EdgeArray& ret = ptr->OutEdges(etype, vid);
    return {ret.dst, ret.src, ret.id};
  } else {
    return ptr->InEdges(etype, vid);
  }
907
908
}

Minjie Wang's avatar
Minjie Wang committed
909
EdgeArray UnitGraph::InEdges(dgl_type_t etype, IdArray vids) const {
910
  const SparseFormat fmt = SelectFormat(SparseFormat::kCSC);
911
  const auto ptr = GetFormat(fmt);
912
  if (fmt == SparseFormat::kCSC) {
913
914
915
916
917
    const EdgeArray& ret = ptr->OutEdges(etype, vids);
    return {ret.dst, ret.src, ret.id};
  } else {
    return ptr->InEdges(etype, vids);
  }
918
919
}

Minjie Wang's avatar
Minjie Wang committed
920
EdgeArray UnitGraph::OutEdges(dgl_type_t etype, dgl_id_t vid) const {
921
  const SparseFormat fmt = SelectFormat(SparseFormat::kCSR);
922
923
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdges(etype, vid);
924
925
}

Minjie Wang's avatar
Minjie Wang committed
926
EdgeArray UnitGraph::OutEdges(dgl_type_t etype, IdArray vids) const {
927
  const SparseFormat fmt = SelectFormat(SparseFormat::kCSR);
928
929
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdges(etype, vids);
930
931
}

Minjie Wang's avatar
Minjie Wang committed
932
EdgeArray UnitGraph::Edges(dgl_type_t etype, const std::string &order) const {
933
934
  SparseFormat fmt;
  if (order == std::string("eid")) {
935
    fmt = SelectFormat(SparseFormat::kCOO);
936
  } else if (order.empty()) {
937
    // arbitrary order
938
    fmt = SelectFormat(SparseFormat::kAny);
939
  } else if (order == std::string("srcdst")) {
940
    fmt = SelectFormat(SparseFormat::kCSR);
941
942
  } else {
    LOG(FATAL) << "Unsupported order request: " << order;
943
    return {};
944
  }
945
946

  const auto& edges = GetFormat(fmt)->Edges(etype, order);
947
  if (fmt == SparseFormat::kCSC)
948
949
950
    return EdgeArray{edges.dst, edges.src, edges.id};
  else
    return edges;
951
952
}

Minjie Wang's avatar
Minjie Wang committed
953
uint64_t UnitGraph::InDegree(dgl_type_t etype, dgl_id_t vid) const {
954
  SparseFormat fmt = SelectFormat(SparseFormat::kCSC);
955
  const auto ptr = GetFormat(fmt);
956
  if (fmt == SparseFormat::kCSC)
957
958
959
    return ptr->OutDegree(etype, vid);
  else
    return ptr->InDegree(etype, vid);
960
961
}

Minjie Wang's avatar
Minjie Wang committed
962
DegreeArray UnitGraph::InDegrees(dgl_type_t etype, IdArray vids) const {
963
  SparseFormat fmt = SelectFormat(SparseFormat::kCSC);
964
  const auto ptr = GetFormat(fmt);
965
  if (fmt == SparseFormat::kCSC)
966
967
968
    return ptr->OutDegrees(etype, vids);
  else
    return ptr->InDegrees(etype, vids);
969
970
}

Minjie Wang's avatar
Minjie Wang committed
971
uint64_t UnitGraph::OutDegree(dgl_type_t etype, dgl_id_t vid) const {
972
  SparseFormat fmt = SelectFormat(SparseFormat::kCSR);
973
974
  const auto ptr = GetFormat(fmt);
  return ptr->OutDegree(etype, vid);
975
976
}

Minjie Wang's avatar
Minjie Wang committed
977
DegreeArray UnitGraph::OutDegrees(dgl_type_t etype, IdArray vids) const {
978
  SparseFormat fmt = SelectFormat(SparseFormat::kCSR);
979
980
  const auto ptr = GetFormat(fmt);
  return ptr->OutDegrees(etype, vids);
981
982
}

Minjie Wang's avatar
Minjie Wang committed
983
DGLIdIters UnitGraph::SuccVec(dgl_type_t etype, dgl_id_t vid) const {
984
  SparseFormat fmt = SelectFormat(SparseFormat::kCSR);
985
986
  const auto ptr = GetFormat(fmt);
  return ptr->SuccVec(etype, vid);
987
988
}

Minjie Wang's avatar
Minjie Wang committed
989
DGLIdIters UnitGraph::OutEdgeVec(dgl_type_t etype, dgl_id_t vid) const {
990
  SparseFormat fmt = SelectFormat(SparseFormat::kCSR);
991
992
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdgeVec(etype, vid);
993
994
}

Minjie Wang's avatar
Minjie Wang committed
995
DGLIdIters UnitGraph::PredVec(dgl_type_t etype, dgl_id_t vid) const {
996
  SparseFormat fmt = SelectFormat(SparseFormat::kCSC);
997
  const auto ptr = GetFormat(fmt);
998
  if (fmt == SparseFormat::kCSC)
999
1000
1001
    return ptr->SuccVec(etype, vid);
  else
    return ptr->PredVec(etype, vid);
1002
1003
}

Minjie Wang's avatar
Minjie Wang committed
1004
DGLIdIters UnitGraph::InEdgeVec(dgl_type_t etype, dgl_id_t vid) const {
1005
  SparseFormat fmt = SelectFormat(SparseFormat::kCSC);
1006
  const auto ptr = GetFormat(fmt);
1007
  if (fmt == SparseFormat::kCSC)
1008
1009
1010
    return ptr->OutEdgeVec(etype, vid);
  else
    return ptr->InEdgeVec(etype, vid);
1011
1012
}

Minjie Wang's avatar
Minjie Wang committed
1013
std::vector<IdArray> UnitGraph::GetAdj(
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
    dgl_type_t etype, bool transpose, const std::string &fmt) const {
  // TODO(minjie): Our current semantics of adjacency matrix is row for dst nodes and col for
  //   src nodes. Therefore, we need to flip the transpose flag. For example, transpose=False
  //   is equal to in edge CSR.
  //   We have this behavior because previously we use framework's SPMM and we don't cache
  //   reverse adj. This is not intuitive and also not consistent with networkx's
  //   to_scipy_sparse_matrix. With the upcoming custom kernel change, we should change the
  //   behavior and make row for src and col for dst.
  if (fmt == std::string("csr")) {
    return transpose? GetOutCSR()->GetAdj(etype, false, "csr")
      : GetInCSR()->GetAdj(etype, false, "csr");
  } else if (fmt == std::string("coo")) {
    return GetCOO()->GetAdj(etype, !transpose, fmt);
  } else {
    LOG(FATAL) << "unsupported adjacency matrix format: " << fmt;
    return {};
  }
}

Minjie Wang's avatar
Minjie Wang committed
1033
HeteroSubgraph UnitGraph::VertexSubgraph(const std::vector<IdArray>& vids) const {
1034
  // We prefer to generate a subgraph from out-csr.
1035
  SparseFormat fmt = SelectFormat(SparseFormat::kCSR);
1036
  HeteroSubgraph sg = GetFormat(fmt)->VertexSubgraph(vids);
1037
1038
  CSRPtr subcsr = std::dynamic_pointer_cast<CSR>(sg.graph);
  HeteroSubgraph ret;
Minjie Wang's avatar
Minjie Wang committed
1039
  ret.graph = HeteroGraphPtr(new UnitGraph(meta_graph(), nullptr, subcsr, nullptr));
1040
1041
1042
1043
1044
  ret.induced_vertices = std::move(sg.induced_vertices);
  ret.induced_edges = std::move(sg.induced_edges);
  return ret;
}

Minjie Wang's avatar
Minjie Wang committed
1045
HeteroSubgraph UnitGraph::EdgeSubgraph(
1046
    const std::vector<IdArray>& eids, bool preserve_nodes) const {
1047
  SparseFormat fmt = SelectFormat(SparseFormat::kCOO);
1048
  auto sg = GetFormat(fmt)->EdgeSubgraph(eids, preserve_nodes);
1049
1050
  COOPtr subcoo = std::dynamic_pointer_cast<COO>(sg.graph);
  HeteroSubgraph ret;
Minjie Wang's avatar
Minjie Wang committed
1051
  ret.graph = HeteroGraphPtr(new UnitGraph(meta_graph(), nullptr, nullptr, subcoo));
1052
1053
1054
1055
1056
  ret.induced_vertices = std::move(sg.induced_vertices);
  ret.induced_edges = std::move(sg.induced_edges);
  return ret;
}

Minjie Wang's avatar
Minjie Wang committed
1057
HeteroGraphPtr UnitGraph::CreateFromCOO(
1058
1059
    int64_t num_vtypes, int64_t num_src, int64_t num_dst,
    IdArray row, IdArray col,
1060
    SparseFormat restrict_format) {
Minjie Wang's avatar
Minjie Wang committed
1061
1062
1063
1064
1065
  CHECK(num_vtypes == 1 || num_vtypes == 2);
  if (num_vtypes == 1)
    CHECK_EQ(num_src, num_dst);
  auto mg = CreateUnitGraphMetaGraph(num_vtypes);
  COOPtr coo(new COO(mg, num_src, num_dst, row, col));
1066
1067
1068

  return HeteroGraphPtr(
      new UnitGraph(mg, nullptr, nullptr, coo, restrict_format));
1069
1070
}

1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
HeteroGraphPtr UnitGraph::CreateFromCOO(
    int64_t num_vtypes, const aten::COOMatrix& mat,
    SparseFormat restrict_format) {
  CHECK(num_vtypes == 1 || num_vtypes == 2);
  if (num_vtypes == 1)
    CHECK_EQ(mat.num_rows, mat.num_cols);
  auto mg = CreateUnitGraphMetaGraph(num_vtypes);
  COOPtr coo(new COO(mg, mat));
  return HeteroGraphPtr(
      new UnitGraph(mg, nullptr, nullptr, coo, restrict_format));
}

Minjie Wang's avatar
Minjie Wang committed
1083
1084
HeteroGraphPtr UnitGraph::CreateFromCSR(
    int64_t num_vtypes, int64_t num_src, int64_t num_dst,
1085
    IdArray indptr, IdArray indices, IdArray edge_ids, SparseFormat restrict_format) {
Minjie Wang's avatar
Minjie Wang committed
1086
1087
1088
1089
1090
  CHECK(num_vtypes == 1 || num_vtypes == 2);
  if (num_vtypes == 1)
    CHECK_EQ(num_src, num_dst);
  auto mg = CreateUnitGraphMetaGraph(num_vtypes);
  CSRPtr csr(new CSR(mg, num_src, num_dst, indptr, indices, edge_ids));
1091
  return HeteroGraphPtr(new UnitGraph(mg, nullptr, csr, nullptr, restrict_format));
1092
1093
}

1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
HeteroGraphPtr UnitGraph::CreateFromCSR(
    int64_t num_vtypes, const aten::CSRMatrix& mat,
    SparseFormat restrict_format) {
  CHECK(num_vtypes == 1 || num_vtypes == 2);
  if (num_vtypes == 1)
    CHECK_EQ(mat.num_rows, mat.num_cols);
  auto mg = CreateUnitGraphMetaGraph(num_vtypes);
  CSRPtr csr(new CSR(mg, mat));
  return HeteroGraphPtr(new UnitGraph(mg, nullptr, csr, nullptr, restrict_format));
}

1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
HeteroGraphPtr UnitGraph::CreateFromCSC(
    int64_t num_vtypes, int64_t num_src, int64_t num_dst,
    IdArray indptr, IdArray indices, IdArray edge_ids, SparseFormat restrict_format) {
  CHECK(num_vtypes == 1 || num_vtypes == 2);
  if (num_vtypes == 1)
    CHECK_EQ(num_src, num_dst);
  auto mg = CreateUnitGraphMetaGraph(num_vtypes);
  CSRPtr csc(new CSR(mg, num_src, num_dst, indptr, indices, edge_ids));
  return HeteroGraphPtr(new UnitGraph(mg, csc, nullptr, nullptr, restrict_format));
}

HeteroGraphPtr UnitGraph::CreateFromCSC(
    int64_t num_vtypes, const aten::CSRMatrix& mat,
    SparseFormat restrict_format) {
  CHECK(num_vtypes == 1 || num_vtypes == 2);
  if (num_vtypes == 1)
    CHECK_EQ(mat.num_rows, mat.num_cols);
  auto mg = CreateUnitGraphMetaGraph(num_vtypes);
  CSRPtr csc(new CSR(mg, mat));
  return HeteroGraphPtr(new UnitGraph(mg, csc, nullptr, nullptr, restrict_format));
}

Minjie Wang's avatar
Minjie Wang committed
1127
HeteroGraphPtr UnitGraph::AsNumBits(HeteroGraphPtr g, uint8_t bits) {
1128
1129
1130
1131
1132
1133
1134
  if (g->NumBits() == bits) {
    return g;
  } else {
    // TODO(minjie): since we don't have int32 operations,
    //   we make sure that this graph (on CPU) has materialized CSR,
    //   and then copy them to other context (usually GPU). This should
    //   be fixed later.
Minjie Wang's avatar
Minjie Wang committed
1135
    auto bg = std::dynamic_pointer_cast<UnitGraph>(g);
1136
    CHECK_NOTNULL(bg);
1137

1138
1139
    CSRPtr new_incsr = CSRPtr(new CSR(bg->GetInCSR()->AsNumBits(bits)));
    CSRPtr new_outcsr = CSRPtr(new CSR(bg->GetOutCSR()->AsNumBits(bits)));
1140
1141
    return HeteroGraphPtr(
        new UnitGraph(g->meta_graph(), new_incsr, new_outcsr, nullptr, bg->restrict_format_));
1142
1143
1144
  }
}

Minjie Wang's avatar
Minjie Wang committed
1145
HeteroGraphPtr UnitGraph::CopyTo(HeteroGraphPtr g, const DLContext& ctx) {
1146
1147
1148
1149
1150
1151
1152
  if (ctx == g->Context()) {
    return g;
  }
  // TODO(minjie): since we don't have GPU implementation of COO<->CSR,
  //   we make sure that this graph (on CPU) has materialized CSR,
  //   and then copy them to other context (usually GPU). This should
  //   be fixed later.
Minjie Wang's avatar
Minjie Wang committed
1153
  auto bg = std::dynamic_pointer_cast<UnitGraph>(g);
1154
  CHECK_NOTNULL(bg);
1155

1156
1157
  CSRPtr new_incsr = CSRPtr(new CSR(bg->GetInCSR()->CopyTo(ctx)));
  CSRPtr new_outcsr = CSRPtr(new CSR(bg->GetOutCSR()->CopyTo(ctx)));
1158
1159
  return HeteroGraphPtr(
      new UnitGraph(g->meta_graph(), new_incsr, new_outcsr, nullptr, bg->restrict_format_));
1160
1161
}

1162
1163
UnitGraph::UnitGraph(GraphPtr metagraph, CSRPtr in_csr, CSRPtr out_csr, COOPtr coo,
                     SparseFormat restrict_format)
Minjie Wang's avatar
Minjie Wang committed
1164
  : BaseHeteroGraph(metagraph), in_csr_(in_csr), out_csr_(out_csr), coo_(coo) {
1165
1166
1167
1168
1169
  restrict_format_ = restrict_format;

  // If the graph is hypersparse and in COO format, switch the restricted format to COO.
  // If the graph is given as CSR, the indptr array is already materialized so we don't
  // care about restricting conversion anyway (even if it is hypersparse).
1170
  if (restrict_format == SparseFormat::kAny) {
1171
    if (coo && coo->IsHypersparse())
1172
      restrict_format_ = SparseFormat::kCOO;
1173
1174
  }

1175
1176
1177
  CHECK(GetAny()) << "At least one graph structure should exist.";
}

Minjie Wang's avatar
Minjie Wang committed
1178
UnitGraph::CSRPtr UnitGraph::GetInCSR() const {
1179
1180
1181
  if (!in_csr_) {
    if (out_csr_) {
      const auto& newadj = aten::CSRTranspose(out_csr_->adj());
Minjie Wang's avatar
Minjie Wang committed
1182
      const_cast<UnitGraph*>(this)->in_csr_ = std::make_shared<CSR>(meta_graph(), newadj);
1183
1184
1185
1186
1187
    } else {
      CHECK(coo_) << "None of CSR, COO exist";
      const auto& adj = coo_->adj();
      const auto& newadj = aten::COOToCSR(
          aten::COOMatrix{adj.num_cols, adj.num_rows, adj.col, adj.row});
Minjie Wang's avatar
Minjie Wang committed
1188
      const_cast<UnitGraph*>(this)->in_csr_ = std::make_shared<CSR>(meta_graph(), newadj);
1189
1190
1191
1192
1193
1194
    }
  }
  return in_csr_;
}

/* !\brief Return out csr. If not exist, transpose the other one.*/
Minjie Wang's avatar
Minjie Wang committed
1195
UnitGraph::CSRPtr UnitGraph::GetOutCSR() const {
1196
1197
1198
  if (!out_csr_) {
    if (in_csr_) {
      const auto& newadj = aten::CSRTranspose(in_csr_->adj());
Minjie Wang's avatar
Minjie Wang committed
1199
      const_cast<UnitGraph*>(this)->out_csr_ = std::make_shared<CSR>(meta_graph(), newadj);
1200
1201
1202
    } else {
      CHECK(coo_) << "None of CSR, COO exist";
      const auto& newadj = aten::COOToCSR(coo_->adj());
Minjie Wang's avatar
Minjie Wang committed
1203
      const_cast<UnitGraph*>(this)->out_csr_ = std::make_shared<CSR>(meta_graph(), newadj);
1204
1205
1206
1207
1208
1209
    }
  }
  return out_csr_;
}

/* !\brief Return coo. If not exist, create from csr.*/
Minjie Wang's avatar
Minjie Wang committed
1210
UnitGraph::COOPtr UnitGraph::GetCOO() const {
1211
1212
  if (!coo_) {
    if (in_csr_) {
1213
1214
      const auto& newadj = aten::COOTranspose(aten::CSRToCOO(in_csr_->adj(), true));
      const_cast<UnitGraph*>(this)->coo_ = std::make_shared<COO>(meta_graph(), newadj);
1215
1216
1217
    } else {
      CHECK(out_csr_) << "Both CSR are missing.";
      const auto& newadj = aten::CSRToCOO(out_csr_->adj(), true);
Minjie Wang's avatar
Minjie Wang committed
1218
      const_cast<UnitGraph*>(this)->coo_ = std::make_shared<COO>(meta_graph(), newadj);
1219
1220
1221
1222
1223
    }
  }
  return coo_;
}

1224
aten::CSRMatrix UnitGraph::GetCSCMatrix(dgl_type_t etype) const {
1225
1226
1227
  return GetInCSR()->adj();
}

1228
aten::CSRMatrix UnitGraph::GetCSRMatrix(dgl_type_t etype) const {
1229
1230
1231
  return GetOutCSR()->adj();
}

1232
aten::COOMatrix UnitGraph::GetCOOMatrix(dgl_type_t etype) const {
1233
1234
1235
  return GetCOO()->adj();
}

Minjie Wang's avatar
Minjie Wang committed
1236
HeteroGraphPtr UnitGraph::GetAny() const {
1237
1238
1239
1240
1241
1242
1243
1244
1245
  if (in_csr_) {
    return in_csr_;
  } else if (out_csr_) {
    return out_csr_;
  } else {
    return coo_;
  }
}

1246
1247
HeteroGraphPtr UnitGraph::GetFormat(SparseFormat format) const {
  switch (format) {
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
  case SparseFormat::kCSR:
    return GetOutCSR();
  case SparseFormat::kCSC:
    return GetInCSR();
  case SparseFormat::kCOO:
    return GetCOO();
  case SparseFormat::kAny:
    return GetAny();
  default:
    LOG(FATAL) << "unsupported format code";
    return nullptr;
1259
1260
1261
1262
  }
}

SparseFormat UnitGraph::SelectFormat(SparseFormat preferred_format) const {
1263
  if (restrict_format_ != SparseFormat::kAny)
1264
    return restrict_format_;
1265
  else if (preferred_format != SparseFormat::kAny)
1266
1267
    return preferred_format;
  else if (in_csr_)
1268
    return SparseFormat::kCSC;
1269
  else if (out_csr_)
1270
    return SparseFormat::kCSR;
1271
  else
1272
    return SparseFormat::kCOO;
1273
1274
}

1275
1276
1277
1278
1279
1280
constexpr uint64_t kDGLSerialize_UnitGraphMagic = 0xDD2E60F0F6B4A127;

bool UnitGraph::Load(dmlc::Stream* fs) {
  uint64_t magicNum;
  CHECK(fs->Read(&magicNum)) << "Invalid Magic Number";
  CHECK_EQ(magicNum, kDGLSerialize_UnitGraphMagic) << "Invalid UnitGraph Data";
1281
1282
1283
1284
1285
1286

  int64_t format_code;
  CHECK(fs->Read(&format_code)) << "Invalid format";
  restrict_format_ = static_cast<SparseFormat>(format_code);

  switch (restrict_format_) {
1287
    case SparseFormat::kCOO:
1288
1289
      fs->Read(&coo_);
      break;
1290
    case SparseFormat::kCSR:
1291
1292
      fs->Read(&out_csr_);
      break;
1293
    case SparseFormat::kCSC:
1294
1295
1296
1297
1298
1299
1300
1301
1302
      fs->Read(&in_csr_);
      break;
    default:
      LOG(FATAL) << "unsupported format code";
      break;
  }

  meta_graph_ = GetAny()->meta_graph();

1303
1304
1305
  return true;
}

1306

1307
1308
void UnitGraph::Save(dmlc::Stream* fs) const {
  fs->Write(kDGLSerialize_UnitGraphMagic);
1309
1310
  // Didn't write UnitGraph::meta_graph_, since it's included in the underlying
  // sparse matrix
1311
  auto avail_fmt = SelectFormat(SparseFormat::kAny);
1312
1313
  fs->Write(static_cast<int64_t>(avail_fmt));
  switch (avail_fmt) {
1314
    case SparseFormat::kCOO:
1315
1316
      fs->Write(GetCOO());
      break;
1317
    case SparseFormat::kCSR:
1318
1319
      fs->Write(GetOutCSR());
      break;
1320
    case SparseFormat::kCSC:
1321
1322
1323
1324
1325
1326
      fs->Write(GetInCSR());
      break;
    default:
      LOG(FATAL) << "unsupported format code";
      break;
  }
1327
1328
}

1329
}  // namespace dgl