unit_graph.cc 53.3 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

72
73
74
75
  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.
76
    CHECK(!COOHasData(coo)) << "[BUG] COO should not contain data.";
77
    adj_.data = aten::NullArray();
78
  }
79

80
81
82
83
84
85
86
87
88
89
90
  COO() {
    // set magic num_rows/num_cols to mark it as undefined
    // adj_.num_rows == 0 and adj_.num_cols == 0 means empty UnitGraph which is supported
    adj_.num_rows = -1;
    adj_.num_cols = -1;
  };

  bool defined() const {
    return (adj_.num_rows >= 0) && (adj_.num_cols >= 0);
  }

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

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

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

  HeteroGraphPtr GetRelationGraph(dgl_type_t etype) const override {
Minjie Wang's avatar
Minjie Wang committed
104
    LOG(FATAL) << "The method shouldn't be called for UnitGraph graph. "
105
106
107
108
109
      << "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
110
    LOG(FATAL) << "UnitGraph graph is not mutable.";
111
112
113
  }

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

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

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

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

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

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

137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
  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));
    return ret;
  }

  COO CopyTo(const DLContext& ctx) const {
    if (Context() == ctx)
      return *this;
152
    return COO(meta_graph_, adj_.CopyTo(ctx));
153
154
  }

155
  bool IsMultigraph() const override {
156
    return aten::COOHasDuplicate(adj_);
157
158
159
160
161
162
163
  }

  bool IsReadonly() const override {
    return true;
  }

  uint64_t NumVertices(dgl_type_t vtype) const override {
Minjie Wang's avatar
Minjie Wang committed
164
    if (vtype == SrcType()) {
165
      return adj_.num_rows;
Minjie Wang's avatar
Minjie Wang committed
166
    } else if (vtype == DstType()) {
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
      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 {
188
189
190
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
    return aten::COOIsNonZero(adj_, src, dst);
191
192
193
  }

  BoolArray HasEdgesBetween(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) const override {
194
195
196
    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);
197
198
199
  }

  IdArray Predecessors(dgl_type_t etype, dgl_id_t dst) const override {
200
201
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
    return aten::COOGetRowDataAndIndices(aten::COOTranspose(adj_), dst).second;
202
203
204
  }

  IdArray Successors(dgl_type_t etype, dgl_id_t src) const override {
205
206
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    return aten::COOGetRowDataAndIndices(adj_, src).second;
207
208
209
  }

  IdArray EdgeId(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const override {
210
211
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
212
    return aten::COOGetAllData(adj_, src, dst);
213
214
  }

215
  EdgeArray EdgeIdsAll(dgl_type_t etype, IdArray src, IdArray dst) const override {
216
217
218
219
    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]};
220
221
  }

222
223
224
225
  IdArray EdgeIdsOne(dgl_type_t etype, IdArray src, IdArray dst) const override {
    return aten::COOGetData(adj_, src, dst);
  }

226
227
  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;
228
229
    const dgl_id_t src = aten::IndexSelect<int64_t>(adj_.row, eid);
    const dgl_id_t dst = aten::IndexSelect<int64_t>(adj_.col, eid);
230
231
232
233
    return std::pair<dgl_id_t, dgl_id_t>(src, dst);
  }

  EdgeArray FindEdges(dgl_type_t etype, IdArray eids) const override {
234
    CHECK(aten::IsValidIdArray(eids)) << "Invalid edge id array";
235
236
    BUG_ON(aten::IsNullArray(adj_.data)) <<
      "FindEdges requires the internal COO matrix not having EIDs.";
237
238
239
240
241
242
    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 {
243
244
245
246
247
    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};
248
249
250
  }

  EdgeArray InEdges(dgl_type_t etype, IdArray vids) const override {
251
252
253
254
    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};
255
256
257
  }

  EdgeArray OutEdges(dgl_type_t etype, dgl_id_t vid) const override {
258
259
260
261
    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};
262
263
264
  }

  EdgeArray OutEdges(dgl_type_t etype, IdArray vids) const override {
265
266
267
268
    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};
269
270
271
272
273
274
275
276
277
278
279
  }

  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 {
280
281
    CHECK(HasVertex(DstType(), vid)) << "Invalid dst vertex id: " << vid;
    return aten::COOGetRowNNZ(aten::COOTranspose(adj_), vid);
282
283
284
  }

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

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

  DegreeArray OutDegrees(dgl_type_t etype, IdArray vids) const override {
295
296
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
    return aten::COOGetRowNNZ(adj_, vids);
297
298
299
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
  }

  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)};
    }
  }

329
330
331
332
333
334
335
336
337
338
339
340
341
342
  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();
  }

343
  SparseFormat SelectFormat(dgl_type_t etype, dgl_format_code_t preferred_formats) const override {
344
    LOG(FATAL) << "Not enabled for COO graph";
345
    return SparseFormat::kCOO;
346
347
  }

348
  dgl_format_code_t GetAllowedFormats() const override {
349
    LOG(FATAL) << "Not enabled for COO graph";
350
    return 0;
351
352
  }

353
  dgl_format_code_t GetCreatedFormats() const override {
354
355
356
357
    LOG(FATAL) << "Not enabled for COO graph";
    return 0;
  }

358
  HeteroSubgraph VertexSubgraph(const std::vector<IdArray>& vids) const override {
359
360
361
362
363
364
365
366
367
368
369
370
    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;
371
372
373
374
375
376
377
378
379
380
381
382
383
384
  }

  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
385
          meta_graph(), new_nsrc, new_ndst, new_src, new_dst);
386
387
388
389
      subg.induced_edges = eids;
    } else {
      IdArray new_src = aten::IndexSelect(adj_.row, eids[0]);
      IdArray new_dst = aten::IndexSelect(adj_.col, eids[0]);
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
390
391
392
393
      subg.induced_vertices.emplace_back(
          aten::Range(0, NumVertices(SrcType()), NumBits(), Context()));
      subg.induced_vertices.emplace_back(
          aten::Range(0, NumVertices(DstType()), NumBits(), Context()));
394
      subg.graph = std::make_shared<COO>(
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
395
          meta_graph(), NumVertices(SrcType()), NumVertices(DstType()), new_src, new_dst);
396
397
398
399
400
      subg.induced_edges = eids;
    }
    return subg;
  }

401
  HeteroGraphPtr GetGraphInFormat(dgl_format_code_t formats) const override {
402
403
404
405
    LOG(FATAL) << "Not enabled for COO graph.";
    return nullptr;
  }

406
407
408
409
  aten::COOMatrix adj() const {
    return adj_;
  }

410
411
412
413
414
415
416
417
418
  /*!
   * \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);
  }

419
420
421
422
423
424
425
426
427
428
429
430
431
  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_);
  }

432
 private:
433
434
  friend class Serializer;

435
436
437
438
439
440
441
442
443
444
445
  /*! \brief internal adjacency matrix. Data array is empty */
  aten::COOMatrix adj_;
};

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

