linalg.py 17 KB

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