forked from scipy/scipy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
test_base.py
4990 lines (4122 loc) · 178 KB
/
test_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
#
# Authors: Travis Oliphant, Ed Schofield, Robert Cimrman, Nathan Bell, and others
""" Test functions for sparse matrices. Each class in the "Matrix class
based tests" section become subclasses of the classes in the "Generic
tests" section. This is done by the functions in the "Tailored base
class for generic tests" section.
"""
import contextlib
import functools
import operator
import platform
import itertools
import sys
from scipy._lib import _pep440
import numpy as np
from numpy import (arange, zeros, array, dot, asarray,
vstack, ndarray, transpose, diag, kron, inf, conjugate,
int8, ComplexWarning)
import random
from numpy.testing import (assert_equal, assert_array_equal,
assert_array_almost_equal, assert_almost_equal, assert_,
assert_allclose,suppress_warnings)
from pytest import raises as assert_raises
import scipy.linalg
import scipy.sparse as sparse
from scipy.sparse import (csc_matrix, csr_matrix, dok_matrix,
coo_matrix, lil_matrix, dia_matrix, bsr_matrix,
eye, isspmatrix, SparseEfficiencyWarning)
from scipy.sparse._sputils import (supported_dtypes, isscalarlike,
get_index_dtype, asmatrix, matrix)
from scipy.sparse.linalg import splu, expm, inv
from scipy._lib.decorator import decorator
import pytest
IS_COLAB = ('google.colab' in sys.modules)
def assert_in(member, collection, msg=None):
assert_(member in collection, msg=msg if msg is not None else "%r not found in %r" % (member, collection))
def assert_array_equal_dtype(x, y, **kwargs):
assert_(x.dtype == y.dtype)
assert_array_equal(x, y, **kwargs)
NON_ARRAY_BACKED_FORMATS = frozenset(['dok'])
def sparse_may_share_memory(A, B):
# Checks if A and B have any numpy array sharing memory.
def _underlying_arrays(x):
# Given any object (e.g. a sparse array), returns all numpy arrays
# stored in any attribute.
arrays = []
for a in x.__dict__.values():
if isinstance(a, (np.ndarray, np.generic)):
arrays.append(a)
return arrays
for a in _underlying_arrays(A):
for b in _underlying_arrays(B):
if np.may_share_memory(a, b):
return True
return False
sup_complex = suppress_warnings()
sup_complex.filter(ComplexWarning)
def with_64bit_maxval_limit(maxval_limit=None, random=False, fixed_dtype=None,
downcast_maxval=None, assert_32bit=False):
"""
Monkeypatch the maxval threshold at which scipy.sparse switches to
64-bit index arrays, or make it (pseudo-)random.
"""
if maxval_limit is None:
maxval_limit = 10
if assert_32bit:
def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
tp = get_index_dtype(arrays, maxval, check_contents)
assert_equal(np.iinfo(tp).max, np.iinfo(np.int32).max)
assert_(tp == np.int32 or tp == np.intc)
return tp
elif fixed_dtype is not None:
def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
return fixed_dtype
elif random:
counter = np.random.RandomState(seed=1234)
def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
return (np.int32, np.int64)[counter.randint(2)]
else:
def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
dtype = np.int32
if maxval is not None:
if maxval > maxval_limit:
dtype = np.int64
for arr in arrays:
arr = np.asarray(arr)
if arr.dtype > np.int32:
if check_contents:
if arr.size == 0:
# a bigger type not needed
continue
elif np.issubdtype(arr.dtype, np.integer):
maxval = arr.max()
minval = arr.min()
if minval >= -maxval_limit and maxval <= maxval_limit:
# a bigger type not needed
continue
dtype = np.int64
return dtype
if downcast_maxval is not None:
def new_downcast_intp_index(arr):
if arr.max() > downcast_maxval:
raise AssertionError("downcast limited")
return arr.astype(np.intp)
@decorator
def deco(func, *a, **kw):
backup = []
modules = [scipy.sparse._bsr, scipy.sparse._coo, scipy.sparse._csc,
scipy.sparse._csr, scipy.sparse._dia, scipy.sparse._dok,
scipy.sparse._lil, scipy.sparse._sputils,
scipy.sparse._compressed, scipy.sparse._construct]
try:
for mod in modules:
backup.append((mod, 'get_index_dtype',
getattr(mod, 'get_index_dtype', None)))
setattr(mod, 'get_index_dtype', new_get_index_dtype)
if downcast_maxval is not None:
backup.append((mod, 'downcast_intp_index',
getattr(mod, 'downcast_intp_index', None)))
setattr(mod, 'downcast_intp_index', new_downcast_intp_index)
return func(*a, **kw)
finally:
for mod, name, oldfunc in backup:
if oldfunc is not None:
setattr(mod, name, oldfunc)
return deco
def toarray(a):
if isinstance(a, np.ndarray) or isscalarlike(a):
return a
return a.toarray()
class BinopTester:
# Custom type to test binary operations on sparse matrices.
def __add__(self, mat):
return "matrix on the right"
def __mul__(self, mat):
return "matrix on the right"
def __sub__(self, mat):
return "matrix on the right"
def __radd__(self, mat):
return "matrix on the left"
def __rmul__(self, mat):
return "matrix on the left"
def __rsub__(self, mat):
return "matrix on the left"
def __matmul__(self, mat):
return "matrix on the right"
def __rmatmul__(self, mat):
return "matrix on the left"
class BinopTester_with_shape:
# Custom type to test binary operations on sparse matrices
# with object which has shape attribute.
def __init__(self,shape):
self._shape = shape
def shape(self):
return self._shape
def ndim(self):
return len(self._shape)
def __add__(self, mat):
return "matrix on the right"
def __mul__(self, mat):
return "matrix on the right"
def __sub__(self, mat):
return "matrix on the right"
def __radd__(self, mat):
return "matrix on the left"
def __rmul__(self, mat):
return "matrix on the left"
def __rsub__(self, mat):
return "matrix on the left"
def __matmul__(self, mat):
return "matrix on the right"
def __rmatmul__(self, mat):
return "matrix on the left"
#------------------------------------------------------------------------------
# Generic tests
#------------------------------------------------------------------------------
# TODO test prune
# TODO test has_sorted_indices
class _TestCommon:
"""test common functionality shared by all sparse formats"""
math_dtypes = supported_dtypes
@classmethod
def init_class(cls):
# Canonical data.
cls.dat = array([[1, 0, 0, 2], [3, 0, 1, 0], [0, 2, 0, 0]], 'd')
cls.datsp = cls.spmatrix(cls.dat)
# Some sparse and dense matrices with data for every supported
# dtype.
# This set union is a workaround for numpy#6295, which means that
# two np.int64 dtypes don't hash to the same value.
cls.checked_dtypes = set(supported_dtypes).union(cls.math_dtypes)
cls.dat_dtypes = {}
cls.datsp_dtypes = {}
for dtype in cls.checked_dtypes:
cls.dat_dtypes[dtype] = cls.dat.astype(dtype)
cls.datsp_dtypes[dtype] = cls.spmatrix(cls.dat.astype(dtype))
# Check that the original data is equivalent to the
# corresponding dat_dtypes & datsp_dtypes.
assert_equal(cls.dat, cls.dat_dtypes[np.float64])
assert_equal(cls.datsp.toarray(),
cls.datsp_dtypes[np.float64].toarray())
def test_bool(self):
def check(dtype):
datsp = self.datsp_dtypes[dtype]
assert_raises(ValueError, bool, datsp)
assert_(self.spmatrix([1]))
assert_(not self.spmatrix([0]))
if isinstance(self, TestDOK):
pytest.skip("Cannot create a rank <= 2 DOK matrix.")
for dtype in self.checked_dtypes:
check(dtype)
def test_bool_rollover(self):
# bool's underlying dtype is 1 byte, check that it does not
# rollover True -> False at 256.
dat = array([[True, False]])
datsp = self.spmatrix(dat)
for _ in range(10):
datsp = datsp + datsp
dat = dat + dat
assert_array_equal(dat, datsp.toarray())
def test_eq(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datbsr = bsr_matrix(dat)
datcsr = csr_matrix(dat)
datcsc = csc_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat == dat2, (datsp == datsp2).toarray())
# mix sparse types
assert_array_equal_dtype(dat == dat2, (datbsr == datsp2).toarray())
assert_array_equal_dtype(dat == dat2, (datcsr == datsp2).toarray())
assert_array_equal_dtype(dat == dat2, (datcsc == datsp2).toarray())
assert_array_equal_dtype(dat == dat2, (datlil == datsp2).toarray())
# sparse/dense
assert_array_equal_dtype(dat == datsp2, datsp2 == dat)
# sparse/scalar
assert_array_equal_dtype(dat == 0, (datsp == 0).toarray())
assert_array_equal_dtype(dat == 1, (datsp == 1).toarray())
assert_array_equal_dtype(dat == np.nan,
(datsp == np.nan).toarray())
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_ne(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datbsr = bsr_matrix(dat)
datcsc = csc_matrix(dat)
datcsr = csr_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat != dat2, (datsp != datsp2).toarray())
# mix sparse types
assert_array_equal_dtype(dat != dat2, (datbsr != datsp2).toarray())
assert_array_equal_dtype(dat != dat2, (datcsc != datsp2).toarray())
assert_array_equal_dtype(dat != dat2, (datcsr != datsp2).toarray())
assert_array_equal_dtype(dat != dat2, (datlil != datsp2).toarray())
# sparse/dense
assert_array_equal_dtype(dat != datsp2, datsp2 != dat)
# sparse/scalar
assert_array_equal_dtype(dat != 0, (datsp != 0).toarray())
assert_array_equal_dtype(dat != 1, (datsp != 1).toarray())
assert_array_equal_dtype(0 != dat, (0 != datsp).toarray())
assert_array_equal_dtype(1 != dat, (1 != datsp).toarray())
assert_array_equal_dtype(dat != np.nan,
(datsp != np.nan).toarray())
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_lt(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
# data
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datcomplex = dat.astype(complex)
datcomplex[:,0] = 1 + 1j
datspcomplex = self.spmatrix(datcomplex)
datbsr = bsr_matrix(dat)
datcsc = csc_matrix(dat)
datcsr = csr_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat < dat2, (datsp < datsp2).toarray())
assert_array_equal_dtype(datcomplex < dat2,
(datspcomplex < datsp2).toarray())
# mix sparse types
assert_array_equal_dtype(dat < dat2, (datbsr < datsp2).toarray())
assert_array_equal_dtype(dat < dat2, (datcsc < datsp2).toarray())
assert_array_equal_dtype(dat < dat2, (datcsr < datsp2).toarray())
assert_array_equal_dtype(dat < dat2, (datlil < datsp2).toarray())
assert_array_equal_dtype(dat2 < dat, (datsp2 < datbsr).toarray())
assert_array_equal_dtype(dat2 < dat, (datsp2 < datcsc).toarray())
assert_array_equal_dtype(dat2 < dat, (datsp2 < datcsr).toarray())
assert_array_equal_dtype(dat2 < dat, (datsp2 < datlil).toarray())
# sparse/dense
assert_array_equal_dtype(dat < dat2, datsp < dat2)
assert_array_equal_dtype(datcomplex < dat2, datspcomplex < dat2)
# sparse/scalar
assert_array_equal_dtype((datsp < 2).toarray(), dat < 2)
assert_array_equal_dtype((datsp < 1).toarray(), dat < 1)
assert_array_equal_dtype((datsp < 0).toarray(), dat < 0)
assert_array_equal_dtype((datsp < -1).toarray(), dat < -1)
assert_array_equal_dtype((datsp < -2).toarray(), dat < -2)
with np.errstate(invalid='ignore'):
assert_array_equal_dtype((datsp < np.nan).toarray(),
dat < np.nan)
assert_array_equal_dtype((2 < datsp).toarray(), 2 < dat)
assert_array_equal_dtype((1 < datsp).toarray(), 1 < dat)
assert_array_equal_dtype((0 < datsp).toarray(), 0 < dat)
assert_array_equal_dtype((-1 < datsp).toarray(), -1 < dat)
assert_array_equal_dtype((-2 < datsp).toarray(), -2 < dat)
# data
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
# dense rhs
assert_array_equal_dtype(dat < datsp2, datsp < dat2)
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_gt(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datcomplex = dat.astype(complex)
datcomplex[:,0] = 1 + 1j
datspcomplex = self.spmatrix(datcomplex)
datbsr = bsr_matrix(dat)
datcsc = csc_matrix(dat)
datcsr = csr_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat > dat2, (datsp > datsp2).toarray())
assert_array_equal_dtype(datcomplex > dat2,
(datspcomplex > datsp2).toarray())
# mix sparse types
assert_array_equal_dtype(dat > dat2, (datbsr > datsp2).toarray())
assert_array_equal_dtype(dat > dat2, (datcsc > datsp2).toarray())
assert_array_equal_dtype(dat > dat2, (datcsr > datsp2).toarray())
assert_array_equal_dtype(dat > dat2, (datlil > datsp2).toarray())
assert_array_equal_dtype(dat2 > dat, (datsp2 > datbsr).toarray())
assert_array_equal_dtype(dat2 > dat, (datsp2 > datcsc).toarray())
assert_array_equal_dtype(dat2 > dat, (datsp2 > datcsr).toarray())
assert_array_equal_dtype(dat2 > dat, (datsp2 > datlil).toarray())
# sparse/dense
assert_array_equal_dtype(dat > dat2, datsp > dat2)
assert_array_equal_dtype(datcomplex > dat2, datspcomplex > dat2)
# sparse/scalar
assert_array_equal_dtype((datsp > 2).toarray(), dat > 2)
assert_array_equal_dtype((datsp > 1).toarray(), dat > 1)
assert_array_equal_dtype((datsp > 0).toarray(), dat > 0)
assert_array_equal_dtype((datsp > -1).toarray(), dat > -1)
assert_array_equal_dtype((datsp > -2).toarray(), dat > -2)
with np.errstate(invalid='ignore'):
assert_array_equal_dtype((datsp > np.nan).toarray(),
dat > np.nan)
assert_array_equal_dtype((2 > datsp).toarray(), 2 > dat)
assert_array_equal_dtype((1 > datsp).toarray(), 1 > dat)
assert_array_equal_dtype((0 > datsp).toarray(), 0 > dat)
assert_array_equal_dtype((-1 > datsp).toarray(), -1 > dat)
assert_array_equal_dtype((-2 > datsp).toarray(), -2 > dat)
# data
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
# dense rhs
assert_array_equal_dtype(dat > datsp2, datsp > dat2)
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_le(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datcomplex = dat.astype(complex)
datcomplex[:,0] = 1 + 1j
datspcomplex = self.spmatrix(datcomplex)
datbsr = bsr_matrix(dat)
datcsc = csc_matrix(dat)
datcsr = csr_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat <= dat2, (datsp <= datsp2).toarray())
assert_array_equal_dtype(datcomplex <= dat2,
(datspcomplex <= datsp2).toarray())
# mix sparse types
assert_array_equal_dtype((datbsr <= datsp2).toarray(), dat <= dat2)
assert_array_equal_dtype((datcsc <= datsp2).toarray(), dat <= dat2)
assert_array_equal_dtype((datcsr <= datsp2).toarray(), dat <= dat2)
assert_array_equal_dtype((datlil <= datsp2).toarray(), dat <= dat2)
assert_array_equal_dtype((datsp2 <= datbsr).toarray(), dat2 <= dat)
assert_array_equal_dtype((datsp2 <= datcsc).toarray(), dat2 <= dat)
assert_array_equal_dtype((datsp2 <= datcsr).toarray(), dat2 <= dat)
assert_array_equal_dtype((datsp2 <= datlil).toarray(), dat2 <= dat)
# sparse/dense
assert_array_equal_dtype(datsp <= dat2, dat <= dat2)
assert_array_equal_dtype(datspcomplex <= dat2, datcomplex <= dat2)
# sparse/scalar
assert_array_equal_dtype((datsp <= 2).toarray(), dat <= 2)
assert_array_equal_dtype((datsp <= 1).toarray(), dat <= 1)
assert_array_equal_dtype((datsp <= -1).toarray(), dat <= -1)
assert_array_equal_dtype((datsp <= -2).toarray(), dat <= -2)
assert_array_equal_dtype((2 <= datsp).toarray(), 2 <= dat)
assert_array_equal_dtype((1 <= datsp).toarray(), 1 <= dat)
assert_array_equal_dtype((-1 <= datsp).toarray(), -1 <= dat)
assert_array_equal_dtype((-2 <= datsp).toarray(), -2 <= dat)
# data
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
# dense rhs
assert_array_equal_dtype(dat <= datsp2, datsp <= dat2)
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_ge(self):
sup = suppress_warnings()
sup.filter(SparseEfficiencyWarning)
@sup
@sup_complex
def check(dtype):
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
datcomplex = dat.astype(complex)
datcomplex[:,0] = 1 + 1j
datspcomplex = self.spmatrix(datcomplex)
datbsr = bsr_matrix(dat)
datcsc = csc_matrix(dat)
datcsr = csr_matrix(dat)
datlil = lil_matrix(dat)
# sparse/sparse
assert_array_equal_dtype(dat >= dat2, (datsp >= datsp2).toarray())
assert_array_equal_dtype(datcomplex >= dat2,
(datspcomplex >= datsp2).toarray())
# mix sparse types
assert_array_equal_dtype((datbsr >= datsp2).toarray(), dat >= dat2)
assert_array_equal_dtype((datcsc >= datsp2).toarray(), dat >= dat2)
assert_array_equal_dtype((datcsr >= datsp2).toarray(), dat >= dat2)
assert_array_equal_dtype((datlil >= datsp2).toarray(), dat >= dat2)
assert_array_equal_dtype((datsp2 >= datbsr).toarray(), dat2 >= dat)
assert_array_equal_dtype((datsp2 >= datcsc).toarray(), dat2 >= dat)
assert_array_equal_dtype((datsp2 >= datcsr).toarray(), dat2 >= dat)
assert_array_equal_dtype((datsp2 >= datlil).toarray(), dat2 >= dat)
# sparse/dense
assert_array_equal_dtype(datsp >= dat2, dat >= dat2)
assert_array_equal_dtype(datspcomplex >= dat2, datcomplex >= dat2)
# sparse/scalar
assert_array_equal_dtype((datsp >= 2).toarray(), dat >= 2)
assert_array_equal_dtype((datsp >= 1).toarray(), dat >= 1)
assert_array_equal_dtype((datsp >= -1).toarray(), dat >= -1)
assert_array_equal_dtype((datsp >= -2).toarray(), dat >= -2)
assert_array_equal_dtype((2 >= datsp).toarray(), 2 >= dat)
assert_array_equal_dtype((1 >= datsp).toarray(), 1 >= dat)
assert_array_equal_dtype((-1 >= datsp).toarray(), -1 >= dat)
assert_array_equal_dtype((-2 >= datsp).toarray(), -2 >= dat)
# dense data
dat = self.dat_dtypes[dtype]
datsp = self.datsp_dtypes[dtype]
dat2 = dat.copy()
dat2[:,0] = 0
datsp2 = self.spmatrix(dat2)
# dense rhs
assert_array_equal_dtype(dat >= datsp2, datsp >= dat2)
if not isinstance(self, (TestBSR, TestCSC, TestCSR)):
pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
for dtype in self.checked_dtypes:
check(dtype)
def test_empty(self):
# create empty matrices
assert_equal(self.spmatrix((3, 3)).toarray(), zeros((3, 3)))
assert_equal(self.spmatrix((3, 3)).nnz, 0)
assert_equal(self.spmatrix((3, 3)).count_nonzero(), 0)
def test_count_nonzero(self):
expected = np.count_nonzero(self.datsp.toarray())
assert_equal(self.datsp.count_nonzero(), expected)
assert_equal(self.datsp.T.count_nonzero(), expected)
def test_invalid_shapes(self):
assert_raises(ValueError, self.spmatrix, (-1,3))
assert_raises(ValueError, self.spmatrix, (3,-1))
assert_raises(ValueError, self.spmatrix, (-1,-1))
def test_repr(self):
repr(self.datsp)
def test_str(self):
str(self.datsp)
def test_empty_arithmetic(self):
# Test manipulating empty matrices. Fails in SciPy SVN <= r1768
shape = (5, 5)
for mytype in [np.dtype('int32'), np.dtype('float32'),
np.dtype('float64'), np.dtype('complex64'),
np.dtype('complex128')]:
a = self.spmatrix(shape, dtype=mytype)
b = a + a
c = 2 * a
d = a * a.tocsc()
e = a * a.tocsr()
f = a * a.tocoo()
for m in [a,b,c,d,e,f]:
assert_equal(m.A, a.A*a.A)
# These fail in all revisions <= r1768:
assert_equal(m.dtype,mytype)
assert_equal(m.A.dtype,mytype)
def test_abs(self):
A = array([[-1, 0, 17], [0, -5, 0], [1, -4, 0], [0, 0, 0]], 'd')
assert_equal(abs(A), abs(self.spmatrix(A)).toarray())
def test_round(self):
decimal = 1
A = array([[-1.35, 0.56], [17.25, -5.98]], 'd')
assert_equal(np.around(A, decimals=decimal),
round(self.spmatrix(A), ndigits=decimal).toarray())
def test_elementwise_power(self):
A = array([[-4, -3, -2], [-1, 0, 1], [2, 3, 4]], 'd')
assert_equal(np.power(A, 2), self.spmatrix(A).power(2).toarray())
#it's element-wise power function, input has to be a scalar
assert_raises(NotImplementedError, self.spmatrix(A).power, A)
def test_neg(self):
A = array([[-1, 0, 17], [0, -5, 0], [1, -4, 0], [0, 0, 0]], 'd')
assert_equal(-A, (-self.spmatrix(A)).toarray())
# see gh-5843
A = array([[True, False, False], [False, False, True]])
assert_raises(NotImplementedError, self.spmatrix(A).__neg__)
def test_real(self):
D = array([[1 + 3j, 2 - 4j]])
A = self.spmatrix(D)
assert_equal(A.real.toarray(), D.real)
def test_imag(self):
D = array([[1 + 3j, 2 - 4j]])
A = self.spmatrix(D)
assert_equal(A.imag.toarray(), D.imag)
def test_diagonal(self):
# Does the matrix's .diagonal() method work?
mats = []
mats.append([[1,0,2]])
mats.append([[1],[0],[2]])
mats.append([[0,1],[0,2],[0,3]])
mats.append([[0,0,1],[0,0,2],[0,3,0]])
mats.append([[1,0],[0,0]])
mats.append(kron(mats[0],[[1,2]]))
mats.append(kron(mats[0],[[1],[2]]))
mats.append(kron(mats[1],[[1,2],[3,4]]))
mats.append(kron(mats[2],[[1,2],[3,4]]))
mats.append(kron(mats[3],[[1,2],[3,4]]))
mats.append(kron(mats[3],[[1,2,3,4]]))
for m in mats:
rows, cols = array(m).shape
sparse_mat = self.spmatrix(m)
for k in range(-rows-1, cols+2):
assert_equal(sparse_mat.diagonal(k=k), diag(m, k=k))
# Test for k beyond boundaries(issue #11949)
assert_equal(sparse_mat.diagonal(k=10), diag(m, k=10))
assert_equal(sparse_mat.diagonal(k=-99), diag(m, k=-99))
# Test all-zero matrix.
assert_equal(self.spmatrix((40, 16130)).diagonal(), np.zeros(40))
# Test empty matrix
# https://github.com/scipy/scipy/issues/11949
assert_equal(self.spmatrix((0, 0)).diagonal(), np.empty(0))
assert_equal(self.spmatrix((15, 0)).diagonal(), np.empty(0))
assert_equal(self.spmatrix((0, 5)).diagonal(10), np.empty(0))
def test_trace(self):
# For square matrix
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = self.spmatrix(A)
for k in range(-2, 3):
assert_equal(A.trace(offset=k), B.trace(offset=k))
# For rectangular matrix
A = np.array([[1, 2, 3], [4, 5, 6]])
B = self.spmatrix(A)
for k in range(-1, 3):
assert_equal(A.trace(offset=k), B.trace(offset=k))
def test_reshape(self):
# This first example is taken from the lil_matrix reshaping test.
x = self.spmatrix([[1, 0, 7], [0, 0, 0], [0, 3, 0], [0, 0, 5]])
for order in ['C', 'F']:
for s in [(12, 1), (1, 12)]:
assert_array_equal(x.reshape(s, order=order).toarray(),
x.toarray().reshape(s, order=order))
# This example is taken from the stackoverflow answer at
# https://stackoverflow.com/q/16511879
x = self.spmatrix([[0, 10, 0, 0], [0, 0, 0, 0], [0, 20, 30, 40]])
y = x.reshape((2, 6)) # Default order is 'C'
desired = [[0, 10, 0, 0, 0, 0], [0, 0, 0, 20, 30, 40]]
assert_array_equal(y.A, desired)
# Reshape with negative indexes
y = x.reshape((2, -1))
assert_array_equal(y.A, desired)
y = x.reshape((-1, 6))
assert_array_equal(y.A, desired)
assert_raises(ValueError, x.reshape, (-1, -1))
# Reshape with star args
y = x.reshape(2, 6)
assert_array_equal(y.A, desired)
assert_raises(TypeError, x.reshape, 2, 6, not_an_arg=1)
# Reshape with same size is noop unless copy=True
y = x.reshape((3, 4))
assert_(y is x)
y = x.reshape((3, 4), copy=True)
assert_(y is not x)
# Ensure reshape did not alter original size
assert_array_equal(x.shape, (3, 4))
# Reshape in place
x.shape = (2, 6)
assert_array_equal(x.A, desired)
# Reshape to bad ndim
assert_raises(ValueError, x.reshape, (x.size,))
assert_raises(ValueError, x.reshape, (1, x.size, 1))
@pytest.mark.slow
def test_setdiag_comprehensive(self):
def dense_setdiag(a, v, k):
v = np.asarray(v)
if k >= 0:
n = min(a.shape[0], a.shape[1] - k)
if v.ndim != 0:
n = min(n, len(v))
v = v[:n]
i = np.arange(0, n)
j = np.arange(k, k + n)
a[i,j] = v
elif k < 0:
dense_setdiag(a.T, v, -k)
def check_setdiag(a, b, k):
# Check setting diagonal using a scalar, a vector of
# correct length, and too short or too long vectors
for r in [-1, len(np.diag(a, k)), 2, 30]:
if r < 0:
v = np.random.choice(range(1, 20))
else:
v = np.random.randint(1, 20, size=r)
dense_setdiag(a, v, k)
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure of a cs[cr]_matrix is expensive")
b.setdiag(v, k)
# check that dense_setdiag worked
d = np.diag(a, k)
if np.asarray(v).ndim == 0:
assert_array_equal(d, v, err_msg="%s %d" % (msg, r))
else:
n = min(len(d), len(v))
assert_array_equal(d[:n], v[:n], err_msg="%s %d" % (msg, r))
# check that sparse setdiag worked
assert_array_equal(b.A, a, err_msg="%s %d" % (msg, r))
# comprehensive test
np.random.seed(1234)
shapes = [(0,5), (5,0), (1,5), (5,1), (5,5)]
for dtype in [np.int8, np.float64]:
for m,n in shapes:
ks = np.arange(-m+1, n-1)
for k in ks:
msg = repr((dtype, m, n, k))
a = np.zeros((m, n), dtype=dtype)
b = self.spmatrix((m, n), dtype=dtype)
check_setdiag(a, b, k)
# check overwriting etc
for k2 in np.random.choice(ks, size=min(len(ks), 5)):
check_setdiag(a, b, k2)
def test_setdiag(self):
# simple test cases
m = self.spmatrix(np.eye(3))
m2 = self.spmatrix((4, 4))
values = [3, 2, 1]
with suppress_warnings() as sup:
sup.filter(SparseEfficiencyWarning,
"Changing the sparsity structure of a cs[cr]_matrix is expensive")
assert_raises(ValueError, m.setdiag, values, k=4)
m.setdiag(values)
assert_array_equal(m.diagonal(), values)
m.setdiag(values, k=1)
assert_array_equal(m.A, np.array([[3, 3, 0],
[0, 2, 2],
[0, 0, 1]]))
m.setdiag(values, k=-2)
assert_array_equal(m.A, np.array([[3, 3, 0],
[0, 2, 2],
[3, 0, 1]]))
m.setdiag((9,), k=2)
assert_array_equal(m.A[0,2], 9)
m.setdiag((9,), k=-2)
assert_array_equal(m.A[2,0], 9)
# test short values on an empty matrix
m2.setdiag([1], k=2)
assert_array_equal(m2.A[0], [0, 0, 1, 0])
# test overwriting that same diagonal
m2.setdiag([1, 1], k=2)
assert_array_equal(m2.A[:2], [[0, 0, 1, 0],
[0, 0, 0, 1]])
def test_nonzero(self):
A = array([[1, 0, 1],[0, 1, 1],[0, 0, 1]])
Asp = self.spmatrix(A)
A_nz = set([tuple(ij) for ij in transpose(A.nonzero())])
Asp_nz = set([tuple(ij) for ij in transpose(Asp.nonzero())])
assert_equal(A_nz, Asp_nz)
def test_numpy_nonzero(self):
# See gh-5987
A = array([[1, 0, 1], [0, 1, 1], [0, 0, 1]])
Asp = self.spmatrix(A)
A_nz = set([tuple(ij) for ij in transpose(np.nonzero(A))])
Asp_nz = set([tuple(ij) for ij in transpose(np.nonzero(Asp))])
assert_equal(A_nz, Asp_nz)
def test_getrow(self):
assert_array_equal(self.datsp.getrow(1).toarray(), self.dat[[1], :])
assert_array_equal(self.datsp.getrow(-1).toarray(), self.dat[[-1], :])
def test_getcol(self):
assert_array_equal(self.datsp.getcol(1).toarray(), self.dat[:, [1]])
assert_array_equal(self.datsp.getcol(-1).toarray(), self.dat[:, [-1]])
def test_sum(self):
np.random.seed(1234)
dat_1 = matrix([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
dat_2 = np.random.rand(5, 5)
dat_3 = np.array([[]])
dat_4 = np.zeros((40, 40))
dat_5 = sparse.rand(5, 5, density=1e-2).A
matrices = [dat_1, dat_2, dat_3, dat_4, dat_5]
def check(dtype, j):
dat = matrix(matrices[j], dtype=dtype)
datsp = self.spmatrix(dat, dtype=dtype)
with np.errstate(over='ignore'):
assert_array_almost_equal(dat.sum(), datsp.sum())
assert_equal(dat.sum().dtype, datsp.sum().dtype)
assert_(np.isscalar(datsp.sum(axis=None)))
assert_array_almost_equal(dat.sum(axis=None),
datsp.sum(axis=None))
assert_equal(dat.sum(axis=None).dtype,
datsp.sum(axis=None).dtype)
assert_array_almost_equal(dat.sum(axis=0), datsp.sum(axis=0))
assert_equal(dat.sum(axis=0).dtype, datsp.sum(axis=0).dtype)
assert_array_almost_equal(dat.sum(axis=1), datsp.sum(axis=1))
assert_equal(dat.sum(axis=1).dtype, datsp.sum(axis=1).dtype)
assert_array_almost_equal(dat.sum(axis=-2), datsp.sum(axis=-2))
assert_equal(dat.sum(axis=-2).dtype, datsp.sum(axis=-2).dtype)
assert_array_almost_equal(dat.sum(axis=-1), datsp.sum(axis=-1))
assert_equal(dat.sum(axis=-1).dtype, datsp.sum(axis=-1).dtype)
for dtype in self.checked_dtypes:
for j in range(len(matrices)):
check(dtype, j)
def test_sum_invalid_params(self):
out = np.zeros((1, 3))
dat = array([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
assert_raises(ValueError, datsp.sum, axis=3)
assert_raises(TypeError, datsp.sum, axis=(0, 1))
assert_raises(TypeError, datsp.sum, axis=1.5)
assert_raises(ValueError, datsp.sum, axis=1, out=out)
def test_sum_dtype(self):
dat = array([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
def check(dtype):
dat_mean = dat.mean(dtype=dtype)
datsp_mean = datsp.mean(dtype=dtype)
assert_array_almost_equal(dat_mean, datsp_mean)
assert_equal(dat_mean.dtype, datsp_mean.dtype)
for dtype in self.checked_dtypes:
check(dtype)
def test_sum_out(self):
dat = array([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
dat_out = array([[0]])
datsp_out = matrix([[0]])
dat.sum(out=dat_out, keepdims=True)
datsp.sum(out=datsp_out)
assert_array_almost_equal(dat_out, datsp_out)
dat_out = np.zeros((3, 1))
datsp_out = asmatrix(np.zeros((3, 1)))
dat.sum(axis=1, out=dat_out, keepdims=True)
datsp.sum(axis=1, out=datsp_out)
assert_array_almost_equal(dat_out, datsp_out)
def test_numpy_sum(self):
# See gh-5987
dat = array([[0, 1, 2],
[3, -4, 5],
[-6, 7, 9]])
datsp = self.spmatrix(dat)
dat_mean = np.sum(dat)
datsp_mean = np.sum(datsp)
assert_array_almost_equal(dat_mean, datsp_mean)