/*! \brief CSR graph */
Minjie Wang's avatar
Minjie Wang committed
446
class UnitGraph::CSR : public BaseHeteroGraph {
447
 public:
Minjie Wang's avatar
Minjie Wang committed
448
  CSR(GraphPtr metagraph, int64_t num_src, int64_t num_dst,
449
      IdArray indptr, IdArray indices, IdArray edge_ids)
Minjie Wang's avatar
Minjie Wang committed
450
    : BaseHeteroGraph(metagraph) {
451
452
453
454
455
    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";
456

457
458
459
    adj_ = aten::CSRMatrix{num_src, num_dst, indptr, indices, edge_ids};
  }

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

464
465
466
467
468
469
470
471
472
473
474
  CSR() {
    // set magic num_rows/num_cols to mark it as undefined
    // adj_.num_rows == 0 and adj_.num_cols == 0 means empty UnitGraph which is supported
    adj_.num_rows = -1;
    adj_.num_cols = -1;
  };

  bool defined() const {
    return (adj_.num_rows >= 0) || (adj_.num_cols >= 0);
  }

Minjie Wang's avatar
Minjie Wang committed
475
476
  inline dgl_type_t SrcType() const {
    return 0;
477
  }
Minjie Wang's avatar
Minjie Wang committed
478
479
480
481
482
483
484

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

  inline dgl_type_t EdgeType() const {
    return 0;
485
486
487
  }

  HeteroGraphPtr GetRelationGraph(dgl_type_t etype) const override {
Minjie Wang's avatar
Minjie Wang committed
488
    LOG(FATAL) << "The method shouldn't be called for UnitGraph graph. "
489
490
491
492
493
      << "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
494
    LOG(FATAL) << "UnitGraph graph is not mutable.";
495
496
497
  }

  void AddEdge(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) override {
Minjie Wang's avatar
Minjie Wang committed
498
    LOG(FATAL) << "UnitGraph graph is not mutable.";
499
500
501
  }

  void AddEdges(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) override {
Minjie Wang's avatar
Minjie Wang committed
502
    LOG(FATAL) << "UnitGraph graph is not mutable.";
503
504
505
  }

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

509
510
511
512
  DLDataType DataType() const override {
    return adj_.indices->dtype;
  }

513
514
515
516
517
518
519
520
  DLContext Context() const override {
    return adj_.indices->ctx;
  }

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

521
522
523
524
525
  CSR AsNumBits(uint8_t bits) const {
    if (NumBits() == bits) {
      return *this;
    } else {
      CSR ret(
Minjie Wang's avatar
Minjie Wang committed
526
          meta_graph_,
527
528
529
530
531
532
533
534
535
536
537
538
          adj_.num_rows, adj_.num_cols,
          aten::AsNumBits(adj_.indptr, bits),
          aten::AsNumBits(adj_.indices, bits),
          aten::AsNumBits(adj_.data, bits));
      return ret;
    }
  }

  CSR CopyTo(const DLContext& ctx) const {
    if (Context() == ctx) {
      return *this;
    } else {
539
      return CSR(meta_graph_, adj_.CopyTo(ctx));
540
541
542
    }
  }

543
  bool IsMultigraph() const override {
544
    return aten::CSRHasDuplicate(adj_);
545
546
547
548
549
550
551
  }

  bool IsReadonly() const override {
    return true;
  }

  uint64_t NumVertices(dgl_type_t vtype) const override {
Minjie Wang's avatar
Minjie Wang committed
552
    if (vtype == SrcType()) {
553
      return adj_.num_rows;
Minjie Wang's avatar
Minjie Wang committed
554
    } else if (vtype == DstType()) {
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
      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
576
577
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
578
579
580
581
    return aten::CSRIsNonZero(adj_, src, dst);
  }

  BoolArray HasEdgesBetween(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) const override {
582
583
    CHECK(aten::IsValidIdArray(src_ids)) << "Invalid vertex id array.";
    CHECK(aten::IsValidIdArray(dst_ids)) << "Invalid vertex id array.";
584
585
586
587
588
589
590
591
592
    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
593
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
594
595
596
597
    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
598
599
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
600
    return aten::CSRGetAllData(adj_, src, dst);
601
602
  }

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

610
611
612
613
  IdArray EdgeIdsOne(dgl_type_t etype, IdArray src, IdArray dst) const override {
    return aten::CSRGetData(adj_, src, dst);
  }

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

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

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

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

  EdgeArray OutEdges(dgl_type_t etype, dgl_id_t vid) const override {
Minjie Wang's avatar
Minjie Wang committed
635
    CHECK(HasVertex(SrcType(), vid)) << "Invalid src vertex id: " << vid;
636
637
638
639
640
641
642
    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 {
643
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
644
645
646
647
648
649
650
651
652
653
654
655
    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 << "\".";
656
657
658
659
660
    auto coo = aten::CSRToCOO(adj_, false);
    if (order == std::string("srcdst")) {
      // make sure the coo is sorted if an order is requested
      coo = aten::COOSort(coo, true);
    }
661
662
663
664
    return EdgeArray{coo.row, coo.col, coo.data};
  }

  uint64_t InDegree(dgl_type_t etype, dgl_id_t vid) const override {
665
    LOG(FATAL) << "Not enabled for CSR graph.";
666
667
668
669
    return {};
  }

  DegreeArray InDegrees(dgl_type_t etype, IdArray vids) const override {
670
    LOG(FATAL) << "Not enabled for CSR graph.";
671
672
673
674
    return {};
  }

  uint64_t OutDegree(dgl_type_t etype, dgl_id_t vid) const override {
Minjie Wang's avatar
Minjie Wang committed
675
    CHECK(HasVertex(SrcType(), vid)) << "Invalid src vertex id: " << vid;
676
677
678
679
    return aten::CSRGetRowNNZ(adj_, vid);
  }

  DegreeArray OutDegrees(dgl_type_t etype, IdArray vids) const override {
680
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
681
682
683
684
685
686
    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.
687
    CHECK_EQ(NumBits(), 64);
688
689
690
691
692
693
694
    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);
  }

695
696
697
698
699
700
701
702
703
704
  DGLIdIters32 SuccVec32(dgl_type_t etype, dgl_id_t vid) {
    // TODO(minjie): This still assumes the data type and device context
    //   of this graph. Should fix later.
    const int32_t* indptr_data = static_cast<int32_t*>(adj_.indptr->data);
    const int32_t* indices_data = static_cast<int32_t*>(adj_.indices->data);
    const int32_t start = indptr_data[vid];
    const int32_t end = indptr_data[vid + 1];
    return DGLIdIters32(indices_data + start, indices_data + end);
  }

705
706
707
  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.
708
    CHECK_EQ(NumBits(), 64);
709
710
711
712
713
714
715
716
    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 {
717
    LOG(FATAL) << "Not enabled for CSR graph.";
718
719
720
721
    return {};
  }

  DGLIdIters InEdgeVec(dgl_type_t etype, dgl_id_t vid) const override {
722
    LOG(FATAL) << "Not enabled for CSR graph.";
723
724
725
726
727
728
729
730
731
    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};
  }

732
733
734
735
736
737
738
739
740
741
742
743
744
745
  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_;
  }

