base.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. """Base class for sparse matrices"""
  2. from __future__ import division, print_function, absolute_import
  3. import sys
  4. import numpy as np
  5. from scipy._lib.six import xrange
  6. from scipy._lib._numpy_compat import broadcast_to
  7. from .sputils import (isdense, isscalarlike, isintlike,
  8. get_sum_dtype, validateaxis, check_reshape_kwargs,
  9. check_shape)
  10. __all__ = ['spmatrix', 'isspmatrix', 'issparse',
  11. 'SparseWarning', 'SparseEfficiencyWarning']
  12. class SparseWarning(Warning):
  13. pass
  14. class SparseFormatWarning(SparseWarning):
  15. pass
  16. class SparseEfficiencyWarning(SparseWarning):
  17. pass
  18. # The formats that we might potentially understand.
  19. _formats = {'csc': [0, "Compressed Sparse Column"],
  20. 'csr': [1, "Compressed Sparse Row"],
  21. 'dok': [2, "Dictionary Of Keys"],
  22. 'lil': [3, "LInked List"],
  23. 'dod': [4, "Dictionary of Dictionaries"],
  24. 'sss': [5, "Symmetric Sparse Skyline"],
  25. 'coo': [6, "COOrdinate"],
  26. 'lba': [7, "Linpack BAnded"],
  27. 'egd': [8, "Ellpack-itpack Generalized Diagonal"],
  28. 'dia': [9, "DIAgonal"],
  29. 'bsr': [10, "Block Sparse Row"],
  30. 'msr': [11, "Modified compressed Sparse Row"],
  31. 'bsc': [12, "Block Sparse Column"],
  32. 'msc': [13, "Modified compressed Sparse Column"],
  33. 'ssk': [14, "Symmetric SKyline"],
  34. 'nsk': [15, "Nonsymmetric SKyline"],
  35. 'jad': [16, "JAgged Diagonal"],
  36. 'uss': [17, "Unsymmetric Sparse Skyline"],
  37. 'vbr': [18, "Variable Block Row"],
  38. 'und': [19, "Undefined"]
  39. }
  40. # These univariate ufuncs preserve zeros.
  41. _ufuncs_with_fixed_point_at_zero = frozenset([
  42. np.sin, np.tan, np.arcsin, np.arctan, np.sinh, np.tanh, np.arcsinh,
  43. np.arctanh, np.rint, np.sign, np.expm1, np.log1p, np.deg2rad,
  44. np.rad2deg, np.floor, np.ceil, np.trunc, np.sqrt])
  45. MAXPRINT = 50
  46. class spmatrix(object):
  47. """ This class provides a base class for all sparse matrices. It
  48. cannot be instantiated. Most of the work is provided by subclasses.
  49. """
  50. __array_priority__ = 10.1
  51. ndim = 2
  52. def __init__(self, maxprint=MAXPRINT):
  53. self._shape = None
  54. if self.__class__.__name__ == 'spmatrix':
  55. raise ValueError("This class is not intended"
  56. " to be instantiated directly.")
  57. self.maxprint = maxprint
  58. def set_shape(self, shape):
  59. """See `reshape`."""
  60. # Make sure copy is False since this is in place
  61. # Make sure format is unchanged because we are doing a __dict__ swap
  62. new_matrix = self.reshape(shape, copy=False).asformat(self.format)
  63. self.__dict__ = new_matrix.__dict__
  64. def get_shape(self):
  65. """Get shape of a matrix."""
  66. return self._shape
  67. shape = property(fget=get_shape, fset=set_shape)
  68. def reshape(self, *args, **kwargs):
  69. """reshape(self, shape, order='C', copy=False)
  70. Gives a new shape to a sparse matrix without changing its data.
  71. Parameters
  72. ----------
  73. shape : length-2 tuple of ints
  74. The new shape should be compatible with the original shape.
  75. order : {'C', 'F'}, optional
  76. Read the elements using this index order. 'C' means to read and
  77. write the elements using C-like index order; e.g. read entire first
  78. row, then second row, etc. 'F' means to read and write the elements
  79. using Fortran-like index order; e.g. read entire first column, then
  80. second column, etc.
  81. copy : bool, optional
  82. Indicates whether or not attributes of self should be copied
  83. whenever possible. The degree to which attributes are copied varies
  84. depending on the type of sparse matrix being used.
  85. Returns
  86. -------
  87. reshaped_matrix : sparse matrix
  88. A sparse matrix with the given `shape`, not necessarily of the same
  89. format as the current object.
  90. See Also
  91. --------
  92. np.matrix.reshape : NumPy's implementation of 'reshape' for matrices
  93. """
  94. # If the shape already matches, don't bother doing an actual reshape
  95. # Otherwise, the default is to convert to COO and use its reshape
  96. shape = check_shape(args, self.shape)
  97. order, copy = check_reshape_kwargs(kwargs)
  98. if shape == self.shape:
  99. if copy:
  100. return self.copy()
  101. else:
  102. return self
  103. return self.tocoo(copy=copy).reshape(shape, order=order, copy=False)
  104. def resize(self, shape):
  105. """Resize the matrix in-place to dimensions given by ``shape``
  106. Any elements that lie within the new shape will remain at the same
  107. indices, while non-zero elements lying outside the new shape are
  108. removed.
  109. Parameters
  110. ----------
  111. shape : (int, int)
  112. number of rows and columns in the new matrix
  113. Notes
  114. -----
  115. The semantics are not identical to `numpy.ndarray.resize` or
  116. `numpy.resize`. Here, the same data will be maintained at each index
  117. before and after reshape, if that index is within the new bounds. In
  118. numpy, resizing maintains contiguity of the array, moving elements
  119. around in the logical matrix but not within a flattened representation.
  120. We give no guarantees about whether the underlying data attributes
  121. (arrays, etc.) will be modified in place or replaced with new objects.
  122. """
  123. # As an inplace operation, this requires implementation in each format.
  124. raise NotImplementedError(
  125. '{}.resize is not implemented'.format(type(self).__name__))
  126. def astype(self, dtype, casting='unsafe', copy=True):
  127. """Cast the matrix elements to a specified type.
  128. Parameters
  129. ----------
  130. dtype : string or numpy dtype
  131. Typecode or data-type to which to cast the data.
  132. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
  133. Controls what kind of data casting may occur.
  134. Defaults to 'unsafe' for backwards compatibility.
  135. 'no' means the data types should not be cast at all.
  136. 'equiv' means only byte-order changes are allowed.
  137. 'safe' means only casts which can preserve values are allowed.
  138. 'same_kind' means only safe casts or casts within a kind,
  139. like float64 to float32, are allowed.
  140. 'unsafe' means any data conversions may be done.
  141. copy : bool, optional
  142. If `copy` is `False`, the result might share some memory with this
  143. matrix. If `copy` is `True`, it is guaranteed that the result and
  144. this matrix do not share any memory.
  145. """
  146. dtype = np.dtype(dtype)
  147. if self.dtype != dtype:
  148. return self.tocsr().astype(
  149. dtype, casting=casting, copy=copy).asformat(self.format)
  150. elif copy:
  151. return self.copy()
  152. else:
  153. return self
  154. def asfptype(self):
  155. """Upcast matrix to a floating point format (if necessary)"""
  156. fp_types = ['f', 'd', 'F', 'D']
  157. if self.dtype.char in fp_types:
  158. return self
  159. else:
  160. for fp_type in fp_types:
  161. if self.dtype <= np.dtype(fp_type):
  162. return self.astype(fp_type)
  163. raise TypeError('cannot upcast [%s] to a floating '
  164. 'point format' % self.dtype.name)
  165. def __iter__(self):
  166. for r in xrange(self.shape[0]):
  167. yield self[r, :]
  168. def getmaxprint(self):
  169. """Maximum number of elements to display when printed."""
  170. return self.maxprint
  171. def count_nonzero(self):
  172. """Number of non-zero entries, equivalent to
  173. np.count_nonzero(a.toarray())
  174. Unlike getnnz() and the nnz property, which return the number of stored
  175. entries (the length of the data attribute), this method counts the
  176. actual number of non-zero entries in data.
  177. """
  178. raise NotImplementedError("count_nonzero not implemented for %s." %
  179. self.__class__.__name__)
  180. def getnnz(self, axis=None):
  181. """Number of stored values, including explicit zeros.
  182. Parameters
  183. ----------
  184. axis : None, 0, or 1
  185. Select between the number of values across the whole matrix, in
  186. each column, or in each row.
  187. See also
  188. --------
  189. count_nonzero : Number of non-zero entries
  190. """
  191. raise NotImplementedError("getnnz not implemented for %s." %
  192. self.__class__.__name__)
  193. @property
  194. def nnz(self):
  195. """Number of stored values, including explicit zeros.
  196. See also
  197. --------
  198. count_nonzero : Number of non-zero entries
  199. """
  200. return self.getnnz()
  201. def getformat(self):
  202. """Format of a matrix representation as a string."""
  203. return getattr(self, 'format', 'und')
  204. def __repr__(self):
  205. _, format_name = _formats[self.getformat()]
  206. return "<%dx%d sparse matrix of type '%s'\n" \
  207. "\twith %d stored elements in %s format>" % \
  208. (self.shape + (self.dtype.type, self.nnz, format_name))
  209. def __str__(self):
  210. maxprint = self.getmaxprint()
  211. A = self.tocoo()
  212. # helper function, outputs "(i,j) v"
  213. def tostr(row, col, data):
  214. triples = zip(list(zip(row, col)), data)
  215. return '\n'.join([(' %s\t%s' % t) for t in triples])
  216. if self.nnz > maxprint:
  217. half = maxprint // 2
  218. out = tostr(A.row[:half], A.col[:half], A.data[:half])
  219. out += "\n :\t:\n"
  220. half = maxprint - maxprint//2
  221. out += tostr(A.row[-half:], A.col[-half:], A.data[-half:])
  222. else:
  223. out = tostr(A.row, A.col, A.data)
  224. return out
  225. def __bool__(self): # Simple -- other ideas?
  226. if self.shape == (1, 1):
  227. return self.nnz != 0
  228. else:
  229. raise ValueError("The truth value of an array with more than one "
  230. "element is ambiguous. Use a.any() or a.all().")
  231. __nonzero__ = __bool__
  232. # What should len(sparse) return? For consistency with dense matrices,
  233. # perhaps it should be the number of rows? But for some uses the number of
  234. # non-zeros is more important. For now, raise an exception!
  235. def __len__(self):
  236. raise TypeError("sparse matrix length is ambiguous; use getnnz()"
  237. " or shape[0]")
  238. def asformat(self, format, copy=False):
  239. """Return this matrix in the passed format.
  240. Parameters
  241. ----------
  242. format : {str, None}
  243. The desired matrix format ("csr", "csc", "lil", "dok", "array", ...)
  244. or None for no conversion.
  245. copy : bool, optional
  246. If True, the result is guaranteed to not share data with self.
  247. Returns
  248. -------
  249. A : This matrix in the passed format.
  250. """
  251. if format is None or format == self.format:
  252. if copy:
  253. return self.copy()
  254. else:
  255. return self
  256. else:
  257. try:
  258. convert_method = getattr(self, 'to' + format)
  259. except AttributeError:
  260. raise ValueError('Format {} is unknown.'.format(format))
  261. # Forward the copy kwarg, if it's accepted.
  262. try:
  263. return convert_method(copy=copy)
  264. except TypeError:
  265. return convert_method()
  266. ###################################################################
  267. # NOTE: All arithmetic operations use csr_matrix by default.
  268. # Therefore a new sparse matrix format just needs to define a
  269. # .tocsr() method to provide arithmetic support. Any of these
  270. # methods can be overridden for efficiency.
  271. ####################################################################
  272. def multiply(self, other):
  273. """Point-wise multiplication by another matrix
  274. """
  275. return self.tocsr().multiply(other)
  276. def maximum(self, other):
  277. """Element-wise maximum between this and another matrix."""
  278. return self.tocsr().maximum(other)
  279. def minimum(self, other):
  280. """Element-wise minimum between this and another matrix."""
  281. return self.tocsr().minimum(other)
  282. def dot(self, other):
  283. """Ordinary dot product
  284. Examples
  285. --------
  286. >>> import numpy as np
  287. >>> from scipy.sparse import csr_matrix
  288. >>> A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
  289. >>> v = np.array([1, 0, -1])
  290. >>> A.dot(v)
  291. array([ 1, -3, -1], dtype=int64)
  292. """
  293. return self * other
  294. def power(self, n, dtype=None):
  295. """Element-wise power."""
  296. return self.tocsr().power(n, dtype=dtype)
  297. def __eq__(self, other):
  298. return self.tocsr().__eq__(other)
  299. def __ne__(self, other):
  300. return self.tocsr().__ne__(other)
  301. def __lt__(self, other):
  302. return self.tocsr().__lt__(other)
  303. def __gt__(self, other):
  304. return self.tocsr().__gt__(other)
  305. def __le__(self, other):
  306. return self.tocsr().__le__(other)
  307. def __ge__(self, other):
  308. return self.tocsr().__ge__(other)
  309. def __abs__(self):
  310. return abs(self.tocsr())
  311. def _add_sparse(self, other):
  312. return self.tocsr()._add_sparse(other)
  313. def _add_dense(self, other):
  314. return self.tocoo()._add_dense(other)
  315. def _sub_sparse(self, other):
  316. return self.tocsr()._sub_sparse(other)
  317. def _sub_dense(self, other):
  318. return self.todense() - other
  319. def _rsub_dense(self, other):
  320. # note: this can't be replaced by other + (-self) for unsigned types
  321. return other - self.todense()
  322. def __add__(self, other): # self + other
  323. if isscalarlike(other):
  324. if other == 0:
  325. return self.copy()
  326. # Now we would add this scalar to every element.
  327. raise NotImplementedError('adding a nonzero scalar to a '
  328. 'sparse matrix is not supported')
  329. elif isspmatrix(other):
  330. if other.shape != self.shape:
  331. raise ValueError("inconsistent shapes")
  332. return self._add_sparse(other)
  333. elif isdense(other):
  334. other = broadcast_to(other, self.shape)
  335. return self._add_dense(other)
  336. else:
  337. return NotImplemented
  338. def __radd__(self,other): # other + self
  339. return self.__add__(other)
  340. def __sub__(self, other): # self - other
  341. if isscalarlike(other):
  342. if other == 0:
  343. return self.copy()
  344. raise NotImplementedError('subtracting a nonzero scalar from a '
  345. 'sparse matrix is not supported')
  346. elif isspmatrix(other):
  347. if other.shape != self.shape:
  348. raise ValueError("inconsistent shapes")
  349. return self._sub_sparse(other)
  350. elif isdense(other):
  351. other = broadcast_to(other, self.shape)
  352. return self._sub_dense(other)
  353. else:
  354. return NotImplemented
  355. def __rsub__(self,other): # other - self
  356. if isscalarlike(other):
  357. if other == 0:
  358. return -self.copy()
  359. raise NotImplementedError('subtracting a sparse matrix from a '
  360. 'nonzero scalar is not supported')
  361. elif isdense(other):
  362. other = broadcast_to(other, self.shape)
  363. return self._rsub_dense(other)
  364. else:
  365. return NotImplemented
  366. def __mul__(self, other):
  367. """interpret other and call one of the following
  368. self._mul_scalar()
  369. self._mul_vector()
  370. self._mul_multivector()
  371. self._mul_sparse_matrix()
  372. """
  373. M, N = self.shape
  374. if other.__class__ is np.ndarray:
  375. # Fast path for the most common case
  376. if other.shape == (N,):
  377. return self._mul_vector(other)
  378. elif other.shape == (N, 1):
  379. return self._mul_vector(other.ravel()).reshape(M, 1)
  380. elif other.ndim == 2 and other.shape[0] == N:
  381. return self._mul_multivector(other)
  382. if isscalarlike(other):
  383. # scalar value
  384. return self._mul_scalar(other)
  385. if issparse(other):
  386. if self.shape[1] != other.shape[0]:
  387. raise ValueError('dimension mismatch')
  388. return self._mul_sparse_matrix(other)
  389. # If it's a list or whatever, treat it like a matrix
  390. other_a = np.asanyarray(other)
  391. if other_a.ndim == 0 and other_a.dtype == np.object_:
  392. # Not interpretable as an array; return NotImplemented so that
  393. # other's __rmul__ can kick in if that's implemented.
  394. return NotImplemented
  395. try:
  396. other.shape
  397. except AttributeError:
  398. other = other_a
  399. if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1:
  400. # dense row or column vector
  401. if other.shape != (N,) and other.shape != (N, 1):
  402. raise ValueError('dimension mismatch')
  403. result = self._mul_vector(np.ravel(other))
  404. if isinstance(other, np.matrix):
  405. result = np.asmatrix(result)
  406. if other.ndim == 2 and other.shape[1] == 1:
  407. # If 'other' was an (nx1) column vector, reshape the result
  408. result = result.reshape(-1, 1)
  409. return result
  410. elif other.ndim == 2:
  411. ##
  412. # dense 2D array or matrix ("multivector")
  413. if other.shape[0] != self.shape[1]:
  414. raise ValueError('dimension mismatch')
  415. result = self._mul_multivector(np.asarray(other))
  416. if isinstance(other, np.matrix):
  417. result = np.asmatrix(result)
  418. return result
  419. else:
  420. raise ValueError('could not interpret dimensions')
  421. # by default, use CSR for __mul__ handlers
  422. def _mul_scalar(self, other):
  423. return self.tocsr()._mul_scalar(other)
  424. def _mul_vector(self, other):
  425. return self.tocsr()._mul_vector(other)
  426. def _mul_multivector(self, other):
  427. return self.tocsr()._mul_multivector(other)
  428. def _mul_sparse_matrix(self, other):
  429. return self.tocsr()._mul_sparse_matrix(other)
  430. def __rmul__(self, other): # other * self
  431. if isscalarlike(other):
  432. return self.__mul__(other)
  433. else:
  434. # Don't use asarray unless we have to
  435. try:
  436. tr = other.transpose()
  437. except AttributeError:
  438. tr = np.asarray(other).transpose()
  439. return (self.transpose() * tr).transpose()
  440. #####################################
  441. # matmul (@) operator (Python 3.5+) #
  442. #####################################
  443. def __matmul__(self, other):
  444. if isscalarlike(other):
  445. raise ValueError("Scalar operands are not allowed, "
  446. "use '*' instead")
  447. return self.__mul__(other)
  448. def __rmatmul__(self, other):
  449. if isscalarlike(other):
  450. raise ValueError("Scalar operands are not allowed, "
  451. "use '*' instead")
  452. return self.__rmul__(other)
  453. ####################
  454. # Other Arithmetic #
  455. ####################
  456. def _divide(self, other, true_divide=False, rdivide=False):
  457. if isscalarlike(other):
  458. if rdivide:
  459. if true_divide:
  460. return np.true_divide(other, self.todense())
  461. else:
  462. return np.divide(other, self.todense())
  463. if true_divide and np.can_cast(self.dtype, np.float_):
  464. return self.astype(np.float_)._mul_scalar(1./other)
  465. else:
  466. r = self._mul_scalar(1./other)
  467. scalar_dtype = np.asarray(other).dtype
  468. if (np.issubdtype(self.dtype, np.integer) and
  469. np.issubdtype(scalar_dtype, np.integer)):
  470. return r.astype(self.dtype)
  471. else:
  472. return r
  473. elif isdense(other):
  474. if not rdivide:
  475. if true_divide:
  476. return np.true_divide(self.todense(), other)
  477. else:
  478. return np.divide(self.todense(), other)
  479. else:
  480. if true_divide:
  481. return np.true_divide(other, self.todense())
  482. else:
  483. return np.divide(other, self.todense())
  484. elif isspmatrix(other):
  485. if rdivide:
  486. return other._divide(self, true_divide, rdivide=False)
  487. self_csr = self.tocsr()
  488. if true_divide and np.can_cast(self.dtype, np.float_):
  489. return self_csr.astype(np.float_)._divide_sparse(other)
  490. else:
  491. return self_csr._divide_sparse(other)
  492. else:
  493. return NotImplemented
  494. def __truediv__(self, other):
  495. return self._divide(other, true_divide=True)
  496. def __div__(self, other):
  497. # Always do true division
  498. return self._divide(other, true_divide=True)
  499. def __rtruediv__(self, other):
  500. # Implementing this as the inverse would be too magical -- bail out
  501. return NotImplemented
  502. def __rdiv__(self, other):
  503. # Implementing this as the inverse would be too magical -- bail out
  504. return NotImplemented
  505. def __neg__(self):
  506. return -self.tocsr()
  507. def __iadd__(self, other):
  508. return NotImplemented
  509. def __isub__(self, other):
  510. return NotImplemented
  511. def __imul__(self, other):
  512. return NotImplemented
  513. def __idiv__(self, other):
  514. return self.__itruediv__(other)
  515. def __itruediv__(self, other):
  516. return NotImplemented
  517. def __pow__(self, other):
  518. if self.shape[0] != self.shape[1]:
  519. raise TypeError('matrix is not square')
  520. if isintlike(other):
  521. other = int(other)
  522. if other < 0:
  523. raise ValueError('exponent must be >= 0')
  524. if other == 0:
  525. from .construct import eye
  526. return eye(self.shape[0], dtype=self.dtype)
  527. elif other == 1:
  528. return self.copy()
  529. else:
  530. tmp = self.__pow__(other//2)
  531. if (other % 2):
  532. return self * tmp * tmp
  533. else:
  534. return tmp * tmp
  535. elif isscalarlike(other):
  536. raise ValueError('exponent must be an integer')
  537. else:
  538. return NotImplemented
  539. def __getattr__(self, attr):
  540. if attr == 'A':
  541. return self.toarray()
  542. elif attr == 'T':
  543. return self.transpose()
  544. elif attr == 'H':
  545. return self.getH()
  546. elif attr == 'real':
  547. return self._real()
  548. elif attr == 'imag':
  549. return self._imag()
  550. elif attr == 'size':
  551. return self.getnnz()
  552. else:
  553. raise AttributeError(attr + " not found")
  554. def transpose(self, axes=None, copy=False):
  555. """
  556. Reverses the dimensions of the sparse matrix.
  557. Parameters
  558. ----------
  559. axes : None, optional
  560. This argument is in the signature *solely* for NumPy
  561. compatibility reasons. Do not pass in anything except
  562. for the default value.
  563. copy : bool, optional
  564. Indicates whether or not attributes of `self` should be
  565. copied whenever possible. The degree to which attributes
  566. are copied varies depending on the type of sparse matrix
  567. being used.
  568. Returns
  569. -------
  570. p : `self` with the dimensions reversed.
  571. See Also
  572. --------
  573. np.matrix.transpose : NumPy's implementation of 'transpose'
  574. for matrices
  575. """
  576. return self.tocsr(copy=copy).transpose(axes=axes, copy=False)
  577. def conj(self, copy=True):
  578. """Element-wise complex conjugation.
  579. If the matrix is of non-complex data type and `copy` is False,
  580. this method does nothing and the data is not copied.
  581. Parameters
  582. ----------
  583. copy : bool, optional
  584. If True, the result is guaranteed to not share data with self.
  585. Returns
  586. -------
  587. A : The element-wise complex conjugate.
  588. """
  589. if np.issubdtype(self.dtype, np.complexfloating):
  590. return self.tocsr(copy=copy).conj(copy=False)
  591. elif copy:
  592. return self.copy()
  593. else:
  594. return self
  595. def conjugate(self, copy=True):
  596. return self.conj(copy=copy)
  597. conjugate.__doc__ = conj.__doc__
  598. # Renamed conjtranspose() -> getH() for compatibility with dense matrices
  599. def getH(self):
  600. """Return the Hermitian transpose of this matrix.
  601. See Also
  602. --------
  603. np.matrix.getH : NumPy's implementation of `getH` for matrices
  604. """
  605. return self.transpose().conj()
  606. def _real(self):
  607. return self.tocsr()._real()
  608. def _imag(self):
  609. return self.tocsr()._imag()
  610. def nonzero(self):
  611. """nonzero indices
  612. Returns a tuple of arrays (row,col) containing the indices
  613. of the non-zero elements of the matrix.
  614. Examples
  615. --------
  616. >>> from scipy.sparse import csr_matrix
  617. >>> A = csr_matrix([[1,2,0],[0,0,3],[4,0,5]])
  618. >>> A.nonzero()
  619. (array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2]))
  620. """
  621. # convert to COOrdinate format
  622. A = self.tocoo()
  623. nz_mask = A.data != 0
  624. return (A.row[nz_mask], A.col[nz_mask])
  625. def getcol(self, j):
  626. """Returns a copy of column j of the matrix, as an (m x 1) sparse
  627. matrix (column vector).
  628. """
  629. # Spmatrix subclasses should override this method for efficiency.
  630. # Post-multiply by a (n x 1) column vector 'a' containing all zeros
  631. # except for a_j = 1
  632. from .csc import csc_matrix
  633. n = self.shape[1]
  634. if j < 0:
  635. j += n
  636. if j < 0 or j >= n:
  637. raise IndexError("index out of bounds")
  638. col_selector = csc_matrix(([1], [[j], [0]]),
  639. shape=(n, 1), dtype=self.dtype)
  640. return self * col_selector
  641. def getrow(self, i):
  642. """Returns a copy of row i of the matrix, as a (1 x n) sparse
  643. matrix (row vector).
  644. """
  645. # Spmatrix subclasses should override this method for efficiency.
  646. # Pre-multiply by a (1 x m) row vector 'a' containing all zeros
  647. # except for a_i = 1
  648. from .csr import csr_matrix
  649. m = self.shape[0]
  650. if i < 0:
  651. i += m
  652. if i < 0 or i >= m:
  653. raise IndexError("index out of bounds")
  654. row_selector = csr_matrix(([1], [[0], [i]]),
  655. shape=(1, m), dtype=self.dtype)
  656. return row_selector * self
  657. # def __array__(self):
  658. # return self.toarray()
  659. def todense(self, order=None, out=None):
  660. """
  661. Return a dense matrix representation of this matrix.
  662. Parameters
  663. ----------
  664. order : {'C', 'F'}, optional
  665. Whether to store multi-dimensional data in C (row-major)
  666. or Fortran (column-major) order in memory. The default
  667. is 'None', indicating the NumPy default of C-ordered.
  668. Cannot be specified in conjunction with the `out`
  669. argument.
  670. out : ndarray, 2-dimensional, optional
  671. If specified, uses this array (or `numpy.matrix`) as the
  672. output buffer instead of allocating a new array to
  673. return. The provided array must have the same shape and
  674. dtype as the sparse matrix on which you are calling the
  675. method.
  676. Returns
  677. -------
  678. arr : numpy.matrix, 2-dimensional
  679. A NumPy matrix object with the same shape and containing
  680. the same data represented by the sparse matrix, with the
  681. requested memory order. If `out` was passed and was an
  682. array (rather than a `numpy.matrix`), it will be filled
  683. with the appropriate values and returned wrapped in a
  684. `numpy.matrix` object that shares the same memory.
  685. """
  686. return np.asmatrix(self.toarray(order=order, out=out))
  687. def toarray(self, order=None, out=None):
  688. """
  689. Return a dense ndarray representation of this matrix.
  690. Parameters
  691. ----------
  692. order : {'C', 'F'}, optional
  693. Whether to store multi-dimensional data in C (row-major)
  694. or Fortran (column-major) order in memory. The default
  695. is 'None', indicating the NumPy default of C-ordered.
  696. Cannot be specified in conjunction with the `out`
  697. argument.
  698. out : ndarray, 2-dimensional, optional
  699. If specified, uses this array as the output buffer
  700. instead of allocating a new array to return. The provided
  701. array must have the same shape and dtype as the sparse
  702. matrix on which you are calling the method. For most
  703. sparse types, `out` is required to be memory contiguous
  704. (either C or Fortran ordered).
  705. Returns
  706. -------
  707. arr : ndarray, 2-dimensional
  708. An array with the same shape and containing the same
  709. data represented by the sparse matrix, with the requested
  710. memory order. If `out` was passed, the same object is
  711. returned after being modified in-place to contain the
  712. appropriate values.
  713. """
  714. return self.tocoo(copy=False).toarray(order=order, out=out)
  715. # Any sparse matrix format deriving from spmatrix must define one of
  716. # tocsr or tocoo. The other conversion methods may be implemented for
  717. # efficiency, but are not required.
  718. def tocsr(self, copy=False):
  719. """Convert this matrix to Compressed Sparse Row format.
  720. With copy=False, the data/indices may be shared between this matrix and
  721. the resultant csr_matrix.
  722. """
  723. return self.tocoo(copy=copy).tocsr(copy=False)
  724. def todok(self, copy=False):
  725. """Convert this matrix to Dictionary Of Keys format.
  726. With copy=False, the data/indices may be shared between this matrix and
  727. the resultant dok_matrix.
  728. """
  729. return self.tocoo(copy=copy).todok(copy=False)
  730. def tocoo(self, copy=False):
  731. """Convert this matrix to COOrdinate format.
  732. With copy=False, the data/indices may be shared between this matrix and
  733. the resultant coo_matrix.
  734. """
  735. return self.tocsr(copy=False).tocoo(copy=copy)
  736. def tolil(self, copy=False):
  737. """Convert this matrix to LInked List format.
  738. With copy=False, the data/indices may be shared between this matrix and
  739. the resultant lil_matrix.
  740. """
  741. return self.tocsr(copy=False).tolil(copy=copy)
  742. def todia(self, copy=False):
  743. """Convert this matrix to sparse DIAgonal format.
  744. With copy=False, the data/indices may be shared between this matrix and
  745. the resultant dia_matrix.
  746. """
  747. return self.tocoo(copy=copy).todia(copy=False)
  748. def tobsr(self, blocksize=None, copy=False):
  749. """Convert this matrix to Block Sparse Row format.
  750. With copy=False, the data/indices may be shared between this matrix and
  751. the resultant bsr_matrix.
  752. When blocksize=(R, C) is provided, it will be used for construction of
  753. the bsr_matrix.
  754. """
  755. return self.tocsr(copy=False).tobsr(blocksize=blocksize, copy=copy)
  756. def tocsc(self, copy=False):
  757. """Convert this matrix to Compressed Sparse Column format.
  758. With copy=False, the data/indices may be shared between this matrix and
  759. the resultant csc_matrix.
  760. """
  761. return self.tocsr(copy=copy).tocsc(copy=False)
  762. def copy(self):
  763. """Returns a copy of this matrix.
  764. No data/indices will be shared between the returned value and current
  765. matrix.
  766. """
  767. return self.__class__(self, copy=True)
  768. def sum(self, axis=None, dtype=None, out=None):
  769. """
  770. Sum the matrix elements over a given axis.
  771. Parameters
  772. ----------
  773. axis : {-2, -1, 0, 1, None} optional
  774. Axis along which the sum is computed. The default is to
  775. compute the sum of all the matrix elements, returning a scalar
  776. (i.e. `axis` = `None`).
  777. dtype : dtype, optional
  778. The type of the returned matrix and of the accumulator in which
  779. the elements are summed. The dtype of `a` is used by default
  780. unless `a` has an integer dtype of less precision than the default
  781. platform integer. In that case, if `a` is signed then the platform
  782. integer is used while if `a` is unsigned then an unsigned integer
  783. of the same precision as the platform integer is used.
  784. .. versionadded:: 0.18.0
  785. out : np.matrix, optional
  786. Alternative output matrix in which to place the result. It must
  787. have the same shape as the expected output, but the type of the
  788. output values will be cast if necessary.
  789. .. versionadded:: 0.18.0
  790. Returns
  791. -------
  792. sum_along_axis : np.matrix
  793. A matrix with the same shape as `self`, with the specified
  794. axis removed.
  795. See Also
  796. --------
  797. np.matrix.sum : NumPy's implementation of 'sum' for matrices
  798. """
  799. validateaxis(axis)
  800. # We use multiplication by a matrix of ones to achieve this.
  801. # For some sparse matrix formats more efficient methods are
  802. # possible -- these should override this function.
  803. m, n = self.shape
  804. # Mimic numpy's casting.
  805. res_dtype = get_sum_dtype(self.dtype)
  806. if axis is None:
  807. # sum over rows and columns
  808. return (self * np.asmatrix(np.ones(
  809. (n, 1), dtype=res_dtype))).sum(
  810. dtype=dtype, out=out)
  811. if axis < 0:
  812. axis += 2
  813. # axis = 0 or 1 now
  814. if axis == 0:
  815. # sum over columns
  816. ret = np.asmatrix(np.ones(
  817. (1, m), dtype=res_dtype)) * self
  818. else:
  819. # sum over rows
  820. ret = self * np.asmatrix(
  821. np.ones((n, 1), dtype=res_dtype))
  822. if out is not None and out.shape != ret.shape:
  823. raise ValueError("dimensions do not match")
  824. return ret.sum(axis=(), dtype=dtype, out=out)
  825. def mean(self, axis=None, dtype=None, out=None):
  826. """
  827. Compute the arithmetic mean along the specified axis.
  828. Returns the average of the matrix elements. The average is taken
  829. over all elements in the matrix by default, otherwise over the
  830. specified axis. `float64` intermediate and return values are used
  831. for integer inputs.
  832. Parameters
  833. ----------
  834. axis : {-2, -1, 0, 1, None} optional
  835. Axis along which the mean is computed. The default is to compute
  836. the mean of all elements in the matrix (i.e. `axis` = `None`).
  837. dtype : data-type, optional
  838. Type to use in computing the mean. For integer inputs, the default
  839. is `float64`; for floating point inputs, it is the same as the
  840. input dtype.
  841. .. versionadded:: 0.18.0
  842. out : np.matrix, optional
  843. Alternative output matrix in which to place the result. It must
  844. have the same shape as the expected output, but the type of the
  845. output values will be cast if necessary.
  846. .. versionadded:: 0.18.0
  847. Returns
  848. -------
  849. m : np.matrix
  850. See Also
  851. --------
  852. np.matrix.mean : NumPy's implementation of 'mean' for matrices
  853. """
  854. def _is_integral(dtype):
  855. return (np.issubdtype(dtype, np.integer) or
  856. np.issubdtype(dtype, np.bool_))
  857. validateaxis(axis)
  858. res_dtype = self.dtype.type
  859. integral = _is_integral(self.dtype)
  860. # output dtype
  861. if dtype is None:
  862. if integral:
  863. res_dtype = np.float64
  864. else:
  865. res_dtype = np.dtype(dtype).type
  866. # intermediate dtype for summation
  867. inter_dtype = np.float64 if integral else res_dtype
  868. inter_self = self.astype(inter_dtype)
  869. if axis is None:
  870. return (inter_self / np.array(
  871. self.shape[0] * self.shape[1]))\
  872. .sum(dtype=res_dtype, out=out)
  873. if axis < 0:
  874. axis += 2
  875. # axis = 0 or 1 now
  876. if axis == 0:
  877. return (inter_self * (1.0 / self.shape[0])).sum(
  878. axis=0, dtype=res_dtype, out=out)
  879. else:
  880. return (inter_self * (1.0 / self.shape[1])).sum(
  881. axis=1, dtype=res_dtype, out=out)
  882. def diagonal(self, k=0):
  883. """Returns the k-th diagonal of the matrix.
  884. Parameters
  885. ----------
  886. k : int, optional
  887. Which diagonal to set, corresponding to elements a[i, i+k].
  888. Default: 0 (the main diagonal).
  889. .. versionadded:: 1.0
  890. See also
  891. --------
  892. numpy.diagonal : Equivalent numpy function.
  893. Examples
  894. --------
  895. >>> from scipy.sparse import csr_matrix
  896. >>> A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
  897. >>> A.diagonal()
  898. array([1, 0, 5])
  899. >>> A.diagonal(k=1)
  900. array([2, 3])
  901. """
  902. return self.tocsr().diagonal(k=k)
  903. def setdiag(self, values, k=0):
  904. """
  905. Set diagonal or off-diagonal elements of the array.
  906. Parameters
  907. ----------
  908. values : array_like
  909. New values of the diagonal elements.
  910. Values may have any length. If the diagonal is longer than values,
  911. then the remaining diagonal entries will not be set. If values if
  912. longer than the diagonal, then the remaining values are ignored.
  913. If a scalar value is given, all of the diagonal is set to it.
  914. k : int, optional
  915. Which off-diagonal to set, corresponding to elements a[i,i+k].
  916. Default: 0 (the main diagonal).
  917. """
  918. M, N = self.shape
  919. if (k > 0 and k >= N) or (k < 0 and -k >= M):
  920. raise ValueError("k exceeds matrix dimensions")
  921. self._setdiag(np.asarray(values), k)
  922. def _setdiag(self, values, k):
  923. M, N = self.shape
  924. if k < 0:
  925. if values.ndim == 0:
  926. # broadcast
  927. max_index = min(M+k, N)
  928. for i in xrange(max_index):
  929. self[i - k, i] = values
  930. else:
  931. max_index = min(M+k, N, len(values))
  932. if max_index <= 0:
  933. return
  934. for i, v in enumerate(values[:max_index]):
  935. self[i - k, i] = v
  936. else:
  937. if values.ndim == 0:
  938. # broadcast
  939. max_index = min(M, N-k)
  940. for i in xrange(max_index):
  941. self[i, i + k] = values
  942. else:
  943. max_index = min(M, N-k, len(values))
  944. if max_index <= 0:
  945. return
  946. for i, v in enumerate(values[:max_index]):
  947. self[i, i + k] = v
  948. def _process_toarray_args(self, order, out):
  949. if out is not None:
  950. if order is not None:
  951. raise ValueError('order cannot be specified if out '
  952. 'is not None')
  953. if out.shape != self.shape or out.dtype != self.dtype:
  954. raise ValueError('out array must be same dtype and shape as '
  955. 'sparse matrix')
  956. out[...] = 0.
  957. return out
  958. else:
  959. return np.zeros(self.shape, dtype=self.dtype, order=order)
  960. def isspmatrix(x):
  961. """Is x of a sparse matrix type?
  962. Parameters
  963. ----------
  964. x
  965. object to check for being a sparse matrix
  966. Returns
  967. -------
  968. bool
  969. True if x is a sparse matrix, False otherwise
  970. Notes
  971. -----
  972. issparse and isspmatrix are aliases for the same function.
  973. Examples
  974. --------
  975. >>> from scipy.sparse import csr_matrix, isspmatrix
  976. >>> isspmatrix(csr_matrix([[5]]))
  977. True
  978. >>> from scipy.sparse import isspmatrix
  979. >>> isspmatrix(5)
  980. False
  981. """
  982. return isinstance(x, spmatrix)
  983. issparse = isspmatrix