-
-
Notifications
You must be signed in to change notification settings - Fork 785
/
coo.py
248 lines (190 loc) · 7.51 KB
/
coo.py
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
import numpy
try:
import scipy.sparse
_scipy_available = True
except ImportError:
_scipy_available = False
import cupy
from cupy import cusparse
from cupy.sparse import base
from cupy.sparse import csr
from cupy.sparse import data as sparse_data
from cupy.sparse import util
class coo_matrix(sparse_data._data_matrix):
"""COOrdinate format sparse matrix.
Now it has only one initializer format below:
``coo_matrix((M, N), [dtype])``
It constructs an empty matrix whose shape is ``(M, N)``. Default dtype
is float64.
``coo_matrix((data, (row, col))``
All ``data``, ``row`` and ``col`` are one-dimenaional
:class:`cupy.ndarray`.
Args:
arg1: Arguments for the initializer.
shape (tuple): Shape of a matrix. Its length must be two.
dtype: Data type. It must be an argument of :class:`numpy.dtype`.
copy (bool): If ``True``, copies of given data are always used.
.. see::
:class:`scipy.sparse.coo_matrix`
"""
format = 'coo'
def __init__(self, arg1, shape=None, dtype=None, copy=False):
if shape is not None and len(shape) != 2:
raise ValueError(
'Only two-dimensional sparse arrays are supported.')
if util.isshape(arg1):
m, n = arg1
m, n = int(m), int(n)
data = cupy.zeros(0, dtype if dtype else 'd')
row = cupy.zeros(0, dtype='i')
col = cupy.zeros(0, dtype='i')
# shape and copy argument is ignored
shape = (m, n)
copy = False
elif isinstance(arg1, tuple) and len(arg1) == 2:
try:
data, (row, col) = arg1
except (TypeError, ValueError):
raise TypeError('invalid input format')
if not (base.isdense(data) and data.ndim == 1 and
base.isdense(row) and row.ndim == 1 and
base.isdense(col) and col.ndim == 1):
raise ValueError('row, column, and data arrays must be 1-D')
if not (len(data) == len(row) == len(col)):
raise ValueError(
'row, column, and data array must all be the same length')
elif isspmatrix_coo(arg1):
data = arg1.data
row = arg1.row
col = arg1.col
if shape is None:
shape = arg1.shape
else:
raise ValueError(
'Only (data, (row, col)) format is supported')
if dtype is None:
dtype = data.dtype
else:
dtype = numpy.dtype(dtype)
if dtype != 'f' and dtype != 'd':
raise ValueError('Only float32 and float64 are supported')
data = data.astype(dtype, copy=copy)
row = row.astype('i', copy=copy)
col = col.astype('i', copy=copy)
if shape is None:
if len(row) == 0 or len(col) == 0:
raise ValueError(
'cannot infer dimensions from zero sized index arrays')
shape = (int(row.max()) + 1, int(col.max()) + 1)
if len(data) > 0:
if row.max() >= shape[0]:
raise ValueError('row index exceeds matrix dimensions')
if col.max() >= shape[1]:
raise ValueError('column index exceeds matrix dimensions')
if row.min() < 0:
raise ValueError('negative row index found')
if col.min() < 0:
raise ValueError('negative column index found')
sparse_data._data_matrix.__init__(self, data)
self.row = row
self.col = col
self._shape = shape
def _with_data(self, data):
return coo_matrix(
(data, (self.row.copy(), self.col.copy())), shape=self.shape)
def get_shape(self):
"""Returns the shape of the matrix.
Returns:
tuple: Shape of the matrix.
"""
return self._shape
def getnnz(self, axis=None):
"""Returns the number of stored values, including explicit zeros."""
if axis is None:
return self.data.size
else:
raise ValueError
def get(self, stream=None):
"""Returns a copy of the array on host memory.
Args:
stream (cupy.cuda.Stream): CUDA stream object. If it is given, the
copy runs asynchronously. Otherwise, the copy is synchronous.
Returns:
scipy.sparse.coo_matrix: Copy of the array on host memory.
"""
if not _scipy_available:
raise RuntimeError('scipy is not available')
data = self.data.get(stream)
row = self.row.get(stream)
col = self.col.get(stream)
return scipy.sparse.coo_matrix(
(data, (row, col)), shape=self.shape)
def toarray(self, order=None, out=None):
"""Returns a dense matrix representing the same value.
Args:
order (str): Not supported.
out: Not supported.
Returns:
cupy.ndarray: Dense array representing the same value.
.. seealso:: :func:`cupy.sparse.coo_array.toarray`
"""
return self.tocsr().toarray(order=order, out=out)
def tocoo(self, copy=False):
"""Converts the matrix to COOdinate format.
Args:
copy (bool): If ``False``, it shares data arrays as much as
possible.
Returns:
cupy.sparse.coo_matrix: Converted matrix.
"""
if copy:
return self.copy()
else:
return self
def tocsc(self, copy=False):
"""Converts the matrix to Compressed Sparse Column format.
Args:
copy (bool): If ``False``, it shares data arrays as much as
possible. Actually this option is ignored because all
arrays in a matrix cannot be shared in coo to csc conversion.
Returns:
cupy.sparse.csc_matrix: Converted matrix.
"""
return self.T.tocsr().T
def tocsr(self, copy=False):
"""Converts the matrix to Compressed Sparse Row format.
Args:
copy (bool): If ``False``, it shares data arrays as much as
possible. Actually this option is ignored because all
arrays in a matrix cannot be shared in coo to csr conversion.
Returns:
cupy.sparse.csr_matrix: Converted matrix.
"""
if self.nnz == 0:
return csr.csr_matrix(self.shape, dtype=self.dtype)
# copy is ignored because coosort method breaks an original.
x = self.copy()
cusparse.coosort(x)
return cusparse.coo2csr(x)
def transpose(self, axes=None, copy=False):
"""Returns a transpose matrix.
Args:
axes: This option is not supported.
copy (bool): If ``True``, a returned matrix shares no data.
Otherwise, it shared data arrays as much as possible.
Returns:
cupy.sparse.spmatrix: Transpose matrix.
"""
if axes is not None:
raise ValueError(
'Sparse matrices do not support an \'axes\' parameter because '
'swapping dimensions is the only logical permutation.')
shape = self.shape[1], self.shape[0]
return coo_matrix(
(self.data, (self.col, self.row)), shape=shape, copy=copy)
def isspmatrix_coo(x):
"""Checks if a given matrix is of COO format.
Returns:
bool: Returns if ``x`` is :class:`cupy.sparse.coo_matrix`.
"""
return isinstance(x, coo_matrix)