linalg.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. from __future__ import annotations
  2. from ._dtypes import (
  3. _floating_dtypes,
  4. _numeric_dtypes,
  5. float32,
  6. float64,
  7. complex64,
  8. complex128
  9. )
  10. from ._manipulation_functions import reshape
  11. from ._array_object import Array
  12. from ..core.numeric import normalize_axis_tuple
  13. from typing import TYPE_CHECKING
  14. if TYPE_CHECKING:
  15. from ._typing import Literal, Optional, Sequence, Tuple, Union, Dtype
  16. from typing import NamedTuple
  17. import numpy.linalg
  18. import numpy as np
  19. class EighResult(NamedTuple):
  20. eigenvalues: Array
  21. eigenvectors: Array
  22. class QRResult(NamedTuple):
  23. Q: Array
  24. R: Array
  25. class SlogdetResult(NamedTuple):
  26. sign: Array
  27. logabsdet: Array
  28. class SVDResult(NamedTuple):
  29. U: Array
  30. S: Array
  31. Vh: Array
  32. # Note: the inclusion of the upper keyword is different from
  33. # np.linalg.cholesky, which does not have it.
  34. def cholesky(x: Array, /, *, upper: bool = False) -> Array:
  35. """
  36. Array API compatible wrapper for :py:func:`np.linalg.cholesky <numpy.linalg.cholesky>`.
  37. See its docstring for more information.
  38. """
  39. # Note: the restriction to floating-point dtypes only is different from
  40. # np.linalg.cholesky.
  41. if x.dtype not in _floating_dtypes:
  42. raise TypeError('Only floating-point dtypes are allowed in cholesky')
  43. L = np.linalg.cholesky(x._array)
  44. if upper:
  45. return Array._new(L).mT
  46. return Array._new(L)
  47. # Note: cross is the numpy top-level namespace, not np.linalg
  48. def cross(x1: Array, x2: Array, /, *, axis: int = -1) -> Array:
  49. """
  50. Array API compatible wrapper for :py:func:`np.cross <numpy.cross>`.
  51. See its docstring for more information.
  52. """
  53. if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
  54. raise TypeError('Only numeric dtypes are allowed in cross')
  55. # Note: this is different from np.cross(), which broadcasts
  56. if x1.shape != x2.shape:
  57. raise ValueError('x1 and x2 must have the same shape')
  58. if x1.ndim == 0:
  59. raise ValueError('cross() requires arrays of dimension at least 1')
  60. # Note: this is different from np.cross(), which allows dimension 2
  61. if x1.shape[axis] != 3:
  62. raise ValueError('cross() dimension must equal 3')
  63. return Array._new(np.cross(x1._array, x2._array, axis=axis))
  64. def det(x: Array, /) -> Array:
  65. """
  66. Array API compatible wrapper for :py:func:`np.linalg.det <numpy.linalg.det>`.
  67. See its docstring for more information.
  68. """
  69. # Note: the restriction to floating-point dtypes only is different from
  70. # np.linalg.det.
  71. if x.dtype not in _floating_dtypes:
  72. raise TypeError('Only floating-point dtypes are allowed in det')
  73. return Array._new(np.linalg.det(x._array))
  74. # Note: diagonal is the numpy top-level namespace, not np.linalg
  75. def diagonal(x: Array, /, *, offset: int = 0) -> Array:
  76. """
  77. Array API compatible wrapper for :py:func:`np.diagonal <numpy.diagonal>`.
  78. See its docstring for more information.
  79. """
  80. # Note: diagonal always operates on the last two axes, whereas np.diagonal
  81. # operates on the first two axes by default
  82. return Array._new(np.diagonal(x._array, offset=offset, axis1=-2, axis2=-1))
  83. def eigh(x: Array, /) -> EighResult:
  84. """
  85. Array API compatible wrapper for :py:func:`np.linalg.eigh <numpy.linalg.eigh>`.
  86. See its docstring for more information.
  87. """
  88. # Note: the restriction to floating-point dtypes only is different from
  89. # np.linalg.eigh.
  90. if x.dtype not in _floating_dtypes:
  91. raise TypeError('Only floating-point dtypes are allowed in eigh')
  92. # Note: the return type here is a namedtuple, which is different from
  93. # np.eigh, which only returns a tuple.
  94. return EighResult(*map(Array._new, np.linalg.eigh(x._array)))
  95. def eigvalsh(x: Array, /) -> Array:
  96. """
  97. Array API compatible wrapper for :py:func:`np.linalg.eigvalsh <numpy.linalg.eigvalsh>`.
  98. See its docstring for more information.
  99. """
  100. # Note: the restriction to floating-point dtypes only is different from
  101. # np.linalg.eigvalsh.
  102. if x.dtype not in _floating_dtypes:
  103. raise TypeError('Only floating-point dtypes are allowed in eigvalsh')
  104. return Array._new(np.linalg.eigvalsh(x._array))
  105. def inv(x: Array, /) -> Array:
  106. """
  107. Array API compatible wrapper for :py:func:`np.linalg.inv <numpy.linalg.inv>`.
  108. See its docstring for more information.
  109. """
  110. # Note: the restriction to floating-point dtypes only is different from
  111. # np.linalg.inv.
  112. if x.dtype not in _floating_dtypes:
  113. raise TypeError('Only floating-point dtypes are allowed in inv')
  114. return Array._new(np.linalg.inv(x._array))
  115. # Note: matmul is the numpy top-level namespace but not in np.linalg
  116. def matmul(x1: Array, x2: Array, /) -> Array:
  117. """
  118. Array API compatible wrapper for :py:func:`np.matmul <numpy.matmul>`.
  119. See its docstring for more information.
  120. """
  121. # Note: the restriction to numeric dtypes only is different from
  122. # np.matmul.
  123. if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
  124. raise TypeError('Only numeric dtypes are allowed in matmul')
  125. return Array._new(np.matmul(x1._array, x2._array))
  126. # Note: the name here is different from norm(). The array API norm is split
  127. # into matrix_norm and vector_norm().
  128. # The type for ord should be Optional[Union[int, float, Literal[np.inf,
  129. # -np.inf, 'fro', 'nuc']]], but Literal does not support floating-point
  130. # literals.
  131. def matrix_norm(x: Array, /, *, keepdims: bool = False, ord: Optional[Union[int, float, Literal['fro', 'nuc']]] = 'fro') -> Array:
  132. """
  133. Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`.
  134. See its docstring for more information.
  135. """
  136. # Note: the restriction to floating-point dtypes only is different from
  137. # np.linalg.norm.
  138. if x.dtype not in _floating_dtypes:
  139. raise TypeError('Only floating-point dtypes are allowed in matrix_norm')
  140. return Array._new(np.linalg.norm(x._array, axis=(-2, -1), keepdims=keepdims, ord=ord))
  141. def matrix_power(x: Array, n: int, /) -> Array:
  142. """
  143. Array API compatible wrapper for :py:func:`np.matrix_power <numpy.matrix_power>`.
  144. See its docstring for more information.
  145. """
  146. # Note: the restriction to floating-point dtypes only is different from
  147. # np.linalg.matrix_power.
  148. if x.dtype not in _floating_dtypes:
  149. raise TypeError('Only floating-point dtypes are allowed for the first argument of matrix_power')
  150. # np.matrix_power already checks if n is an integer
  151. return Array._new(np.linalg.matrix_power(x._array, n))
  152. # Note: the keyword argument name rtol is different from np.linalg.matrix_rank
  153. def matrix_rank(x: Array, /, *, rtol: Optional[Union[float, Array]] = None) -> Array:
  154. """
  155. Array API compatible wrapper for :py:func:`np.matrix_rank <numpy.matrix_rank>`.
  156. See its docstring for more information.
  157. """
  158. # Note: this is different from np.linalg.matrix_rank, which supports 1
  159. # dimensional arrays.
  160. if x.ndim < 2:
  161. raise np.linalg.LinAlgError("1-dimensional array given. Array must be at least two-dimensional")
  162. S = np.linalg.svd(x._array, compute_uv=False)
  163. if rtol is None:
  164. tol = S.max(axis=-1, keepdims=True) * max(x.shape[-2:]) * np.finfo(S.dtype).eps
  165. else:
  166. if isinstance(rtol, Array):
  167. rtol = rtol._array
  168. # Note: this is different from np.linalg.matrix_rank, which does not multiply
  169. # the tolerance by the largest singular value.
  170. tol = S.max(axis=-1, keepdims=True)*np.asarray(rtol)[..., np.newaxis]
  171. return Array._new(np.count_nonzero(S > tol, axis=-1))
  172. # Note: this function is new in the array API spec. Unlike transpose, it only
  173. # transposes the last two axes.
  174. def matrix_transpose(x: Array, /) -> Array:
  175. if x.ndim < 2:
  176. raise ValueError("x must be at least 2-dimensional for matrix_transpose")
  177. return Array._new(np.swapaxes(x._array, -1, -2))
  178. # Note: outer is the numpy top-level namespace, not np.linalg
  179. def outer(x1: Array, x2: Array, /) -> Array:
  180. """
  181. Array API compatible wrapper for :py:func:`np.outer <numpy.outer>`.
  182. See its docstring for more information.
  183. """
  184. # Note: the restriction to numeric dtypes only is different from
  185. # np.outer.
  186. if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
  187. raise TypeError('Only numeric dtypes are allowed in outer')
  188. # Note: the restriction to only 1-dim arrays is different from np.outer
  189. if x1.ndim != 1 or x2.ndim != 1:
  190. raise ValueError('The input arrays to outer must be 1-dimensional')
  191. return Array._new(np.outer(x1._array, x2._array))
  192. # Note: the keyword argument name rtol is different from np.linalg.pinv
  193. def pinv(x: Array, /, *, rtol: Optional[Union[float, Array]] = None) -> Array:
  194. """
  195. Array API compatible wrapper for :py:func:`np.linalg.pinv <numpy.linalg.pinv>`.
  196. See its docstring for more information.
  197. """
  198. # Note: the restriction to floating-point dtypes only is different from
  199. # np.linalg.pinv.
  200. if x.dtype not in _floating_dtypes:
  201. raise TypeError('Only floating-point dtypes are allowed in pinv')
  202. # Note: this is different from np.linalg.pinv, which does not multiply the
  203. # default tolerance by max(M, N).
  204. if rtol is None:
  205. rtol = max(x.shape[-2:]) * np.finfo(x.dtype).eps
  206. return Array._new(np.linalg.pinv(x._array, rcond=rtol))
  207. def qr(x: Array, /, *, mode: Literal['reduced', 'complete'] = 'reduced') -> QRResult:
  208. """
  209. Array API compatible wrapper for :py:func:`np.linalg.qr <numpy.linalg.qr>`.
  210. See its docstring for more information.
  211. """
  212. # Note: the restriction to floating-point dtypes only is different from
  213. # np.linalg.qr.
  214. if x.dtype not in _floating_dtypes:
  215. raise TypeError('Only floating-point dtypes are allowed in qr')
  216. # Note: the return type here is a namedtuple, which is different from
  217. # np.linalg.qr, which only returns a tuple.
  218. return QRResult(*map(Array._new, np.linalg.qr(x._array, mode=mode)))
  219. def slogdet(x: Array, /) -> SlogdetResult:
  220. """
  221. Array API compatible wrapper for :py:func:`np.linalg.slogdet <numpy.linalg.slogdet>`.
  222. See its docstring for more information.
  223. """
  224. # Note: the restriction to floating-point dtypes only is different from
  225. # np.linalg.slogdet.
  226. if x.dtype not in _floating_dtypes:
  227. raise TypeError('Only floating-point dtypes are allowed in slogdet')
  228. # Note: the return type here is a namedtuple, which is different from
  229. # np.linalg.slogdet, which only returns a tuple.
  230. return SlogdetResult(*map(Array._new, np.linalg.slogdet(x._array)))
  231. # Note: unlike np.linalg.solve, the array API solve() only accepts x2 as a
  232. # vector when it is exactly 1-dimensional. All other cases treat x2 as a stack
  233. # of matrices. The np.linalg.solve behavior of allowing stacks of both
  234. # matrices and vectors is ambiguous c.f.
  235. # https://github.com/numpy/numpy/issues/15349 and
  236. # https://github.com/data-apis/array-api/issues/285.
  237. # To workaround this, the below is the code from np.linalg.solve except
  238. # only calling solve1 in the exactly 1D case.
  239. def _solve(a, b):
  240. from ..linalg.linalg import (_makearray, _assert_stacked_2d,
  241. _assert_stacked_square, _commonType,
  242. isComplexType, get_linalg_error_extobj,
  243. _raise_linalgerror_singular)
  244. from ..linalg import _umath_linalg
  245. a, _ = _makearray(a)
  246. _assert_stacked_2d(a)
  247. _assert_stacked_square(a)
  248. b, wrap = _makearray(b)
  249. t, result_t = _commonType(a, b)
  250. # This part is different from np.linalg.solve
  251. if b.ndim == 1:
  252. gufunc = _umath_linalg.solve1
  253. else:
  254. gufunc = _umath_linalg.solve
  255. # This does nothing currently but is left in because it will be relevant
  256. # when complex dtype support is added to the spec in 2022.
  257. signature = 'DD->D' if isComplexType(t) else 'dd->d'
  258. extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
  259. r = gufunc(a, b, signature=signature, extobj=extobj)
  260. return wrap(r.astype(result_t, copy=False))
  261. def solve(x1: Array, x2: Array, /) -> Array:
  262. """
  263. Array API compatible wrapper for :py:func:`np.linalg.solve <numpy.linalg.solve>`.
  264. See its docstring for more information.
  265. """
  266. # Note: the restriction to floating-point dtypes only is different from
  267. # np.linalg.solve.
  268. if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes:
  269. raise TypeError('Only floating-point dtypes are allowed in solve')
  270. return Array._new(_solve(x1._array, x2._array))
  271. def svd(x: Array, /, *, full_matrices: bool = True) -> SVDResult:
  272. """
  273. Array API compatible wrapper for :py:func:`np.linalg.svd <numpy.linalg.svd>`.
  274. See its docstring for more information.
  275. """
  276. # Note: the restriction to floating-point dtypes only is different from
  277. # np.linalg.svd.
  278. if x.dtype not in _floating_dtypes:
  279. raise TypeError('Only floating-point dtypes are allowed in svd')
  280. # Note: the return type here is a namedtuple, which is different from
  281. # np.svd, which only returns a tuple.
  282. return SVDResult(*map(Array._new, np.linalg.svd(x._array, full_matrices=full_matrices)))
  283. # Note: svdvals is not in NumPy (but it is in SciPy). It is equivalent to
  284. # np.linalg.svd(compute_uv=False).
  285. def svdvals(x: Array, /) -> Union[Array, Tuple[Array, ...]]:
  286. if x.dtype not in _floating_dtypes:
  287. raise TypeError('Only floating-point dtypes are allowed in svdvals')
  288. return Array._new(np.linalg.svd(x._array, compute_uv=False))
  289. # Note: tensordot is the numpy top-level namespace but not in np.linalg
  290. # Note: axes must be a tuple, unlike np.tensordot where it can be an array or array-like.
  291. def tensordot(x1: Array, x2: Array, /, *, axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2) -> Array:
  292. # Note: the restriction to numeric dtypes only is different from
  293. # np.tensordot.
  294. if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
  295. raise TypeError('Only numeric dtypes are allowed in tensordot')
  296. return Array._new(np.tensordot(x1._array, x2._array, axes=axes))
  297. # Note: trace is the numpy top-level namespace, not np.linalg
  298. def trace(x: Array, /, *, offset: int = 0, dtype: Optional[Dtype] = None) -> Array:
  299. """
  300. Array API compatible wrapper for :py:func:`np.trace <numpy.trace>`.
  301. See its docstring for more information.
  302. """
  303. if x.dtype not in _numeric_dtypes:
  304. raise TypeError('Only numeric dtypes are allowed in trace')
  305. # Note: trace() works the same as sum() and prod() (see
  306. # _statistical_functions.py)
  307. if dtype is None:
  308. if x.dtype == float32:
  309. dtype = float64
  310. elif x.dtype == complex64:
  311. dtype = complex128
  312. # Note: trace always operates on the last two axes, whereas np.trace
  313. # operates on the first two axes by default
  314. return Array._new(np.asarray(np.trace(x._array, offset=offset, axis1=-2, axis2=-1, dtype=dtype)))
  315. # Note: vecdot is not in NumPy
  316. def vecdot(x1: Array, x2: Array, /, *, axis: int = -1) -> Array:
  317. if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
  318. raise TypeError('Only numeric dtypes are allowed in vecdot')
  319. ndim = max(x1.ndim, x2.ndim)
  320. x1_shape = (1,)*(ndim - x1.ndim) + tuple(x1.shape)
  321. x2_shape = (1,)*(ndim - x2.ndim) + tuple(x2.shape)
  322. if x1_shape[axis] != x2_shape[axis]:
  323. raise ValueError("x1 and x2 must have the same size along the given axis")
  324. x1_, x2_ = np.broadcast_arrays(x1._array, x2._array)
  325. x1_ = np.moveaxis(x1_, axis, -1)
  326. x2_ = np.moveaxis(x2_, axis, -1)
  327. res = x1_[..., None, :] @ x2_[..., None]
  328. return Array._new(res[..., 0, 0])
  329. # Note: the name here is different from norm(). The array API norm is split
  330. # into matrix_norm and vector_norm().
  331. # The type for ord should be Optional[Union[int, float, Literal[np.inf,
  332. # -np.inf]]] but Literal does not support floating-point literals.
  333. def vector_norm(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> Array:
  334. """
  335. Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`.
  336. See its docstring for more information.
  337. """
  338. # Note: the restriction to floating-point dtypes only is different from
  339. # np.linalg.norm.
  340. if x.dtype not in _floating_dtypes:
  341. raise TypeError('Only floating-point dtypes are allowed in norm')
  342. # np.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or
  343. # when axis=None and the input is 2-D, so to force a vector norm, we make
  344. # it so the input is 1-D (for axis=None), or reshape so that norm is done
  345. # on a single dimension.
  346. a = x._array
  347. if axis is None:
  348. # Note: np.linalg.norm() doesn't handle 0-D arrays
  349. a = a.ravel()
  350. _axis = 0
  351. elif isinstance(axis, tuple):
  352. # Note: The axis argument supports any number of axes, whereas
  353. # np.linalg.norm() only supports a single axis for vector norm.
  354. normalized_axis = normalize_axis_tuple(axis, x.ndim)
  355. rest = tuple(i for i in range(a.ndim) if i not in normalized_axis)
  356. newshape = axis + rest
  357. a = np.transpose(a, newshape).reshape(
  358. (np.prod([a.shape[i] for i in axis], dtype=int), *[a.shape[i] for i in rest]))
  359. _axis = 0
  360. else:
  361. _axis = axis
  362. res = Array._new(np.linalg.norm(a, axis=_axis, ord=ord))
  363. if keepdims:
  364. # We can't reuse np.linalg.norm(keepdims) because of the reshape hacks
  365. # above to avoid matrix norm logic.
  366. shape = list(x.shape)
  367. _axis = normalize_axis_tuple(range(x.ndim) if axis is None else axis, x.ndim)
  368. for i in _axis:
  369. shape[i] = 1
  370. res = reshape(res, tuple(shape))
  371. return res
  372. __all__ = ['cholesky', 'cross', 'det', 'diagonal', 'eigh', 'eigvalsh', 'inv', 'matmul', 'matrix_norm', 'matrix_power', 'matrix_rank', 'matrix_transpose', 'outer', 'pinv', 'qr', 'slogdet', 'solve', 'svd', 'svdvals', 'tensordot', 'trace', 'vecdot', 'vector_norm']