unit_graph.cc 39.8 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
7
8
 */
#include <dgl/array.h>
#include <dgl/lazy.h>
#include <dgl/immutable_graph.h>
9
#include <dgl/base_heterograph.h>
10

Minjie Wang's avatar
Minjie Wang committed
11
#include "./unit_graph.h"
12
13
14
#include "../c_api_common.h"

namespace dgl {
15

16
namespace {
Minjie Wang's avatar
Minjie Wang committed
17
18
19
20
21
22
23
24
25
26
// 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;
}
27

Minjie Wang's avatar
Minjie Wang committed
28
29
30
31
32
// 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);
33
34
35
36
37
  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
38
39
40
41
42
43
44
45
46
47
48
49

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 {};
}
50
51

};  // namespace
52
53
54
55
56
57
58

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

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

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

Minjie Wang's avatar
Minjie Wang committed
79
80
  explicit COO(GraphPtr metagraph, const aten::COOMatrix& coo)
    : BaseHeteroGraph(metagraph), adj_(coo) {}
81

Minjie Wang's avatar
Minjie Wang committed
82
83
  inline dgl_type_t SrcType() const {
    return 0;
84
  }
Minjie Wang's avatar
Minjie Wang committed
85
86
87
88
89
90
91

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

  inline dgl_type_t EdgeType() const {
    return 0;
92
93
94
  }

  HeteroGraphPtr GetRelationGraph(dgl_type_t etype) const override {
Minjie Wang's avatar
Minjie Wang committed
95
    LOG(FATAL) << "The method shouldn't be called for UnitGraph graph. "
96
97
98
99
100
      << "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
101
    LOG(FATAL) << "UnitGraph graph is not mutable.";
102
103
104
  }

  void AddEdge(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) override {
Minjie Wang's avatar
Minjie Wang committed
105
    LOG(FATAL) << "UnitGraph graph is not mutable.";
106
107
108
  }

  void AddEdges(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) override {
Minjie Wang's avatar
Minjie Wang committed
109
    LOG(FATAL) << "UnitGraph graph is not mutable.";
110
111
112
  }

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

116
117
118
119
  DLDataType DataType() const override {
    return adj_.row->dtype;
  }

120
121
122
123
124
125
126
127
  DLContext Context() const override {
    return adj_.row->ctx;
  }

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

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
  COO AsNumBits(uint8_t bits) const {
    if (NumBits() == bits)
      return *this;

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

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

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

154
155
156
157
158
159
160
161
162
163
164
  bool IsMultigraph() const override {
    return const_cast<COO*>(this)->is_multigraph_.Get([this] () {
        return aten::COOHasDuplicate(adj_);
      });
  }

  bool IsReadonly() const override {
    return true;
  }

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

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

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

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

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

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

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

  EdgeArray FindEdges(dgl_type_t etype, IdArray eids) const override {
231
    CHECK(aten::IsValidIdArray(eids)) << "Invalid edge id array";
232
233
234
235
236
237
    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 {
238
239
240
241
242
    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};
243
244
245
  }

  EdgeArray InEdges(dgl_type_t etype, IdArray vids) const override {
246
247
248
249
    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};
250
251
252
  }

  EdgeArray OutEdges(dgl_type_t etype, dgl_id_t vid) const override {
253
254
255
256
    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};
257
258
259
  }

  EdgeArray OutEdges(dgl_type_t etype, IdArray vids) const override {
260
261
262
263
    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};
264
265
266
267
268
269
270
271
272
273
274
  }

  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 {
275
276
    CHECK(HasVertex(DstType(), vid)) << "Invalid dst vertex id: " << vid;
    return aten::COOGetRowNNZ(aten::COOTranspose(adj_), vid);
277
278
279
  }

  DegreeArray InDegrees(dgl_type_t etype, IdArray vids) const override {
280
281
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
    return aten::COOGetRowNNZ(aten::COOTranspose(adj_), vids);
282
283
284
  }

  uint64_t OutDegree(dgl_type_t etype, dgl_id_t vid) const override {
285
286
    CHECK(HasVertex(SrcType(), vid)) << "Invalid src vertex id: " << vid;
    return aten::COOGetRowNNZ(adj_, vid);
287
288
289
  }

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

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

  HeteroSubgraph VertexSubgraph(const std::vector<IdArray>& vids) const override {
325
326
327
328
329
330
331
332
333
334
335
336
    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;
337
338
339
340
341
342
343
344
345
346
347
348
349
350
  }

  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
351
          meta_graph(), new_nsrc, new_ndst, new_src, new_dst);