746
  SparseFormat SelectFormat(dgl_type_t etype, dgl_format_code_t preferred_formats) const override {
747
    LOG(FATAL) << "Not enabled for CSR graph";
748
    return SparseFormat::kCSR;
749
750
  }

751
752
753
  dgl_format_code_t GetAllowedFormats() const override {
    LOG(FATAL) << "Not enabled for COO graph";
    return 0;
754
755
  }

756
  dgl_format_code_t GetCreatedFormats() const override {
757
758
759
760
    LOG(FATAL) << "Not enabled for CSR graph";
    return 0;
  }

761
  HeteroSubgraph VertexSubgraph(const std::vector<IdArray>& vids) const override {
Minjie Wang's avatar
Minjie Wang committed
762
763
764
765
    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.";
766
    HeteroSubgraph subg;
Minjie Wang's avatar
Minjie Wang committed
767
    const auto& submat = aten::CSRSliceMatrix(adj_, srcvids, dstvids);
768
    IdArray sub_eids = aten::Range(0, submat.data->shape[0], NumBits(), Context());
Minjie Wang's avatar
Minjie Wang committed
769
    subg.graph = std::make_shared<CSR>(meta_graph(), submat.num_rows, submat.num_cols,
770
771
772
773
774
775
776
777
        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 {
778
    LOG(FATAL) << "Not enabled for CSR graph.";
779
780
781
    return {};
  }

782
  HeteroGraphPtr GetGraphInFormat(dgl_format_code_t formats) const override {
783
784
785
786
    LOG(FATAL) << "Not enabled for CSR graph.";
    return nullptr;
  }

787
788
789
790
  aten::CSRMatrix adj() const {
    return adj_;
  }

791
792
793
794
795
796
797
798
799
800
801
802
803
  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_);
  }

804
 private:
805
806
  friend class Serializer;

807
808
809
810
811
812
  /*! \brief internal adjacency matrix. Data array stores edge ids */
  aten::CSRMatrix adj_;
};

//////////////////////////////////////////////////////////
//
Minjie Wang's avatar
Minjie Wang committed
813
// unit graph implementation
814
815
816
//
//////////////////////////////////////////////////////////

817
818
819
820
DLDataType UnitGraph::DataType() const {
  return GetAny()->DataType();
}

Minjie Wang's avatar
Minjie Wang committed
821
DLContext UnitGraph::Context() const {
822
823
824
  return GetAny()->Context();
}

Minjie Wang's avatar
Minjie Wang committed
825
uint8_t UnitGraph::NumBits() const {
826
827
828
  return GetAny()->NumBits();
}

Minjie Wang's avatar
Minjie Wang committed
829
bool UnitGraph::IsMultigraph() const {
830
  const SparseFormat fmt = SelectFormat(CSC_CODE);
831
832
  const auto ptr = GetFormat(fmt);
  return ptr->IsMultigraph();
833
834
}

Minjie Wang's avatar
Minjie Wang committed
835
uint64_t UnitGraph::NumVertices(dgl_type_t vtype) const {
836
  const SparseFormat fmt = SelectFormat(ALL_CODE);
837
838
839
  const auto ptr = GetFormat(fmt);
  // TODO(BarclayII): we have a lot of special handling for CSC.
  // Need to have a UnitGraph::CSC backend instead.
840
  if (fmt == SparseFormat::kCSC)
Minjie Wang's avatar
Minjie Wang committed
841
    vtype = (vtype == SrcType()) ? DstType() : SrcType();
842
  return ptr->NumVertices(vtype);
843
844
}

Minjie Wang's avatar
Minjie Wang committed
845
uint64_t UnitGraph::NumEdges(dgl_type_t etype) const {
846
847
848
  return GetAny()->NumEdges(etype);
}

Minjie Wang's avatar
Minjie Wang committed
849
bool UnitGraph::HasVertex(dgl_type_t vtype, dgl_id_t vid) const {
850
  const SparseFormat fmt = SelectFormat(ALL_CODE);
851
  const auto ptr = GetFormat(fmt);
852
  if (fmt == SparseFormat::kCSC)
Minjie Wang's avatar
Minjie Wang committed
853
    vtype = (vtype == SrcType()) ? DstType() : SrcType();
854
  return ptr->HasVertex(vtype, vid);
855
856
}

Minjie Wang's avatar
Minjie Wang committed
857
BoolArray UnitGraph::HasVertices(dgl_type_t vtype, IdArray vids) const {
858
  CHECK(aten::IsValidIdArray(vids)) << "Invalid id array input";
859
860
861
  return aten::LT(vids, NumVertices(vtype));
}

