Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/scipy/sparse/_matrix_io.py: 16%

37 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-12-12 06:31 +0000

1import numpy as np 

2import scipy.sparse 

3 

4__all__ = ['save_npz', 'load_npz'] 

5 

6 

7# Make loading safe vs. malicious input 

8PICKLE_KWARGS = dict(allow_pickle=False) 

9 

10 

11def save_npz(file, matrix, compressed=True): 

12 """ Save a sparse matrix to a file using ``.npz`` format. 

13 

14 Parameters 

15 ---------- 

16 file : str or file-like object 

17 Either the file name (string) or an open file (file-like object) 

18 where the data will be saved. If file is a string, the ``.npz`` 

19 extension will be appended to the file name if it is not already 

20 there. 

21 matrix: spmatrix (format: ``csc``, ``csr``, ``bsr``, ``dia`` or coo``) 

22 The sparse matrix to save. 

23 compressed : bool, optional 

24 Allow compressing the file. Default: True 

25 

26 See Also 

27 -------- 

28 scipy.sparse.load_npz: Load a sparse matrix from a file using ``.npz`` format. 

29 numpy.savez: Save several arrays into a ``.npz`` archive. 

30 numpy.savez_compressed : Save several arrays into a compressed ``.npz`` archive. 

31 

32 Examples 

33 -------- 

34 Store sparse matrix to disk, and load it again: 

35 

36 >>> import numpy as np 

37 >>> import scipy.sparse 

38 >>> sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]])) 

39 >>> sparse_matrix 

40 <2x3 sparse matrix of type '<class 'numpy.int64'>' 

41 with 2 stored elements in Compressed Sparse Column format> 

42 >>> sparse_matrix.toarray() 

43 array([[0, 0, 3], 

44 [4, 0, 0]], dtype=int64) 

45 

46 >>> scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) 

47 >>> sparse_matrix = scipy.sparse.load_npz('/tmp/sparse_matrix.npz') 

48 

49 >>> sparse_matrix 

50 <2x3 sparse matrix of type '<class 'numpy.int64'>' 

51 with 2 stored elements in Compressed Sparse Column format> 

52 >>> sparse_matrix.toarray() 

53 array([[0, 0, 3], 

54 [4, 0, 0]], dtype=int64) 

55 """ 

56 arrays_dict = {} 

57 if matrix.format in ('csc', 'csr', 'bsr'): 

58 arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr) 

59 elif matrix.format == 'dia': 

60 arrays_dict.update(offsets=matrix.offsets) 

61 elif matrix.format == 'coo': 

62 arrays_dict.update(row=matrix.row, col=matrix.col) 

63 else: 

64 raise NotImplementedError('Save is not implemented for sparse matrix of format {}.'.format(matrix.format)) 

65 arrays_dict.update( 

66 format=matrix.format.encode('ascii'), 

67 shape=matrix.shape, 

68 data=matrix.data 

69 ) 

70 if compressed: 

71 np.savez_compressed(file, **arrays_dict) 

72 else: 

73 np.savez(file, **arrays_dict) 

74 

75 

76def load_npz(file): 

77 """ Load a sparse matrix from a file using ``.npz`` format. 

78 

79 Parameters 

80 ---------- 

81 file : str or file-like object 

82 Either the file name (string) or an open file (file-like object) 

83 where the data will be loaded. 

84 

85 Returns 

86 ------- 

87 result : csc_matrix, csr_matrix, bsr_matrix, dia_matrix or coo_matrix 

88 A sparse matrix containing the loaded data. 

89 

90 Raises 

91 ------ 

92 OSError 

93 If the input file does not exist or cannot be read. 

94 

95 See Also 

96 -------- 

97 scipy.sparse.save_npz: Save a sparse matrix to a file using ``.npz`` format. 

98 numpy.load: Load several arrays from a ``.npz`` archive. 

99 

100 Examples 

101 -------- 

102 Store sparse matrix to disk, and load it again: 

103 

104 >>> import numpy as np 

105 >>> import scipy.sparse 

106 >>> sparse_matrix = scipy.sparse.csc_matrix(np.array([[0, 0, 3], [4, 0, 0]])) 

107 >>> sparse_matrix 

108 <2x3 sparse matrix of type '<class 'numpy.int64'>' 

109 with 2 stored elements in Compressed Sparse Column format> 

110 >>> sparse_matrix.toarray() 

111 array([[0, 0, 3], 

112 [4, 0, 0]], dtype=int64) 

113 

114 >>> scipy.sparse.save_npz('/tmp/sparse_matrix.npz', sparse_matrix) 

115 >>> sparse_matrix = scipy.sparse.load_npz('/tmp/sparse_matrix.npz') 

116 

117 >>> sparse_matrix 

118 <2x3 sparse matrix of type '<class 'numpy.int64'>' 

119 with 2 stored elements in Compressed Sparse Column format> 

120 >>> sparse_matrix.toarray() 

121 array([[0, 0, 3], 

122 [4, 0, 0]], dtype=int64) 

123 """ 

124 

125 with np.load(file, **PICKLE_KWARGS) as loaded: 

126 try: 

127 matrix_format = loaded['format'] 

128 except KeyError as e: 

129 raise ValueError('The file {} does not contain a sparse matrix.'.format(file)) from e 

130 

131 matrix_format = matrix_format.item() 

132 

133 if not isinstance(matrix_format, str): 

134 # Play safe with Python 2 vs 3 backward compatibility; 

135 # files saved with SciPy < 1.0.0 may contain unicode or bytes. 

136 matrix_format = matrix_format.decode('ascii') 

137 

138 try: 

139 cls = getattr(scipy.sparse, '{}_matrix'.format(matrix_format)) 

140 except AttributeError as e: 

141 raise ValueError('Unknown matrix format "{}"'.format(matrix_format)) from e 

142 

143 if matrix_format in ('csc', 'csr', 'bsr'): 

144 return cls((loaded['data'], loaded['indices'], loaded['indptr']), shape=loaded['shape']) 

145 elif matrix_format == 'dia': 

146 return cls((loaded['data'], loaded['offsets']), shape=loaded['shape']) 

147 elif matrix_format == 'coo': 

148 return cls((loaded['data'], (loaded['row'], loaded['col'])), shape=loaded['shape']) 

149 else: 

150 raise NotImplementedError('Load is not implemented for ' 

151 'sparse matrix of format {}.'.format(matrix_format))