352
353
354
355
356
357
358
      subg.induced_edges = eids;
    } else {
      IdArray new_src = aten::IndexSelect(adj_.row, eids[0]);
      IdArray new_dst = aten::IndexSelect(adj_.col, eids[0]);
      subg.induced_vertices.emplace_back(aten::Range(0, NumVertices(0), NumBits(), Context()));
      subg.induced_vertices.emplace_back(aten::Range(0, NumVertices(1), NumBits(), Context()));
      subg.graph = std::make_shared<COO>(
Minjie Wang's avatar
Minjie Wang committed
359
          meta_graph(), NumVertices(0), NumVertices(1), new_src, new_dst);
360
361
362
363
364
365
366
367
368
      subg.induced_edges = eids;
    }
    return subg;
  }

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

369
370
371
372
373
374
375
376
377
  /*!
   * \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);
  }

378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
 private:
  /*! \brief internal adjacency matrix. Data array is empty */
  aten::COOMatrix adj_;

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

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

/*! \brief CSR graph */
Minjie Wang's avatar
Minjie Wang committed
393
class UnitGraph::CSR : public BaseHeteroGraph {
394
 public:
Minjie Wang's avatar
Minjie Wang committed
395
  CSR(GraphPtr metagraph, int64_t num_src, int64_t num_dst,
396
      IdArray indptr, IdArray indices, IdArray edge_ids)
Minjie Wang's avatar
Minjie Wang committed
397
    : BaseHeteroGraph(metagraph) {
398
399
400
401
402
    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";
403
    adj_ = aten::CSRMatrix{num_src, num_dst, indptr, indices, edge_ids};
Da Zheng's avatar
Da Zheng committed
404
    sorted_ = false;
405
406
  }

Minjie Wang's avatar
Minjie Wang committed
407
  CSR(GraphPtr metagraph, int64_t num_src, int64_t num_dst,
408
      IdArray indptr, IdArray indices, IdArray edge_ids, bool is_multigraph)
Minjie Wang's avatar
Minjie Wang committed
409
    : BaseHeteroGraph(metagraph), is_multigraph_(is_multigraph) {
410
411
412
413
414
    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";
415
    adj_ = aten::CSRMatrix{num_src, num_dst, indptr, indices, edge_ids};
Da Zheng's avatar
Da Zheng committed
416
    sorted_ = false;
417
418
  }

Minjie Wang's avatar
Minjie Wang committed
419
  explicit CSR(GraphPtr metagraph, const aten::CSRMatrix& csr)
Da Zheng's avatar
Da Zheng committed
420
421
422
    : BaseHeteroGraph(metagraph), adj_(csr) {
    sorted_ = false;
  }
423

Minjie Wang's avatar
Minjie Wang committed
424
425
  inline dgl_type_t SrcType() const {
    return 0;
426
  }
Minjie Wang's avatar
Minjie Wang committed
427
428
429
430
431
432
433

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

  inline dgl_type_t EdgeType() const {
    return 0;
434
435
436
  }

  HeteroGraphPtr GetRelationGraph(dgl_type_t etype) const override {
Minjie Wang's avatar
Minjie Wang committed
437
    LOG(FATAL) << "The method shouldn't be called for UnitGraph graph. "
438
439
440
441
442
      << "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
443
    LOG(FATAL) << "UnitGraph graph is not mutable.";
444
445
446
  }

  void AddEdge(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) override {
Minjie Wang's avatar
Minjie Wang committed
447
    LOG(FATAL) << "UnitGraph graph is not mutable.";
448
449
450
  }

  void AddEdges(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) override {
Minjie Wang's avatar
Minjie Wang committed
451
    LOG(FATAL) << "UnitGraph graph is not mutable.";
452
453
454
  }

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

458
459
460
461
  DLDataType DataType() const override {
    return adj_.indices->dtype;
  }

462
463
464
465
466
467
468
469
  DLContext Context() const override {
    return adj_.indices->ctx;
  }

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

470
471
472
473
474
  CSR AsNumBits(uint8_t bits) const {
    if (NumBits() == bits) {
      return *this;
    } else {
      CSR ret(
Minjie Wang's avatar
Minjie Wang committed
475
          meta_graph_,
476
477
478
479
480
481
482
483
484
485
486
487
488
489
          adj_.num_rows, adj_.num_cols,
          aten::AsNumBits(adj_.indptr, bits),
          aten::AsNumBits(adj_.indices, bits),
          aten::AsNumBits(adj_.data, bits));
      ret.is_multigraph_ = is_multigraph_;
      return ret;
    }
  }

  CSR CopyTo(const DLContext& ctx) const {
    if (Context() == ctx) {
      return *this;
    } else {
      CSR ret(
Minjie Wang's avatar
Minjie Wang committed
490
          meta_graph_,
491
492
493
494
495
496
497
498
499
          adj_.num_rows, adj_.num_cols,
          adj_.indptr.CopyTo(ctx),
          adj_.indices.CopyTo(ctx),
          adj_.data.CopyTo(ctx));
      ret.is_multigraph_ = is_multigraph_;
      return ret;
    }
  }

500
501
502
503
504
505
506
507
508
509
510
  bool IsMultigraph() const override {
    return const_cast<CSR*>(this)->is_multigraph_.Get([this] () {
        return aten::CSRHasDuplicate(adj_);
      });
  }