Minjie Wang's avatar
Minjie Wang committed
862
bool UnitGraph::HasEdgeBetween(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const {
863
  const SparseFormat fmt = SelectFormat(CSC_CODE);
864
  const auto ptr = GetFormat(fmt);
865
  if (fmt == SparseFormat::kCSC)
866
867
868
    return ptr->HasEdgeBetween(etype, dst, src);
  else
    return ptr->HasEdgeBetween(etype, src, dst);
869
870
}

Minjie Wang's avatar
Minjie Wang committed
871
BoolArray UnitGraph::HasEdgesBetween(
872
    dgl_type_t etype, IdArray src, IdArray dst) const {
873
  const SparseFormat fmt = SelectFormat(CSC_CODE);
874
  const auto ptr = GetFormat(fmt);
875
  if (fmt == SparseFormat::kCSC)
876
877
878
    return ptr->HasEdgesBetween(etype, dst, src);
  else
    return ptr->HasEdgesBetween(etype, src, dst);
879
880
}

Minjie Wang's avatar
Minjie Wang committed
881
IdArray UnitGraph::Predecessors(dgl_type_t etype, dgl_id_t dst) const {
882
  const SparseFormat fmt = SelectFormat(CSC_CODE);
883
  const auto ptr = GetFormat(fmt);
884
  if (fmt == SparseFormat::kCSC)
885
886
887
    return ptr->Successors(etype, dst);
  else
    return ptr->Predecessors(etype, dst);
888
889
}

Minjie Wang's avatar
Minjie Wang committed
890
IdArray UnitGraph::Successors(dgl_type_t etype, dgl_id_t src) const {
891
  const SparseFormat fmt = SelectFormat(CSR_CODE);
892
893
  const auto ptr = GetFormat(fmt);
  return ptr->Successors(etype, src);
894
895
}

Minjie Wang's avatar
Minjie Wang committed
896
IdArray UnitGraph::EdgeId(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const {
897
  const SparseFormat fmt = SelectFormat(CSR_CODE);
898
  const auto ptr = GetFormat(fmt);
899
  if (fmt == SparseFormat::kCSC)
900
901
902
    return ptr->EdgeId(etype, dst, src);
  else
    return ptr->EdgeId(etype, src, dst);
903
904
}

905
EdgeArray UnitGraph::EdgeIdsAll(dgl_type_t etype, IdArray src, IdArray dst) const {
906
  const SparseFormat fmt = SelectFormat(CSR_CODE);
907
  const auto ptr = GetFormat(fmt);
908
  if (fmt == SparseFormat::kCSC) {
909
    EdgeArray edges = ptr->EdgeIdsAll(etype, dst, src);
910
911
    return EdgeArray{edges.dst, edges.src, edges.id};
  } else {
912
913
914
915
916
    return ptr->EdgeIdsAll(etype, src, dst);
  }
}

IdArray UnitGraph::EdgeIdsOne(dgl_type_t etype, IdArray src, IdArray dst) const {
917
  const SparseFormat fmt = SelectFormat(CSR_CODE);
918
919
920
921
922
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::kCSC) {
    return ptr->EdgeIdsOne(etype, dst, src);
  } else {
    return ptr->EdgeIdsOne(etype, src, dst);
923
924
925
  }
}

Minjie Wang's avatar
Minjie Wang committed
926
std::pair<dgl_id_t, dgl_id_t> UnitGraph::FindEdge(dgl_type_t etype, dgl_id_t eid) const {
927
  const SparseFormat fmt = SelectFormat(COO_CODE);
928
929
  const auto ptr = GetFormat(fmt);
  return ptr->FindEdge(etype, eid);
930
931
}

Minjie Wang's avatar
Minjie Wang committed
932
EdgeArray UnitGraph::FindEdges(dgl_type_t etype, IdArray eids) const {
933
  const SparseFormat fmt = SelectFormat(COO_CODE);
934
935
  const auto ptr = GetFormat(fmt);
  return ptr->FindEdges(etype, eids);
936
937
}

Minjie Wang's avatar
Minjie Wang committed
938
EdgeArray UnitGraph::InEdges(dgl_type_t etype, dgl_id_t vid) const {
939
  const SparseFormat fmt = SelectFormat(CSC_CODE);
940
  const auto ptr = GetFormat(fmt);
941
  if (fmt == SparseFormat::kCSC) {
942
943
944
945
946
    const EdgeArray& ret = ptr->OutEdges(etype, vid);
    return {ret.dst, ret.src, ret.id};
  } else {
    return ptr->InEdges(etype, vid);
  }
947
948
}

Minjie Wang's avatar
Minjie Wang committed
949
EdgeArray UnitGraph::InEdges(dgl_type_t etype, IdArray vids) const {
950
  const SparseFormat fmt = SelectFormat(CSC_CODE);
951
  const auto ptr = GetFormat(fmt);
952
  if (fmt == SparseFormat::kCSC) {
953
954
955
956
957
    const EdgeArray& ret = ptr->OutEdges(etype, vids);
    return {ret.dst, ret.src, ret.id};
  } else {
    return ptr->InEdges(etype, vids);
  }
958
959
}

Minjie Wang's avatar
Minjie Wang committed
960
EdgeArray UnitGraph::OutEdges(dgl_type_t etype, dgl_id_t vid) const {
961
  const SparseFormat fmt = SelectFormat(CSR_CODE);
962
963
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdges(etype, vid);
964
965
}

Minjie Wang's avatar
Minjie Wang committed
966
EdgeArray UnitGraph::OutEdges(dgl_type_t etype, IdArray vids) const {
967
  const SparseFormat fmt = SelectFormat(CSR_CODE);
968
969
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdges(etype, vids);
970
971
}

Minjie Wang's avatar
Minjie Wang committed
972
EdgeArray UnitGraph::Edges(dgl_type_t etype, const std::string &order) const {
973
974
  SparseFormat fmt;
  if (order == std::string("eid")) {
975
    fmt = SelectFormat(COO_CODE);
976
  } else if (order.empty()) {
977
    // arbitrary order
978
    fmt = SelectFormat(ALL_CODE);
979
  } else if (order == std::string("srcdst")) {
980
    fmt = SelectFormat(CSR_CODE);
981
982
  } else {
    LOG(FATAL) << "Unsupported order request: " << order;
983
    return {};
984
  }
985
986

  const auto& edges = GetFormat(fmt)->Edges(etype, order);
987
  if (fmt == SparseFormat::kCSC)
988
989
990
    return EdgeArray{edges.dst, edges.src, edges.id};
  else
    return edges;
991
992
}

Minjie Wang's avatar
Minjie Wang committed
993
uint64_t UnitGraph::InDegree(dgl_type_t etype, dgl_id_t vid) const {
994
  SparseFormat fmt = SelectFormat(CSC_CODE);
995
  const auto ptr = GetFormat(fmt);
996
  if (fmt == SparseFormat::kCSC)
997
998
999
    return ptr->OutDegree(etype, vid);
  else
    return ptr->InDegree(etype, vid);
1000
1001
}

Minjie Wang's avatar
Minjie Wang committed
1002
DegreeArray UnitGraph::InDegrees(dgl_type_t etype, IdArray vids) const {
1003
  SparseFormat fmt = SelectFormat(CSC_CODE);
1004
  const auto ptr = GetFormat(fmt);
1005
  if (fmt == SparseFormat::kCSC)
1006
1007
1008
    return ptr->OutDegrees(etype, vids);
  else
    return ptr->InDegrees(etype, vids);
1009
1010
}

Minjie Wang's avatar
Minjie Wang committed
1011
uint64_t UnitGraph::OutDegree(dgl_type_t etype, dgl_id_t vid) const {
1012
  SparseFormat fmt = SelectFormat(CSR_CODE);
1013
1014
  const auto ptr = GetFormat(fmt);
  return ptr->OutDegree(etype, vid);
1015
1016
}

Minjie Wang's avatar
Minjie Wang committed
1017
DegreeArray UnitGraph::OutDegrees(dgl_type_t etype, IdArray vids) const {
1018
  SparseFormat fmt = SelectFormat(CSR_CODE);
1019
1020
  const auto ptr = GetFormat(fmt);
  return ptr->OutDegrees(etype, vids);
1021
1022
}

Minjie Wang's avatar
Minjie Wang committed
1023
DGLIdIters UnitGraph::SuccVec(dgl_type_t etype, dgl_id_t vid) const {
1024
  SparseFormat fmt = SelectFormat(CSR_CODE);
1025
1026
  const auto ptr = GetFormat(fmt);
  return ptr->SuccVec(etype, vid);
1027
1028
}

1029
DGLIdIters32 UnitGraph::SuccVec32(dgl_type_t etype, dgl_id_t vid) const {
1030
  SparseFormat fmt = SelectFormat(CSR_CODE);
1031
1032
1033
1034
1035
  const auto ptr = std::dynamic_pointer_cast<CSR>(GetFormat(fmt));
  CHECK_NOTNULL(ptr);
  return ptr->SuccVec32(etype, vid);
}

Minjie Wang's avatar
Minjie Wang committed
1036
DGLIdIters UnitGraph::OutEdgeVec(dgl_type_t etype, dgl_id_t vid) const {
1037
  SparseFormat fmt = SelectFormat(CSR_CODE);
1038
1039
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdgeVec(etype, vid);
1040
1041
}

Minjie Wang's avatar
Minjie Wang committed
1042
DGLIdIters UnitGraph::PredVec(dgl_type_t etype, dgl_id_t vid) const {
1043
  SparseFormat fmt = SelectFormat(CSC_CODE);
1044
  const auto ptr = GetFormat(fmt);
1045
  if (fmt == SparseFormat::kCSC)
1046
1047
1048
    return ptr->SuccVec(etype, vid);
  else
    return ptr->PredVec(etype, vid);
1049
1050
}

Minjie Wang's avatar
Minjie Wang committed
1051
DGLIdIters UnitGraph::InEdgeVec(dgl_type_t etype, dgl_id_t vid) const {
1052
  SparseFormat fmt = SelectFormat(CSC_CODE);
1053
  const auto ptr = GetFormat(fmt);
1054
  if (fmt == SparseFormat::kCSC)
1055
1056
1057
    return ptr->OutEdgeVec(etype, vid);
  else
    return ptr->InEdgeVec(etype, vid);
1058
1059
}

Minjie Wang's avatar
Minjie Wang committed
1060
std::vector<IdArray> UnitGraph::GetAdj(
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
    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
1080
HeteroSubgraph UnitGraph::VertexSubgraph(const std::vector<IdArray>& vids) const {
1081
  // We prefer to generate a subgraph from out-csr.
1082
  SparseFormat fmt = SelectFormat(CSR_CODE);
1083
  HeteroSubgraph sg = GetFormat(fmt)->VertexSubgraph(vids);
1084
  HeteroSubgraph ret;
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104

  CSRPtr subcsr = nullptr;
  CSRPtr subcsc = nullptr;
  COOPtr subcoo = nullptr;
  switch (fmt) {
    case SparseFormat::kCSR:
      subcsr = std::dynamic_pointer_cast<CSR>(sg.graph);
      break;
    case SparseFormat::kCSC:
      subcsc = std::dynamic_pointer_cast<CSR>(sg.graph);
      break;
    case SparseFormat::kCOO:
      subcoo = std::dynamic_pointer_cast<COO>(sg.graph);
      break;
    default:
      LOG(FATAL) << "[BUG] unsupported format " << static_cast<int>(fmt);
      return ret;
  }

  ret.graph = HeteroGraphPtr(new UnitGraph(meta_graph(), subcsc, subcsr, subcoo));
1105
1106
1107
1108
1109
  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
1110
HeteroSubgraph UnitGraph::EdgeSubgraph(
1111
    const std::vector<IdArray>& eids, bool preserve_nodes) const {
1112
  SparseFormat fmt = SelectFormat(COO_CODE);
1113
  auto sg = GetFormat(fmt)->EdgeSubgraph(eids, preserve_nodes);
1114
  HeteroSubgraph ret;
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134

  CSRPtr subcsr = nullptr;
  CSRPtr subcsc = nullptr;
  COOPtr subcoo = nullptr;
  switch (fmt) {
    case SparseFormat::kCSR:
      subcsr = std::dynamic_pointer_cast<CSR>(sg.graph);
      break;
    case SparseFormat::kCSC:
      subcsc = std::dynamic_pointer_cast<CSR>(sg.graph);
      break;
    case SparseFormat::kCOO:
      subcoo = std::dynamic_pointer_cast<COO>(sg.graph);
      break;
    default:
      LOG(FATAL) << "[BUG] unsupported format " << static_cast<int>(fmt);
      return ret;
  }

  ret.graph = HeteroGraphPtr(new UnitGraph(meta_graph(), subcsc, subcsr, subcoo));
1135
1136
1137
1138
1139
  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
1140
HeteroGraphPtr UnitGraph::CreateFromCOO(
1141
1142
    int64_t num_vtypes, int64_t num_src, int64_t num_dst,
    IdArray row, IdArray col,
1143
    dgl_format_code_t formats) {
Minjie Wang's avatar
Minjie Wang committed
1144
1145
1146
1147
1148
  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));
1149
1150

  return HeteroGraphPtr(
1151
      new UnitGraph(mg, nullptr, nullptr, coo, formats));
1152
1153
}

1154
1155
HeteroGraphPtr UnitGraph::CreateFromCOO(
    int64_t num_vtypes, const aten::COOMatrix& mat,
1156
    dgl_format_code_t formats) {
1157
1158
1159
1160
1161
  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));
1162

1163
  return HeteroGraphPtr(
1164
      new UnitGraph(mg, nullptr, nullptr, coo, formats));
1165
1166
}

