unit_graph.cc 53.7 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:
64
65
  COO(GraphPtr metagraph, int64_t num_src, int64_t num_dst, IdArray src,
      IdArray dst, bool row_sorted = false, bool col_sorted = false)
Minjie Wang's avatar
Minjie Wang committed
66
    : BaseHeteroGraph(metagraph) {
67
68
69
    CHECK(aten::IsValidIdArray(src));
    CHECK(aten::IsValidIdArray(dst));
    CHECK_EQ(src->shape[0], dst->shape[0]) << "Input arrays should have the same length.";
70
71
72
    adj_ = aten::COOMatrix{num_src, num_dst, src, dst,
        NullArray(),
        row_sorted, col_sorted};
73
  }
74

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

83
84
85
86
87
88
89
90
91
92
93
  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
94
95
  inline dgl_type_t SrcType() const {
    return 0;
96
  }
Minjie Wang's avatar
Minjie Wang committed
97
98
99
100
101
102
103

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

  inline dgl_type_t EdgeType() const {
    return 0;
104
105
106
  }

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

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

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

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

128
129
130
131
  DLDataType DataType() const override {
    return adj_.row->dtype;
  }

132
133
134
135
136
137
138
139
  DLContext Context() const override {
    return adj_.row->ctx;
  }

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

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
  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;
155
    return COO(meta_graph_, adj_.CopyTo(ctx));
156
157
  }

158
  bool IsMultigraph() const override {
159
    return aten::COOHasDuplicate(adj_);
160
161
162
163
164
165
166
  }

  bool IsReadonly() const override {
    return true;
  }

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

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

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

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

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

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

225
226
227
228
  IdArray EdgeIdsOne(dgl_type_t etype, IdArray src, IdArray dst) const override {
    return aten::COOGetData(adj_, src, dst);
  }

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

  EdgeArray FindEdges(dgl_type_t etype, IdArray eids) const override {
237
    CHECK(aten::IsValidIdArray(eids)) << "Invalid edge id array";
238
    BUG_IF_FAIL(aten::IsNullArray(adj_.data)) <<
239
      "FindEdges requires the internal COO matrix not having EIDs.";
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
  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();
  }

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

351
  dgl_format_code_t GetAllowedFormats() const override {
352
    LOG(FATAL) << "Not enabled for COO graph";
353
    return 0;
354
355
  }

356
  dgl_format_code_t GetCreatedFormats() const override {
357
358
359
360
    LOG(FATAL) << "Not enabled for COO graph";
    return 0;
  }

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

  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
388
          meta_graph(), new_nsrc, new_ndst, new_src, new_dst);
389
390
391
392
      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
393
394
395
396
      subg.induced_vertices.emplace_back(
          aten::Range(0, NumVertices(SrcType()), NumBits(), Context()));
      subg.induced_vertices.emplace_back(
          aten::Range(0, NumVertices(DstType()), NumBits(), Context()));
397
      subg.graph = std::make_shared<COO>(
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
398
          meta_graph(), NumVertices(SrcType()), NumVertices(DstType()), new_src, new_dst);
399
400
401
402
403
      subg.induced_edges = eids;
    }
    return subg;
  }

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

409
410
411
412
  aten::COOMatrix adj() const {
    return adj_;
  }

413
414
415
416
417
418
419
420
421
  /*!
   * \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);
  }

422
423
424
425
426
427
428
429
430
431
432
433
434
  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_);
  }

435
 private:
436
437
  friend class Serializer;

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

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

/*! \brief CSR graph */
Minjie Wang's avatar
Minjie Wang committed
449
class UnitGraph::CSR : public BaseHeteroGraph {
450
 public:
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)
Minjie Wang's avatar
Minjie Wang committed
453
    : BaseHeteroGraph(metagraph) {
454
455
    CHECK(aten::IsValidIdArray(indptr));
    CHECK(aten::IsValidIdArray(indices));
456
457
458
    if (aten::IsValidIdArray(edge_ids))
      CHECK((indices->shape[0] == edge_ids->shape[0]) || aten::IsNullArray(edge_ids))
        << "edge id arrays should have the same length as indices if not empty";
459
460
    CHECK_EQ(num_src, indptr->shape[0] - 1)
      << "number of nodes do not match the length of indptr minus 1.";
461

462
463
464
    adj_ = aten::CSRMatrix{num_src, num_dst, indptr, indices, edge_ids};
  }