  bool IsReadonly() const override {
    return true;
  }

  uint64_t NumVertices(dgl_type_t vtype) const override {
Minjie Wang's avatar
Minjie Wang committed
511
    if (vtype == SrcType()) {
512
      return adj_.num_rows;
Minjie Wang's avatar
Minjie Wang committed
513
    } else if (vtype == DstType()) {
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
      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
535
536
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
537
538
539
540
    return aten::CSRIsNonZero(adj_, src, dst);
  }

  BoolArray HasEdgesBetween(dgl_type_t etype, IdArray src_ids, IdArray dst_ids) const override {
541
542
    CHECK(aten::IsValidIdArray(src_ids)) << "Invalid vertex id array.";
    CHECK(aten::IsValidIdArray(dst_ids)) << "Invalid vertex id array.";
543
544
545
546
547
548
549
550
551
    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
552
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
553
554
555
556
    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
557
558
    CHECK(HasVertex(SrcType(), src)) << "Invalid src vertex id: " << src;
    CHECK(HasVertex(DstType(), dst)) << "Invalid dst vertex id: " << dst;
559
560
561
562
    return aten::CSRGetData(adj_, src, dst);
  }

  EdgeArray EdgeIds(dgl_type_t etype, IdArray src, IdArray dst) const override {
563
564
    CHECK(aten::IsValidIdArray(src)) << "Invalid vertex id array.";
    CHECK(aten::IsValidIdArray(dst)) << "Invalid vertex id array.";
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
    const auto& arrs = aten::CSRGetDataAndIndices(adj_, src, dst);
    return EdgeArray{arrs[0], arrs[1], arrs[2]};
  }

  std::pair<dgl_id_t, dgl_id_t> FindEdge(dgl_type_t etype, dgl_id_t eid) const override {
    LOG(INFO) << "Not enabled for CSR graph.";
    return {};
  }

  EdgeArray FindEdges(dgl_type_t etype, IdArray eids) const override {
    LOG(INFO) << "Not enabled for CSR graph.";
    return {};
  }

  EdgeArray InEdges(dgl_type_t etype, dgl_id_t vid) const override {
    LOG(INFO) << "Not enabled for CSR graph.";
    return {};
  }

  EdgeArray InEdges(dgl_type_t etype, IdArray vids) const override {
    LOG(INFO) << "Not enabled for CSR graph.";
    return {};
  }

  EdgeArray OutEdges(dgl_type_t etype, dgl_id_t vid) const override {
Minjie Wang's avatar
Minjie Wang committed
590
    CHECK(HasVertex(SrcType(), vid)) << "Invalid src vertex id: " << vid;
591
592
593
594
595
596
597
    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 {
598
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
    auto csrsubmat = aten::CSRSliceRows(adj_, vids);
    auto coosubmat = aten::CSRToCOO(csrsubmat, false);
    // Note that the row id in the csr submat is relabled, so
    // we need to recover it using an index select.
    auto row = aten::IndexSelect(vids, coosubmat.row);
    return EdgeArray{row, coosubmat.col, coosubmat.data};
  }

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

  uint64_t InDegree(dgl_type_t etype, dgl_id_t vid) const override {
    LOG(INFO) << "Not enabled for CSR graph.";
    return {};
  }

  DegreeArray InDegrees(dgl_type_t etype, IdArray vids) const override {
    LOG(INFO) << "Not enabled for CSR graph.";
    return {};
  }

  uint64_t OutDegree(dgl_type_t etype, dgl_id_t vid) const override {
Minjie Wang's avatar
Minjie Wang committed
626
    CHECK(HasVertex(SrcType(), vid)) << "Invalid src vertex id: " << vid;
627
628
629
630
    return aten::CSRGetRowNNZ(adj_, vid);
  }

  DegreeArray OutDegrees(dgl_type_t etype, IdArray vids) const override {
631
    CHECK(aten::IsValidIdArray(vids)) << "Invalid vertex id array.";
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
    return aten::CSRGetRowNNZ(adj_, vids);
  }

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

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

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

  DGLIdIters InEdgeVec(dgl_type_t etype, dgl_id_t vid) const override {
    LOG(INFO) << "Not enabled for CSR graph.";
    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};
  }

  HeteroSubgraph VertexSubgraph(const std::vector<IdArray>& vids) const override {
Minjie Wang's avatar
Minjie Wang committed
672
673
674
675
    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.";
676
    HeteroSubgraph subg;
Minjie Wang's avatar
Minjie Wang committed
677
    const auto& submat = aten::CSRSliceMatrix(adj_, srcvids, dstvids);
678
    IdArray sub_eids = aten::Range(0, submat.data->shape[0], NumBits(), Context());
Minjie Wang's avatar
Minjie Wang committed
679
    subg.graph = std::make_shared<CSR>(meta_graph(), submat.num_rows, submat.num_cols,
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
        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 {
    LOG(INFO) << "Not enabled for CSR graph.";
    return {};
  }

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

 private:
  /*! \brief internal adjacency matrix. Data array stores edge ids */
  aten::CSRMatrix adj_;

  /*! \brief multi-graph flag */
  Lazy<bool> is_multigraph_;
Da Zheng's avatar
Da Zheng committed
702
703
704

  /*! \brief indicate that the edges are stored in the sorted order. */
  bool sorted_;
705
706
707
708
};

//////////////////////////////////////////////////////////
//
Minjie Wang's avatar
Minjie Wang committed
709
// unit graph implementation
710
711
712
//
//////////////////////////////////////////////////////////

713
714
715
716
DLDataType UnitGraph::DataType() const {
  return GetAny()->DataType();
}

Minjie Wang's avatar
Minjie Wang committed
717
DLContext UnitGraph::Context() const {
718
719
720
  return GetAny()->Context();
}

Minjie Wang's avatar
Minjie Wang committed
721
uint8_t UnitGraph::NumBits() const {
722
723
724
  return GetAny()->NumBits();
}

Minjie Wang's avatar
Minjie Wang committed
725
bool UnitGraph::IsMultigraph() const {
726
727
728
  return GetAny()->IsMultigraph();
}

Minjie Wang's avatar
Minjie Wang committed
729
uint64_t UnitGraph::NumVertices(dgl_type_t vtype) const {
730
731
732
733
734
  const SparseFormat fmt = SelectFormat(SparseFormat::ANY);
  const auto ptr = GetFormat(fmt);
  // TODO(BarclayII): we have a lot of special handling for CSC.
  // Need to have a UnitGraph::CSC backend instead.
  if (fmt == SparseFormat::CSC)
Minjie Wang's avatar
Minjie Wang committed
735
    vtype = (vtype == SrcType()) ? DstType() : SrcType();
736
  return ptr->NumVertices(vtype);
737
738
}

Minjie Wang's avatar
Minjie Wang committed
739
uint64_t UnitGraph::NumEdges(dgl_type_t etype) const {
740
741
742
  return GetAny()->NumEdges(etype);
}

Minjie Wang's avatar
Minjie Wang committed
743
bool UnitGraph::HasVertex(dgl_type_t vtype, dgl_id_t vid) const {
744
745
746
  const SparseFormat fmt = SelectFormat(SparseFormat::ANY);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC)
Minjie Wang's avatar
Minjie Wang committed
747
    vtype = (vtype == SrcType()) ? DstType() : SrcType();
748
  return ptr->HasVertex(vtype, vid);
749
750
}

Minjie Wang's avatar
Minjie Wang committed
751
BoolArray UnitGraph::HasVertices(dgl_type_t vtype, IdArray vids) const {
752
  CHECK(aten::IsValidIdArray(vids)) << "Invalid id array input";
753
754
755
  return aten::LT(vids, NumVertices(vtype));
}

Minjie Wang's avatar
Minjie Wang committed
756
bool UnitGraph::HasEdgeBetween(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const {
757
758
759
760
761
762
  const SparseFormat fmt = SelectFormat(SparseFormat::ANY);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC)
    return ptr->HasEdgeBetween(etype, dst, src);
  else
    return ptr->HasEdgeBetween(etype, src, dst);
763
764
}

Minjie Wang's avatar
Minjie Wang committed
765
BoolArray UnitGraph::HasEdgesBetween(
766
    dgl_type_t etype, IdArray src, IdArray dst) const {
767
768
769
770
771
772
  const SparseFormat fmt = SelectFormat(SparseFormat::ANY);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC)
    return ptr->HasEdgesBetween(etype, dst, src);
  else
    return ptr->HasEdgesBetween(etype, src, dst);
773
774
}

Minjie Wang's avatar
Minjie Wang committed
775
IdArray UnitGraph::Predecessors(dgl_type_t etype, dgl_id_t dst) const {
776
777
778
779
780
781
  const SparseFormat fmt = SelectFormat(SparseFormat::CSC);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC)
    return ptr->Successors(etype, dst);
  else
    return ptr->Predecessors(etype, dst);
782
783
}