Minjie Wang's avatar
Minjie Wang committed
1167
1168
HeteroGraphPtr UnitGraph::CreateFromCSR(
    int64_t num_vtypes, int64_t num_src, int64_t num_dst,
1169
    IdArray indptr, IdArray indices, IdArray edge_ids, dgl_format_code_t formats) {
Minjie Wang's avatar
Minjie Wang committed
1170
1171
1172
1173
1174
  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));
1175
  return HeteroGraphPtr(new UnitGraph(mg, nullptr, csr, nullptr, formats));
1176
1177
}

1178
1179
HeteroGraphPtr UnitGraph::CreateFromCSR(
    int64_t num_vtypes, const aten::CSRMatrix& mat,
1180
    dgl_format_code_t formats) {
1181
1182
1183
1184
1185
  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));
1186
  return HeteroGraphPtr(new UnitGraph(mg, nullptr, csr, nullptr, formats));
1187
1188
}

1189
1190
HeteroGraphPtr UnitGraph::CreateFromCSC(
    int64_t num_vtypes, int64_t num_src, int64_t num_dst,
1191
    IdArray indptr, IdArray indices, IdArray edge_ids, dgl_format_code_t formats) {
1192
1193
1194
1195
1196
  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));
1197
  return HeteroGraphPtr(new UnitGraph(mg, csc, nullptr, nullptr, formats));
1198
1199
1200
1201
}

HeteroGraphPtr UnitGraph::CreateFromCSC(
    int64_t num_vtypes, const aten::CSRMatrix& mat,
1202
    dgl_format_code_t formats) {
1203
1204
1205
1206
1207
  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));
1208
  return HeteroGraphPtr(new UnitGraph(mg, csc, nullptr, nullptr, formats));
1209
1210
}