465
  CSR(GraphPtr metagraph, const aten::CSRMatrix& csr)
Da Zheng's avatar
Da Zheng committed
466
467
    : BaseHeteroGraph(metagraph), adj_(csr) {
  }
468

469
470
471
472
473
474
475
476
477
478
479
  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
480
481
  inline dgl_type_t SrcType() const {
    return 0;
482
  }
Minjie Wang's avatar
Minjie Wang committed
483
484
485
486
487
488
489

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

  inline dgl_type_t EdgeType() const {
    return 0;
490
491
492
  }

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

  void AddEdge(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) override {
Minjie Wang's avatar
Minjie Wang committed
503
    LOG(FATAL) << "UnitGraph graph is not mutable.";
504
505
506
  }

  void AddEdges(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) override {
Minjie Wang's avatar
Minjie Wang committed
507
    LOG(FATAL) << "UnitGraph graph is not mutable.";
508
509
510
  }

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

514
515
516
517
  DLDataType DataType() const override {
    return adj_.indices->dtype;
  }

518
519
520
521
522
523
524
525
  DLContext Context() const override {
    return adj_.indices->ctx;
  }

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

526
527
528
529
530
  CSR AsNumBits(uint8_t bits) const {
    if (NumBits() == bits) {
      return *this;
    } else {
      CSR ret(
Minjie Wang's avatar
Minjie Wang committed
531
          meta_graph_,
532
533
534
535
536
537
538
539
540
541
542
543
          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 {
544
      return CSR(meta_graph_, adj_.CopyTo(ctx));
545
546
547
    }
  }

548
  bool IsMultigraph() const override {
549
    return aten::CSRHasDuplicate(adj_);
550
551
552
553
554
555
556
  }

  bool IsReadonly() const override {
    return true;
  }

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

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

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

615
616
617
618
  IdArray EdgeIdsOne(dgl_type_t etype, IdArray src, IdArray dst) const override {
    return aten::CSRGetData(adj_, src, dst);
  }

619
  std::pair<dgl_id_t, dgl_id_t> FindEdge(dgl_type_t etype, dgl_id_t eid) const override {
620
    LOG(FATAL) << "Not enabled for CSR graph.";
621
622
623
624
    return {};
  }

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

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

  EdgeArray InEdges(dgl_type_t etype, IdArray vids) const override {
635
    LOG(FATAL) << "Not enabled for CSR graph.";
636
637
638
639
    return {};
  }

  EdgeArray OutEdges(dgl_type_t etype, dgl_id_t vid) const override {
Minjie Wang's avatar
Minjie Wang committed
640
    CHECK(HasVertex(SrcType(), vid)) << "Invalid src vertex id: " << vid;
641
642
643
644
645
646
647
    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 {
648
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
649
650
651
652
653
654
655
656
657
658
659
660
    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 << "\".";
661
662
663
664
665
    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);
    }
666
667
668
669
    return EdgeArray{coo.row, coo.col, coo.data};
  }

  uint64_t InDegree(dgl_type_t etype, dgl_id_t vid) const override {
670
    LOG(FATAL) << "Not enabled for CSR graph.";
671
672
673
674
    return {};
  }

  DegreeArray InDegrees(dgl_type_t etype, IdArray vids) const override {
675
    LOG(FATAL) << "Not enabled for CSR graph.";
676
677
678
679
    return {};
  }

  uint64_t OutDegree(dgl_type_t etype, dgl_id_t vid) const override {
Minjie Wang's avatar
Minjie Wang committed
680
    CHECK(HasVertex(SrcType(), vid)) << "Invalid src vertex id: " << vid;
681
682
683
684
    return aten::CSRGetRowNNZ(adj_, vid);
  }

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

700
701
702
703
704
705
706
707
708
709
  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);
  }

710
711
712
  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.
713
    CHECK_EQ(NumBits(), 64);