Minjie Wang's avatar
Minjie Wang committed
784
IdArray UnitGraph::Successors(dgl_type_t etype, dgl_id_t src) const {
785
786
787
  const SparseFormat fmt = SelectFormat(SparseFormat::CSR);
  const auto ptr = GetFormat(fmt);
  return ptr->Successors(etype, src);
788
789
}

Minjie Wang's avatar
Minjie Wang committed
790
IdArray UnitGraph::EdgeId(dgl_type_t etype, dgl_id_t src, dgl_id_t dst) const {
791
792
793
794
795
796
  const SparseFormat fmt = SelectFormat(SparseFormat::ANY);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC)
    return ptr->EdgeId(etype, dst, src);
  else
    return ptr->EdgeId(etype, src, dst);
797
798
}

Minjie Wang's avatar
Minjie Wang committed
799
EdgeArray UnitGraph::EdgeIds(dgl_type_t etype, IdArray src, IdArray dst) const {
800
801
802
803
  const SparseFormat fmt = SelectFormat(SparseFormat::ANY);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC) {
    EdgeArray edges = ptr->EdgeIds(etype, dst, src);
804
805
    return EdgeArray{edges.dst, edges.src, edges.id};
  } else {
806
    return ptr->EdgeIds(etype, src, dst);
807
808
809
  }
}