Minjie Wang's avatar
Minjie Wang committed
1211
HeteroGraphPtr UnitGraph::AsNumBits(HeteroGraphPtr g, uint8_t bits) {
1212
1213
1214
  if (g->NumBits() == bits) {
    return g;
  } else {
Minjie Wang's avatar
Minjie Wang committed
1215
    auto bg = std::dynamic_pointer_cast<UnitGraph>(g);
1216
    CHECK_NOTNULL(bg);
1217
1218
1219
1220
1221
1222
    CSRPtr new_incsr =
      (bg->in_csr_->defined())? CSRPtr(new CSR(bg->in_csr_->AsNumBits(bits))) : nullptr;
    CSRPtr new_outcsr =
      (bg->out_csr_->defined())? CSRPtr(new CSR(bg->out_csr_->AsNumBits(bits))) : nullptr;
    COOPtr new_coo =
      (bg->coo_->defined())? COOPtr(new COO(bg->coo_->AsNumBits(bits))) : nullptr;
1223
    return HeteroGraphPtr(
1224
        new UnitGraph(g->meta_graph(), new_incsr, new_outcsr, new_coo, bg->formats_));
1225
1226
1227
  }
}

Minjie Wang's avatar
Minjie Wang committed
1228
HeteroGraphPtr UnitGraph::CopyTo(HeteroGraphPtr g, const DLContext& ctx) {
1229
1230
  if (ctx == g->Context()) {
    return g;
1231
1232
1233
  } else {
    auto bg = std::dynamic_pointer_cast<UnitGraph>(g);
    CHECK_NOTNULL(bg);
1234
1235
1236
1237
1238
1239
    CSRPtr new_incsr =
      (bg->in_csr_->defined())? CSRPtr(new CSR(bg->in_csr_->CopyTo(ctx))) : nullptr;
    CSRPtr new_outcsr =
      (bg->out_csr_->defined())? CSRPtr(new CSR(bg->out_csr_->CopyTo(ctx))) : nullptr;
    COOPtr new_coo =
      (bg->coo_->defined())? COOPtr(new COO(bg->coo_->CopyTo(ctx))) : nullptr;
1240
    return HeteroGraphPtr(
1241
        new UnitGraph(g->meta_graph(), new_incsr, new_outcsr, new_coo, bg->formats_));
1242
1243
1244
  }
}

1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
void UnitGraph::InvalidateCSR() {
  this->out_csr_ = CSRPtr(new CSR());
}

void UnitGraph::InvalidateCSC() {
  this->in_csr_ = CSRPtr(new CSR());
}

void UnitGraph::InvalidateCOO() {
  this->coo_ = COOPtr(new COO());
}

1257
UnitGraph::UnitGraph(GraphPtr metagraph, CSRPtr in_csr, CSRPtr out_csr, COOPtr coo,
1258
                     dgl_format_code_t formats)
Minjie Wang's avatar
Minjie Wang committed
1259
  : BaseHeteroGraph(metagraph), in_csr_(in_csr), out_csr_(out_csr), coo_(coo) {
1260
1261
1262
1263
1264
1265
1266
1267
1268
  if (!in_csr_) {
    in_csr_ = CSRPtr(new CSR());
  }
  if (!out_csr_) {
    out_csr_ = CSRPtr(new CSR());
  }
  if (!coo_) {
    coo_ = COOPtr(new COO());
  }
1269
1270
1271
1272
1273
  formats_ = formats;
  dgl_format_code_t created = GetCreatedFormats();
  if ((formats | created) != formats)
    LOG(FATAL) << "Graph created from formats: " << CodeToStr(created) <<
      ", which is not compatible with available formats: " << CodeToStr(formats);
1274
1275
1276
  CHECK(GetAny()) << "At least one graph structure should exist.";
}

1277
1278
1279
1280
1281
1282
1283
HeteroGraphPtr UnitGraph::CreateHomographFrom(
    const aten::CSRMatrix &in_csr,
    const aten::CSRMatrix &out_csr,
    const aten::COOMatrix &coo,
    bool has_in_csr,
    bool has_out_csr,
    bool has_coo,
1284
    dgl_format_code_t formats) {
1285
1286
1287
1288
1289
1290
1291
1292
  auto mg = CreateUnitGraphMetaGraph1();

  CSRPtr in_csr_ptr = nullptr;
  CSRPtr out_csr_ptr = nullptr;
  COOPtr coo_ptr = nullptr;

  if (has_in_csr)
    in_csr_ptr = CSRPtr(new CSR(mg, in_csr));
1293
1294
  else
    in_csr_ptr = CSRPtr(new CSR());
1295
1296
  if (has_out_csr)
    out_csr_ptr = CSRPtr(new CSR(mg, out_csr));
1297
1298
  else
    out_csr_ptr = CSRPtr(new CSR());
1299
1300
  if (has_coo)
    coo_ptr = COOPtr(new COO(mg, coo));
1301
1302
  else
    coo_ptr = COOPtr(new COO());
1303

1304
  return HeteroGraphPtr(new UnitGraph(mg, in_csr_ptr, out_csr_ptr, coo_ptr, formats));
1305
1306
}

1307
1308
UnitGraph::CSRPtr UnitGraph::GetInCSR(bool inplace) const {
  if (inplace)
1309
    if (!(formats_ & CSC_CODE))
1310
1311
      LOG(FATAL) << "The graph have restricted sparse format " <<
        CodeToStr(formats_) << ", cannot create CSC matrix.";
1312
  CSRPtr ret = in_csr_;
1313
1314
  // Prefers converting from COO since it is parallelized.
  // TODO(BarclayII): need benchmarking.
1315
  if (!in_csr_->defined()) {
1316
1317
1318
    if (coo_->defined()) {
      const auto& newadj = aten::COOToCSR(
            aten::COOTranspose(coo_->adj()));
1319

1320
      if (inplace)
1321
1322
1323
        *(const_cast<UnitGraph*>(this)->in_csr_) = CSR(meta_graph(), newadj);
      else
        ret = std::make_shared<CSR>(meta_graph(), newadj);
1324
    } else {
1325
1326
      CHECK(out_csr_->defined()) << "None of CSR, COO exist";
      const auto& newadj = aten::CSRTranspose(out_csr_->adj());
1327

1328
      if (inplace)
1329
1330
1331
        *(const_cast<UnitGraph*>(this)->in_csr_) = CSR(meta_graph(), newadj);
      else
        ret = std::make_shared<CSR>(meta_graph(), newadj);
1332
1333
    }
  }
1334
  return ret;
1335
1336
1337
}