714
715
716
717
718
719
720
721
    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 {
722
    LOG(FATAL) << "Not enabled for CSR graph.";
723
724
725
726
    return {};
  }

  DGLIdIters InEdgeVec(dgl_type_t etype, dgl_id_t vid) const override {
727
    LOG(FATAL) << "Not enabled for CSR graph.";
728
729
730
731
732
733
734
735
736
    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};
  }

737
738
739
740
741
742
743
744
745
746
747
748
749
750
  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_;
  }

751
  SparseFormat SelectFormat(dgl_type_t etype, dgl_format_code_t preferred_formats) const override {
752
    LOG(FATAL) << "Not enabled for CSR graph";
753
    return SparseFormat::kCSR;
754
755
  }

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

761
  dgl_format_code_t GetCreatedFormats() const override {
762
763
764
765
    LOG(FATAL) << "Not enabled for CSR graph";
    return 0;
  }

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

787
  HeteroGraphPtr GetGraphInFormat(dgl_format_code_t formats) const override {
788
789
790
791
    LOG(FATAL) << "Not enabled for CSR graph.";
    return nullptr;
  }

792
793
794
795
  aten::CSRMatrix adj() const {
    return adj_;
  }

796
797
798
799
800
801
802
803
804
805
806
807
808
  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_);
  }

809
 private:
810
811
  friend class Serializer;

812
813
814
815
816
817
  /*! \brief internal adjacency matrix. Data array stores edge ids */
  aten::CSRMatrix adj_;
};

//////////////////////////////////////////////////////////
//
Minjie Wang's avatar
Minjie Wang committed
818
// unit graph implementation
819
820
821
//
//////////////////////////////////////////////////////////

822
823
824
825
DLDataType UnitGraph::DataType() const {
  return GetAny()->DataType();
}

Minjie Wang's avatar
Minjie Wang committed
826
DLContext UnitGraph::Context() const {
827
828
829
  return GetAny()->Context();
}

Minjie Wang's avatar
Minjie Wang committed
830
uint8_t UnitGraph::NumBits() const {
831
832
833
  return GetAny()->NumBits();
}

Minjie Wang's avatar
Minjie Wang committed
834
bool UnitGraph::IsMultigraph() const {
835
  const SparseFormat fmt = SelectFormat(CSC_CODE);
836
837
  const auto ptr = GetFormat(fmt);
  return ptr->IsMultigraph();
838
839
}

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

Minjie Wang's avatar
Minjie Wang committed
850
uint64_t UnitGraph::NumEdges(dgl_type_t etype) const {
851
852
853
  return GetAny()->NumEdges(etype);
}

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

Minjie Wang's avatar
Minjie Wang committed
862
BoolArray UnitGraph::HasVertices(dgl_type_t vtype, IdArray vids) const {
863
  CHECK(aten::IsValidIdArray(vids)) << "Invalid id array input";
864
865
866
  return aten::LT(vids, NumVertices(vtype));
}

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

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

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

Minjie Wang's avatar
Minjie Wang committed
895
IdArray UnitGraph::Successors(dgl_type_t etype, dgl_id_t src) const {
896
  const SparseFormat fmt = SelectFormat(CSR_CODE);
897
898
  const auto ptr = GetFormat(fmt);
  return ptr->Successors(etype, src);
899
900
}

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

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

IdArray UnitGraph::EdgeIdsOne(dgl_type_t etype, IdArray src, IdArray dst) const {
922
  const SparseFormat fmt = SelectFormat(CSR_CODE);
923
924
925
926
927
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::kCSC) {
    return ptr->EdgeIdsOne(etype, dst, src);
  } else {
    return ptr->EdgeIdsOne(etype, src, dst);
928
929
930
  }
}

Minjie Wang's avatar
Minjie Wang committed
931
std::pair<dgl_id_t, dgl_id_t> UnitGraph::FindEdge(dgl_type_t etype, dgl_id_t eid) const {
932
  const SparseFormat fmt = SelectFormat(COO_CODE);
933
934
  const auto ptr = GetFormat(fmt);
  return ptr->FindEdge(etype, eid);
935
936
}