Minjie Wang's avatar
Minjie Wang committed
810
std::pair<dgl_id_t, dgl_id_t> UnitGraph::FindEdge(dgl_type_t etype, dgl_id_t eid) const {
811
812
813
  const SparseFormat fmt = SelectFormat(SparseFormat::COO);
  const auto ptr = GetFormat(fmt);
  return ptr->FindEdge(etype, eid);
814
815
}

Minjie Wang's avatar
Minjie Wang committed
816
EdgeArray UnitGraph::FindEdges(dgl_type_t etype, IdArray eids) const {
817
818
819
  const SparseFormat fmt = SelectFormat(SparseFormat::COO);
  const auto ptr = GetFormat(fmt);
  return ptr->FindEdges(etype, eids);
820
821
}

Minjie Wang's avatar
Minjie Wang committed
822
EdgeArray UnitGraph::InEdges(dgl_type_t etype, dgl_id_t vid) const {
823
824
825
826
827
828
829
830
  const SparseFormat fmt = SelectFormat(SparseFormat::CSC);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC) {
    const EdgeArray& ret = ptr->OutEdges(etype, vid);
    return {ret.dst, ret.src, ret.id};
  } else {
    return ptr->InEdges(etype, vid);
  }
831
832
}

Minjie Wang's avatar
Minjie Wang committed
833
EdgeArray UnitGraph::InEdges(dgl_type_t etype, IdArray vids) const {
834
835
836
837
838
839
840
841
  const SparseFormat fmt = SelectFormat(SparseFormat::CSC);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC) {
    const EdgeArray& ret = ptr->OutEdges(etype, vids);
    return {ret.dst, ret.src, ret.id};
  } else {
    return ptr->InEdges(etype, vids);
  }
842
843
}

Minjie Wang's avatar
Minjie Wang committed
844
EdgeArray UnitGraph::OutEdges(dgl_type_t etype, dgl_id_t vid) const {
845
846
847
  const SparseFormat fmt = SelectFormat(SparseFormat::CSR);
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdges(etype, vid);
848
849
}

Minjie Wang's avatar
Minjie Wang committed
850
EdgeArray UnitGraph::OutEdges(dgl_type_t etype, IdArray vids) const {
851
852
853
  const SparseFormat fmt = SelectFormat(SparseFormat::CSR);
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdges(etype, vids);
854
855
}

Minjie Wang's avatar
Minjie Wang committed
856
EdgeArray UnitGraph::Edges(dgl_type_t etype, const std::string &order) const {
857
858
859
860
  SparseFormat fmt;
  if (order == std::string("eid")) {
    fmt = SelectFormat(SparseFormat::COO);
  } else if (order.empty()) {
861
    // arbitrary order
862
    fmt = SelectFormat(SparseFormat::ANY);
863
  } else if (order == std::string("srcdst")) {
864
    fmt = SelectFormat(SparseFormat::CSR);
865
866
  } else {
    LOG(FATAL) << "Unsupported order request: " << order;
867
    return {};
868
  }
869
870
871
872
873
874

  const auto& edges = GetFormat(fmt)->Edges(etype, order);
  if (fmt == SparseFormat::CSC)
    return EdgeArray{edges.dst, edges.src, edges.id};
  else
    return edges;
875
876
}

Minjie Wang's avatar
Minjie Wang committed
877
uint64_t UnitGraph::InDegree(dgl_type_t etype, dgl_id_t vid) const {
878
879
880
881
882
883
  SparseFormat fmt = SelectFormat(SparseFormat::CSC);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC)
    return ptr->OutDegree(etype, vid);
  else
    return ptr->InDegree(etype, vid);
