-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
_base.py
1516 lines (1228 loc) · 48.8 KB
/
_base.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
"""Base class for sparse matrices"""
from warnings import warn
import numpy as np
from ._sputils import (asmatrix, check_reshape_kwargs, check_shape,
get_sum_dtype, isdense, isscalarlike,
matrix, validateaxis,)
from ._matrix import spmatrix
__all__ = ['isspmatrix', 'issparse', 'sparray',
'SparseWarning', 'SparseEfficiencyWarning']
class SparseWarning(Warning):
pass
class SparseFormatWarning(SparseWarning):
pass
class SparseEfficiencyWarning(SparseWarning):
pass
# The formats that we might potentially understand.
_formats = {'csc': [0, "Compressed Sparse Column"],
'csr': [1, "Compressed Sparse Row"],
'dok': [2, "Dictionary Of Keys"],
'lil': [3, "List of Lists"],
'dod': [4, "Dictionary of Dictionaries"],
'sss': [5, "Symmetric Sparse Skyline"],
'coo': [6, "COOrdinate"],
'lba': [7, "Linpack BAnded"],
'egd': [8, "Ellpack-itpack Generalized Diagonal"],
'dia': [9, "DIAgonal"],
'bsr': [10, "Block Sparse Row"],
'msr': [11, "Modified compressed Sparse Row"],
'bsc': [12, "Block Sparse Column"],
'msc': [13, "Modified compressed Sparse Column"],
'ssk': [14, "Symmetric SKyline"],
'nsk': [15, "Nonsymmetric SKyline"],
'jad': [16, "JAgged Diagonal"],
'uss': [17, "Unsymmetric Sparse Skyline"],
'vbr': [18, "Variable Block Row"],
'und': [19, "Undefined"]
}
# These univariate ufuncs preserve zeros.
_ufuncs_with_fixed_point_at_zero = frozenset([
np.sin, np.tan, np.arcsin, np.arctan, np.sinh, np.tanh, np.arcsinh,
np.arctanh, np.rint, np.sign, np.expm1, np.log1p, np.deg2rad,
np.rad2deg, np.floor, np.ceil, np.trunc, np.sqrt])
MAXPRINT = 50
class _spbase:
""" This class provides a base class for all sparse arrays. It
cannot be instantiated. Most of the work is provided by subclasses.
"""
__array_priority__ = 10.1
_format = 'und' # undefined
ndim = 2
@property
def _bsr_container(self):
from ._bsr import bsr_array
return bsr_array
@property
def _coo_container(self):
from ._coo import coo_array
return coo_array
@property
def _csc_container(self):
from ._csc import csc_array
return csc_array
@property
def _csr_container(self):
from ._csr import csr_array
return csr_array
@property
def _dia_container(self):
from ._dia import dia_array
return dia_array
@property
def _dok_container(self):
from ._dok import dok_array
return dok_array
@property
def _lil_container(self):
from ._lil import lil_array
return lil_array
_is_array = True
def __init__(self, maxprint=MAXPRINT):
self._shape = None
if self.__class__.__name__ == '_spbase':
raise ValueError("This class is not intended"
" to be instantiated directly.")
self.maxprint = maxprint
# Use this in 1.13.0 and later:
#
# @property
# def shape(self):
# return self._shape
def reshape(self, *args, **kwargs):
"""reshape(self, shape, order='C', copy=False)
Gives a new shape to a sparse array without changing its data.
Parameters
----------
shape : length-2 tuple of ints
The new shape should be compatible with the original shape.
order : {'C', 'F'}, optional
Read the elements using this index order. 'C' means to read and
write the elements using C-like index order; e.g., read entire first
row, then second row, etc. 'F' means to read and write the elements
using Fortran-like index order; e.g., read entire first column, then
second column, etc.
copy : bool, optional
Indicates whether or not attributes of self should be copied
whenever possible. The degree to which attributes are copied varies
depending on the type of sparse array being used.
Returns
-------
reshaped : sparse array
A sparse array with the given `shape`, not necessarily of the same
format as the current object.
See Also
--------
numpy.reshape : NumPy's implementation of 'reshape' for ndarrays
"""
# If the shape already matches, don't bother doing an actual reshape
# Otherwise, the default is to convert to COO and use its reshape
shape = check_shape(args, self.shape)
order, copy = check_reshape_kwargs(kwargs)
if shape == self.shape:
if copy:
return self.copy()
else:
return self
return self.tocoo(copy=copy).reshape(shape, order=order, copy=False)
def resize(self, shape):
"""Resize the array in-place to dimensions given by ``shape``
Any elements that lie within the new shape will remain at the same
indices, while non-zero elements lying outside the new shape are
removed.
Parameters
----------
shape : (int, int)
number of rows and columns in the new array
Notes
-----
The semantics are not identical to `numpy.ndarray.resize` or
`numpy.resize`. Here, the same data will be maintained at each index
before and after reshape, if that index is within the new bounds. In
numpy, resizing maintains contiguity of the array, moving elements
around in the logical array but not within a flattened representation.
We give no guarantees about whether the underlying data attributes
(arrays, etc.) will be modified in place or replaced with new objects.
"""
# As an inplace operation, this requires implementation in each format.
raise NotImplementedError(
f'{type(self).__name__}.resize is not implemented')
def astype(self, dtype, casting='unsafe', copy=True):
"""Cast the array elements to a specified type.
Parameters
----------
dtype : string or numpy dtype
Typecode or data-type to which to cast the data.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur.
Defaults to 'unsafe' for backwards compatibility.
'no' means the data types should not be cast at all.
'equiv' means only byte-order changes are allowed.
'safe' means only casts which can preserve values are allowed.
'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
'unsafe' means any data conversions may be done.
copy : bool, optional
If `copy` is `False`, the result might share some memory with this
array. If `copy` is `True`, it is guaranteed that the result and
this array do not share any memory.
"""
dtype = np.dtype(dtype)
if self.dtype != dtype:
return self.tocsr().astype(
dtype, casting=casting, copy=copy).asformat(self.format)
elif copy:
return self.copy()
else:
return self
@classmethod
def _ascontainer(cls, X, **kwargs):
if cls._is_array:
return np.asarray(X, **kwargs)
else:
return asmatrix(X, **kwargs)
@classmethod
def _container(cls, X, **kwargs):
if cls._is_array:
return np.array(X, **kwargs)
else:
return matrix(X, **kwargs)
def _asfptype(self):
"""Upcast array to a floating point format (if necessary)"""
fp_types = ['f', 'd', 'F', 'D']
if self.dtype.char in fp_types:
return self
else:
for fp_type in fp_types:
if self.dtype <= np.dtype(fp_type):
return self.astype(fp_type)
raise TypeError('cannot upcast [%s] to a floating '
'point format' % self.dtype.name)
def __iter__(self):
for r in range(self.shape[0]):
yield self[r, :]
def _getmaxprint(self):
"""Maximum number of elements to display when printed."""
return self.maxprint
def count_nonzero(self):
"""Number of non-zero entries, equivalent to
np.count_nonzero(a.toarray())
Unlike the nnz property, which return the number of stored
entries (the length of the data attribute), this method counts the
actual number of non-zero entries in data.
"""
raise NotImplementedError("count_nonzero not implemented for %s." %
self.__class__.__name__)
def _getnnz(self, axis=None):
"""Number of stored values, including explicit zeros.
Parameters
----------
axis : None, 0, or 1
Select between the number of values across the whole array, in
each column, or in each row.
See also
--------
count_nonzero : Number of non-zero entries
"""
raise NotImplementedError("getnnz not implemented for %s." %
self.__class__.__name__)
@property
def nnz(self):
"""Number of stored values, including explicit zeros.
See also
--------
count_nonzero : Number of non-zero entries
"""
return self._getnnz()
@property
def format(self):
return self._format
def __repr__(self):
_, format_name = _formats[self.format]
sparse_cls = 'array' if self._is_array else 'matrix'
return f"<%dx%d sparse {sparse_cls} of type '%s'\n" \
"\twith %d stored elements in %s format>" % \
(self.shape + (self.dtype.type, self.nnz, format_name))
def __str__(self):
maxprint = self._getmaxprint()
A = self.tocoo()
# helper function, outputs "(i,j) v"
def tostr(row, col, data):
triples = zip(list(zip(row, col)), data)
return '\n'.join([(' %s\t%s' % t) for t in triples])
if self.nnz > maxprint:
half = maxprint // 2
out = tostr(A.row[:half], A.col[:half], A.data[:half])
out += "\n :\t:\n"
half = maxprint - maxprint//2
out += tostr(A.row[-half:], A.col[-half:], A.data[-half:])
else:
out = tostr(A.row, A.col, A.data)
return out
def __bool__(self): # Simple -- other ideas?
if self.shape == (1, 1):
return self.nnz != 0
else:
raise ValueError("The truth value of an array with more than one "
"element is ambiguous. Use a.any() or a.all().")
__nonzero__ = __bool__
# What should len(sparse) return? For consistency with dense matrices,
# perhaps it should be the number of rows? But for some uses the number of
# non-zeros is more important. For now, raise an exception!
def __len__(self):
raise TypeError("sparse array length is ambiguous; use getnnz()"
" or shape[0]")
def asformat(self, format, copy=False):
"""Return this array in the passed format.
Parameters
----------
format : {str, None}
The desired sparse format ("csr", "csc", "lil", "dok", "array", ...)
or None for no conversion.
copy : bool, optional
If True, the result is guaranteed to not share data with self.
Returns
-------
A : This array in the passed format.
"""
if format is None or format == self.format:
if copy:
return self.copy()
else:
return self
else:
try:
convert_method = getattr(self, 'to' + format)
except AttributeError as e:
raise ValueError(f'Format {format} is unknown.') from e
# Forward the copy kwarg, if it's accepted.
try:
return convert_method(copy=copy)
except TypeError:
return convert_method()
###################################################################
# NOTE: All arithmetic operations use csr_matrix by default.
# Therefore a new sparse array format just needs to define a
# .tocsr() method to provide arithmetic support. Any of these
# methods can be overridden for efficiency.
####################################################################
def multiply(self, other):
"""Point-wise multiplication by another array
"""
return self.tocsr().multiply(other)
def maximum(self, other):
"""Element-wise maximum between this and another array."""
return self.tocsr().maximum(other)
def minimum(self, other):
"""Element-wise minimum between this and another array."""
return self.tocsr().minimum(other)
def dot(self, other):
"""Ordinary dot product
Examples
--------
>>> import numpy as np
>>> from scipy.sparse import csr_array
>>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
>>> v = np.array([1, 0, -1])
>>> A.dot(v)
array([ 1, -3, -1], dtype=int64)
"""
if np.isscalar(other):
return self * other
else:
return self @ other
def power(self, n, dtype=None):
"""Element-wise power."""
return self.tocsr().power(n, dtype=dtype)
def __eq__(self, other):
return self.tocsr().__eq__(other)
def __ne__(self, other):
return self.tocsr().__ne__(other)
def __lt__(self, other):
return self.tocsr().__lt__(other)
def __gt__(self, other):
return self.tocsr().__gt__(other)
def __le__(self, other):
return self.tocsr().__le__(other)
def __ge__(self, other):
return self.tocsr().__ge__(other)
def __abs__(self):
return abs(self.tocsr())
def __round__(self, ndigits=0):
return round(self.tocsr(), ndigits=ndigits)
def _add_sparse(self, other):
return self.tocsr()._add_sparse(other)
def _add_dense(self, other):
return self.tocoo()._add_dense(other)
def _sub_sparse(self, other):
return self.tocsr()._sub_sparse(other)
def _sub_dense(self, other):
return self.todense() - other
def _rsub_dense(self, other):
# note: this can't be replaced by other + (-self) for unsigned types
return other - self.todense()
def __add__(self, other): # self + other
if isscalarlike(other):
if other == 0:
return self.copy()
# Now we would add this scalar to every element.
raise NotImplementedError('adding a nonzero scalar to a '
'sparse array is not supported')
elif issparse(other):
if other.shape != self.shape:
raise ValueError("inconsistent shapes")
return self._add_sparse(other)
elif isdense(other):
other = np.broadcast_to(other, self.shape)
return self._add_dense(other)
else:
return NotImplemented
def __radd__(self,other): # other + self
return self.__add__(other)
def __sub__(self, other): # self - other
if isscalarlike(other):
if other == 0:
return self.copy()
raise NotImplementedError('subtracting a nonzero scalar from a '
'sparse array is not supported')
elif issparse(other):
if other.shape != self.shape:
raise ValueError("inconsistent shapes")
return self._sub_sparse(other)
elif isdense(other):
other = np.broadcast_to(other, self.shape)
return self._sub_dense(other)
else:
return NotImplemented
def __rsub__(self,other): # other - self
if isscalarlike(other):
if other == 0:
return -self.copy()
raise NotImplementedError('subtracting a sparse array from a '
'nonzero scalar is not supported')
elif isdense(other):
other = np.broadcast_to(other, self.shape)
return self._rsub_dense(other)
else:
return NotImplemented
def _mul_dispatch(self, other):
"""`np.matrix`-compatible mul, i.e. `dot` or `NotImplemented`
interpret other and call one of the following
self._mul_scalar()
self._mul_vector()
self._mul_multivector()
self._mul_sparse_matrix()
"""
# This method has to be different from `__matmul__` because it is also
# called by sparse matrix classes.
M, N = self.shape
if other.__class__ is np.ndarray:
# Fast path for the most common case
if other.shape == (N,):
return self._mul_vector(other)
elif other.shape == (N, 1):
return self._mul_vector(other.ravel()).reshape(M, 1)
elif other.ndim == 2 and other.shape[0] == N:
return self._mul_multivector(other)
if isscalarlike(other):
# scalar value
return self._mul_scalar(other)
if issparse(other):
if self.shape[1] != other.shape[0]:
raise ValueError('dimension mismatch')
return self._mul_sparse_matrix(other)
# If it's a list or whatever, treat it like an array
other_a = np.asanyarray(other)
if other_a.ndim == 0 and other_a.dtype == np.object_:
# Not interpretable as an array; return NotImplemented so that
# other's __rmul__ can kick in if that's implemented.
return NotImplemented
try:
other.shape
except AttributeError:
other = other_a
if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1:
# dense row or column vector
if other.shape != (N,) and other.shape != (N, 1):
raise ValueError('dimension mismatch')
result = self._mul_vector(np.ravel(other))
if isinstance(other, np.matrix):
result = self._ascontainer(result)
if other.ndim == 2 and other.shape[1] == 1:
# If 'other' was an (nx1) column vector, reshape the result
result = result.reshape(-1, 1)
return result
elif other.ndim == 2:
##
# dense 2D array or matrix ("multivector")
if other.shape[0] != self.shape[1]:
raise ValueError('dimension mismatch')
result = self._mul_multivector(np.asarray(other))
if isinstance(other, np.matrix):
result = self._ascontainer(result)
return result
else:
raise ValueError('could not interpret dimensions')
def __mul__(self, *args, **kwargs):
return self.multiply(*args, **kwargs)
# by default, use CSR for __mul__ handlers
def _mul_scalar(self, other):
return self.tocsr()._mul_scalar(other)
def _mul_vector(self, other):
return self.tocsr()._mul_vector(other)
def _mul_multivector(self, other):
return self.tocsr()._mul_multivector(other)
def _mul_sparse_matrix(self, other):
return self.tocsr()._mul_sparse_matrix(other)
def _rmul_dispatch(self, other):
if isscalarlike(other):
return self._mul_scalar(other)
else:
# Don't use asarray unless we have to
try:
tr = other.transpose()
except AttributeError:
tr = np.asarray(other).transpose()
ret = self.transpose()._mul_dispatch(tr)
if ret is NotImplemented:
return NotImplemented
return ret.transpose()
def __rmul__(self, *args, **kwargs): # other * self
return self.multiply(*args, **kwargs)
#######################
# matmul (@) operator #
#######################
def __matmul__(self, other):
if isscalarlike(other):
raise ValueError("Scalar operands are not allowed, "
"use '*' instead")
return self._mul_dispatch(other)
def __rmatmul__(self, other):
if isscalarlike(other):
raise ValueError("Scalar operands are not allowed, "
"use '*' instead")
return self._rmul_dispatch(other)
####################
# Other Arithmetic #
####################
def _divide(self, other, true_divide=False, rdivide=False):
if isscalarlike(other):
if rdivide:
if true_divide:
return np.true_divide(other, self.todense())
else:
return np.divide(other, self.todense())
if true_divide and np.can_cast(self.dtype, np.float_):
return self.astype(np.float_)._mul_scalar(1./other)
else:
r = self._mul_scalar(1./other)
scalar_dtype = np.asarray(other).dtype
if (np.issubdtype(self.dtype, np.integer) and
np.issubdtype(scalar_dtype, np.integer)):
return r.astype(self.dtype)
else:
return r
elif isdense(other):
if not rdivide:
if true_divide:
recip = np.true_divide(1., other)
else:
recip = np.divide(1., other)
return self.multiply(recip)
else:
if true_divide:
return np.true_divide(other, self.todense())
else:
return np.divide(other, self.todense())
elif issparse(other):
if rdivide:
return other._divide(self, true_divide, rdivide=False)
self_csr = self.tocsr()
if true_divide and np.can_cast(self.dtype, np.float_):
return self_csr.astype(np.float_)._divide_sparse(other)
else:
return self_csr._divide_sparse(other)
else:
return NotImplemented
def __truediv__(self, other):
return self._divide(other, true_divide=True)
def __div__(self, other):
# Always do true division
return self._divide(other, true_divide=True)
def __rtruediv__(self, other):
# Implementing this as the inverse would be too magical -- bail out
return NotImplemented
def __rdiv__(self, other):
# Implementing this as the inverse would be too magical -- bail out
return NotImplemented
def __neg__(self):
return -self.tocsr()
def __iadd__(self, other):
return NotImplemented
def __isub__(self, other):
return NotImplemented
def __imul__(self, other):
return NotImplemented
def __idiv__(self, other):
return self.__itruediv__(other)
def __itruediv__(self, other):
return NotImplemented
def __pow__(self, *args, **kwargs):
return self.power(*args, **kwargs)
@property
def A(self) -> np.ndarray:
if self._is_array:
warn(np.VisibleDeprecationWarning(
"`.A` is deprecated and will be removed in v1.13.0. "
"Use `.toarray()` instead."
))
return self.toarray()
@property
def T(self):
return self.transpose()
@property
def H(self):
if self._is_array:
warn(np.VisibleDeprecationWarning(
"`.H` is deprecated and will be removed in v1.13.0. "
"Please use `.T.conjugate()` instead."
))
return self.T.conjugate()
@property
def real(self):
return self._real()
@property
def imag(self):
return self._imag()
@property
def size(self):
return self._getnnz()
def transpose(self, axes=None, copy=False):
"""
Reverses the dimensions of the sparse array.
Parameters
----------
axes : None, optional
This argument is in the signature *solely* for NumPy
compatibility reasons. Do not pass in anything except
for the default value.
copy : bool, optional
Indicates whether or not attributes of `self` should be
copied whenever possible. The degree to which attributes
are copied varies depending on the type of sparse array
being used.
Returns
-------
p : `self` with the dimensions reversed.
See Also
--------
numpy.transpose : NumPy's implementation of 'transpose' for ndarrays
"""
return self.tocsr(copy=copy).transpose(axes=axes, copy=False)
def conjugate(self, copy=True):
"""Element-wise complex conjugation.
If the array is of non-complex data type and `copy` is False,
this method does nothing and the data is not copied.
Parameters
----------
copy : bool, optional
If True, the result is guaranteed to not share data with self.
Returns
-------
A : The element-wise complex conjugate.
"""
if np.issubdtype(self.dtype, np.complexfloating):
return self.tocsr(copy=copy).conjugate(copy=False)
elif copy:
return self.copy()
else:
return self
def conj(self, copy=True):
return self.conjugate(copy=copy)
conj.__doc__ = conjugate.__doc__
def _real(self):
return self.tocsr()._real()
def _imag(self):
return self.tocsr()._imag()
def nonzero(self):
"""nonzero indices
Returns a tuple of arrays (row,col) containing the indices
of the non-zero elements of the array.
Examples
--------
>>> from scipy.sparse import csr_array
>>> A = csr_array([[1,2,0],[0,0,3],[4,0,5]])
>>> A.nonzero()
(array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2]))
"""
# convert to COOrdinate format
A = self.tocoo()
nz_mask = A.data != 0
return (A.row[nz_mask], A.col[nz_mask])
def _getcol(self, j):
"""Returns a copy of column j of the array, as an (m x 1) sparse
array (column vector).
"""
# Subclasses should override this method for efficiency.
# Post-multiply by a (n x 1) column vector 'a' containing all zeros
# except for a_j = 1
n = self.shape[1]
if j < 0:
j += n
if j < 0 or j >= n:
raise IndexError("index out of bounds")
col_selector = self._csc_container(([1], [[j], [0]]),
shape=(n, 1), dtype=self.dtype)
return self @ col_selector
def _getrow(self, i):
"""Returns a copy of row i of the array, as a (1 x n) sparse
array (row vector).
"""
# Subclasses should override this method for efficiency.
# Pre-multiply by a (1 x m) row vector 'a' containing all zeros
# except for a_i = 1
m = self.shape[0]
if i < 0:
i += m
if i < 0 or i >= m:
raise IndexError("index out of bounds")
row_selector = self._csr_container(([1], [[0], [i]]),
shape=(1, m), dtype=self.dtype)
return row_selector @ self
# The following dunder methods cannot be implemented.
#
# def __array__(self):
# # Sparse matrices rely on NumPy wrapping them in object arrays under
# # the hood to make unary ufuncs work on them. So we cannot raise
# # TypeError here - which would be handy to not give users object
# # arrays they probably don't want (they're looking for `.toarray()`).
# #
# # Conversion with `toarray()` would also break things because of the
# # behavior discussed above, plus we want to avoid densification by
# # accident because that can too easily blow up memory.
#
# def __array_ufunc__(self):
# # We cannot implement __array_ufunc__ due to mismatching semantics.
# # See gh-7707 and gh-7349 for details.
#
# def __array_function__(self):
# # We cannot implement __array_function__ due to mismatching semantics.
# # See gh-10362 for details.
def todense(self, order=None, out=None):
"""
Return a dense matrix representation of this sparse array.
Parameters
----------
order : {'C', 'F'}, optional
Whether to store multi-dimensional data in C (row-major)
or Fortran (column-major) order in memory. The default
is 'None', which provides no ordering guarantees.
Cannot be specified in conjunction with the `out`
argument.
out : ndarray, 2-D, optional
If specified, uses this array (or `numpy.matrix`) as the
output buffer instead of allocating a new array to
return. The provided array must have the same shape and
dtype as the sparse array on which you are calling the
method.
Returns
-------
arr : numpy.matrix, 2-D
A NumPy matrix object with the same shape and containing
the same data represented by the sparse array, with the
requested memory order. If `out` was passed and was an
array (rather than a `numpy.matrix`), it will be filled
with the appropriate values and returned wrapped in a
`numpy.matrix` object that shares the same memory.
"""
return self._ascontainer(self.toarray(order=order, out=out))
def toarray(self, order=None, out=None):
"""
Return a dense ndarray representation of this sparse array.
Parameters
----------
order : {'C', 'F'}, optional
Whether to store multidimensional data in C (row-major)
or Fortran (column-major) order in memory. The default
is 'None', which provides no ordering guarantees.
Cannot be specified in conjunction with the `out`
argument.
out : ndarray, 2-D, optional
If specified, uses this array as the output buffer
instead of allocating a new array to return. The provided
array must have the same shape and dtype as the sparse
array on which you are calling the method. For most
sparse types, `out` is required to be memory contiguous
(either C or Fortran ordered).
Returns
-------
arr : ndarray, 2-D
An array with the same shape and containing the same
data represented by the sparse array, with the requested
memory order. If `out` was passed, the same object is
returned after being modified in-place to contain the
appropriate values.
"""
return self.tocoo(copy=False).toarray(order=order, out=out)
# Any sparse array format deriving from _spbase must define one of
# tocsr or tocoo. The other conversion methods may be implemented for
# efficiency, but are not required.
def tocsr(self, copy=False):
"""Convert this array to Compressed Sparse Row format.
With copy=False, the data/indices may be shared between this array and
the resultant csr_array.
"""
return self.tocoo(copy=copy).tocsr(copy=False)
def todok(self, copy=False):
"""Convert this array to Dictionary Of Keys format.
With copy=False, the data/indices may be shared between this array and
the resultant dok_array.
"""
return self.tocoo(copy=copy).todok(copy=False)
def tocoo(self, copy=False):
"""Convert this array to COOrdinate format.
With copy=False, the data/indices may be shared between this array and
the resultant coo_array.
"""
return self.tocsr(copy=False).tocoo(copy=copy)
def tolil(self, copy=False):
"""Convert this array to List of Lists format.
With copy=False, the data/indices may be shared between this array and
the resultant lil_array.
"""
return self.tocsr(copy=False).tolil(copy=copy)
def todia(self, copy=False):
"""Convert this array to sparse DIAgonal format.
With copy=False, the data/indices may be shared between this array and
the resultant dia_array.
"""
return self.tocoo(copy=copy).todia(copy=False)
def tobsr(self, blocksize=None, copy=False):
"""Convert this array to Block Sparse Row format.
With copy=False, the data/indices may be shared between this array and
the resultant bsr_array.
When blocksize=(R, C) is provided, it will be used for construction of
the bsr_array.
"""
return self.tocsr(copy=False).tobsr(blocksize=blocksize, copy=copy)
def tocsc(self, copy=False):