_sputils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. """ Utility functions for sparse matrix module
  2. """
  3. import sys
  4. from typing import Any, Literal, Union
  5. import operator
  6. import numpy as np
  7. from math import prod
  8. import scipy.sparse as sp
  9. from scipy._lib._util import np_long, np_ulong
  10. __all__ = ['upcast', 'getdtype', 'getdata', 'isscalarlike', 'isintlike',
  11. 'isshape', 'issequence', 'isdense', 'ismatrix', 'get_sum_dtype',
  12. 'broadcast_shapes']
  13. supported_dtypes = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc,
  14. np.uintc, np_long, np_ulong, np.longlong, np.ulonglong,
  15. np.float32, np.float64, np.longdouble,
  16. np.complex64, np.complex128, np.clongdouble]
  17. _upcast_memo = {}
  18. def upcast(*args):
  19. """Returns the nearest supported sparse dtype for the
  20. combination of one or more types.
  21. upcast(t0, t1, ..., tn) -> T where T is a supported dtype
  22. Examples
  23. --------
  24. >>> from scipy.sparse._sputils import upcast
  25. >>> upcast('int32')
  26. <class 'numpy.int32'>
  27. >>> upcast('bool')
  28. <class 'numpy.bool'>
  29. >>> upcast('int32','float32')
  30. <class 'numpy.float64'>
  31. >>> upcast('bool',complex,float)
  32. <class 'numpy.complex128'>
  33. """
  34. t = _upcast_memo.get(hash(args))
  35. if t is not None:
  36. return t
  37. upcast = np.result_type(*args)
  38. for t in supported_dtypes:
  39. if np.can_cast(upcast, t):
  40. _upcast_memo[hash(args)] = t
  41. return t
  42. raise TypeError(f'no supported conversion for types: {args!r}')
  43. def upcast_char(*args):
  44. """Same as `upcast` but taking dtype.char as input (faster)."""
  45. t = _upcast_memo.get(args)
  46. if t is not None:
  47. return t
  48. t = upcast(*map(np.dtype, args))
  49. _upcast_memo[args] = t
  50. return t
  51. def upcast_scalar(dtype, scalar):
  52. """Determine data type for binary operation between an array of
  53. type `dtype` and a scalar.
  54. """
  55. return (np.array([0], dtype=dtype) * scalar).dtype
  56. def downcast_intp_index(arr):
  57. """
  58. Down-cast index array to np.intp dtype if it is of a larger dtype.
  59. Raise an error if the array contains a value that is too large for
  60. intp.
  61. """
  62. if arr.dtype.itemsize > np.dtype(np.intp).itemsize:
  63. if arr.size == 0:
  64. return arr.astype(np.intp)
  65. maxval = arr.max()
  66. minval = arr.min()
  67. if maxval > np.iinfo(np.intp).max or minval < np.iinfo(np.intp).min:
  68. raise ValueError("Cannot deal with arrays with indices larger "
  69. "than the machine maximum address size "
  70. "(e.g. 64-bit indices on 32-bit machine).")
  71. return arr.astype(np.intp)
  72. return arr
  73. def to_native(A):
  74. """
  75. Ensure that the data type of the NumPy array `A` has native byte order.
  76. `A` must be a NumPy array. If the data type of `A` does not have native
  77. byte order, a copy of `A` with a native byte order is returned. Otherwise
  78. `A` is returned.
  79. """
  80. dt = A.dtype
  81. if dt.isnative:
  82. # Don't call `asarray()` if A is already native, to avoid unnecessarily
  83. # creating a view of the input array.
  84. return A
  85. return np.asarray(A, dtype=dt.newbyteorder('native'))
  86. def getdtype(dtype, a=None, default=None):
  87. """Form a supported numpy dtype based on input arguments.
  88. Returns a valid ``numpy.dtype`` from `dtype` if not None,
  89. or else ``a.dtype`` if possible, or else the given `default`
  90. if not None, or else raise a ``TypeError``.
  91. The resulting ``dtype`` must be in ``supported_dtypes``:
  92. bool_, int8, uint8, int16, uint16, int32, uint32,
  93. int64, uint64, longlong, ulonglong, float32, float64,
  94. longdouble, complex64, complex128, clongdouble
  95. """
  96. if dtype is None:
  97. try:
  98. newdtype = a.dtype
  99. except AttributeError as e:
  100. if default is not None:
  101. newdtype = np.dtype(default)
  102. else:
  103. raise TypeError("could not interpret data type") from e
  104. else:
  105. newdtype = np.dtype(dtype)
  106. if newdtype not in supported_dtypes:
  107. supported_dtypes_fmt = ", ".join(t.__name__ for t in supported_dtypes)
  108. raise ValueError(f"scipy.sparse does not support dtype {newdtype}. "
  109. f"The only supported types are: {supported_dtypes_fmt}.")
  110. return newdtype
  111. def getdata(obj, dtype=None, copy=False) -> np.ndarray:
  112. """
  113. This is a wrapper of `np.array(obj, dtype=dtype, copy=copy)`
  114. that will generate a warning if the result is an object array.
  115. """
  116. data = np.array(obj, dtype=dtype, copy=copy)
  117. # Defer to getdtype for checking that the dtype is OK.
  118. # This is called for the validation only; we don't need the return value.
  119. getdtype(data.dtype)
  120. return data
  121. def safely_cast_index_arrays(A, idx_dtype=np.int32, msg=""):
  122. """Safely cast sparse array indices to `idx_dtype`.
  123. Check the shape of `A` to determine if it is safe to cast its index
  124. arrays to dtype `idx_dtype`. If any dimension in shape is larger than
  125. fits in the dtype, casting is unsafe so raise ``ValueError``.
  126. If safe, cast the index arrays to `idx_dtype` and return the result
  127. without changing the input `A`. The caller can assign results to `A`
  128. attributes if desired or use the recast index arrays directly.
  129. Unless downcasting is needed, the original index arrays are returned.
  130. You can test e.g. ``A.indptr is new_indptr`` to see if downcasting occurred.
  131. .. versionadded:: 1.15.0
  132. Parameters
  133. ----------
  134. A : sparse array or matrix
  135. The array for which index arrays should be downcast.
  136. idx_dtype : dtype
  137. Desired dtype. Should be an integer dtype (default: ``np.int32``).
  138. Most of scipy.sparse uses either int64 or int32.
  139. msg : string, optional
  140. A string to be added to the end of the ValueError message
  141. if the array shape is too big to fit in `idx_dtype`.
  142. The error message is ``f"<index> values too large for {msg}"``
  143. It should indicate why the downcasting is needed, e.g. "SuperLU",
  144. and defaults to f"dtype {idx_dtype}".
  145. Returns
  146. -------
  147. idx_arrays : ndarray or tuple of ndarrays
  148. Based on ``A.format``, index arrays are returned after casting to `idx_dtype`.
  149. For CSC/CSR, returns ``(indices, indptr)``.
  150. For COO, returns ``coords``.
  151. For DIA, returns ``offsets``.
  152. For BSR, returns ``(indices, indptr)``.
  153. Raises
  154. ------
  155. ValueError
  156. If the array has shape that would not fit in the new dtype, or if
  157. the sparse format does not use index arrays.
  158. Examples
  159. --------
  160. >>> import numpy as np
  161. >>> from scipy import sparse
  162. >>> data = [3]
  163. >>> coords = (np.array([3]), np.array([1])) # Note: int64 arrays
  164. >>> A = sparse.coo_array((data, coords))
  165. >>> A.coords[0].dtype
  166. dtype('int64')
  167. >>> # rescast after construction, raising exception if shape too big
  168. >>> coords = sparse.safely_cast_index_arrays(A, np.int32)
  169. >>> A.coords[0] is coords[0] # False if casting is needed
  170. False
  171. >>> A.coords = coords # set the index dtype of A
  172. >>> A.coords[0].dtype
  173. dtype('int32')
  174. """
  175. if not msg:
  176. msg = f"dtype {idx_dtype}"
  177. # check for safe downcasting
  178. max_value = np.iinfo(idx_dtype).max
  179. if A.format in ("csc", "csr"):
  180. # indptr[-1] is max b/c indptr always sorted
  181. if A.indptr[-1] > max_value:
  182. raise ValueError(f"indptr values too large for {msg}")
  183. # check shape vs dtype
  184. if max(*A.shape) > max_value:
  185. if (A.indices > max_value).any():
  186. raise ValueError(f"indices values too large for {msg}")
  187. indices = A.indices.astype(idx_dtype, copy=False)
  188. indptr = A.indptr.astype(idx_dtype, copy=False)
  189. return indices, indptr
  190. elif A.format == "coo":
  191. if max(*A.shape) > max_value:
  192. if any((co > max_value).any() for co in A.coords):
  193. raise ValueError(f"coords values too large for {msg}")
  194. return tuple(co.astype(idx_dtype, copy=False) for co in A.coords)
  195. elif A.format == "dia":
  196. if max(*A.shape) > max_value:
  197. if (A.offsets > max_value).any():
  198. raise ValueError(f"offsets values too large for {msg}")
  199. offsets = A.offsets.astype(idx_dtype, copy=False)
  200. return offsets
  201. elif A.format == 'bsr':
  202. R, C = A.blocksize
  203. if A.indptr[-1] * R > max_value:
  204. raise ValueError("indptr values too large for {msg}")
  205. if max(*A.shape) > max_value:
  206. if (A.indices * C > max_value).any():
  207. raise ValueError(f"indices values too large for {msg}")
  208. indices = A.indices.astype(idx_dtype, copy=False)
  209. indptr = A.indptr.astype(idx_dtype, copy=False)
  210. return indices, indptr
  211. else:
  212. raise TypeError(f'Format {A.format} is not associated with index arrays. '
  213. 'DOK and LIL have dict and list, not array.')
  214. def get_index_dtype(arrays=(), maxval=None, check_contents=False):
  215. """
  216. Based on input (integer) arrays `a`, determine a suitable index data
  217. type that can hold the data in the arrays.
  218. Parameters
  219. ----------
  220. arrays : tuple of array_like
  221. Input arrays whose types/contents to check
  222. maxval : float, optional
  223. Maximum value needed
  224. check_contents : bool, optional
  225. Whether to check the values in the arrays and not just their types.
  226. Default: False (check only the types)
  227. Returns
  228. -------
  229. dtype : dtype
  230. Suitable index data type (int32 or int64)
  231. Examples
  232. --------
  233. >>> import numpy as np
  234. >>> from scipy import sparse
  235. >>> # select index dtype based on shape
  236. >>> shape = (3, 3)
  237. >>> idx_dtype = sparse.get_index_dtype(maxval=max(shape))
  238. >>> data = [1.1, 3.0, 1.5]
  239. >>> indices = np.array([0, 1, 0], dtype=idx_dtype)
  240. >>> indptr = np.array([0, 2, 3, 3], dtype=idx_dtype)
  241. >>> A = sparse.csr_array((data, indices, indptr), shape=shape)
  242. >>> A.indptr.dtype
  243. dtype('int32')
  244. >>> # select based on larger of existing arrays and shape
  245. >>> shape = (3, 3)
  246. >>> idx_dtype = sparse.get_index_dtype(A.indptr, maxval=max(shape))
  247. >>> idx_dtype
  248. <class 'numpy.int32'>
  249. """
  250. # not using intc directly due to misinteractions with pythran
  251. if np.intc().itemsize != 4:
  252. return np.int64
  253. int32min = np.int32(np.iinfo(np.int32).min)
  254. int32max = np.int32(np.iinfo(np.int32).max)
  255. if maxval is not None:
  256. maxval = np.int64(maxval)
  257. if maxval > int32max:
  258. return np.int64
  259. if isinstance(arrays, np.ndarray):
  260. arrays = (arrays,)
  261. for arr in arrays:
  262. arr = np.asarray(arr)
  263. if not np.can_cast(arr.dtype, np.int32):
  264. if check_contents:
  265. if arr.size == 0:
  266. # a bigger type not needed
  267. continue
  268. elif np.issubdtype(arr.dtype, np.integer):
  269. maxval = arr.max()
  270. minval = arr.min()
  271. if minval >= int32min and maxval <= int32max:
  272. # a bigger type not needed
  273. continue
  274. return np.int64
  275. return np.int32
  276. def get_sum_dtype(dtype: np.dtype) -> np.dtype:
  277. """Mimic numpy's casting for np.sum"""
  278. if dtype.kind == 'u' and np.can_cast(dtype, np.uint):
  279. return np.uint
  280. if np.can_cast(dtype, np.int_):
  281. return np.int_
  282. return dtype
  283. def isscalarlike(x) -> bool:
  284. """Is x either a scalar, an array scalar, or a 0-dim array?"""
  285. return np.isscalar(x) or (isdense(x) and x.ndim == 0)
  286. def isintlike(x) -> bool:
  287. """Is x appropriate as an index into a sparse matrix? Returns True
  288. if it can be cast safely to a machine int.
  289. """
  290. # Fast-path check to eliminate non-scalar values. operator.index would
  291. # catch this case too, but the exception catching is slow.
  292. if np.ndim(x) != 0:
  293. return False
  294. try:
  295. operator.index(x)
  296. except (TypeError, ValueError):
  297. try:
  298. loose_int = bool(int(x) == x)
  299. except (TypeError, ValueError):
  300. return False
  301. if loose_int:
  302. msg = "Inexact indices into sparse matrices are not allowed"
  303. raise ValueError(msg)
  304. return loose_int
  305. return True
  306. def isshape(x, nonneg=False, *, allow_nd=(2,)) -> bool:
  307. """Is x a valid tuple of dimensions?
  308. If nonneg, also checks that the dimensions are non-negative.
  309. Shapes of length in the tuple allow_nd are allowed.
  310. """
  311. ndim = len(x)
  312. if ndim not in allow_nd:
  313. return False
  314. for d in x:
  315. if not isintlike(d):
  316. return False
  317. if nonneg and d < 0:
  318. return False
  319. return True
  320. def issequence(t) -> bool:
  321. return ((isinstance(t, list | tuple) and
  322. (len(t) == 0 or np.isscalar(t[0]))) or
  323. (isinstance(t, np.ndarray) and (t.ndim == 1)))
  324. def ismatrix(t) -> bool:
  325. return ((isinstance(t, list | tuple) and
  326. len(t) > 0 and issequence(t[0])) or
  327. (isinstance(t, np.ndarray) and t.ndim == 2))
  328. def isdense(x) -> bool:
  329. return isinstance(x, np.ndarray)
  330. def validateaxis(axis, *, ndim=2) -> tuple[int, ...] | None:
  331. if axis is None:
  332. return None
  333. if axis == ():
  334. raise ValueError(
  335. "sparse does not accept 0D axis (). Either use toarray (for dense) "
  336. "or copy (for sparse)."
  337. )
  338. if not isinstance(axis, tuple):
  339. # If not a tuple, check that the provided axis is actually
  340. # an integer and raise a TypeError similar to NumPy's
  341. if not np.issubdtype(np.dtype(type(axis)), np.integer):
  342. raise TypeError(f'axis must be an integer/tuple of ints, not {type(axis)}')
  343. axis = (axis,)
  344. canon_axis = []
  345. for ax in axis:
  346. if not isintlike(ax):
  347. raise TypeError(f"axis must be an integer. (given {ax})")
  348. if ax < 0:
  349. ax += ndim
  350. if ax < 0 or ax >= ndim:
  351. raise ValueError("axis out of range for ndim")
  352. canon_axis.append(ax)
  353. len_axis = len(canon_axis)
  354. if len_axis != len(set(canon_axis)):
  355. raise ValueError("duplicate value in axis")
  356. elif len_axis > ndim:
  357. raise ValueError("axis tuple has too many elements")
  358. elif len_axis == ndim:
  359. return None
  360. else:
  361. return tuple(canon_axis)
  362. def check_shape(args, current_shape=None, *, allow_nd=(2,)) -> tuple[int, ...]:
  363. """Imitate numpy.matrix handling of shape arguments
  364. Parameters
  365. ----------
  366. args : array_like
  367. Data structures providing information about the shape of the sparse array.
  368. current_shape : tuple, optional
  369. The current shape of the sparse array or matrix.
  370. If None (default), the current shape will be inferred from args.
  371. allow_nd : tuple of ints, optional default: (2,)
  372. If shape does not have a length in the tuple allow_nd an error is raised.
  373. Returns
  374. -------
  375. new_shape: tuple
  376. The new shape after validation.
  377. """
  378. if len(args) == 0:
  379. raise TypeError("function missing 1 required positional argument: 'shape'")
  380. if len(args) == 1:
  381. try:
  382. shape_iter = iter(args[0])
  383. except TypeError:
  384. new_shape = (operator.index(args[0]), )
  385. else:
  386. new_shape = tuple(operator.index(arg) for arg in shape_iter)
  387. else:
  388. new_shape = tuple(operator.index(arg) for arg in args)
  389. if current_shape is None:
  390. if len(new_shape) not in allow_nd:
  391. raise ValueError(f'shape must have length in {allow_nd}. Got {new_shape=}')
  392. if any(d < 0 for d in new_shape):
  393. raise ValueError("'shape' elements cannot be negative")
  394. else:
  395. # Check the current size only if needed
  396. current_size = prod(current_shape)
  397. # Check for negatives
  398. negative_indexes = [i for i, x in enumerate(new_shape) if x < 0]
  399. if not negative_indexes:
  400. new_size = prod(new_shape)
  401. if new_size != current_size:
  402. raise ValueError(f'cannot reshape array of size {current_size}'
  403. f' into shape {new_shape}')
  404. elif len(negative_indexes) == 1:
  405. skip = negative_indexes[0]
  406. specified = prod(new_shape[:skip] + new_shape[skip+1:])
  407. unspecified, remainder = divmod(current_size, specified)
  408. if remainder != 0:
  409. err_shape = tuple('newshape' if x < 0 else x for x in new_shape)
  410. raise ValueError(f'cannot reshape array of size {current_size}'
  411. f' into shape {err_shape}')
  412. new_shape = new_shape[:skip] + (unspecified,) + new_shape[skip+1:]
  413. else:
  414. raise ValueError('can only specify one unknown dimension')
  415. if len(new_shape) not in allow_nd:
  416. raise ValueError(f'shape must have length in {allow_nd}. Got {new_shape=}')
  417. return new_shape
  418. def broadcast_shapes(*shapes):
  419. """Check if shapes can be broadcast and return resulting shape
  420. This is similar to the NumPy ``broadcast_shapes`` function but
  421. does not check memory consequences of the resulting dense matrix.
  422. Parameters
  423. ----------
  424. *shapes : tuple of shape tuples
  425. The tuple of shapes to be considered for broadcasting.
  426. Shapes should be tuples of non-negative integers.
  427. Returns
  428. -------
  429. new_shape : tuple of integers
  430. The shape that results from broadcasting th input shapes.
  431. """
  432. if not shapes:
  433. return ()
  434. shapes = [shp if isinstance(shp, tuple | list) else (shp,) for shp in shapes]
  435. big_shp = max(shapes, key=len)
  436. out = list(big_shp)
  437. for shp in shapes:
  438. if shp is big_shp:
  439. continue
  440. for i, x in enumerate(shp, start=-len(shp)):
  441. if x != 1 and x != out[i]:
  442. if out[i] != 1:
  443. raise ValueError("shapes cannot be broadcast to a single shape.")
  444. out[i] = x
  445. return (*out,)
  446. def check_reshape_kwargs(kwargs):
  447. """Unpack keyword arguments for reshape function.
  448. This is useful because keyword arguments after star arguments are not
  449. allowed in Python 2, but star keyword arguments are. This function unpacks
  450. 'order' and 'copy' from the star keyword arguments (with defaults) and
  451. throws an error for any remaining.
  452. """
  453. order = kwargs.pop('order', 'C')
  454. copy = kwargs.pop('copy', False)
  455. if kwargs: # Some unused kwargs remain
  456. raise TypeError("reshape() got unexpected keywords arguments: "
  457. f"{', '.join(kwargs.keys())}")
  458. return order, copy
  459. def is_pydata_spmatrix(m) -> bool:
  460. """
  461. Check whether object is pydata/sparse matrix, avoiding importing the module.
  462. """
  463. base_cls = getattr(sys.modules.get('sparse'), 'SparseArray', None)
  464. return base_cls is not None and isinstance(m, base_cls)
  465. def convert_pydata_sparse_to_scipy(
  466. arg: Any,
  467. target_format: None | Literal["csc", "csr"] = None,
  468. accept_fv: Any = None,
  469. ) -> Union[Any, "sp.spmatrix"]:
  470. """
  471. Convert a pydata/sparse array to scipy sparse matrix,
  472. pass through anything else.
  473. """
  474. if is_pydata_spmatrix(arg):
  475. # The `accept_fv` keyword is new in PyData Sparse 0.15.4 (May 2024),
  476. # remove the `except` once the minimum supported version is >=0.15.4
  477. try:
  478. arg = arg.to_scipy_sparse(accept_fv=accept_fv)
  479. except TypeError:
  480. arg = arg.to_scipy_sparse()
  481. if target_format is not None:
  482. arg = arg.asformat(target_format)
  483. elif arg.format not in ("csc", "csr"):
  484. arg = arg.tocsc()
  485. return arg
  486. ###############################################################################
  487. # Wrappers for NumPy types that are deprecated
  488. # Numpy versions of these functions raise deprecation warnings, the
  489. # ones below do not.
  490. def matrix(*args, **kwargs):
  491. return np.array(*args, **kwargs).view(np.matrix)
  492. def asmatrix(data, dtype=None):
  493. if isinstance(data, np.matrix) and (dtype is None or data.dtype == dtype):
  494. return data
  495. return np.asarray(data, dtype=dtype).view(np.matrix)
  496. ###############################################################################
  497. def _todata(s) -> np.ndarray:
  498. """Access nonzero values, possibly after summing duplicates.
  499. Parameters
  500. ----------
  501. s : sparse array
  502. Input sparse array.
  503. Returns
  504. -------
  505. data: ndarray
  506. Nonzero values of the array, with shape (s.nnz,)
  507. """
  508. if isinstance(s, sp._data._data_matrix):
  509. return s._deduped_data()
  510. if isinstance(s, sp.dok_array):
  511. return np.fromiter(s.values(), dtype=s.dtype, count=s.nnz)
  512. if isinstance(s, sp.lil_array):
  513. data = np.empty(s.nnz, dtype=s.dtype)
  514. sp._csparsetools.lil_flatten_to_array(s.data, data)
  515. return data
  516. return s.tocoo()._deduped_data()