884
885
}

Minjie Wang's avatar
Minjie Wang committed
886
DegreeArray UnitGraph::InDegrees(dgl_type_t etype, IdArray vids) const {
887
888
889
890
891
892
  SparseFormat fmt = SelectFormat(SparseFormat::CSC);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC)
    return ptr->OutDegrees(etype, vids);
  else
    return ptr->InDegrees(etype, vids);
893
894
}

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

Minjie Wang's avatar
Minjie Wang committed
901
DegreeArray UnitGraph::OutDegrees(dgl_type_t etype, IdArray vids) const {
902
903
904
  SparseFormat fmt = SelectFormat(SparseFormat::CSR);
  const auto ptr = GetFormat(fmt);
  return ptr->OutDegrees(etype, vids);
905
906
}

Minjie Wang's avatar
Minjie Wang committed
907
DGLIdIters UnitGraph::SuccVec(dgl_type_t etype, dgl_id_t vid) const {
908
909
910
  SparseFormat fmt = SelectFormat(SparseFormat::CSR);
  const auto ptr = GetFormat(fmt);
  return ptr->SuccVec(etype, vid);
911
912
}

Minjie Wang's avatar
Minjie Wang committed
913
DGLIdIters UnitGraph::OutEdgeVec(dgl_type_t etype, dgl_id_t vid) const {
914
915
916
  SparseFormat fmt = SelectFormat(SparseFormat::CSR);
  const auto ptr = GetFormat(fmt);
  return ptr->OutEdgeVec(etype, vid);
917
918
}

Minjie Wang's avatar
Minjie Wang committed
919
DGLIdIters UnitGraph::PredVec(dgl_type_t etype, dgl_id_t vid) const {
920
921
922
923
924
925
  SparseFormat fmt = SelectFormat(SparseFormat::CSC);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC)
    return ptr->SuccVec(etype, vid);
  else
    return ptr->PredVec(etype, vid);
926
927
}

Minjie Wang's avatar
Minjie Wang committed
928
DGLIdIters UnitGraph::InEdgeVec(dgl_type_t etype, dgl_id_t vid) const {
929
930
931
932
933
934
  SparseFormat fmt = SelectFormat(SparseFormat::CSC);
  const auto ptr = GetFormat(fmt);
  if (fmt == SparseFormat::CSC)
    return ptr->OutEdgeVec(etype, vid);
  else
    return ptr->InEdgeVec(etype, vid);
935
936
}

Minjie Wang's avatar
Minjie Wang committed
937
std::vector<IdArray> UnitGraph::GetAdj(
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
    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
957
HeteroSubgraph UnitGraph::VertexSubgraph(const std::vector<IdArray>& vids) const {
958
  // We prefer to generate a subgraph from out-csr.
959
960
  SparseFormat fmt = SelectFormat(SparseFormat::CSR);
  HeteroSubgraph sg = GetFormat(fmt)->VertexSubgraph(vids);
961
962
  CSRPtr subcsr = std::dynamic_pointer_cast<CSR>(sg.graph);
  HeteroSubgraph ret;
Minjie Wang's avatar
Minjie Wang committed
963
  ret.graph = HeteroGraphPtr(new UnitGraph(meta_graph(), nullptr, subcsr, nullptr));
964
965
966
967
968
  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
969
HeteroSubgraph UnitGraph::EdgeSubgraph(
970
    const std::vector<IdArray>& eids, bool preserve_nodes) const {
971
972
  SparseFormat fmt = SelectFormat(SparseFormat::COO);
  auto sg = GetFormat(fmt)->EdgeSubgraph(eids, preserve_nodes);
973
974
  COOPtr subcoo = std::dynamic_pointer_cast<COO>(sg.graph);
  HeteroSubgraph ret;
Minjie Wang's avatar
Minjie Wang committed
975
  ret.graph = HeteroGraphPtr(new UnitGraph(meta_graph(), nullptr, nullptr, subcoo));
976
977
978
979
980
  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
981
HeteroGraphPtr UnitGraph::CreateFromCOO(
982
983
    int64_t num_vtypes, int64_t num_src, int64_t num_dst, IdArray row, IdArray col,
    SparseFormat restrict_format) {
Minjie Wang's avatar
Minjie Wang committed
984
985
986
987
988
  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));
989
990
991

  return HeteroGraphPtr(
      new UnitGraph(mg, nullptr, nullptr, coo, restrict_format));
992
993
}

Minjie Wang's avatar
Minjie Wang committed
994
995
HeteroGraphPtr UnitGraph::CreateFromCSR(
    int64_t num_vtypes, int64_t num_src, int64_t num_dst,
996
    IdArray indptr, IdArray indices, IdArray edge_ids, SparseFormat restrict_format) {
Minjie Wang's avatar
Minjie Wang committed
997
998
999
1000
1001
  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));