/* !\brief Return out csr. If not exist, transpose the other one.*/
1338
1339
UnitGraph::CSRPtr UnitGraph::GetOutCSR(bool inplace) const {
  if (inplace)
1340
    if (!(formats_ & CSR_CODE))
1341
1342
      LOG(FATAL) << "The graph have restricted sparse format " <<
        CodeToStr(formats_) << ", cannot create CSR matrix.";
1343
  CSRPtr ret = out_csr_;
1344
1345
  // Prefers converting from COO since it is parallelized.
  // TODO(BarclayII): need benchmarking.
1346
  if (!out_csr_->defined()) {
1347
1348
    if (coo_->defined()) {
      const auto& newadj = aten::COOToCSR(coo_->adj());
1349

1350
      if (inplace)
1351
1352
1353
        *(const_cast<UnitGraph*>(this)->out_csr_) = CSR(meta_graph(), newadj);
      else
        ret = std::make_shared<CSR>(meta_graph(), newadj);
1354
    } else {
1355
1356
      CHECK(in_csr_->defined()) << "None of CSR, COO exist";
      const auto& newadj = aten::CSRTranspose(in_csr_->adj());
1357

1358
      if (inplace)
1359
1360
1361
        *(const_cast<UnitGraph*>(this)->out_csr_) = CSR(meta_graph(), newadj);
      else
        ret = std::make_shared<CSR>(meta_graph(), newadj);
1362
1363
    }
  }
1364
  return ret;
1365
1366
1367
}

/* !\brief Return coo. If not exist, create from csr.*/
1368
1369
UnitGraph::COOPtr UnitGraph::GetCOO(bool inplace) const {
  if (inplace)
1370
    if (!(formats_ & COO_CODE))
1371
1372
      LOG(FATAL) << "The graph have restricted sparse format " <<
        CodeToStr(formats_) << ", cannot create COO matrix.";
1373
  COOPtr ret = coo_;
1374
1375
  if (!coo_->defined()) {
    if (in_csr_->defined()) {
1376
      const auto& newadj = aten::COOTranspose(aten::CSRToCOO(in_csr_->adj(), true));
1377

1378
      if (inplace)
1379
1380
1381
        *(const_cast<UnitGraph*>(this)->coo_) = COO(meta_graph(), newadj);
      else
        ret = std::make_shared<COO>(meta_graph(), newadj);
1382
    } else {
1383
      CHECK(out_csr_->defined()) << "Both CSR are missing.";
1384
      const auto& newadj = aten::CSRToCOO(out_csr_->adj(), true);
1385

1386
      if (inplace)
1387
1388
1389
        *(const_cast<UnitGraph*>(this)->coo_) = COO(meta_graph(), newadj);
      else
        ret = std::make_shared<COO>(meta_graph(), newadj);
1390
1391
    }
  }
1392
  return ret;
1393
1394
}

1395
aten::CSRMatrix UnitGraph::GetCSCMatrix(dgl_type_t etype) const {
1396
1397
1398
  return GetInCSR()->adj();
}

1399
aten::CSRMatrix UnitGraph::GetCSRMatrix(dgl_type_t etype) const {
1400
1401
1402
  return GetOutCSR()->adj();
}

1403
aten::COOMatrix UnitGraph::GetCOOMatrix(dgl_type_t etype) const {
1404
1405
1406
  return GetCOO()->adj();
}

Minjie Wang's avatar
Minjie Wang committed
1407
HeteroGraphPtr UnitGraph::GetAny() const {
1408
  if (in_csr_->defined()) {
1409
    return in_csr_;
1410
  } else if (out_csr_->defined()) {
1411
1412
1413
1414
1415
1416
    return out_csr_;
  } else {
    return coo_;
  }
}

1417
dgl_format_code_t UnitGraph::GetCreatedFormats() const {
1418
  dgl_format_code_t ret = 0;
1419
  if (in_csr_->defined())
1420
    ret |= CSC_CODE;
1421
  if (out_csr_->defined())
1422
    ret |= CSR_CODE;
1423
  if (coo_->defined())
1424
    ret |= COO_CODE;
1425
1426
1427
  return ret;
}

1428
1429
1430
1431
dgl_format_code_t UnitGraph::GetAllowedFormats() const {
  return formats_;
}

1432
1433
HeteroGraphPtr UnitGraph::GetFormat(SparseFormat format) const {
  switch (format) {
1434
1435
1436
1437
  case SparseFormat::kCSR:
    return GetOutCSR();
  case SparseFormat::kCSC:
    return GetInCSR();
1438
  default:
1439
    return GetCOO();
1440
1441
1442
  }
}

1443
HeteroGraphPtr UnitGraph::GetGraphInFormat(dgl_format_code_t formats) const {
1444
  if (formats == ALL_CODE)
1445
    return HeteroGraphPtr(
1446
1447
        // TODO(xiangsx) Make it as graph storage.Clone()
        new UnitGraph(meta_graph_,
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
                      (in_csr_->defined())
                          ? CSRPtr(new CSR(*in_csr_))
                          : nullptr,
                      (out_csr_->defined())
                          ? CSRPtr(new CSR(*out_csr_))
                          : nullptr,
                      (coo_->defined())
                          ? COOPtr(new COO(*coo_))
                          : nullptr,
                      formats));
  int64_t num_vtypes = NumVertexTypes();
1459
  if (formats & COO_CODE)
1460
    return CreateFromCOO(num_vtypes, GetCOO(false)->adj(), formats);
1461
  if (formats & CSR_CODE)
1462
1463
1464
1465
1466
1467
1468
1469
1470
    return CreateFromCSR(num_vtypes, GetOutCSR(false)->adj(), formats);
  return CreateFromCSC(num_vtypes, GetInCSR(false)->adj(), formats);
}

SparseFormat UnitGraph::SelectFormat(dgl_format_code_t preferred_formats) const {
  dgl_format_code_t common = preferred_formats & formats_;
  dgl_format_code_t created = GetCreatedFormats();
  if (common & created)
    return DecodeFormat(common & created);
1471
1472
1473
1474
1475

  // NOTE(zihao): hypersparse is currently disabled since many CUDA operators on COO have
  // not been implmented yet.
  // if (coo_->defined() && coo_->IsHypersparse())  // only allow coo for hypersparse graph.
  //   return SparseFormat::kCOO;
1476
1477
1478
  if (common)
    return DecodeFormat(common);
  return DecodeFormat(created);
1479
1480
}

1481
1482
1483
1484
GraphPtr UnitGraph::AsImmutableGraph() const {
  CHECK(NumVertexTypes() == 1) << "not a homogeneous graph";
  dgl::CSRPtr in_csr_ptr = nullptr, out_csr_ptr = nullptr;
  dgl::COOPtr coo_ptr = nullptr;
1485
  if (in_csr_->defined()) {
1486
    aten::CSRMatrix csc = GetCSCMatrix(0);
1487
    in_csr_ptr = dgl::CSRPtr(new dgl::CSR(csc.indptr, csc.indices, csc.data));
1488
  }
1489
  if (out_csr_->defined()) {
1490
    aten::CSRMatrix csr = GetCSRMatrix(0);
1491
    out_csr_ptr = dgl::CSRPtr(new dgl::CSR(csr.indptr, csr.indices, csr.data));
1492
  }
1493
  if (coo_->defined()) {
1494
1495
    aten::COOMatrix coo = GetCOOMatrix(0);
    if (!COOHasData(coo)) {
1496
      coo_ptr = dgl::COOPtr(new dgl::COO(NumVertices(0), coo.row, coo.col));
1497
1498
1499
    } else {
      IdArray new_src = Scatter(coo.row, coo.data);
      IdArray new_dst = Scatter(coo.col, coo.data);
1500
      coo_ptr = dgl::COOPtr(new dgl::COO(NumVertices(0), new_src, new_dst));
1501
1502
1503
1504
1505
    }
  }
  return GraphPtr(new dgl::ImmutableGraph(in_csr_ptr, out_csr_ptr, coo_ptr));
}

