-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract_sparse_array.py
More file actions
219 lines (176 loc) · 8.71 KB
/
Copy pathextract_sparse_array.py
File metadata and controls
219 lines (176 loc) · 8.71 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
from functools import singledispatch
import numpy
from bisect import bisect_left
from typing import Any, Tuple, Sequence, List, Union
from biocutils.package_utils import is_package_installed
from ._subset import _is_subset_noop, _is_subset_consecutive
from ._mask import _convert_to_unmasked_1darray, _convert_to_maybe_masked_1darray, _allocate_unmasked_ndarray, _allocate_maybe_masked_ndarray
from .SparseNdarray import SparseNdarray, _extract_sparse_array_from_SparseNdarray
__author__ = "ltla"
__copyright__ = "ltla"
__license__ = "MIT"
@singledispatch
def extract_sparse_array(x: Any, subset: Tuple[Sequence[int], ...]) -> SparseNdarray:
"""Extract the contents of ``x`` (or a subset thereof) into a
:py:class:`~delayedarray.SparseNdarray.SparseNdarray`. This should only be
used for ``x`` where :py:meth:`~delayedarray.is_sparse.is_sparse` is True.
Args:
x:
Any array-like object containing sparse data.
subset:
Tuple of length equal to the number of dimensions, each containing
a sorted and unique sequence of integers specifying the elements of
each dimension to extract.
Returns:
``SparseNdarray`` for the requested subset. This may be a view so
callers should create a copy if they intend to modify it.
If :py:func:`~delayedarray.is_masked.is_masked` is True for ``x``, the
``SparseNdarray`` will contain NumPy ``MaskedArray``s internally.
"""
raise NotImplementedError("'extract_sparse_array(" + str(type(x)) + ")' has not yet been implemented")
@extract_sparse_array.register
def extract_sparse_array_SparseNdarray(x: SparseNdarray, subset: Tuple[Sequence[int], ...]) -> SparseNdarray:
"""See :py:meth:`~delayedarray.extract_sparse_array.extract_sparse_array`."""
if _is_subset_noop(x.shape, subset):
return x
else:
return _extract_sparse_array_from_SparseNdarray(x, subset)
if is_package_installed("scipy"):
import scipy.sparse as sp
def _set_empty_contents(contents: List) -> Union[List, None]:
for x in contents:
if x is not None:
return contents
return None
@extract_sparse_array.register
def extract_sparse_array_csc_matrix(x: sp.csc_matrix, subset: Tuple[Sequence[int], ...]) -> SparseNdarray:
"""See :py:meth:`~delayedarray.extract_sparse_array.extract_sparse_array`."""
final_shape = [len(s) for s in subset]
new_contents = None
if final_shape[0] != 0 and final_shape[1] != 0:
rowsub = subset[0]
row_consecutive = _is_subset_consecutive(rowsub)
first = rowsub[0]
last = rowsub[-1] + 1
new_contents = []
for ci in subset[1]:
start_pos = x.indptr[ci]
end_pos = x.indptr[ci + 1]
if first != 0:
start_pos = bisect_left(x.indices, first, lo=start_pos, hi=end_pos)
if row_consecutive:
if last != x.shape[0]:
end_pos = bisect_left(x.indices, last, lo=start_pos, hi=end_pos)
if end_pos > start_pos:
tmp = x.indices[start_pos:end_pos]
if first:
tmp = tmp - first # don't use -=, this might modify the view by reference.
new_contents.append((tmp, x.data[start_pos:end_pos]))
else:
new_contents.append(None)
else:
new_val = []
new_idx = []
pos = 0
for p in range(start_pos, end_pos):
ri = x.indices[p]
while pos < len(rowsub) and ri > rowsub[pos]:
pos += 1
if pos == len(rowsub):
break
if ri == rowsub[pos]:
new_idx.append(pos)
new_val.append(x.data[p])
pos += 1
if len(new_val):
new_contents.append((
_convert_to_unmasked_1darray(new_idx, dtype=x.indices.dtype),
_convert_to_maybe_masked_1darray(new_val, dtype=x.data.dtype, masked=numpy.ma.isMaskedArray(x.data))
))
else:
new_contents.append(None)
new_contents = _set_empty_contents(new_contents)
return SparseNdarray((*final_shape,), new_contents, dtype=x.dtype, index_dtype=x.indices.dtype, is_masked=False, check=False)
@extract_sparse_array.register
def extract_sparse_array_csr_matrix(x: sp.csr_matrix, subset: Tuple[Sequence[int], ...]) -> SparseNdarray:
"""See :py:meth:`~delayedarray.extract_sparse_array.extract_sparse_array`."""
final_shape = [len(s) for s in subset]
new_contents = None
if final_shape[0] != 0 and final_shape[1] != 0:
colsub = subset[1]
col_consecutive = _is_subset_consecutive(colsub)
cfirst = colsub[0]
clast = colsub[-1] + 1
new_contents = []
for i in range(len(colsub)):
new_contents.append(([], []))
for rpos, ri in enumerate(subset[0]):
start_pos = x.indptr[ri]
end_pos = x.indptr[ri + 1]
if cfirst != 0:
start_pos = bisect_left(x.indices, cfirst, lo=start_pos, hi=end_pos)
if col_consecutive:
if clast != x.shape[1]:
end_pos = bisect_left(x.indices, clast, lo=start_pos, hi=end_pos)
for p in range(start_pos, end_pos):
ci = x.indices[p]
idx, val = new_contents[ci - cfirst]
idx.append(rpos)
val.append(x.data[p])
else:
cpos = 0
for p in range(start_pos, end_pos):
ci = x.indices[p]
while cpos < len(colsub) and ci > colsub[cpos]:
cpos += 1
if cpos == len(colsub):
break
if ci == colsub[cpos]:
idx, val = new_contents[cpos]
idx.append(rpos)
val.append(x.data[p])
cpos += 1
for i in range(len(new_contents)):
idx, val = new_contents[i]
if len(idx):
new_contents[i] = (
_convert_to_unmasked_1darray(idx, dtype=x.indices.dtype),
_convert_to_maybe_masked_1darray(val, dtype=x.data.dtype, masked=numpy.ma.isMaskedArray(x.data))
)
else:
new_contents[i] = None
new_contents = _set_empty_contents(new_contents)
return SparseNdarray((*final_shape,), new_contents, dtype=x.dtype, index_dtype=x.indices.dtype, is_masked=False, check=False)
@extract_sparse_array.register
def extract_sparse_array_coo_matrix(x: sp.coo_matrix, subset: Tuple[Sequence[int], ...]) -> SparseNdarray:
"""See :py:meth:`~delayedarray.extract_sparse_array.extract_sparse_array`."""
final_shape = [len(s) for s in subset]
new_contents = None
if final_shape[0] != 0 and final_shape[1] != 0:
in_row = {}
for i, y in enumerate(subset[0]):
in_row[y] = i
in_col = {}
new_contents = []
for i, y in enumerate(subset[1]):
in_col[y] = i
new_contents.append([])
for i, v in enumerate(x.data):
r = x.row[i]
c = x.col[i]
if r in in_row and c in in_col:
new_contents[in_col[c]].append((in_row[r], v))
for i, con in enumerate(new_contents):
if len(con):
con.sort()
shape = (len(con),)
idx = _allocate_unmasked_ndarray(shape, dtype=x.row.dtype)
val = _allocate_maybe_masked_ndarray(shape, dtype=x.data.dtype, masked=numpy.ma.isMaskedArray(x.data))
for j, y in enumerate(con):
idx[j] = y[0]
val[j] = y[1]
new_contents[i] = (idx, val)
else:
new_contents[i] = None
new_contents = _set_empty_contents(new_contents)
return SparseNdarray((*final_shape,), new_contents, dtype=x.dtype, index_dtype=x.row.dtype, is_masked=False, check=False)