1002
  return HeteroGraphPtr(new UnitGraph(mg, nullptr, csr, nullptr, restrict_format));
1003
1004
}

Minjie Wang's avatar
Minjie Wang committed
1005
HeteroGraphPtr UnitGraph::AsNumBits(HeteroGraphPtr g, uint8_t bits) {
1006
1007
1008
1009
1010
1011
1012
  if (g->NumBits() == bits) {
    return g;
  } else {
    // TODO(minjie): since we don't have int32 operations,
    //   we make sure that this graph (on CPU) has materialized CSR,
    //   and then copy them to other context (usually GPU). This should
    //   be fixed later.
Minjie Wang's avatar
Minjie Wang committed
1013
    auto bg = std::dynamic_pointer_cast<UnitGraph>(g);
1014
    CHECK_NOTNULL(bg);
1015

1016
1017
    CSRPtr new_incsr = CSRPtr(new CSR(bg->GetInCSR()->AsNumBits(bits)));
    CSRPtr new_outcsr = CSRPtr(new CSR(bg->GetOutCSR()->AsNumBits(bits)));
1018
1019
    return HeteroGraphPtr(
        new UnitGraph(g->meta_graph(), new_incsr, new_outcsr, nullptr, bg->restrict_format_));
1020
1021
1022
  }
}

Minjie Wang's avatar
Minjie Wang committed
1023
HeteroGraphPtr UnitGraph::CopyTo(HeteroGraphPtr g, const DLContext& ctx) {
1024
1025
1026
1027
1028
1029
1030
  if (ctx == g->Context()) {
    return g;
  }
  // TODO(minjie): since we don't have GPU implementation of COO<->CSR,
  //   we make sure that this graph (on CPU) has materialized CSR,
  //   and then copy them to other context (usually GPU). This should
  //   be fixed later.
Minjie Wang's avatar
Minjie Wang committed
1031
  auto bg = std::dynamic_pointer_cast<UnitGraph>(g);
1032
  CHECK_NOTNULL(bg);
1033

1034
1035
  CSRPtr new_incsr = CSRPtr(new CSR(bg->GetInCSR()->CopyTo(ctx)));
  CSRPtr new_outcsr = CSRPtr(new CSR(bg->GetOutCSR()->CopyTo(ctx)));
1036
1037
  return HeteroGraphPtr(
      new UnitGraph(g->meta_graph(), new_incsr, new_outcsr, nullptr, bg->restrict_format_));
1038
1039
}

1040
1041
UnitGraph::UnitGraph(GraphPtr metagraph, CSRPtr in_csr, CSRPtr out_csr, COOPtr coo,
                     SparseFormat restrict_format)
Minjie Wang's avatar
Minjie Wang committed
1042
  : BaseHeteroGraph(metagraph), in_csr_(in_csr), out_csr_(out_csr), coo_(coo) {
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
  restrict_format_ = restrict_format;

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

1053
1054
1055
  CHECK(GetAny()) << "At least one graph structure should exist.";
}

Minjie Wang's avatar
Minjie Wang committed
1056
UnitGraph::CSRPtr UnitGraph::GetInCSR() const {
1057
1058
1059
  if (!in_csr_) {
    if (out_csr_) {
      const auto& newadj = aten::CSRTranspose(out_csr_->adj());
Minjie Wang's avatar
Minjie Wang committed
1060
      const_cast<UnitGraph*>(this)->in_csr_ = std::make_shared<CSR>(meta_graph(), newadj);
1061
1062
1063
1064
1065
    } else {
      CHECK(coo_) << "None of CSR, COO exist";
      const auto& adj = coo_->adj();
      const auto& newadj = aten::COOToCSR(
          aten::COOMatrix{adj.num_cols, adj.num_rows, adj.col, adj.row});
Minjie Wang's avatar
Minjie Wang committed
1066
      const_cast<UnitGraph*>(this)->in_csr_ = std::make_shared<CSR>(meta_graph(), newadj);
1067
1068
1069
1070
1071
1072
    }
  }
  return in_csr_;
}

/* !\brief Return out csr. If not exist, transpose the other one.*/
Minjie Wang's avatar
Minjie Wang committed
1073
UnitGraph::CSRPtr UnitGraph::GetOutCSR() const {
1074
1075
1076
  if (!out_csr_) {
    if (in_csr_) {
      const auto& newadj = aten::CSRTranspose(in_csr_->adj());
Minjie Wang's avatar
Minjie Wang committed
1077
      const_cast<UnitGraph*>(this)->out_csr_ = std::make_shared<CSR>(meta_graph(), newadj);
1078
1079
1080
    } else {
      CHECK(coo_) << "None of CSR, COO exist";
      const auto& newadj = aten::COOToCSR(coo_->adj());
Minjie Wang's avatar
Minjie Wang committed
1081
      const_cast<UnitGraph*>(this)->out_csr_ = std::make_shared<CSR>(meta_graph(), newadj);
1082
1083
1084
1085
1086
1087
    }
  }
  return out_csr_;
}