Minjie Wang's avatar
Minjie Wang committed
937
EdgeArray UnitGraph::FindEdges(dgl_type_t etype, IdArray eids) const {
938
  const SparseFormat fmt = SelectFormat(COO_CODE);
939
940
  const auto ptr = GetFormat(fmt);
  return ptr->FindEdges(etype, eids);
941
942
}

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

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

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

Minjie Wang's avatar
Minjie Wang committed
971
EdgeArray UnitGraph::OutEdges(dgl_type_t etype, IdArray vids) const {
972
  const SparseFormat fmt = SelectFormat(CSR_CODE);
973
974
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdges(etype, vids);
975
976
}

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

  const auto& edges = GetFormat(fmt)->Edges(etype, order);
992
  if (fmt == SparseFormat::kCSC)
993
994
995
    return EdgeArray{edges.dst, edges.src, edges.id};
  else
    return edges;
996
997
}

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

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

Minjie Wang's avatar
Minjie Wang committed
1016
uint64_t UnitGraph::OutDegree(dgl_type_t etype, dgl_id_t vid) const {
1017
  SparseFormat fmt = SelectFormat(CSR_CODE);
1018
1019
  const auto ptr = GetFormat(fmt);
  return ptr->OutDegree(etype, vid);
1020
1021
}

Minjie Wang's avatar
Minjie Wang committed
1022
DegreeArray UnitGraph::OutDegrees(dgl_type_t etype, IdArray vids) const {
1023
  SparseFormat fmt = SelectFormat(CSR_CODE);
1024
1025
  const auto ptr = GetFormat(fmt);
  return ptr->OutDegrees(etype, vids);
1026
1027
}

Minjie Wang's avatar
Minjie Wang committed
1028
DGLIdIters UnitGraph::SuccVec(dgl_type_t etype, dgl_id_t vid) const {
1029
  SparseFormat fmt = SelectFormat(CSR_CODE);
1030
1031
  const auto ptr = GetFormat(fmt);
  return ptr->SuccVec(etype, vid);
1032
1033
}

1034
DGLIdIters32 UnitGraph::SuccVec32(dgl_type_t etype, dgl_id_t vid) const {
1035
  SparseFormat fmt = SelectFormat(CSR_CODE);
1036
1037
1038
1039
1040
  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
1041
DGLIdIters UnitGraph::OutEdgeVec(dgl_type_t etype, dgl_id_t vid) const {
1042
  SparseFormat fmt = SelectFormat(CSR_CODE);
1043
1044
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdgeVec(etype, vid);
1045
1046
}

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

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

Minjie Wang's avatar
Minjie Wang committed
1065
std::vector<IdArray> UnitGraph::GetAdj(
1066
1067
1068
1069
1070
1071
1072
1073
1074
    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")) {
1075
    return !transpose ? GetOutCSR()->GetAdj(etype, false, "csr")
1076
1077
      : GetInCSR()->GetAdj(etype, false, "csr");
  } else if (fmt == std::string("coo")) {
1078
    return GetCOO()->GetAdj(etype, transpose, fmt);
1079
1080
1081
1082
1083
1084
  } else {
    LOG(FATAL) << "unsupported adjacency matrix format: " << fmt;
    return {};
  }
}

Minjie Wang's avatar
Minjie Wang committed
1085
HeteroSubgraph UnitGraph::VertexSubgraph(const std::vector<IdArray>& vids) const {
1086
  // We prefer to generate a subgraph from out-csr.
1087
  SparseFormat fmt = SelectFormat(CSR_CODE);
1088
  HeteroSubgraph sg = GetFormat(fmt)->VertexSubgraph(vids);
1089
  HeteroSubgraph ret;
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109

  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));
1110
1111
1112
1113
1114
  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
1115
HeteroSubgraph UnitGraph::EdgeSubgraph(
1116
    const std::vector<IdArray>& eids, bool preserve_nodes) const {
1117
  SparseFormat fmt = SelectFormat(COO_CODE);
1118
  auto sg = GetFormat(fmt)->EdgeSubgraph(eids, preserve_nodes);
1119
  HeteroSubgraph ret;
Quan (Andy) Gan's avatar
Quan (Andy) Gan committed
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139

  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));
