-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathsparse_matrix.py
More file actions
1477 lines (1222 loc) · 46.7 KB
/
Copy pathsparse_matrix.py
File metadata and controls
1477 lines (1222 loc) · 46.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
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
590
591
592
593
594
595
596
597
598
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
626
627
628
629
630
631
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""DGL sparse matrix module."""
# pylint: disable= invalid-name
from typing import Optional, Tuple
import torch
class SparseMatrix:
r"""Class for sparse matrix."""
def __init__(self, c_sparse_matrix: torch.ScriptObject):
self.c_sparse_matrix = c_sparse_matrix
def __repr__(self):
return _sparse_matrix_str(self)
@property
def val(self) -> torch.Tensor:
"""Returns the values of the non-zero elements.
Returns
-------
torch.Tensor
Values of the non-zero elements
"""
return self.c_sparse_matrix.val()
@property
def shape(self) -> Tuple[int]:
"""Returns the shape of the sparse matrix.
Returns
-------
Tuple[int]
The shape of the sparse matrix
"""
return tuple(self.c_sparse_matrix.shape())
@property
def nnz(self) -> int:
"""Returns the number of non-zero elements in the sparse matrix.
Returns
-------
int
The number of non-zero elements of the matrix
"""
return self.c_sparse_matrix.nnz()
@property
def dtype(self) -> torch.dtype:
"""Returns the data type of the sparse matrix.
Returns
-------
torch.dtype
Data type of the sparse matrix
"""
return self.c_sparse_matrix.val().dtype
@property
def device(self) -> torch.device:
"""Returns the device the sparse matrix is on.
Returns
-------
torch.device
The device the sparse matrix is on
"""
return self.c_sparse_matrix.device()
@property
def row(self) -> torch.Tensor:
"""Returns the row indices of the non-zero elements.
Returns
-------
torch.Tensor
Row indices of the non-zero elements
"""
return self.coo()[0]
@property
def col(self) -> torch.Tensor:
"""Returns the column indices of the non-zero elements.
Returns
-------
torch.Tensor
Column indices of the non-zero elements
"""
return self.coo()[1]
def coo(self) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Returns the coordinate list (COO) representation of the sparse
matrix.
See `COO in Wikipedia <https://en.wikipedia.org/wiki/
Sparse_matrix#Coordinate_list_(COO)>`_.
Returns
-------
torch.Tensor
Row coordinate
torch.Tensor
Column coordinate
Examples
--------
>>> indices = torch.tensor([[1, 2, 1], [2, 4, 3]])
>>> A = dglsp.spmatrix(indices)
>>> A.coo()
(tensor([1, 2, 1]), tensor([2, 4, 3]))
"""
return self.c_sparse_matrix.coo()
def indices(self) -> torch.Tensor:
r"""Returns the coordinate list (COO) representation in one tensor with
shape ``(2, nnz)``.
See `COO in Wikipedia <https://en.wikipedia.org/wiki/
Sparse_matrix#Coordinate_list_(COO)>`_.
Returns
-------
torch.Tensor
Stacked COO tensor with shape ``(2, nnz)``.
Examples
--------
>>> indices = torch.tensor([[1, 2, 1], [2, 4, 3]])
>>> A = dglsp.spmatrix(indices)
>>> A.indices()
tensor([[1, 2, 1],
[2, 4, 3]])
"""
return self.c_sparse_matrix.indices()
def csr(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Returns the compressed sparse row (CSR) representation of the sparse
matrix.
See `CSR in Wikipedia <https://en.wikipedia.org/wiki/
Sparse_matrix#Compressed_sparse_row_(CSR, _CRS_or_Yale_format)>`_.
This function also returns value indices as an index tensor, indicating
the order of the values of non-zero elements in the CSR representation.
A ``None`` value indices array indicates the order of the values stays
the same as the values of the SparseMatrix.
Returns
-------
torch.Tensor
Row indptr
torch.Tensor
Column indices
torch.Tensor
Value indices
Examples
--------
>>> indices = torch.tensor([[1, 2, 1], [2, 4, 3]])
>>> A = dglsp.spmatrix(indices)
>>> A.csr()
(tensor([0, 0, 2, 3]), tensor([2, 3, 4]), tensor([0, 2, 1]))
"""
return self.c_sparse_matrix.csr()
def csc(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Returns the compressed sparse column (CSC) representation of the
sparse matrix.
See `CSC in Wikipedia <https://en.wikipedia.org/wiki/
Sparse_matrix#Compressed_sparse_column_(CSC_or_CCS)>`_.
This function also returns value indices as an index tensor, indicating
the order of the values of non-zero elements in the CSC representation.
A ``None`` value indices array indicates the order of the values stays
the same as the values of the SparseMatrix.
Returns
-------
torch.Tensor
Column indptr
torch.Tensor
Row indices
torch.Tensor
Value indices
Examples
--------
>>> indices = torch.tensor([[1, 2, 1], [2, 4, 3]])
>>> A = dglsp.spmatrix(indices)
>>> A.csc()
(tensor([0, 0, 0, 1, 2, 3]), tensor([1, 1, 2]), tensor([0, 2, 1]))
"""
return self.c_sparse_matrix.csc()
def to_dense(self) -> torch.Tensor:
"""Returns a copy in dense matrix format of the sparse matrix.
Returns
-------
torch.Tensor
The copy in dense matrix format
"""
row, col = self.coo()
val = self.val
shape = self.shape + val.shape[1:]
mat = torch.zeros(shape, device=self.device, dtype=self.dtype)
mat[row, col] = val
return mat
def t(self):
"""Alias of :meth:`transpose()`"""
return self.transpose()
@property
def T(self): # pylint: disable=C0103
"""Alias of :meth:`transpose()`"""
return self.transpose()
def transpose(self):
"""Returns the transpose of this sparse matrix.
Returns
-------
SparseMatrix
The transpose of this sparse matrix.
Examples
--------
>>> indices = torch.tensor([[1, 1, 3], [2, 1, 3]])
>>> val = torch.tensor([1, 1, 2])
>>> A = dglsp.spmatrix(indices, val)
>>> A = A.transpose()
SparseMatrix(indices=tensor([[2, 1, 3],
[1, 1, 3]]),
values=tensor([1, 1, 2]),
shape=(4, 4), nnz=3)
"""
return SparseMatrix(self.c_sparse_matrix.transpose())
def to(self, device=None, dtype=None):
"""Performs matrix dtype and/or device conversion. If the target device
and dtype are already in use, the original matrix will be returned.
Parameters
----------
device : torch.device, optional
The target device of the matrix if provided, otherwise the current
device will be used
dtype : torch.dtype, optional
The target data type of the matrix values if provided, otherwise the
current data type will be used
Returns
-------
SparseMatrix
The converted matrix
Examples
--------
>>> indices = torch.tensor([[1, 1, 2], [1, 2, 0]])
>>> A = dglsp.spmatrix(indices, shape=(3, 4))
>>> A.to(device="cuda:0", dtype=torch.int32)
SparseMatrix(indices=tensor([[1, 1, 2],
[1, 2, 0]], device='cuda:0'),
values=tensor([1, 1, 1], device='cuda:0',
dtype=torch.int32),
shape=(3, 4), nnz=3)
"""
if device is None:
device = self.device
if dtype is None:
dtype = self.dtype
if device == self.device and dtype == self.dtype:
return self
elif device == self.device:
return val_like(self, self.val.to(dtype=dtype))
else:
# TODO(#5119): Find a better moving strategy instead of always
# convert to COO format.
row, col = self.coo()
row = row.to(device=device)
col = col.to(device=device)
val = self.val.to(device=device, dtype=dtype)
return from_coo(row, col, val, self.shape)
def cuda(self):
"""Moves the matrix to GPU. If the matrix is already on GPU, the
original matrix will be returned. If multiple GPU devices exist,
``cuda:0`` will be selected.
Returns
-------
SparseMatrix
The matrix on GPU
Examples
--------
>>> indices = torch.tensor([[1, 1, 2], [1, 2, 0]])
>>> A = dglsp.spmatrix(indices, shape=(3, 4))
>>> A.cuda()
SparseMatrix(indices=tensor([[1, 1, 2],
[1, 2, 0]], device='cuda:0'),
values=tensor([1., 1., 1.], device='cuda:0'),
shape=(3, 4), nnz=3)
"""
return self.to(device="cuda")
def cpu(self):
"""Moves the matrix to CPU. If the matrix is already on CPU, the
original matrix will be returned.
Returns
-------
SparseMatrix
The matrix on CPU
Examples
--------
>>> indices = torch.tensor([[1, 1, 2], [1, 2, 0]]).to("cuda")
>>> A = dglsp.spmatrix(indices, shape=(3, 4))
>>> A.cpu()
SparseMatrix(indices=tensor([[1, 1, 2],
[1, 2, 0]]),
values=tensor([1., 1., 1.]),
shape=(3, 4), nnz=3)
"""
return self.to(device="cpu")
def float(self):
"""Converts the matrix values to float32 data type. If the matrix
already uses float data type, the original matrix will be returned.
Returns
-------
SparseMatrix
The matrix with float values
Examples
--------
>>> indices = torch.tensor([[1, 1, 2], [1, 2, 0]])
>>> val = torch.ones(len(row)).long()
>>> A = dglsp.spmatrix(indices, val, shape=(3, 4))
>>> A.float()
SparseMatrix(indices=tensor([[1, 1, 2],
[1, 2, 0]]),
values=tensor([1., 1., 1.]),
shape=(3, 4), nnz=3)
"""
return self.to(dtype=torch.float)
def double(self):
"""Converts the matrix values to double data type. If the matrix already
uses double data type, the original matrix will be returned.
Returns
-------
SparseMatrix
The matrix with double values
Examples
--------
>>> indices = torch.tensor([[1, 1, 2], [1, 2, 0]])
>>> A = dglsp.spmatrix(indices, shape=(3, 4))
>>> A.double()
SparseMatrix(indices=tensor([[1, 1, 2],
[1, 2, 0]]),
values=tensor([1., 1., 1.], dtype=torch.float64),
shape=(3, 4), nnz=3)
"""
return self.to(dtype=torch.double)
def int(self):
"""Converts the matrix values to int32 data type. If the matrix already
uses int data type, the original matrix will be returned.
Returns
-------
DiagMatrix
The matrix with int values
Examples
--------
>>> indices = torch.tensor([[1, 1, 2], [1, 2, 0]])
>>> A = dglsp.spmatrix(indices, shape=(3, 4))
>>> A.int()
SparseMatrix(indices=tensor([[1, 1, 2],
[1, 2, 0]]),
values=tensor([1, 1, 1], dtype=torch.int32),
shape=(3, 4), nnz=3)
"""
return self.to(dtype=torch.int)
def long(self):
"""Converts the matrix values to long data type. If the matrix already
uses long data type, the original matrix will be returned.
Returns
-------
DiagMatrix
The matrix with long values
Examples
--------
>>> indices = torch.tensor([[1, 1, 2], [1, 2, 0]])
>>> A = dglsp.spmatrix(indices, shape=(3, 4))
>>> A.long()
SparseMatrix(indices=tensor([[1, 1, 2],
[1, 2, 0]]),
values=tensor([1, 1, 1]),
shape=(3, 4), nnz=3)
"""
return self.to(dtype=torch.long)
def coalesce(self):
"""Returns a coalesced sparse matrix.
A coalesced sparse matrix satisfies the following properties:
- the indices of the non-zero elements are unique,
- the indices are sorted in lexicographical order.
The coalescing process will accumulate the non-zero elements of the same
indices by summation.
The function does not support autograd.
Returns
-------
SparseMatrix
The coalesced sparse matrix
Examples
--------
>>> indices = torch.tensor([[1, 0, 0, 0, 1], [1, 1, 1, 2, 2]])
>>> val = torch.tensor([0, 1, 2, 3, 4])
>>> A = dglsp.spmatrix(indices, val)
>>> A.coalesce()
SparseMatrix(indices=tensor([[0, 0, 1, 1],
[1, 2, 1, 2]]),
values=tensor([3, 3, 0, 4]),
shape=(2, 3), nnz=4)
"""
return SparseMatrix(self.c_sparse_matrix.coalesce())
def has_duplicate(self):
"""Returns ``True`` if the sparse matrix contains duplicate indices.
Examples
--------
>>> indices = torch.tensor([[1, 0, 0, 0, 1], [1, 1, 1, 2, 2]])
>>> val = torch.tensor([0, 1, 2, 3, 4])
>>> A = dglsp.spmatrix(indices, val)
>>> A.has_duplicate()
True
>>> A.coalesce().has_duplicate()
False
"""
return self.c_sparse_matrix.has_duplicate()
def is_diag(self):
"""Returns whether the sparse matrix is a diagonal matrix."""
return self.c_sparse_matrix.is_diag()
def index_select(self, dim: int, index: torch.Tensor):
"""Returns a sub-matrix selected according to the given index.
Parameters
----------
dim : int
The dim to select from matrix, should be 0 or 1. `dim = 0` for
rowwise selection and `dim = 1` for columnwise selection.
index : torch.Tensor
The selection index indicates which IDs from the `dim` should
be chosen from the matrix.
Note that duplicated ids are allowed.
The function does not support autograd.
Returns
-------
SparseMatrix
The sub-matrix which contains selected rows or columns.
Examples
--------
>>> indices = torch.tensor([0, 1, 1, 2, 3, 4], [0, 2, 4, 3, 5, 0]])
>>> val = torch.tensor([0, 1, 2, 3, 4, 5])
>>> A = dglsp.spmatrix(indices, val)
Case 1: Select rows by IDs.
>>> row_ids = torch.tensor([0, 1, 4])
>>> A.index_select(0, row_ids)
SparseMatrix(indices=tensor([[0, 1, 1, 2],
[0, 2, 4, 0]]),
values=tensor([0, 1, 2, 5]),
shape=(3, 6), nnz=4)
Case 2: Select columns by IDs.
>>> column_ids = torch.tensor([0, 4, 5])
>>> A.index_select(1, column_ids)
SparseMatrix(indices=tensor([[0, 4, 1, 3],
[0, 0, 1, 2]]),
values=tensor([0, 5, 2, 4]),
shape=(5, 3), nnz=4)
"""
if dim not in (0, 1):
raise ValueError("The selection dimension should be 0 or 1.")
if isinstance(index, torch.Tensor):
return SparseMatrix(self.c_sparse_matrix.index_select(dim, index))
raise TypeError(f"{type(index).__name__} is unsupported input type.")
def range_select(self, dim: int, index: slice):
"""Returns a sub-matrix selected according to the given range index.
Parameters
----------
dim : int
The dim to select from matrix, should be 0 or 1. `dim = 0` for
rowwise selection and `dim = 1` for columnwise selection.
index : slice
The selection slice indicates ID index from the `dim` should
be chosen from the matrix.
The function does not support autograd.
Returns
-------
SparseMatrix
The sub-matrix which contains selected rows or columns.
Examples
--------
>>> indices = torch.tensor([0, 1, 1, 2, 3, 4], [0, 2, 4, 3, 5, 0]])
>>> val = torch.tensor([0, 1, 2, 3, 4, 5])
>>> A = dglsp.spmatrix(indices, val)
Case 1: Select rows with given slice object.
>>> A.range_select(0, slice(1, 3))
SparseMatrix(indices=tensor([[0, 0, 1],
[2, 4, 3]]),
values=tensor([1, 2, 3]),
shape=(2, 6), nnz=3)
Case 2: Select columns with given slice object.
>>> A.range_select(1, slice(3, 6))
SparseMatrix(indices=tensor([[2, 1, 3],
[0, 1, 2]]),
values=tensor([3, 2, 4]),
shape=(5, 3), nnz=3)
"""
if dim not in (0, 1):
raise ValueError("The selection dimension should be 0 or 1.")
if isinstance(index, slice):
if index.step not in (None, 1):
raise NotImplementedError(
"Slice with step other than 1 are not supported yet."
)
start = 0 if index.start is None else index.start
end = index.stop
return SparseMatrix(
self.c_sparse_matrix.range_select(dim, start, end)
)
raise TypeError(f"{type(index).__name__} is unsupported input type.")
def sample(
self,
dim: int,
fanout: int,
ids: Optional[torch.Tensor] = None,
replace: Optional[bool] = False,
bias: Optional[bool] = False,
):
"""Returns a sampled matrix on the given dimension and sample arguments.
Parameters
----------
dim : int
The dimension for sampling, should be 0 or 1. `dim = 0` for
rowwise selection and `dim = 1` for columnwise selection.
fanout : int
The number of elements to randomly sample on each row or column.
ids : torch.Tensor, optional
An optional tensor containing row or column IDs from which to
sample elements.
NOTE: If `ids` is not provided (i.e., `ids = None`), the function
will sample from all rows or columns.
replace : bool, optional
Indicates whether repeated sampling of the same element is allowed.
When `replace = True`, repeated sampling is permitted; when
`replace = False`, it is not allowed.
NOTE: If `replace = False` and there are fewer elements than
`fanout`, all non-zero elements will be sampled.
bias : bool, optional
A boolean flag indicating whether to enable biasing during sampling.
When `bias = True`, the values of the sparse matrix will be used as
bias weights.
The function does not support autograd.
Returns
-------
SparseMatrix
A submatrix with the same shape as the original matrix, containing
the randomly sampled non-zero elements.
Examples
--------
>>> indices = torch.tensor([[0, 0, 1, 1, 2, 2, 2],
[0, 2, 0, 1, 0, 1, 2]])
>>> val = torch.tensor([0, 1, 2, 3, 4, 5, 6])
>>> A = dglsp.spmatrix(indices, val)
Case 1: Sample rows with the given number and disable repeated sampling.
>>> row_ids = torch.tensor([0, 2])
>>> A.sample(0, 2, row_ids)
SparseMatrix(indices=tensor([[0, 0, 1, 1],
[0, 2, 0, 2]]),
values=tensor([0, 1, 4, 6]),
shape=(2, 3), nnz=4)
Case 2: Sample cols with the given number and disable repeated sampling.
>>> col_ids = torch.tensor([0, 2])
>>> A.sample(1, 2, col_ids)
SparseMatrix(indices=tensor([[0, 1, 0, 2],
[0, 0, 1, 1]]),
values=tensor([0, 2, 1, 6]),
shape=(3, 2), nnz=4)
Case 3: Sample rows with the given number and enable repeated sampling.
>>> row_ids = torch.tensor([0, 1])
>>> A.sample(0, 2, row_ids, True)
SparseMatrix(indices=tensor([[0, 0, 1, 1],
[0, 2, 0, 0]]),
values=tensor([0, 1, 2, 2]),
shape=(2, 3), nnz=3)
Case 4: Sample cols with the given number and enable repeated sampling.
>>> col_ids = torch.tensor([0, 1])
>>> A.sample(1, 2, col_ids, True)
SparseMatrix(indices=tensor([[0, 1, 1, 1],
[0, 0, 1, 1]]),
values=tensor([0, 2, 3, 3]),
shape=(3, 2), nnz=3)
"""
if ids is None:
dim_size = self.shape[0] if dim == 0 else self.shape[1]
ids = torch.range(
0, dim_size, dtype=torch.int64, device=self.device
)
return SparseMatrix(
self.c_sparse_matrix.sample(dim, fanout, ids, replace, bias)
)
def compact(
self,
dim: int,
leading_indices: Optional[torch.Tensor] = None,
):
"""Compact sparse matrix by removing rows or columns without non-zero
elements in the sparse matrix and relabeling indices of the dimension.
This function serves a dual purpose: it allows you to reorganize the
indices within a specific dimension (rows or columns) of the sparse
matrix and, if needed, place certain 'leading_indices' at the beginning
of the relabeled dimension.
In the absence of 'leading_indices' (when it's set to `None`), the order
of relabeled indices remains the same as the original order, except that
rows or columns without non-zero elements are removed. When
'leading_indices' are provided, they are positioned at the start of the
relabeled dimension. To be precise, all rows selected by the specified
indices will be remapped from 0 to length(indices) - 1. Rows that are not
selected and contain any non-zero elements will be positioned after those
remapped rows while maintaining their original order.
This function mimics 'dgl.to_block', a method used to compress a sampled
subgraph by eliminating redundant nodes. The 'leading_indices' parameter
replicates the behavior of 'include_dst_in_src' in 'dgl.to_block',
adding destination node information for message passing.
Setting 'leading_indices' to column IDs when relabeling the row
dimension, for example, achieves the same effect as including destination
nodes in source nodes.
Parameters
----------
dim : int
The dimension to relabel. Should be 0 or 1. Use `dim = 0` for rowwise
relabeling and `dim = 1` for columnwise relabeling.
leading_indices : torch.Tensor, optional
An optional tensor containing row or column ids that should be placed
at the beginning of the relabeled dimension.
Returns
-------
Tuple[SparseMatrix, torch.Tensor]
A tuple containing the relabeled sparse matrix and the index mapping
of the relabeled dimension from the new index to the original index.
Examples
--------
>>> indices = torch.tensor([[0, 2],
[1, 2]])
>>> A = dglsp.spmatrix(indices)
>>> print(A.to_dense())
tensor([[0., 1., 0.],
[0., 0., 0.],
[0., 0., 1.]])
Case 1: Compact rows without indices.
>>> B, original_rows = A.compact(dim=0, leading_indices=None)
>>> print(B.to_dense())
tensor([[0., 1., 0.],
[0., 0., 1.]])
>>> print(original_rows)
torch.Tensor([0, 2])
Case 2: Compact rows with indices.
>>> B, original_rows = A.compact(dim=0, leading_indices=[1, 2])
>>> print(B.to_dense())
tensor([[0., 0., 0.],
[0., 0., 1.],
[0., 1., 0.],])
>>> print(original_rows)
torch.Tensor([1, 2, 0])
"""
mat, idx = torch.ops.dgl_sparse.compact(
self.c_sparse_matrix, dim, leading_indices
)
return SparseMatrix(mat), idx
def spmatrix(
indices: torch.Tensor,
val: Optional[torch.Tensor] = None,
shape: Optional[Tuple[int, int]] = None,
) -> SparseMatrix:
r"""Creates a sparse matrix from Coordinate format indices.
Parameters
----------
indices : tensor.Tensor
The indices are the coordinates of the non-zero elements in the matrix,
which should have shape of ``(2, N)`` where the first row is the row
indices and the second row is the column indices of non-zero elements.
val : tensor.Tensor, optional
The values of shape ``(nnz)`` or ``(nnz, D)``. If None, it will be a
tensor of shape ``(nnz)`` filled by 1.
shape : tuple[int, int], optional
If not specified, it will be inferred from :attr:`row` and :attr:`col`,
i.e., ``(row.max() + 1, col.max() + 1)``. Otherwise, :attr:`shape`
should be no smaller than this.
Returns
-------
SparseMatrix
Sparse matrix
Examples
--------
Case1: Sparse matrix with row and column indices without values.
>>> indices = torch.tensor([[1, 1, 2], [2, 4, 3]])
>>> A = dglsp.spmatrix(indices)
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([1., 1., 1.]),
shape=(3, 5), nnz=3)
>>> # Specify shape
>>> A = dglsp.spmatrix(indices, shape=(5, 5))
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([1., 1., 1.]),
shape=(5, 5), nnz=3)
Case2: Sparse matrix with scalar values.
>>> indices = torch.tensor([[1, 1, 2], [2, 4, 3]])
>>> val = torch.tensor([[1.], [2.], [3.]])
>>> A = dglsp.spmatrix(indices, val)
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([[1.],
[2.],
[3.]]),
shape=(3, 5), nnz=3, val_size=(1,))
Case3: Sparse matrix with vector values.
>>> indices = torch.tensor([[1, 1, 2], [2, 4, 3]])
>>> val = torch.tensor([[1., 1.], [2., 2.], [3., 3.]])
>>> A = dglsp.spmatrix(indices, val)
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([[1., 1.],
[2., 2.],
[3., 3.]]),
shape=(3, 5), nnz=3, val_size=(2,))
"""
if shape is None:
shape = (
torch.max(indices[0]).item() + 1,
torch.max(indices[1]).item() + 1,
)
if val is None:
val = torch.ones(indices.shape[1]).to(indices.device)
assert (
val.dim() <= 2
), "The values of a SparseMatrix can only be scalars or vectors."
return SparseMatrix(torch.ops.dgl_sparse.from_coo(indices, val, shape))
def from_coo(
row: torch.Tensor,
col: torch.Tensor,
val: Optional[torch.Tensor] = None,
shape: Optional[Tuple[int, int]] = None,
) -> SparseMatrix:
r"""Creates a sparse matrix from a coordinate list (COO), which stores a list
of (row, column, value) tuples.
See `COO in Wikipedia
<https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)>`_.
Parameters
----------
row : torch.Tensor
The row indices of shape ``(nnz)``
col : torch.Tensor
The column indices of shape ``(nnz)``
val : torch.Tensor, optional
The values of shape ``(nnz)`` or ``(nnz, D)``. If None, it will be a
tensor of shape ``(nnz)`` filled by 1.
shape : tuple[int, int], optional
If not specified, it will be inferred from :attr:`row` and :attr:`col`,
i.e., ``(row.max() + 1, col.max() + 1)``. Otherwise, :attr:`shape`
should be no smaller than this.
Returns
-------
SparseMatrix
Sparse matrix
Examples
--------
Case1: Sparse matrix with row and column indices without values.
>>> dst = torch.tensor([1, 1, 2])
>>> src = torch.tensor([2, 4, 3])
>>> A = dglsp.from_coo(dst, src)
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([1., 1., 1.]),
shape=(3, 5), nnz=3)
>>> # Specify shape
>>> A = dglsp.from_coo(dst, src, shape=(5, 5))
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([1., 1., 1.]),
shape=(5, 5), nnz=3)
Case2: Sparse matrix with scalar values.
>>> indices = torch.tensor([[1, 1, 2], [2, 4, 3]])
>>> val = torch.tensor([[1.], [2.], [3.]])
>>> A = dglsp.spmatrix(indices, val)
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([[1.],
[2.],
[3.]]),
shape=(3, 5), nnz=3, val_size=(1,))
Case3: Sparse matrix with vector values.
>>> dst = torch.tensor([1, 1, 2])
>>> src = torch.tensor([2, 4, 3])
>>> val = torch.tensor([[1., 1.], [2., 2.], [3., 3.]])
>>> A = dglsp.from_coo(dst, src, val)
SparseMatrix(indices=tensor([[1, 1, 2],
[2, 4, 3]]),
values=tensor([[1., 1.],
[2., 2.],
[3., 3.]]),
shape=(3, 5), nnz=3, val_size=(2,))
"""
assert row.shape[0] == col.shape[0]
return spmatrix(torch.stack([row, col]), val, shape)
def from_csr(
indptr: torch.Tensor,
indices: torch.Tensor,
val: Optional[torch.Tensor] = None,
shape: Optional[Tuple[int, int]] = None,
) -> SparseMatrix:
r"""Creates a sparse matrix from compress sparse row (CSR) format.
See `CSR in Wikipedia <https://en.wikipedia.org/wiki/
Sparse_matrix#Compressed_sparse_row_(CSR,_CRS_or_Yale_format)>`_.
For row i of the sparse matrix
- the column indices of the non-zero elements are stored in
``indices[indptr[i]: indptr[i+1]]``
- the corresponding values are stored in ``val[indptr[i]: indptr[i+1]]``
Parameters
----------
indptr : torch.Tensor
Pointer to the column indices of shape ``(N + 1)``, where ``N`` is the
number of rows
indices : torch.Tensor
The column indices of shape ``(nnz)``
val : torch.Tensor, optional
The values of shape ``(nnz)`` or ``(nnz, D)``. If None, it will be a
tensor of shape ``(nnz)`` filled by 1.
shape : tuple[int, int], optional
If not specified, it will be inferred from :attr:`indptr` and
:attr:`indices`, i.e., ``(len(indptr) - 1, indices.max() + 1)``.
Otherwise, :attr:`shape` should be no smaller than this.
Returns
-------
SparseMatrix
Sparse matrix
Examples
--------
Case1: Sparse matrix without values
.. code::
[[0, 1, 0],
[0, 0, 1],
[1, 1, 1]]
>>> indptr = torch.tensor([0, 1, 2, 5])
>>> indices = torch.tensor([1, 2, 0, 1, 2])
>>> A = dglsp.from_csr(indptr, indices)
SparseMatrix(indices=tensor([[0, 1, 2, 2, 2],
[1, 2, 0, 1, 2]]),
values=tensor([1., 1., 1., 1., 1.]),
shape=(3, 3), nnz=5)
>>> # Specify shape
>>> A = dglsp.from_csr(indptr, indices, shape=(3, 5))
SparseMatrix(indices=tensor([[0, 1, 2, 2, 2],
[1, 2, 0, 1, 2]]),
values=tensor([1., 1., 1., 1., 1.]),
shape=(3, 5), nnz=5)
Case2: Sparse matrix with scalar/vector values. Following example is with
vector data.
>>> indptr = torch.tensor([0, 1, 2, 5])
>>> indices = torch.tensor([1, 2, 0, 1, 2])
>>> val = torch.tensor([[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]])
>>> A = dglsp.from_csr(indptr, indices, val)
SparseMatrix(indices=tensor([[0, 1, 2, 2, 2],
[1, 2, 0, 1, 2]]),
values=tensor([[1, 1],
[2, 2],
[3, 3],
[4, 4],
[5, 5]]),
shape=(3, 3), nnz=5, val_size=(2,))