/* !\brief Return coo. If not exist, create from csr.*/
Minjie Wang's avatar
Minjie Wang committed
1088
UnitGraph::COOPtr UnitGraph::GetCOO() const {
1089
1090
1091
  if (!coo_) {
    if (in_csr_) {
      const auto& newadj = aten::CSRToCOO(in_csr_->adj(), true);
Minjie Wang's avatar
Minjie Wang committed
1092
1093
      const_cast<UnitGraph*>(this)->coo_ = std::make_shared<COO>(
          meta_graph(),
1094
1095
1096
1097
          aten::COOMatrix{newadj.num_cols, newadj.num_rows, newadj.col, newadj.row});
    } else {
      CHECK(out_csr_) << "Both CSR are missing.";
      const auto& newadj = aten::CSRToCOO(out_csr_->adj(), true);
Minjie Wang's avatar
Minjie Wang committed
1098
      const_cast<UnitGraph*>(this)->coo_ = std::make_shared<COO>(meta_graph(), newadj);
1099
1100
1101
1102
1103
    }
  }
  return coo_;
}

Minjie Wang's avatar
Minjie Wang committed
1104
aten::CSRMatrix UnitGraph::GetInCSRMatrix() const {
1105
1106
1107
  return GetInCSR()->adj();
}

Minjie Wang's avatar
Minjie Wang committed
1108
aten::CSRMatrix UnitGraph::GetOutCSRMatrix() const {
1109
1110
1111
  return GetOutCSR()->adj();
}

Minjie Wang's avatar
Minjie Wang committed
1112
aten::COOMatrix UnitGraph::GetCOOMatrix() const {
1113
1114
1115
  return GetCOO()->adj();
}

Minjie Wang's avatar
Minjie Wang committed
1116
HeteroGraphPtr UnitGraph::GetAny() const {
1117
1118
1119
1120
1121
1122
1123
1124
1125
  if (in_csr_) {
    return in_csr_;
  } else if (out_csr_) {
    return out_csr_;
  } else {
    return coo_;
  }
}

1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
HeteroGraphPtr UnitGraph::GetFormat(SparseFormat format) const {
  switch (format) {
  case SparseFormat::CSR:
    return GetOutCSR();
  case SparseFormat::CSC:
    return GetInCSR();
  case SparseFormat::COO:
    return GetCOO();
  case SparseFormat::ANY:
    return GetAny();
  default:
    LOG(FATAL) << "unsupported format code";
    return nullptr;
  }
}

SparseFormat UnitGraph::SelectFormat(SparseFormat preferred_format) const {
  if (restrict_format_ != SparseFormat::ANY)
    return restrict_format_;
  else if (preferred_format != SparseFormat::ANY)
    return preferred_format;
  else if (in_csr_)
    return SparseFormat::CSC;
  else if (out_csr_)
    return SparseFormat::CSR;
  else
    return SparseFormat::COO;
}

1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
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";
  uint64_t num_vtypes, num_src, num_dst;
  CHECK(fs->Read(&num_vtypes)) << "Invalid num_vtypes";
  CHECK(fs->Read(&num_src)) << "Invalid num_src";
  CHECK(fs->Read(&num_dst)) << "Invalid num_dst";
  aten::CSRMatrix csr_matrix;
  CHECK(fs->Read(&csr_matrix)) << "Invalid csr_matrix";
  SparseFormat restrict_format;
  CHECK(fs->Read(&restrict_format)) << "Invalid restrict_format";
  auto mg = CreateUnitGraphMetaGraph(num_vtypes);
  CSRPtr csr(new CSR(mg, num_src, num_dst, csr_matrix.indptr, csr_matrix.indices, csr_matrix.data));
  *this = UnitGraph(mg, csr, nullptr, nullptr);
  return true;
}

void UnitGraph::Save(dmlc::Stream* fs) const {
  // Following CreateFromCSR signature
  aten::CSRMatrix csr_matrix = GetInCSRMatrix();
  uint64_t num_vtypes = NumVertexTypes();
  uint64_t num_src = NumVertices(SrcType());
  uint64_t num_dst = NumVertices(DstType());
  SparseFormat restrict_format = restrict_format_;
  fs->Write(kDGLSerialize_UnitGraphMagic);
  fs->Write(num_vtypes);
  fs->Write(num_src);
  fs->Write(num_dst);
  fs->Write(csr_matrix);
  fs->Write(restrict_format);
}

1190
}  // namespace dgl