1506
1507
HeteroGraphPtr UnitGraph::LineGraph(bool backtracking) const {
  // TODO(xiangsx) currently we only support homogeneous graph
1508
  auto fmt = SelectFormat(ALL_CODE);
1509
1510
  switch (fmt) {
    case SparseFormat::kCOO: {
1511
      return CreateFromCOO(1, aten::COOLineGraph(coo_->adj(), backtracking));
1512
1513
1514
1515
    }
    case SparseFormat::kCSR: {
      const aten::CSRMatrix csr = GetCSRMatrix(0);
      const aten::COOMatrix coo = aten::COOLineGraph(aten::CSRToCOO(csr, true), backtracking);
1516
      return CreateFromCOO(1, coo);
1517
1518
1519
1520
1521
    }
    case SparseFormat::kCSC: {
      const aten::CSRMatrix csc = GetCSCMatrix(0);
      const aten::CSRMatrix csr = aten::CSRTranspose(csc);
      const aten::COOMatrix coo = aten::COOLineGraph(aten::CSRToCOO(csr, true), backtracking);
1522
      return CreateFromCOO(1, coo);
1523
1524
1525
1526
1527
1528
1529
1530
    }
    default:
      LOG(FATAL) << "None of CSC, CSR, COO exist";
      break;
  }
  return nullptr;
}

1531
1532
1533
1534
1535
1536
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";
1537

1538
  int64_t save_format_code, formats_code;
1539
  CHECK(fs->Read(&save_format_code)) << "Invalid format";
1540
  CHECK(fs->Read(&formats_code)) << "Invalid format";
1541
  auto save_format = static_cast<SparseFormat>(save_format_code);
1542
1543
1544
1545
1546
1547
  if (formats_code >> 32) {
    formats_ = static_cast<dgl_format_code_t>(0xffffffff & formats_code);
  } else {
    // NOTE(zihao): to be compatible with old formats.
    switch (formats_code & 0xffffffff) {
    case 0:
1548
      formats_ = ALL_CODE;
1549
1550
      break;
    case 1:
1551
      formats_ = COO_CODE;
1552
1553
      break;
    case 2:
1554
      formats_ = CSR_CODE;
1555
1556
      break;
    case 3:
1557
      formats_ = CSC_CODE;
1558
1559
1560
1561
1562
1563
      break;
    default:
      LOG(FATAL) << "Load graph failed, formats code " << formats_code <<
        "not recognized.";
    }
  }
1564

1565
  switch (save_format) {
1566
    case SparseFormat::kCOO:
1567
1568
      fs->Read(&coo_);
      break;
1569
    case SparseFormat::kCSR:
1570
1571
      fs->Read(&out_csr_);
      break;
1572
    case SparseFormat::kCSC:
1573
1574
1575
1576
1577
1578
1579
      fs->Read(&in_csr_);
      break;
    default:
      LOG(FATAL) << "unsupported format code";
      break;
  }

1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
  if (!in_csr_) {
    in_csr_ = CSRPtr(new CSR());
  }
  if (!out_csr_) {
    out_csr_ = CSRPtr(new CSR());
  }
  if (!coo_) {
    coo_ = COOPtr(new COO());
  }

1590
1591
  meta_graph_ = GetAny()->meta_graph();

1592
1593
1594
  return true;
}

1595

1596
1597
void UnitGraph::Save(dmlc::Stream* fs) const {
  fs->Write(kDGLSerialize_UnitGraphMagic);
1598
1599
  // Didn't write UnitGraph::meta_graph_, since it's included in the underlying
  // sparse matrix
1600
  auto avail_fmt = SelectFormat(ALL_CODE);
1601
  fs->Write(static_cast<int64_t>(avail_fmt));
1602
  fs->Write(static_cast<int64_t>(formats_ | 0x100000000));
1603
  switch (avail_fmt) {
1604
    case SparseFormat::kCOO:
1605
1606
      fs->Write(GetCOO());
      break;
1607
    case SparseFormat::kCSR:
1608
1609
      fs->Write(GetOutCSR());
      break;
1610
    case SparseFormat::kCSC:
1611
1612
1613
1614
1615
1616
      fs->Write(GetInCSR());
      break;
    default:
      LOG(FATAL) << "unsupported format code";
      break;
  }
1617
1618
}

1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
UnitGraphPtr UnitGraph::Reverse() const {
  CSRPtr new_incsr = out_csr_, new_outcsr = in_csr_;
  COOPtr new_coo = nullptr;
  if (coo_->defined()) {
    new_coo = COOPtr(new COO(coo_->meta_graph(), aten::COOTranspose(coo_->adj())));
  }

  return UnitGraphPtr(new UnitGraph(meta_graph(), new_incsr, new_outcsr, new_coo));
}

1629
1630
1631
1632
1633
1634
1635
std::tuple<UnitGraphPtr, IdArray, IdArray>
UnitGraph::ToSimple() const {
  CSRPtr new_incsr = nullptr, new_outcsr = nullptr;
  COOPtr new_coo = nullptr;
  IdArray count;
  IdArray edge_map;

1636
  auto avail_fmt = SelectFormat(ALL_CODE);
1637
1638
  switch (avail_fmt) {
    case SparseFormat::kCOO: {
1639
      auto ret = aten::COOToSimple(GetCOO()->adj());
1640
1641
      count = std::get<1>(ret);
      edge_map = std::get<2>(ret);
1642
      new_coo = COOPtr(new COO(meta_graph(), std::get<0>(ret)));
1643
1644
1645
      break;
    }
    case SparseFormat::kCSR: {
1646
      auto ret = aten::CSRToSimple(GetOutCSR()->adj());
1647
1648
      count = std::get<1>(ret);
      edge_map = std::get<2>(ret);
1649
      new_outcsr = CSRPtr(new CSR(meta_graph(), std::get<0>(ret)));
1650
1651
1652
      break;
    }
    case SparseFormat::kCSC: {
1653
      auto ret = aten::CSRToSimple(GetInCSR()->adj());
1654
1655
      count = std::get<1>(ret);
      edge_map = std::get<2>(ret);
1656
      new_incsr = CSRPtr(new CSR(meta_graph(), std::get<0>(ret)));
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
      break;
    }
    default:
      LOG(FATAL) << "At lease one of COO, CSR or CSC adj should exist.";
      break;
  }

  return std::make_tuple(UnitGraphPtr(new UnitGraph(meta_graph(), new_incsr, new_outcsr, new_coo)),
                         count,
                         edge_map);
}

1669
}  // namespace dgl