1140
1141
1142
1143
1144
  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
1145
HeteroGraphPtr UnitGraph::CreateFromCOO(
1146
1147
    int64_t num_vtypes, int64_t num_src, int64_t num_dst,
    IdArray row, IdArray col,
1148
    bool row_sorted, bool col_sorted,
1149
    dgl_format_code_t formats) {
Minjie Wang's avatar
Minjie Wang committed
1150
1151
1152
1153
  CHECK(num_vtypes == 1 || num_vtypes == 2);
  if (num_vtypes == 1)
    CHECK_EQ(num_src, num_dst);
  auto mg = CreateUnitGraphMetaGraph(num_vtypes);
1154
1155
  COOPtr coo(new COO(mg, num_src, num_dst, row, col,
      row_sorted, col_sorted));
1156
1157

  return HeteroGraphPtr(
1158
      new UnitGraph(mg, nullptr, nullptr, coo, formats));
1159
1160
}

1161
1162
HeteroGraphPtr UnitGraph::CreateFromCOO(
    int64_t num_vtypes, const aten::COOMatrix& mat,
1163
    dgl_format_code_t formats) {
1164
1165
1166
1167
1168
  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));
1169

1170
  return HeteroGraphPtr(
1171
      new UnitGraph(mg, nullptr, nullptr, coo, formats));
1172
1173
}

Minjie Wang's avatar
Minjie Wang committed
1174
1175
HeteroGraphPtr UnitGraph::CreateFromCSR(
    int64_t num_vtypes, int64_t num_src, int64_t num_dst,
1176
    IdArray indptr, IdArray indices, IdArray edge_ids, dgl_format_code_t formats) {
Minjie Wang's avatar
Minjie Wang committed
1177
1178
1179
1180
1181
  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));
1182
  return HeteroGraphPtr(new UnitGraph(mg, nullptr, csr, nullptr, formats));
1183
1184
}

1185
1186
HeteroGraphPtr UnitGraph::CreateFromCSR(
    int64_t num_vtypes, const aten::CSRMatrix& mat,
1187
    dgl_format_code_t formats) {
1188
1189
1190
1191
1192
  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));
1193
  return HeteroGraphPtr(new UnitGraph(mg, nullptr, csr, nullptr, formats));
1194
1195
}

1196
1197
HeteroGraphPtr UnitGraph::CreateFromCSC(
    int64_t num_vtypes, int64_t num_src, int64_t num_dst,
1198
    IdArray indptr, IdArray indices, IdArray edge_ids, dgl_format_code_t formats) {
1199
1200
1201
1202
1203
  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));
1204
  return HeteroGraphPtr(new UnitGraph(mg, csc, nullptr, nullptr, formats));
1205
1206
1207
1208
}

HeteroGraphPtr UnitGraph::CreateFromCSC(
    int64_t num_vtypes, const aten::CSRMatrix& mat,
1209
    dgl_format_code_t formats) {
1210
1211
1212
1213
1214
  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));
1215
  return HeteroGraphPtr(new UnitGraph(mg, csc, nullptr, nullptr, formats));
1216
1217
}

Minjie Wang's avatar
Minjie Wang committed
1218
HeteroGraphPtr UnitGraph::AsNumBits(HeteroGraphPtr g, uint8_t bits) {
1219
1220
1221
  if (g->NumBits() == bits) {
    return g;
  } else {
Minjie Wang's avatar
Minjie Wang committed
1222
    auto bg = std::dynamic_pointer_cast<UnitGraph>(g);
1223
    CHECK_NOTNULL(bg);
1224
1225
1226
1227
1228
1229
    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;
1230
    return HeteroGraphPtr(
1231
        new UnitGraph(g->meta_graph(), new_incsr, new_outcsr, new_coo, bg->formats_));
1232
1233
1234
  }
}

