forked from pydata/sparse
/
coo.py
2694 lines (2207 loc) · 82.4 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
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
from __future__ import absolute_import, division, print_function
from collections import Iterable, defaultdict, deque
from functools import reduce
from itertools import product
import numbers
import operator
import numpy as np
import scipy.sparse
from numpy.lib.mixins import NDArrayOperatorsMixin
from .slicing import normalize_index
from .utils import _zero_of_dtype, isscalar
from .sparse_array import SparseArray
from .compatibility import int, zip_longest, range, zip
class COO(SparseArray, NDArrayOperatorsMixin):
"""
A sparse multidimensional array.
This is stored in COO format. It depends on NumPy and Scipy.sparse for
computation, but supports arrays of arbitrary dimension.
Parameters
----------
coords : numpy.ndarray (COO.ndim, COO.nnz)
An array holding the index locations of every value
Should have shape (number of dimensions, number of non-zeros)
data : numpy.ndarray (COO.nnz,)
An array of Values
shape : tuple[int] (COO.ndim,)
The shape of the array.
has_duplicates : bool, optional
A value indicating whether the supplied value for :code:`coords` has
duplicates. Note that setting this to `False` when :code:`coords` does have
duplicates may result in undefined behaviour. See :obj:`COO.sum_duplicates`
sorted : bool, optional
A value indicating whether the values in `coords` are sorted. Note
that setting this to `False` when :code:`coords` isn't sorted may
result in undefined behaviour. See :obj:`COO.sort_indices`.
cache : bool, optional
Whether to enable cacheing for various operations. See
:obj:`COO.enable_caching`
Attributes
----------
coords : numpy.ndarray (ndim, nnz)
An array holding the coordinates of every nonzero element.
data : numpy.ndarray (nnz,)
An array holding the values corresponding to :obj:`COO.coords`.
shape : tuple[int] (ndim,)
The dimensions of this array.
See Also
--------
DOK : A mostly write-only sparse array.
Examples
--------
You can create :obj:`COO` objects from Numpy arrays.
>>> x = np.eye(4, dtype=np.uint8)
>>> x[2, 3] = 5
>>> s = COO.from_numpy(x)
>>> s
<COO: shape=(4, 4), dtype=uint8, nnz=5, sorted=True, duplicates=False>
>>> s.data # doctest: +NORMALIZE_WHITESPACE
array([1, 1, 1, 5, 1], dtype=uint8)
>>> s.coords # doctest: +NORMALIZE_WHITESPACE
array([[0, 1, 2, 2, 3],
[0, 1, 2, 3, 3]], dtype=uint8)
:obj:`COO` objects support basic arithmetic and binary operations.
>>> x2 = np.eye(4, dtype=np.uint8)
>>> x2[3, 2] = 5
>>> s2 = COO.from_numpy(x2)
>>> (s + s2).todense() # doctest: +NORMALIZE_WHITESPACE
array([[2, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 2, 5],
[0, 0, 5, 2]], dtype=uint8)
>>> (s * s2).todense() # doctest: +NORMALIZE_WHITESPACE
array([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]], dtype=uint8)
Binary operations support broadcasting.
>>> x3 = np.zeros((4, 1), dtype=np.uint8)
>>> x3[2, 0] = 1
>>> s3 = COO.from_numpy(x3)
>>> (s * s3).todense() # doctest: +NORMALIZE_WHITESPACE
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 5],
[0, 0, 0, 0]], dtype=uint8)
:obj:`COO` objects also support dot products and reductions.
>>> s.dot(s.T).sum(axis=0).todense() # doctest: +NORMALIZE_WHITESPACE
array([ 1, 1, 31, 6], dtype=uint64)
You can use Numpy :code:`ufunc` operations on :obj:`COO` arrays as well.
>>> np.sum(s, axis=1).todense() # doctest: +NORMALIZE_WHITESPACE
array([1, 1, 6, 1], dtype=uint64)
>>> np.round(np.sqrt(s, dtype=np.float64), decimals=1).todense() # doctest: +SKIP
array([[ 1. , 0. , 0. , 0. ],
[ 0. , 1. , 0. , 0. ],
[ 0. , 0. , 1. , 2.2],
[ 0. , 0. , 0. , 1. ]])
Operations that will result in a dense array will raise a :obj:`ValueError`,
such as the following.
>>> np.exp(s)
Traceback (most recent call last):
...
ValueError: Performing this operation would produce a dense result: <ufunc 'exp'>
You can also create :obj:`COO` arrays from coordinates and data.
>>> coords = [[0, 0, 0, 1, 1],
... [0, 1, 2, 0, 3],
... [0, 3, 2, 0, 1]]
>>> data = [1, 2, 3, 4, 5]
>>> s4 = COO(coords, data, shape=(3, 4, 5))
>>> s4
<COO: shape=(3, 4, 5), dtype=int64, nnz=5, sorted=False, duplicates=True>
Following scipy.sparse conventions you can also pass these as a tuple with
rows and columns
>>> rows = [0, 1, 2, 3, 4]
>>> cols = [0, 0, 0, 1, 1]
>>> data = [10, 20, 30, 40, 50]
>>> z = COO((data, (rows, cols)))
>>> z.todense() # doctest: +NORMALIZE_WHITESPACE
array([[10, 0],
[20, 0],
[30, 0],
[ 0, 40],
[ 0, 50]])
You can also pass a dictionary or iterable of index/value pairs. Repeated
indices imply summation:
>>> d = {(0, 0, 0): 1, (1, 2, 3): 2, (1, 1, 0): 3}
>>> COO(d)
<COO: shape=(2, 3, 4), dtype=int64, nnz=3, sorted=False, duplicates=False>
>>> L = [((0, 0), 1),
... ((1, 1), 2),
... ((0, 0), 3)]
>>> COO(L).todense() # doctest: +NORMALIZE_WHITESPACE
array([[4, 0],
[0, 2]])
You can convert :obj:`DOK` arrays to :obj:`COO` arrays.
>>> from sparse import DOK
>>> s5 = DOK((5, 5), dtype=np.int64)
>>> s5[1:3, 1:3] = [[4, 5], [6, 7]]
>>> s5
<DOK: shape=(5, 5), dtype=int64, nnz=4>
>>> s6 = COO(s5)
>>> s6
<COO: shape=(5, 5), dtype=int64, nnz=4, sorted=False, duplicates=False>
>>> s6.todense() # doctest: +NORMALIZE_WHITESPACE
array([[0, 0, 0, 0, 0],
[0, 4, 5, 0, 0],
[0, 6, 7, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
"""
__array_priority__ = 12
def __init__(self, coords, data=None, shape=None, has_duplicates=True,
sorted=False, cache=False):
self._cache = None
if cache:
self.enable_caching()
if data is None:
from .dok import DOK
if isinstance(coords, COO):
self._make_shallow_copy_of(coords)
return
if isinstance(coords, DOK):
shape = coords.shape
coords = coords.data
# {(i, j, k): x, (i, j, k): y, ...}
if isinstance(coords, dict):
coords = list(coords.items())
has_duplicates = False
if isinstance(coords, np.ndarray):
result = COO.from_numpy(coords)
self._make_shallow_copy_of(result)
return
if isinstance(coords, scipy.sparse.spmatrix):
result = COO.from_scipy_sparse(coords)
self._make_shallow_copy_of(result)
return
# []
if not coords:
data = []
coords = []
# [((i, j, k), value), (i, j, k), value), ...]
elif isinstance(coords[0][0], Iterable):
if coords:
assert len(coords[0]) == 2
data = [x[1] for x in coords]
coords = [x[0] for x in coords]
coords = np.asarray(coords).T
# (data, (row, col, slab, ...))
else:
data = coords[0]
coords = np.stack(coords[1], axis=0)
self.data = np.asarray(data)
self.coords = np.asarray(coords)
if self.coords.ndim == 1:
self.coords = self.coords[None, :]
if shape and not self.coords.size:
self.coords = np.zeros((len(shape), 0), dtype=np.uint64)
if shape is None:
if self.coords.nbytes:
shape = tuple((self.coords.max(axis=1) + 1).tolist())
else:
shape = ()
super(COO, self).__init__(shape)
if self.shape:
dtype = np.min_scalar_type(max(self.shape))
else:
dtype = np.uint8
self.coords = self.coords.astype(dtype)
assert not self.shape or len(data) == self.coords.shape[1]
self.has_duplicates = has_duplicates
self.sorted = sorted
def _make_shallow_copy_of(self, other):
self.coords = other.coords
self.data = other.data
self.has_duplicates = other.has_duplicates
self.sorted = other.sorted
super(COO, self).__init__(other.shape)
def enable_caching(self):
""" Enable caching of reshape, transpose, and tocsr/csc operations
This enables efficient iterative workflows that make heavy use of
csr/csc operations, such as tensordot. This maintains a cache of
recent results of reshape and transpose so that operations like
tensordot (which uses both internally) store efficiently stored
representations for repeated use. This can significantly cut down on
computational costs in common numeric algorithms.
However, this also assumes that neither this object, nor the downstream
objects will have their data mutated.
Examples
--------
>>> s.enable_caching() # doctest: +SKIP
>>> csr1 = s.transpose((2, 0, 1)).reshape((100, 120)).tocsr() # doctest: +SKIP
>>> csr2 = s.transpose((2, 0, 1)).reshape((100, 120)).tocsr() # doctest: +SKIP
>>> csr1 is csr2 # doctest: +SKIP
True
"""
self._cache = defaultdict(lambda: deque(maxlen=3))
return self
@classmethod
def from_numpy(cls, x):
"""
Convert the given :obj:`numpy.ndarray` to a :obj:`COO` object.
Parameters
----------
x : np.ndarray
The dense array to convert.
Returns
-------
COO
The converted COO array.
Examples
--------
>>> x = np.eye(5)
>>> s = COO.from_numpy(x)
>>> s
<COO: shape=(5, 5), dtype=float64, nnz=5, sorted=True, duplicates=False>
"""
x = np.asanyarray(x)
if x.shape:
coords = np.where(x)
data = x[coords]
coords = np.vstack(coords)
else:
coords = np.empty((0, 1), dtype=np.uint8)
data = np.array(x, ndmin=1)
return cls(coords, data, shape=x.shape, has_duplicates=False,
sorted=True)
def todense(self):
"""
Convert this :obj:`COO` array to a dense :obj:`numpy.ndarray`. Note that
this may take a large amount of memory if the :obj:`COO` object's :code:`shape`
is large.
Returns
-------
numpy.ndarray
The converted dense array.
See Also
--------
DOK.todense : Equivalent :obj:`DOK` array method.
scipy.sparse.coo_matrix.todense : Equivalent Scipy method.
Examples
--------
>>> x = np.random.randint(100, size=(7, 3))
>>> s = COO.from_numpy(x)
>>> x2 = s.todense()
>>> np.array_equal(x, x2)
True
"""
self.sum_duplicates()
x = np.zeros(shape=self.shape, dtype=self.dtype)
coords = tuple([self.coords[i, :] for i in range(self.ndim)])
data = self.data
if coords != ():
x[coords] = data
else:
if len(data) != 0:
x[coords] = data
return x
@classmethod
def from_scipy_sparse(cls, x):
"""
Construct a :obj:`COO` array from a :obj:`scipy.sparse.spmatrix`
Parameters
----------
x : scipy.sparse.spmatrix
The sparse matrix to construct the array from.
Returns
-------
COO
The converted :obj:`COO` object.
Examples
--------
>>> x = scipy.sparse.rand(6, 3, density=0.2)
>>> s = COO.from_scipy_sparse(x)
>>> np.array_equal(x.todense(), s.todense())
True
"""
x = scipy.sparse.coo_matrix(x)
coords = np.empty((2, x.nnz), dtype=x.row.dtype)
coords[0, :] = x.row
coords[1, :] = x.col
return COO(coords, x.data, shape=x.shape,
has_duplicates=not x.has_canonical_format,
sorted=x.has_canonical_format)
@property
def dtype(self):
"""
The datatype of this array.
Returns
-------
numpy.dtype
The datatype of this array.
See Also
--------
numpy.ndarray.dtype : Numpy equivalent property.
scipy.sparse.coo_matrix.dtype : Scipy equivalent property.
Examples
--------
>>> x = (200 * np.random.rand(5, 4)).astype(np.int32)
>>> s = COO.from_numpy(x)
>>> s.dtype
dtype('int32')
>>> x.dtype == s.dtype
True
"""
return self.data.dtype
@property
def nnz(self):
"""
The number of nonzero elements in this array. Note that any duplicates in
:code:`coords` are counted multiple times. To avoid this, call :obj:`COO.sum_duplicates`.
Returns
-------
int
The number of nonzero elements in this array.
See Also
--------
DOK.nnz : Equivalent :obj:`DOK` array property.
numpy.count_nonzero : A similar Numpy function.
scipy.sparse.coo_matrix.nnz : The Scipy equivalent property.
Examples
--------
>>> x = np.array([0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 0])
>>> np.count_nonzero(x)
6
>>> s = COO.from_numpy(x)
>>> s.nnz
6
>>> np.count_nonzero(x) == s.nnz
True
"""
return self.coords.shape[1]
@property
def nbytes(self):
"""
The number of bytes taken up by this object. Note that for small arrays,
this may undercount the number of bytes due to the large constant overhead.
Returns
-------
int
The approximate bytes of memory taken by this object.
See Also
--------
numpy.ndarray.nbytes : The equivalent Numpy property.
Examples
--------
>>> data = np.arange(6, dtype=np.uint8)
>>> coords = np.random.randint(1000, size=(3, 6), dtype=np.uint16)
>>> s = COO(coords, data, shape=(1000, 1000, 1000))
>>> s.nbytes
42
"""
return self.data.nbytes + self.coords.nbytes
def __len__(self):
"""
Get "length" of array, which is by definition the size of the first
dimension.
Returns
-------
int
The size of the first dimension.
See Also
--------
numpy.ndarray.__len__ : Numpy equivalent property.
Examples
--------
>>> x = np.zeros((10, 10))
>>> s = COO.from_numpy(x)
>>> len(s)
10
"""
return self.shape[0]
def __sizeof__(self):
return self.nbytes
def __getitem__(self, index):
if not isinstance(index, tuple):
if isinstance(index, str):
data = self.data[index]
idx = np.where(data)
coords = list(self.coords[:, idx[0]])
coords.extend(idx[1:])
return COO(coords, data[idx].flatten(),
shape=self.shape + self.data.dtype[index].shape,
has_duplicates=self.has_duplicates,
sorted=self.sorted)
else:
index = (index,)
last_ellipsis = len(index) > 0 and index[-1] is Ellipsis
index = normalize_index(index, self.shape)
if len(index) != 0 and all(not isinstance(ind, Iterable) and ind == slice(None) for ind in index):
return self
mask = np.ones(self.nnz, dtype=np.bool)
for i, ind in enumerate([i for i in index if i is not None]):
if not isinstance(ind, Iterable) and ind == slice(None):
continue
mask &= _mask(self.coords[i], ind, self.shape[i])
n = mask.sum()
coords = []
shape = []
i = 0
for ind in index:
if isinstance(ind, numbers.Integral):
i += 1
continue
elif isinstance(ind, slice):
step = ind.step if ind.step is not None else 1
if step > 0:
start = ind.start if ind.start is not None else 0
start = max(start, 0)
stop = ind.stop if ind.stop is not None else self.shape[i]
stop = min(stop, self.shape[i])
if start > stop:
start = stop
shape.append((stop - start + step - 1) // step)
else:
start = ind.start or self.shape[i] - 1
stop = ind.stop if ind.stop is not None else -1
start = min(start, self.shape[i] - 1)
stop = max(stop, -1)
if start < stop:
start = stop
shape.append((start - stop - step - 1) // (-step))
dt = np.min_scalar_type(min(-(dim - 1) if dim != 0 else -1 for dim in shape))
coords.append((self.coords[i, mask].astype(dt) - start) // step)
i += 1
elif isinstance(ind, Iterable):
old = self.coords[i][mask]
new = np.empty(shape=old.shape, dtype=old.dtype)
for j, item in enumerate(ind):
new[old == item] = j
coords.append(new)
shape.append(len(ind))
i += 1
elif ind is None:
coords.append(np.zeros(n))
shape.append(1)
for j in range(i, self.ndim):
coords.append(self.coords[j][mask])
shape.append(self.shape[j])
if coords:
coords = np.stack(coords, axis=0)
else:
if last_ellipsis:
coords = np.empty((0, np.sum(mask)), dtype=np.uint8)
else:
if np.sum(mask) != 0:
return self.data[mask][0]
else:
return _zero_of_dtype(self.dtype)[()]
shape = tuple(shape)
data = self.data[mask]
return COO(coords, data, shape=shape,
has_duplicates=self.has_duplicates,
sorted=self.sorted)
def __str__(self):
return "<COO: shape=%s, dtype=%s, nnz=%d, sorted=%s, duplicates=%s>" % (
self.shape, self.dtype, self.nnz, self.sorted,
self.has_duplicates)
__repr__ = __str__
@staticmethod
def _reduce(method, *args, **kwargs):
assert len(args) == 1
self = args[0]
if isinstance(self, scipy.sparse.spmatrix):
self = COO.from_scipy_sparse(self)
return self.reduce(method, **kwargs)
def reduce(self, method, axis=None, keepdims=False, **kwargs):
"""
Performs a reduction operation on this array.
Parameters
----------
method : numpy.ufunc
The method to use for performing the reduction.
axis : Union[int, Iterable[int]], optional
The axes along which to perform the reduction. Uses all axes by default.
keepdims : bool, optional
Whether or not to keep the dimensions of the original array.
kwargs : dict
Any extra arguments to pass to the reduction operation.
Returns
-------
COO
The result of the reduction operation.
Raises
------
ValueError
If reducing an all-zero axis would produce a nonzero result.
Notes
-----
This function internally calls :obj:`COO.sum_duplicates` to bring the array into
canonical form.
See Also
--------
numpy.ufunc.reduce : A similar Numpy method.
Examples
--------
You can use the :obj:`COO.reduce` method to apply a reduction operation to
any Numpy :code:`ufunc`.
>>> x = np.ones((5, 5), dtype=np.int)
>>> s = COO.from_numpy(x)
>>> s2 = s.reduce(np.add, axis=1)
>>> s2.todense() # doctest: +NORMALIZE_WHITESPACE
array([5, 5, 5, 5, 5])
You can also use the :code:`keepdims` argument to keep the dimensions after the
reduction.
>>> s3 = s.reduce(np.add, axis=1, keepdims=True)
>>> s3.shape
(5, 1)
You can also pass in any keyword argument that :obj:`numpy.ufunc.reduce` supports.
For example, :code:`dtype`. Note that :code:`out` isn't supported.
>>> s4 = s.reduce(np.add, axis=1, dtype=np.float16)
>>> s4.dtype
dtype('float16')
By default, this reduces the array down to one number, reducing along all axes.
>>> s.reduce(np.add)
25
"""
zero_reduce_result = method.reduce([_zero_of_dtype(self.dtype)], **kwargs)
if zero_reduce_result != _zero_of_dtype(np.dtype(zero_reduce_result)):
raise ValueError("Performing this reduction operation would produce "
"a dense result: %s" % str(method))
# Needed for more esoteric reductions like product.
self.sum_duplicates()
if axis is None:
axis = tuple(range(self.ndim))
if not isinstance(axis, tuple):
axis = (axis,)
if set(axis) == set(range(self.ndim)):
result = method.reduce(self.data, **kwargs)
if self.nnz != self.size:
result = method(result, _zero_of_dtype(self.dtype)[()], **kwargs)
else:
axis = tuple(axis)
neg_axis = tuple(ax for ax in range(self.ndim) if ax not in axis)
a = self.transpose(neg_axis + axis)
a = a.reshape((np.prod([self.shape[d] for d in neg_axis]),
np.prod([self.shape[d] for d in axis])))
a.sort_indices()
result, inv_idx, counts = _grouped_reduce(a.data, a.coords[0], method, **kwargs)
missing_counts = counts != a.shape[1]
result[missing_counts] = method(result[missing_counts],
_zero_of_dtype(self.dtype), **kwargs)
coords = a.coords[0:1, inv_idx]
a = COO(coords, result, shape=(a.shape[0],),
has_duplicates=False, sorted=True)
a = a.reshape([self.shape[d] for d in neg_axis])
result = a
if keepdims:
result = _keepdims(self, result, axis)
return result
def sum(self, axis=None, keepdims=False, dtype=None, out=None):
"""
Performs a sum operation along the given axes. Uses all axes by default.
Parameters
----------
axis : Union[int, Iterable[int]], optional
The axes along which to sum. Uses all axes by default.
keepdims : bool, optional
Whether or not to keep the dimensions of the original array.
dtype: numpy.dtype
The data type of the output array.
Returns
-------
COO
The reduced output sparse array.
See Also
--------
:obj:`numpy.sum` : Equivalent numpy function.
scipy.sparse.coo_matrix.sum : Equivalent Scipy function.
Notes
-----
* This function internally calls :obj:`COO.sum_duplicates` to bring the array into
canonical form.
* The :code:`out` parameter is provided just for compatibility with Numpy and
isn't actually supported.
Examples
--------
You can use :obj:`COO.sum` to sum an array across any dimension.
>>> x = np.ones((5, 5), dtype=np.int)
>>> s = COO.from_numpy(x)
>>> s2 = s.sum(axis=1)
>>> s2.todense() # doctest: +NORMALIZE_WHITESPACE
array([5, 5, 5, 5, 5])
You can also use the :code:`keepdims` argument to keep the dimensions after the
sum.
>>> s3 = s.sum(axis=1, keepdims=True)
>>> s3.shape
(5, 1)
You can pass in an output datatype, if needed.
>>> s4 = s.sum(axis=1, dtype=np.float16)
>>> s4.dtype
dtype('float16')
By default, this reduces the array down to one number, summing along all axes.
>>> s.sum()
25
"""
assert out is None
return self.reduce(np.add, axis=axis, keepdims=keepdims, dtype=dtype)
def max(self, axis=None, keepdims=False, out=None):
"""
Maximize along the given axes. Uses all axes by default.
Parameters
----------
axis : Union[int, Iterable[int]], optional
The axes along which to maximize. Uses all axes by default.
keepdims : bool, optional
Whether or not to keep the dimensions of the original array.
dtype: numpy.dtype
The data type of the output array.
Returns
-------
COO
The reduced output sparse array.
See Also
--------
:obj:`numpy.max` : Equivalent numpy function.
scipy.sparse.coo_matrix.max : Equivalent Scipy function.
Notes
-----
* This function internally calls :obj:`COO.sum_duplicates` to bring the array into
canonical form.
* The :code:`out` parameter is provided just for compatibility with Numpy and
isn't actually supported.
Examples
--------
You can use :obj:`COO.max` to maximize an array across any dimension.
>>> x = np.add.outer(np.arange(5), np.arange(5))
>>> x # doctest: +NORMALIZE_WHITESPACE
array([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
>>> s = COO.from_numpy(x)
>>> s2 = s.max(axis=1)
>>> s2.todense() # doctest: +NORMALIZE_WHITESPACE
array([4, 5, 6, 7, 8])
You can also use the :code:`keepdims` argument to keep the dimensions after the
maximization.
>>> s3 = s.max(axis=1, keepdims=True)
>>> s3.shape
(5, 1)
By default, this reduces the array down to one number, maximizing along all axes.
>>> s.max()
8
"""
assert out is None
return self.reduce(np.maximum, axis=axis, keepdims=keepdims)
def min(self, axis=None, keepdims=False, out=None):
"""
Minimize along the given axes. Uses all axes by default.
Parameters
----------
axis : Union[int, Iterable[int]], optional
The axes along which to minimize. Uses all axes by default.
keepdims : bool, optional
Whether or not to keep the dimensions of the original array.
dtype: numpy.dtype
The data type of the output array.
Returns
-------
COO
The reduced output sparse array.
See Also
--------
:obj:`numpy.min` : Equivalent numpy function.
scipy.sparse.coo_matrix.min : Equivalent Scipy function.
Notes
-----
* This function internally calls :obj:`COO.sum_duplicates` to bring the array into
canonical form.
* The :code:`out` parameter is provided just for compatibility with Numpy and
isn't actually supported.
Examples
--------
You can use :obj:`COO.min` to minimize an array across any dimension.
>>> x = np.add.outer(np.arange(5), np.arange(5))
>>> x # doctest: +NORMALIZE_WHITESPACE
array([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
>>> s = COO.from_numpy(x)
>>> s2 = s.min(axis=1)
>>> s2.todense() # doctest: +NORMALIZE_WHITESPACE
array([0, 1, 2, 3, 4])
You can also use the :code:`keepdims` argument to keep the dimensions after the
minimization.
>>> s3 = s.min(axis=1, keepdims=True)
>>> s3.shape
(5, 1)
By default, this reduces the array down to one number, minimizing along all axes.
>>> s.min()
0
"""
assert out is None
return self.reduce(np.minimum, axis=axis, keepdims=keepdims)
def prod(self, axis=None, keepdims=False, dtype=None, out=None):
"""
Performs a product operation along the given axes. Uses all axes by default.
Parameters
----------
axis : Union[int, Iterable[int]], optional
The axes along which to multiply. Uses all axes by default.
keepdims : bool, optional
Whether or not to keep the dimensions of the original array.
dtype: numpy.dtype
The data type of the output array.
Returns
-------
COO
The reduced output sparse array.
See Also
--------
:obj:`numpy.prod` : Equivalent numpy function.
Notes
-----
* This function internally calls :obj:`COO.sum_duplicates` to bring the array into
canonical form.
* The :code:`out` parameter is provided just for compatibility with Numpy and
isn't actually supported.
Examples
--------
You can use :obj:`COO.prod` to multiply an array across any dimension.
>>> x = np.add.outer(np.arange(5), np.arange(5))
>>> x # doctest: +NORMALIZE_WHITESPACE
array([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
>>> s = COO.from_numpy(x)
>>> s2 = s.prod(axis=1)
>>> s2.todense() # doctest: +NORMALIZE_WHITESPACE
array([ 0, 120, 720, 2520, 6720])
You can also use the :code:`keepdims` argument to keep the dimensions after the
reduction.
>>> s3 = s.prod(axis=1, keepdims=True)
>>> s3.shape
(5, 1)
You can pass in an output datatype, if needed.
>>> s4 = s.prod(axis=1, dtype=np.float16)
>>> s4.dtype
dtype('float16')
By default, this reduces the array down to one number, multiplying along all axes.
>>> s.prod()
0
"""
assert out is None
return self.reduce(np.multiply, axis=axis, keepdims=keepdims, dtype=dtype)
def transpose(self, axes=None):
"""
Returns a new array which has the order of the axes switched.
Parameters
----------
axes : Iterable[int], optional
The new order of the axes compared to the previous one. Reverses the axes
by default.
Returns
-------
COO
The new array with the axes in the desired order.
See Also
--------
:obj:`COO.T` : A quick property to reverse the order of the axes.
numpy.ndarray.transpose : Numpy equivalent function.
Examples
--------
We can change the order of the dimensions of any :obj:`COO` array with this
function.
>>> x = np.add.outer(np.arange(5), np.arange(5)[::-1])
>>> x # doctest: +NORMALIZE_WHITESPACE
array([[4, 3, 2, 1, 0],
[5, 4, 3, 2, 1],
[6, 5, 4, 3, 2],
[7, 6, 5, 4, 3],
[8, 7, 6, 5, 4]])
>>> s = COO.from_numpy(x)
>>> s.transpose((1, 0)).todense() # doctest: +NORMALIZE_WHITESPACE
array([[4, 5, 6, 7, 8],
[3, 4, 5, 6, 7],
[2, 3, 4, 5, 6],
[1, 2, 3, 4, 5],
[0, 1, 2, 3, 4]])
Note that by default, this reverses the order of the axes rather than switching
the last and second-to-last axes as required by some linear algebra operations.
>>> x = np.random.rand(2, 3, 4)
>>> s = COO.from_numpy(x)
>>> s.transpose().shape
(4, 3, 2)