-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutils.py
28 lines (21 loc) · 834 Bytes
/
utils.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
"""
Utility Functions
"""
from scipy.sparse import coo_matrix
#taken from http://stackoverflow.com/questions/16511879/reshape-sparse-matrix-efficiently-python-scipy-0-12, because SCIPY doesnt implement reshape
def coo_reshape(a, shape):
"""Reshape the sparse matrix `a`.
Returns a coo_matrix with shape `shape`.
"""
if not hasattr(shape, '__len__') or len(shape) != 2:
raise ValueError('`shape` must be a sequence of two integers')
c = a.tocoo()
nrows, ncols = c.shape
size = nrows * ncols
new_size = shape[0] * shape[1]
if new_size != size:
raise ValueError('total size of new array must be unchanged')
flat_indices = ncols * c.row + c.col
new_row, new_col = divmod(flat_indices, shape[1])
b = coo_matrix((c.data, (new_row, new_col)), shape=shape)
return b