Minjie Wang's avatar
Minjie Wang committed
1235
HeteroGraphPtr UnitGraph::CopyTo(HeteroGraphPtr g, const DLContext& ctx) {
1236
1237
  if (ctx == g->Context()) {
    return g;
1238
1239
1240
  } else {
    auto bg = std::dynamic_pointer_cast<UnitGraph>(g);
    CHECK_NOTNULL(bg);
1241
1242
1243
1244
1245
1246
    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;
1247
    return HeteroGraphPtr(
1248
        new UnitGraph(g->meta_graph(), new_incsr, new_outcsr, new_coo, bg->formats_));
1249
1250
1251
  }
}

1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
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());
}

1264
UnitGraph::UnitGraph(GraphPtr metagraph, CSRPtr in_csr, CSRPtr out_csr, COOPtr coo,
1265
                     dgl_format_code_t formats)
Minjie Wang's avatar
Minjie Wang committed
1266
  : BaseHeteroGraph(metagraph), in_csr_(in_csr), out_csr_(out_csr), coo_(coo) {
1267
1268
1269
1270
1271
1272
1273
1274
1275
  if (!in_csr_) {
    in_csr_ = CSRPtr(new CSR());
  }
  if (!out_csr_) {
    out_csr_ = CSRPtr(new CSR());
  }
  if (!coo_) {
    coo_ = COOPtr(new COO());
  }
1276
1277
1278
1279
1280
  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);
1281
1282
1283
  CHECK(GetAny()) << "At least one graph structure should exist.";
}

1284
1285
1286
1287
1288
1289
1290
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,
1291
    dgl_format_code_t formats) {
1292
1293
1294
1295
1296
1297
1298
1299
  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));
1300
1301
  else
    in_csr_ptr = CSRPtr(new CSR());
1302
1303
  if (has_out_csr)
    out_csr_ptr = CSRPtr(new CSR(mg, out_csr));
1304
1305
  else
    out_csr_ptr = CSRPtr(new CSR());
1306
1307
  if (has_coo)
    coo_ptr = COOPtr(new COO(mg, coo));
1308
1309
  else
    coo_ptr = COOPtr(new COO());
1310

1311
  return HeteroGraphPtr(new UnitGraph(mg, in_csr_ptr, out_csr_ptr, coo_ptr, formats));
1312
1313
}

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

1327
      if (inplace)
1328
1329
1330
        *(const_cast<UnitGraph*>(this)->in_csr_) = CSR(meta_graph(), newadj);
      else
        ret = std::make_shared<CSR>(meta_graph(), newadj);
1331
    } else {
1332
1333
      CHECK(out_csr_->defined()) << "None of CSR, COO exist";
      const auto& newadj = aten::CSRTranspose(out_csr_->adj());
1334

1335
      if (inplace)
1336
1337
1338
        *(const_cast<UnitGraph*>(this)->in_csr_) = CSR(meta_graph(), newadj);
      else
        ret = std::make_shared<CSR>(meta_graph(), newadj);
1339
1340
    }
  }
1341
  return ret;
1342
1343
1344
}

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

1357
      if (inplace)
1358
1359
1360
        *(const_cast<UnitGraph*>(this)->out_csr_) = CSR(meta_graph(), newadj);
      else
        ret = std::make_shared<CSR>(meta_graph(), newadj);
1361
    } else {
1362
1363
      CHECK(in_csr_->defined()) << "None of CSR, COO exist";
      const auto& newadj = aten::CSRTranspose(in_csr_->adj());
1364

1365
      if (inplace)
1366
1367
1368
        *(const_cast<UnitGraph*>(this)->out_csr_) = CSR(meta_graph(), newadj);
      else
        ret = std::make_shared<CSR>(meta_graph(), newadj);
1369
1370
    }
  }
1371
  return ret;
1372
1373
1374
}

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

1385
      if (inplace)
1386
1387
1388
        *(const_cast<UnitGraph*>(this)->coo_) = COO(meta_graph(), newadj);
      else
        ret = std::make_shared<COO>(meta_graph(), newadj);
1389
    } else {
1390
      CHECK(out_csr_->defined()) << "Both CSR are missing.";
1391
      const auto& newadj = aten::CSRToCOO(out_csr_->adj(), true);
1392

1393
      if (inplace)
1394
1395
1396
        *(const_cast<UnitGraph*>(this)->coo_) = COO(meta_graph(), newadj);
      else
        ret = std::make_shared<COO>(meta_graph(), newadj);
1397
1398
    }
  }
1399
  return ret;
1400
1401
}

1402
aten::CSRMatrix UnitGraph::GetCSCMatrix(dgl_type_t etype) const {
1403
1404
1405
  return GetInCSR()->adj();
}

1406
aten::CSRMatrix UnitGraph::GetCSRMatrix(dgl_type_t etype) const {
1407
1408
1409
  return GetOutCSR()->adj();
}

1410
aten::COOMatrix UnitGraph::GetCOOMatrix(dgl_type_t etype) const {
1411
1412
1413
  return GetCOO()->adj();
}

Minjie Wang's avatar
Minjie Wang committed
1414
HeteroGraphPtr UnitGraph::GetAny() const {
1415
  if (in_csr_->defined()) {
1416
    return in_csr_;
1417
  } else if (out_csr_->defined()) {
1418
1419
1420
1421
1422
1423
    return out_csr_;
  } else {
    return coo_;
  }
}

1424
dgl_format_code_t UnitGraph::GetCreatedFormats() const {
1425
  dgl_format_code_t ret = 0;
1426
  if (in_csr_->defined())
1427
    ret |= CSC_CODE;
1428
  if (out_csr_->defined())
1429
    ret |= CSR_CODE;
1430
  if (coo_->defined())
1431
    ret |= COO_CODE;
1432
1433
1434
  return ret;
}

1435
1436
1437
1438
dgl_format_code_t UnitGraph::GetAllowedFormats() const {
  return formats_;
}

1439
1440
HeteroGraphPtr UnitGraph::GetFormat(SparseFormat format) const {
  switch (format) {
1441
1442
1443
1444
  case SparseFormat::kCSR:
    return GetOutCSR();
  case SparseFormat::kCSC:
    return GetInCSR();
1445
  default:
1446
    return GetCOO();
1447
1448
1449
  }
}

1450
HeteroGraphPtr UnitGraph::GetGraphInFormat(dgl_format_code_t formats) const {
1451
  if (formats == ALL_CODE)
1452
    return HeteroGraphPtr(
1453
1454
        // TODO(xiangsx) Make it as graph storage.Clone()
        new UnitGraph(meta_graph_,
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
                      (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();
1466
  if (formats & COO_CODE)
1467
    return CreateFromCOO(num_vtypes, GetCOO(false)->adj(), formats);
1468
  if (formats & CSR_CODE)
1469
1470
1471
1472
1473
1474
1475
1476
1477
    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);
1478
1479
1480
1481
1482

  // 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;
1483
1484
1485
  if (common)
    return DecodeFormat(common);
  return DecodeFormat(created);
1486
1487
}

1488
1489
1490
1491
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;
1492
  if (in_csr_->defined()) {
1493
    aten::CSRMatrix csc = GetCSCMatrix(0);
1494
    in_csr_ptr = dgl::CSRPtr(new dgl::CSR(csc.indptr, csc.indices, csc.data));
1495
  }
1496
  if (out_csr_->defined()) {
1497
    aten::CSRMatrix csr = GetCSRMatrix(0);
1498
    out_csr_ptr = dgl::CSRPtr(new dgl::CSR(csr.indptr, csr.indices, csr.data));
1499
  }
1500
  if (coo_->defined()) {
1501
1502
    aten::COOMatrix coo = GetCOOMatrix(0);
    if (!COOHasData(coo)) {
1503
      coo_ptr = dgl::COOPtr(new dgl::COO(NumVertices(0), coo.row, coo.col));
1504
1505
1506
    } else {
      IdArray new_src = Scatter(coo.row, coo.data);
      IdArray new_dst = Scatter(coo.col, coo.data);
1507
      coo_ptr = dgl::COOPtr(new dgl::COO(NumVertices(0), new_src, new_dst));
1508
1509
1510
1511
1512
    }
  }
  return GraphPtr(new dgl::ImmutableGraph(in_csr_ptr, out_csr_ptr, coo_ptr));
}

1513
1514
HeteroGraphPtr UnitGraph::LineGraph(bool backtracking) const {
  // TODO(xiangsx) currently we only support homogeneous graph
1515
  auto fmt = SelectFormat(ALL_CODE);
1516
1517
  switch (fmt) {
    case SparseFormat::kCOO: {
1518
      return CreateFromCOO(1, aten::COOLineGraph(coo_->adj(), backtracking));
1519
1520
1521
1522
    }
    case SparseFormat::kCSR: {
      const aten::CSRMatrix csr = GetCSRMatrix(0);
      const aten::COOMatrix coo = aten::COOLineGraph(aten::CSRToCOO(csr, true), backtracking);
1523
      return CreateFromCOO(1, coo);
1524
1525
1526
1527
1528
    }
    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);
1529
      return CreateFromCOO(1, coo);
1530
1531
1532
1533
1534
1535
1536
1537
    }
    default:
      LOG(FATAL) << "None of CSC, CSR, COO exist";
      break;
  }
  return nullptr;
}

1538
1539
1540
1541
1542
1543
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";
1544

1545
  int64_t save_format_code, formats_code;
1546
  CHECK(fs->Read(&save_format_code)) << "Invalid format";
1547
  CHECK(fs->Read(&formats_code)) << "Invalid format";
1548
  auto save_format = static_cast<SparseFormat>(save_format_code);
1549
1550
1551
1552
1553
1554
  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:
1555
      formats_ = ALL_CODE;
1556
1557
      break;
    case 1:
1558
      formats_ = COO_CODE;
1559
1560
      break;
    case 2:
1561
      formats_ = CSR_CODE;
1562
1563
      break;
    case 3:
1564
      formats_ = CSC_CODE;
1565
1566
1567
1568
1569
1570
      break;
    default:
      LOG(FATAL) << "Load graph failed, formats code " << formats_code <<
        "not recognized.";
    }
  }
1571

1572
  switch (save_format) {
1573
    case SparseFormat::kCOO:
1574
1575
      fs->Read(&coo_);
      break;
1576
    case SparseFormat::kCSR:
1577
1578
      fs->Read(&out_csr_);
      break;
1579
    case SparseFormat::kCSC:
1580
1581
1582
1583
1584
1585
1586
      fs->Read(&in_csr_);
      break;
    default:
      LOG(FATAL) << "unsupported format code";
      break;
  }

1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
  if (!in_csr_) {
    in_csr_ = CSRPtr(new CSR());
  }
  if (!out_csr_) {
    out_csr_ = CSRPtr(new CSR());
  }
  if (!coo_) {
    coo_ = COOPtr(new COO());
  }

1597
1598
  meta_graph_ = GetAny()->meta_graph();

1599
1600
1601
  return true;
}

1602

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

1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
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));
}

1636
1637
1638
1639
1640
1641
1642
std::tuple<UnitGraphPtr, IdArray, IdArray>
UnitGraph::ToSimple() const {
  CSRPtr new_incsr = nullptr, new_outcsr = nullptr;
  COOPtr new_coo = nullptr;
  IdArray count;
  IdArray edge_map;

1643
  auto avail_fmt = SelectFormat(ALL_CODE);
1644
1645
  switch (avail_fmt) {
    case SparseFormat::kCOO: {
1646
      auto ret = aten::COOToSimple(GetCOO()->adj());
1647
1648
      count = std::get<1>(ret);
      edge_map = std::get<2>(ret);
1649
      new_coo = COOPtr(new COO(meta_graph(), std::get<0>(ret)));
1650
1651
1652
      break;
    }
    case SparseFormat::kCSR: {
1653
      auto ret = aten::CSRToSimple(GetOutCSR()->adj());
1654
1655
      count = std::get<1>(ret);
      edge_map = std::get<2>(ret);
1656
      new_outcsr = CSRPtr(new CSR(meta_graph(), std::get<0>(ret)));
1657
1658
1659
      break;
    }
    case SparseFormat::kCSC: {
1660
      auto ret = aten::CSRToSimple(GetInCSR()->adj());
1661
1662
      count = std::get<1>(ret);
      edge_map = std::get<2>(ret);
1663
      new_incsr = CSRPtr(new CSR(meta_graph(), std::get<0>(ret)));
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
      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);
}

1676
}  // namespace dgl