linalg.py 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836
  1. """Lite version of scipy.linalg.
  2. Notes
  3. -----
  4. This module is a lite version of the linalg.py module in SciPy which
  5. contains high-level Python interface to the LAPACK library. The lite
  6. version only accesses the following LAPACK functions: dgesv, zgesv,
  7. dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf,
  8. zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr.
  9. """
  10. __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv',
  11. 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det',
  12. 'svd', 'eig', 'eigh', 'lstsq', 'norm', 'qr', 'cond', 'matrix_rank',
  13. 'LinAlgError', 'multi_dot']
  14. import functools
  15. import operator
  16. import warnings
  17. from typing import NamedTuple, Any
  18. from .._utils import set_module
  19. from numpy.core import (
  20. array, asarray, zeros, empty, empty_like, intc, single, double,
  21. csingle, cdouble, inexact, complexfloating, newaxis, all, Inf, dot,
  22. add, multiply, sqrt, sum, isfinite,
  23. finfo, errstate, geterrobj, moveaxis, amin, amax, prod, abs,
  24. atleast_2d, intp, asanyarray, object_, matmul,
  25. swapaxes, divide, count_nonzero, isnan, sign, argsort, sort,
  26. reciprocal
  27. )
  28. from numpy.core.multiarray import normalize_axis_index
  29. from numpy.core import overrides
  30. from numpy.lib.twodim_base import triu, eye
  31. from numpy.linalg import _umath_linalg
  32. from numpy._typing import NDArray
  33. class EigResult(NamedTuple):
  34. eigenvalues: NDArray[Any]
  35. eigenvectors: NDArray[Any]
  36. class EighResult(NamedTuple):
  37. eigenvalues: NDArray[Any]
  38. eigenvectors: NDArray[Any]
  39. class QRResult(NamedTuple):
  40. Q: NDArray[Any]
  41. R: NDArray[Any]
  42. class SlogdetResult(NamedTuple):
  43. sign: NDArray[Any]
  44. logabsdet: NDArray[Any]
  45. class SVDResult(NamedTuple):
  46. U: NDArray[Any]
  47. S: NDArray[Any]
  48. Vh: NDArray[Any]
  49. array_function_dispatch = functools.partial(
  50. overrides.array_function_dispatch, module='numpy.linalg')
  51. fortran_int = intc
  52. @set_module('numpy.linalg')
  53. class LinAlgError(ValueError):
  54. """
  55. Generic Python-exception-derived object raised by linalg functions.
  56. General purpose exception class, derived from Python's ValueError
  57. class, programmatically raised in linalg functions when a Linear
  58. Algebra-related condition would prevent further correct execution of the
  59. function.
  60. Parameters
  61. ----------
  62. None
  63. Examples
  64. --------
  65. >>> from numpy import linalg as LA
  66. >>> LA.inv(np.zeros((2,2)))
  67. Traceback (most recent call last):
  68. File "<stdin>", line 1, in <module>
  69. File "...linalg.py", line 350,
  70. in inv return wrap(solve(a, identity(a.shape[0], dtype=a.dtype)))
  71. File "...linalg.py", line 249,
  72. in solve
  73. raise LinAlgError('Singular matrix')
  74. numpy.linalg.LinAlgError: Singular matrix
  75. """
  76. def _determine_error_states():
  77. errobj = geterrobj()
  78. bufsize = errobj[0]
  79. with errstate(invalid='call', over='ignore',
  80. divide='ignore', under='ignore'):
  81. invalid_call_errmask = geterrobj()[1]
  82. return [bufsize, invalid_call_errmask, None]
  83. # Dealing with errors in _umath_linalg
  84. _linalg_error_extobj = _determine_error_states()
  85. del _determine_error_states
  86. def _raise_linalgerror_singular(err, flag):
  87. raise LinAlgError("Singular matrix")
  88. def _raise_linalgerror_nonposdef(err, flag):
  89. raise LinAlgError("Matrix is not positive definite")
  90. def _raise_linalgerror_eigenvalues_nonconvergence(err, flag):
  91. raise LinAlgError("Eigenvalues did not converge")
  92. def _raise_linalgerror_svd_nonconvergence(err, flag):
  93. raise LinAlgError("SVD did not converge")
  94. def _raise_linalgerror_lstsq(err, flag):
  95. raise LinAlgError("SVD did not converge in Linear Least Squares")
  96. def _raise_linalgerror_qr(err, flag):
  97. raise LinAlgError("Incorrect argument found while performing "
  98. "QR factorization")
  99. def get_linalg_error_extobj(callback):
  100. extobj = list(_linalg_error_extobj) # make a copy
  101. extobj[2] = callback
  102. return extobj
  103. def _makearray(a):
  104. new = asarray(a)
  105. wrap = getattr(a, "__array_prepare__", new.__array_wrap__)
  106. return new, wrap
  107. def isComplexType(t):
  108. return issubclass(t, complexfloating)
  109. _real_types_map = {single : single,
  110. double : double,
  111. csingle : single,
  112. cdouble : double}
  113. _complex_types_map = {single : csingle,
  114. double : cdouble,
  115. csingle : csingle,
  116. cdouble : cdouble}
  117. def _realType(t, default=double):
  118. return _real_types_map.get(t, default)
  119. def _complexType(t, default=cdouble):
  120. return _complex_types_map.get(t, default)
  121. def _commonType(*arrays):
  122. # in lite version, use higher precision (always double or cdouble)
  123. result_type = single
  124. is_complex = False
  125. for a in arrays:
  126. type_ = a.dtype.type
  127. if issubclass(type_, inexact):
  128. if isComplexType(type_):
  129. is_complex = True
  130. rt = _realType(type_, default=None)
  131. if rt is double:
  132. result_type = double
  133. elif rt is None:
  134. # unsupported inexact scalar
  135. raise TypeError("array type %s is unsupported in linalg" %
  136. (a.dtype.name,))
  137. else:
  138. result_type = double
  139. if is_complex:
  140. result_type = _complex_types_map[result_type]
  141. return cdouble, result_type
  142. else:
  143. return double, result_type
  144. def _to_native_byte_order(*arrays):
  145. ret = []
  146. for arr in arrays:
  147. if arr.dtype.byteorder not in ('=', '|'):
  148. ret.append(asarray(arr, dtype=arr.dtype.newbyteorder('=')))
  149. else:
  150. ret.append(arr)
  151. if len(ret) == 1:
  152. return ret[0]
  153. else:
  154. return ret
  155. def _assert_2d(*arrays):
  156. for a in arrays:
  157. if a.ndim != 2:
  158. raise LinAlgError('%d-dimensional array given. Array must be '
  159. 'two-dimensional' % a.ndim)
  160. def _assert_stacked_2d(*arrays):
  161. for a in arrays:
  162. if a.ndim < 2:
  163. raise LinAlgError('%d-dimensional array given. Array must be '
  164. 'at least two-dimensional' % a.ndim)
  165. def _assert_stacked_square(*arrays):
  166. for a in arrays:
  167. m, n = a.shape[-2:]
  168. if m != n:
  169. raise LinAlgError('Last 2 dimensions of the array must be square')
  170. def _assert_finite(*arrays):
  171. for a in arrays:
  172. if not isfinite(a).all():
  173. raise LinAlgError("Array must not contain infs or NaNs")
  174. def _is_empty_2d(arr):
  175. # check size first for efficiency
  176. return arr.size == 0 and prod(arr.shape[-2:]) == 0
  177. def transpose(a):
  178. """
  179. Transpose each matrix in a stack of matrices.
  180. Unlike np.transpose, this only swaps the last two axes, rather than all of
  181. them
  182. Parameters
  183. ----------
  184. a : (...,M,N) array_like
  185. Returns
  186. -------
  187. aT : (...,N,M) ndarray
  188. """
  189. return swapaxes(a, -1, -2)
  190. # Linear equations
  191. def _tensorsolve_dispatcher(a, b, axes=None):
  192. return (a, b)
  193. @array_function_dispatch(_tensorsolve_dispatcher)
  194. def tensorsolve(a, b, axes=None):
  195. """
  196. Solve the tensor equation ``a x = b`` for x.
  197. It is assumed that all indices of `x` are summed over in the product,
  198. together with the rightmost indices of `a`, as is done in, for example,
  199. ``tensordot(a, x, axes=x.ndim)``.
  200. Parameters
  201. ----------
  202. a : array_like
  203. Coefficient tensor, of shape ``b.shape + Q``. `Q`, a tuple, equals
  204. the shape of that sub-tensor of `a` consisting of the appropriate
  205. number of its rightmost indices, and must be such that
  206. ``prod(Q) == prod(b.shape)`` (in which sense `a` is said to be
  207. 'square').
  208. b : array_like
  209. Right-hand tensor, which can be of any shape.
  210. axes : tuple of ints, optional
  211. Axes in `a` to reorder to the right, before inversion.
  212. If None (default), no reordering is done.
  213. Returns
  214. -------
  215. x : ndarray, shape Q
  216. Raises
  217. ------
  218. LinAlgError
  219. If `a` is singular or not 'square' (in the above sense).
  220. See Also
  221. --------
  222. numpy.tensordot, tensorinv, numpy.einsum
  223. Examples
  224. --------
  225. >>> a = np.eye(2*3*4)
  226. >>> a.shape = (2*3, 4, 2, 3, 4)
  227. >>> b = np.random.randn(2*3, 4)
  228. >>> x = np.linalg.tensorsolve(a, b)
  229. >>> x.shape
  230. (2, 3, 4)
  231. >>> np.allclose(np.tensordot(a, x, axes=3), b)
  232. True
  233. """
  234. a, wrap = _makearray(a)
  235. b = asarray(b)
  236. an = a.ndim
  237. if axes is not None:
  238. allaxes = list(range(0, an))
  239. for k in axes:
  240. allaxes.remove(k)
  241. allaxes.insert(an, k)
  242. a = a.transpose(allaxes)
  243. oldshape = a.shape[-(an-b.ndim):]
  244. prod = 1
  245. for k in oldshape:
  246. prod *= k
  247. if a.size != prod ** 2:
  248. raise LinAlgError(
  249. "Input arrays must satisfy the requirement \
  250. prod(a.shape[b.ndim:]) == prod(a.shape[:b.ndim])"
  251. )
  252. a = a.reshape(prod, prod)
  253. b = b.ravel()
  254. res = wrap(solve(a, b))
  255. res.shape = oldshape
  256. return res
  257. def _solve_dispatcher(a, b):
  258. return (a, b)
  259. @array_function_dispatch(_solve_dispatcher)
  260. def solve(a, b):
  261. """
  262. Solve a linear matrix equation, or system of linear scalar equations.
  263. Computes the "exact" solution, `x`, of the well-determined, i.e., full
  264. rank, linear matrix equation `ax = b`.
  265. Parameters
  266. ----------
  267. a : (..., M, M) array_like
  268. Coefficient matrix.
  269. b : {(..., M,), (..., M, K)}, array_like
  270. Ordinate or "dependent variable" values.
  271. Returns
  272. -------
  273. x : {(..., M,), (..., M, K)} ndarray
  274. Solution to the system a x = b. Returned shape is identical to `b`.
  275. Raises
  276. ------
  277. LinAlgError
  278. If `a` is singular or not square.
  279. See Also
  280. --------
  281. scipy.linalg.solve : Similar function in SciPy.
  282. Notes
  283. -----
  284. .. versionadded:: 1.8.0
  285. Broadcasting rules apply, see the `numpy.linalg` documentation for
  286. details.
  287. The solutions are computed using LAPACK routine ``_gesv``.
  288. `a` must be square and of full-rank, i.e., all rows (or, equivalently,
  289. columns) must be linearly independent; if either is not true, use
  290. `lstsq` for the least-squares best "solution" of the
  291. system/equation.
  292. References
  293. ----------
  294. .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
  295. FL, Academic Press, Inc., 1980, pg. 22.
  296. Examples
  297. --------
  298. Solve the system of equations ``x0 + 2 * x1 = 1`` and ``3 * x0 + 5 * x1 = 2``:
  299. >>> a = np.array([[1, 2], [3, 5]])
  300. >>> b = np.array([1, 2])
  301. >>> x = np.linalg.solve(a, b)
  302. >>> x
  303. array([-1., 1.])
  304. Check that the solution is correct:
  305. >>> np.allclose(np.dot(a, x), b)
  306. True
  307. """
  308. a, _ = _makearray(a)
  309. _assert_stacked_2d(a)
  310. _assert_stacked_square(a)
  311. b, wrap = _makearray(b)
  312. t, result_t = _commonType(a, b)
  313. # We use the b = (..., M,) logic, only if the number of extra dimensions
  314. # match exactly
  315. if b.ndim == a.ndim - 1:
  316. gufunc = _umath_linalg.solve1
  317. else:
  318. gufunc = _umath_linalg.solve
  319. signature = 'DD->D' if isComplexType(t) else 'dd->d'
  320. extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
  321. r = gufunc(a, b, signature=signature, extobj=extobj)
  322. return wrap(r.astype(result_t, copy=False))
  323. def _tensorinv_dispatcher(a, ind=None):
  324. return (a,)
  325. @array_function_dispatch(_tensorinv_dispatcher)
  326. def tensorinv(a, ind=2):
  327. """
  328. Compute the 'inverse' of an N-dimensional array.
  329. The result is an inverse for `a` relative to the tensordot operation
  330. ``tensordot(a, b, ind)``, i. e., up to floating-point accuracy,
  331. ``tensordot(tensorinv(a), a, ind)`` is the "identity" tensor for the
  332. tensordot operation.
  333. Parameters
  334. ----------
  335. a : array_like
  336. Tensor to 'invert'. Its shape must be 'square', i. e.,
  337. ``prod(a.shape[:ind]) == prod(a.shape[ind:])``.
  338. ind : int, optional
  339. Number of first indices that are involved in the inverse sum.
  340. Must be a positive integer, default is 2.
  341. Returns
  342. -------
  343. b : ndarray
  344. `a`'s tensordot inverse, shape ``a.shape[ind:] + a.shape[:ind]``.
  345. Raises
  346. ------
  347. LinAlgError
  348. If `a` is singular or not 'square' (in the above sense).
  349. See Also
  350. --------
  351. numpy.tensordot, tensorsolve
  352. Examples
  353. --------
  354. >>> a = np.eye(4*6)
  355. >>> a.shape = (4, 6, 8, 3)
  356. >>> ainv = np.linalg.tensorinv(a, ind=2)
  357. >>> ainv.shape
  358. (8, 3, 4, 6)
  359. >>> b = np.random.randn(4, 6)
  360. >>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b))
  361. True
  362. >>> a = np.eye(4*6)
  363. >>> a.shape = (24, 8, 3)
  364. >>> ainv = np.linalg.tensorinv(a, ind=1)
  365. >>> ainv.shape
  366. (8, 3, 24)
  367. >>> b = np.random.randn(24)
  368. >>> np.allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
  369. True
  370. """
  371. a = asarray(a)
  372. oldshape = a.shape
  373. prod = 1
  374. if ind > 0:
  375. invshape = oldshape[ind:] + oldshape[:ind]
  376. for k in oldshape[ind:]:
  377. prod *= k
  378. else:
  379. raise ValueError("Invalid ind argument.")
  380. a = a.reshape(prod, -1)
  381. ia = inv(a)
  382. return ia.reshape(*invshape)
  383. # Matrix inversion
  384. def _unary_dispatcher(a):
  385. return (a,)
  386. @array_function_dispatch(_unary_dispatcher)
  387. def inv(a):
  388. """
  389. Compute the (multiplicative) inverse of a matrix.
  390. Given a square matrix `a`, return the matrix `ainv` satisfying
  391. ``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.
  392. Parameters
  393. ----------
  394. a : (..., M, M) array_like
  395. Matrix to be inverted.
  396. Returns
  397. -------
  398. ainv : (..., M, M) ndarray or matrix
  399. (Multiplicative) inverse of the matrix `a`.
  400. Raises
  401. ------
  402. LinAlgError
  403. If `a` is not square or inversion fails.
  404. See Also
  405. --------
  406. scipy.linalg.inv : Similar function in SciPy.
  407. Notes
  408. -----
  409. .. versionadded:: 1.8.0
  410. Broadcasting rules apply, see the `numpy.linalg` documentation for
  411. details.
  412. Examples
  413. --------
  414. >>> from numpy.linalg import inv
  415. >>> a = np.array([[1., 2.], [3., 4.]])
  416. >>> ainv = inv(a)
  417. >>> np.allclose(np.dot(a, ainv), np.eye(2))
  418. True
  419. >>> np.allclose(np.dot(ainv, a), np.eye(2))
  420. True
  421. If a is a matrix object, then the return value is a matrix as well:
  422. >>> ainv = inv(np.matrix(a))
  423. >>> ainv
  424. matrix([[-2. , 1. ],
  425. [ 1.5, -0.5]])
  426. Inverses of several matrices can be computed at once:
  427. >>> a = np.array([[[1., 2.], [3., 4.]], [[1, 3], [3, 5]]])
  428. >>> inv(a)
  429. array([[[-2. , 1. ],
  430. [ 1.5 , -0.5 ]],
  431. [[-1.25, 0.75],
  432. [ 0.75, -0.25]]])
  433. """
  434. a, wrap = _makearray(a)
  435. _assert_stacked_2d(a)
  436. _assert_stacked_square(a)
  437. t, result_t = _commonType(a)
  438. signature = 'D->D' if isComplexType(t) else 'd->d'
  439. extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
  440. ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj)
  441. return wrap(ainv.astype(result_t, copy=False))
  442. def _matrix_power_dispatcher(a, n):
  443. return (a,)
  444. @array_function_dispatch(_matrix_power_dispatcher)
  445. def matrix_power(a, n):
  446. """
  447. Raise a square matrix to the (integer) power `n`.
  448. For positive integers `n`, the power is computed by repeated matrix
  449. squarings and matrix multiplications. If ``n == 0``, the identity matrix
  450. of the same shape as M is returned. If ``n < 0``, the inverse
  451. is computed and then raised to the ``abs(n)``.
  452. .. note:: Stacks of object matrices are not currently supported.
  453. Parameters
  454. ----------
  455. a : (..., M, M) array_like
  456. Matrix to be "powered".
  457. n : int
  458. The exponent can be any integer or long integer, positive,
  459. negative, or zero.
  460. Returns
  461. -------
  462. a**n : (..., M, M) ndarray or matrix object
  463. The return value is the same shape and type as `M`;
  464. if the exponent is positive or zero then the type of the
  465. elements is the same as those of `M`. If the exponent is
  466. negative the elements are floating-point.
  467. Raises
  468. ------
  469. LinAlgError
  470. For matrices that are not square or that (for negative powers) cannot
  471. be inverted numerically.
  472. Examples
  473. --------
  474. >>> from numpy.linalg import matrix_power
  475. >>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
  476. >>> matrix_power(i, 3) # should = -i
  477. array([[ 0, -1],
  478. [ 1, 0]])
  479. >>> matrix_power(i, 0)
  480. array([[1, 0],
  481. [0, 1]])
  482. >>> matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
  483. array([[ 0., 1.],
  484. [-1., 0.]])
  485. Somewhat more sophisticated example
  486. >>> q = np.zeros((4, 4))
  487. >>> q[0:2, 0:2] = -i
  488. >>> q[2:4, 2:4] = i
  489. >>> q # one of the three quaternion units not equal to 1
  490. array([[ 0., -1., 0., 0.],
  491. [ 1., 0., 0., 0.],
  492. [ 0., 0., 0., 1.],
  493. [ 0., 0., -1., 0.]])
  494. >>> matrix_power(q, 2) # = -np.eye(4)
  495. array([[-1., 0., 0., 0.],
  496. [ 0., -1., 0., 0.],
  497. [ 0., 0., -1., 0.],
  498. [ 0., 0., 0., -1.]])
  499. """
  500. a = asanyarray(a)
  501. _assert_stacked_2d(a)
  502. _assert_stacked_square(a)
  503. try:
  504. n = operator.index(n)
  505. except TypeError as e:
  506. raise TypeError("exponent must be an integer") from e
  507. # Fall back on dot for object arrays. Object arrays are not supported by
  508. # the current implementation of matmul using einsum
  509. if a.dtype != object:
  510. fmatmul = matmul
  511. elif a.ndim == 2:
  512. fmatmul = dot
  513. else:
  514. raise NotImplementedError(
  515. "matrix_power not supported for stacks of object arrays")
  516. if n == 0:
  517. a = empty_like(a)
  518. a[...] = eye(a.shape[-2], dtype=a.dtype)
  519. return a
  520. elif n < 0:
  521. a = inv(a)
  522. n = abs(n)
  523. # short-cuts.
  524. if n == 1:
  525. return a
  526. elif n == 2:
  527. return fmatmul(a, a)
  528. elif n == 3:
  529. return fmatmul(fmatmul(a, a), a)
  530. # Use binary decomposition to reduce the number of matrix multiplications.
  531. # Here, we iterate over the bits of n, from LSB to MSB, raise `a` to
  532. # increasing powers of 2, and multiply into the result as needed.
  533. z = result = None
  534. while n > 0:
  535. z = a if z is None else fmatmul(z, z)
  536. n, bit = divmod(n, 2)
  537. if bit:
  538. result = z if result is None else fmatmul(result, z)
  539. return result
  540. # Cholesky decomposition
  541. @array_function_dispatch(_unary_dispatcher)
  542. def cholesky(a):
  543. """
  544. Cholesky decomposition.
  545. Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`,
  546. where `L` is lower-triangular and .H is the conjugate transpose operator
  547. (which is the ordinary transpose if `a` is real-valued). `a` must be
  548. Hermitian (symmetric if real-valued) and positive-definite. No
  549. checking is performed to verify whether `a` is Hermitian or not.
  550. In addition, only the lower-triangular and diagonal elements of `a`
  551. are used. Only `L` is actually returned.
  552. Parameters
  553. ----------
  554. a : (..., M, M) array_like
  555. Hermitian (symmetric if all elements are real), positive-definite
  556. input matrix.
  557. Returns
  558. -------
  559. L : (..., M, M) array_like
  560. Lower-triangular Cholesky factor of `a`. Returns a matrix object if
  561. `a` is a matrix object.
  562. Raises
  563. ------
  564. LinAlgError
  565. If the decomposition fails, for example, if `a` is not
  566. positive-definite.
  567. See Also
  568. --------
  569. scipy.linalg.cholesky : Similar function in SciPy.
  570. scipy.linalg.cholesky_banded : Cholesky decompose a banded Hermitian
  571. positive-definite matrix.
  572. scipy.linalg.cho_factor : Cholesky decomposition of a matrix, to use in
  573. `scipy.linalg.cho_solve`.
  574. Notes
  575. -----
  576. .. versionadded:: 1.8.0
  577. Broadcasting rules apply, see the `numpy.linalg` documentation for
  578. details.
  579. The Cholesky decomposition is often used as a fast way of solving
  580. .. math:: A \\mathbf{x} = \\mathbf{b}
  581. (when `A` is both Hermitian/symmetric and positive-definite).
  582. First, we solve for :math:`\\mathbf{y}` in
  583. .. math:: L \\mathbf{y} = \\mathbf{b},
  584. and then for :math:`\\mathbf{x}` in
  585. .. math:: L.H \\mathbf{x} = \\mathbf{y}.
  586. Examples
  587. --------
  588. >>> A = np.array([[1,-2j],[2j,5]])
  589. >>> A
  590. array([[ 1.+0.j, -0.-2.j],
  591. [ 0.+2.j, 5.+0.j]])
  592. >>> L = np.linalg.cholesky(A)
  593. >>> L
  594. array([[1.+0.j, 0.+0.j],
  595. [0.+2.j, 1.+0.j]])
  596. >>> np.dot(L, L.T.conj()) # verify that L * L.H = A
  597. array([[1.+0.j, 0.-2.j],
  598. [0.+2.j, 5.+0.j]])
  599. >>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like?
  600. >>> np.linalg.cholesky(A) # an ndarray object is returned
  601. array([[1.+0.j, 0.+0.j],
  602. [0.+2.j, 1.+0.j]])
  603. >>> # But a matrix object is returned if A is a matrix object
  604. >>> np.linalg.cholesky(np.matrix(A))
  605. matrix([[ 1.+0.j, 0.+0.j],
  606. [ 0.+2.j, 1.+0.j]])
  607. """
  608. extobj = get_linalg_error_extobj(_raise_linalgerror_nonposdef)
  609. gufunc = _umath_linalg.cholesky_lo
  610. a, wrap = _makearray(a)
  611. _assert_stacked_2d(a)
  612. _assert_stacked_square(a)
  613. t, result_t = _commonType(a)
  614. signature = 'D->D' if isComplexType(t) else 'd->d'
  615. r = gufunc(a, signature=signature, extobj=extobj)
  616. return wrap(r.astype(result_t, copy=False))
  617. # QR decomposition
  618. def _qr_dispatcher(a, mode=None):
  619. return (a,)
  620. @array_function_dispatch(_qr_dispatcher)
  621. def qr(a, mode='reduced'):
  622. """
  623. Compute the qr factorization of a matrix.
  624. Factor the matrix `a` as *qr*, where `q` is orthonormal and `r` is
  625. upper-triangular.
  626. Parameters
  627. ----------
  628. a : array_like, shape (..., M, N)
  629. An array-like object with the dimensionality of at least 2.
  630. mode : {'reduced', 'complete', 'r', 'raw'}, optional
  631. If K = min(M, N), then
  632. * 'reduced' : returns Q, R with dimensions (..., M, K), (..., K, N) (default)
  633. * 'complete' : returns Q, R with dimensions (..., M, M), (..., M, N)
  634. * 'r' : returns R only with dimensions (..., K, N)
  635. * 'raw' : returns h, tau with dimensions (..., N, M), (..., K,)
  636. The options 'reduced', 'complete, and 'raw' are new in numpy 1.8,
  637. see the notes for more information. The default is 'reduced', and to
  638. maintain backward compatibility with earlier versions of numpy both
  639. it and the old default 'full' can be omitted. Note that array h
  640. returned in 'raw' mode is transposed for calling Fortran. The
  641. 'economic' mode is deprecated. The modes 'full' and 'economic' may
  642. be passed using only the first letter for backwards compatibility,
  643. but all others must be spelled out. See the Notes for more
  644. explanation.
  645. Returns
  646. -------
  647. When mode is 'reduced' or 'complete', the result will be a namedtuple with
  648. the attributes `Q` and `R`.
  649. Q : ndarray of float or complex, optional
  650. A matrix with orthonormal columns. When mode = 'complete' the
  651. result is an orthogonal/unitary matrix depending on whether or not
  652. a is real/complex. The determinant may be either +/- 1 in that
  653. case. In case the number of dimensions in the input array is
  654. greater than 2 then a stack of the matrices with above properties
  655. is returned.
  656. R : ndarray of float or complex, optional
  657. The upper-triangular matrix or a stack of upper-triangular
  658. matrices if the number of dimensions in the input array is greater
  659. than 2.
  660. (h, tau) : ndarrays of np.double or np.cdouble, optional
  661. The array h contains the Householder reflectors that generate q
  662. along with r. The tau array contains scaling factors for the
  663. reflectors. In the deprecated 'economic' mode only h is returned.
  664. Raises
  665. ------
  666. LinAlgError
  667. If factoring fails.
  668. See Also
  669. --------
  670. scipy.linalg.qr : Similar function in SciPy.
  671. scipy.linalg.rq : Compute RQ decomposition of a matrix.
  672. Notes
  673. -----
  674. This is an interface to the LAPACK routines ``dgeqrf``, ``zgeqrf``,
  675. ``dorgqr``, and ``zungqr``.
  676. For more information on the qr factorization, see for example:
  677. https://en.wikipedia.org/wiki/QR_factorization
  678. Subclasses of `ndarray` are preserved except for the 'raw' mode. So if
  679. `a` is of type `matrix`, all the return values will be matrices too.
  680. New 'reduced', 'complete', and 'raw' options for mode were added in
  681. NumPy 1.8.0 and the old option 'full' was made an alias of 'reduced'. In
  682. addition the options 'full' and 'economic' were deprecated. Because
  683. 'full' was the previous default and 'reduced' is the new default,
  684. backward compatibility can be maintained by letting `mode` default.
  685. The 'raw' option was added so that LAPACK routines that can multiply
  686. arrays by q using the Householder reflectors can be used. Note that in
  687. this case the returned arrays are of type np.double or np.cdouble and
  688. the h array is transposed to be FORTRAN compatible. No routines using
  689. the 'raw' return are currently exposed by numpy, but some are available
  690. in lapack_lite and just await the necessary work.
  691. Examples
  692. --------
  693. >>> a = np.random.randn(9, 6)
  694. >>> Q, R = np.linalg.qr(a)
  695. >>> np.allclose(a, np.dot(Q, R)) # a does equal QR
  696. True
  697. >>> R2 = np.linalg.qr(a, mode='r')
  698. >>> np.allclose(R, R2) # mode='r' returns the same R as mode='full'
  699. True
  700. >>> a = np.random.normal(size=(3, 2, 2)) # Stack of 2 x 2 matrices as input
  701. >>> Q, R = np.linalg.qr(a)
  702. >>> Q.shape
  703. (3, 2, 2)
  704. >>> R.shape
  705. (3, 2, 2)
  706. >>> np.allclose(a, np.matmul(Q, R))
  707. True
  708. Example illustrating a common use of `qr`: solving of least squares
  709. problems
  710. What are the least-squares-best `m` and `y0` in ``y = y0 + mx`` for
  711. the following data: {(0,1), (1,0), (1,2), (2,1)}. (Graph the points
  712. and you'll see that it should be y0 = 0, m = 1.) The answer is provided
  713. by solving the over-determined matrix equation ``Ax = b``, where::
  714. A = array([[0, 1], [1, 1], [1, 1], [2, 1]])
  715. x = array([[y0], [m]])
  716. b = array([[1], [0], [2], [1]])
  717. If A = QR such that Q is orthonormal (which is always possible via
  718. Gram-Schmidt), then ``x = inv(R) * (Q.T) * b``. (In numpy practice,
  719. however, we simply use `lstsq`.)
  720. >>> A = np.array([[0, 1], [1, 1], [1, 1], [2, 1]])
  721. >>> A
  722. array([[0, 1],
  723. [1, 1],
  724. [1, 1],
  725. [2, 1]])
  726. >>> b = np.array([1, 2, 2, 3])
  727. >>> Q, R = np.linalg.qr(A)
  728. >>> p = np.dot(Q.T, b)
  729. >>> np.dot(np.linalg.inv(R), p)
  730. array([ 1., 1.])
  731. """
  732. if mode not in ('reduced', 'complete', 'r', 'raw'):
  733. if mode in ('f', 'full'):
  734. # 2013-04-01, 1.8
  735. msg = "".join((
  736. "The 'full' option is deprecated in favor of 'reduced'.\n",
  737. "For backward compatibility let mode default."))
  738. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  739. mode = 'reduced'
  740. elif mode in ('e', 'economic'):
  741. # 2013-04-01, 1.8
  742. msg = "The 'economic' option is deprecated."
  743. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  744. mode = 'economic'
  745. else:
  746. raise ValueError(f"Unrecognized mode '{mode}'")
  747. a, wrap = _makearray(a)
  748. _assert_stacked_2d(a)
  749. m, n = a.shape[-2:]
  750. t, result_t = _commonType(a)
  751. a = a.astype(t, copy=True)
  752. a = _to_native_byte_order(a)
  753. mn = min(m, n)
  754. if m <= n:
  755. gufunc = _umath_linalg.qr_r_raw_m
  756. else:
  757. gufunc = _umath_linalg.qr_r_raw_n
  758. signature = 'D->D' if isComplexType(t) else 'd->d'
  759. extobj = get_linalg_error_extobj(_raise_linalgerror_qr)
  760. tau = gufunc(a, signature=signature, extobj=extobj)
  761. # handle modes that don't return q
  762. if mode == 'r':
  763. r = triu(a[..., :mn, :])
  764. r = r.astype(result_t, copy=False)
  765. return wrap(r)
  766. if mode == 'raw':
  767. q = transpose(a)
  768. q = q.astype(result_t, copy=False)
  769. tau = tau.astype(result_t, copy=False)
  770. return wrap(q), tau
  771. if mode == 'economic':
  772. a = a.astype(result_t, copy=False)
  773. return wrap(a)
  774. # mc is the number of columns in the resulting q
  775. # matrix. If the mode is complete then it is
  776. # same as number of rows, and if the mode is reduced,
  777. # then it is the minimum of number of rows and columns.
  778. if mode == 'complete' and m > n:
  779. mc = m
  780. gufunc = _umath_linalg.qr_complete
  781. else:
  782. mc = mn
  783. gufunc = _umath_linalg.qr_reduced
  784. signature = 'DD->D' if isComplexType(t) else 'dd->d'
  785. extobj = get_linalg_error_extobj(_raise_linalgerror_qr)
  786. q = gufunc(a, tau, signature=signature, extobj=extobj)
  787. r = triu(a[..., :mc, :])
  788. q = q.astype(result_t, copy=False)
  789. r = r.astype(result_t, copy=False)
  790. return QRResult(wrap(q), wrap(r))
  791. # Eigenvalues
  792. @array_function_dispatch(_unary_dispatcher)
  793. def eigvals(a):
  794. """
  795. Compute the eigenvalues of a general matrix.
  796. Main difference between `eigvals` and `eig`: the eigenvectors aren't
  797. returned.
  798. Parameters
  799. ----------
  800. a : (..., M, M) array_like
  801. A complex- or real-valued matrix whose eigenvalues will be computed.
  802. Returns
  803. -------
  804. w : (..., M,) ndarray
  805. The eigenvalues, each repeated according to its multiplicity.
  806. They are not necessarily ordered, nor are they necessarily
  807. real for real matrices.
  808. Raises
  809. ------
  810. LinAlgError
  811. If the eigenvalue computation does not converge.
  812. See Also
  813. --------
  814. eig : eigenvalues and right eigenvectors of general arrays
  815. eigvalsh : eigenvalues of real symmetric or complex Hermitian
  816. (conjugate symmetric) arrays.
  817. eigh : eigenvalues and eigenvectors of real symmetric or complex
  818. Hermitian (conjugate symmetric) arrays.
  819. scipy.linalg.eigvals : Similar function in SciPy.
  820. Notes
  821. -----
  822. .. versionadded:: 1.8.0
  823. Broadcasting rules apply, see the `numpy.linalg` documentation for
  824. details.
  825. This is implemented using the ``_geev`` LAPACK routines which compute
  826. the eigenvalues and eigenvectors of general square arrays.
  827. Examples
  828. --------
  829. Illustration, using the fact that the eigenvalues of a diagonal matrix
  830. are its diagonal elements, that multiplying a matrix on the left
  831. by an orthogonal matrix, `Q`, and on the right by `Q.T` (the transpose
  832. of `Q`), preserves the eigenvalues of the "middle" matrix. In other words,
  833. if `Q` is orthogonal, then ``Q * A * Q.T`` has the same eigenvalues as
  834. ``A``:
  835. >>> from numpy import linalg as LA
  836. >>> x = np.random.random()
  837. >>> Q = np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]])
  838. >>> LA.norm(Q[0, :]), LA.norm(Q[1, :]), np.dot(Q[0, :],Q[1, :])
  839. (1.0, 1.0, 0.0)
  840. Now multiply a diagonal matrix by ``Q`` on one side and by ``Q.T`` on the other:
  841. >>> D = np.diag((-1,1))
  842. >>> LA.eigvals(D)
  843. array([-1., 1.])
  844. >>> A = np.dot(Q, D)
  845. >>> A = np.dot(A, Q.T)
  846. >>> LA.eigvals(A)
  847. array([ 1., -1.]) # random
  848. """
  849. a, wrap = _makearray(a)
  850. _assert_stacked_2d(a)
  851. _assert_stacked_square(a)
  852. _assert_finite(a)
  853. t, result_t = _commonType(a)
  854. extobj = get_linalg_error_extobj(
  855. _raise_linalgerror_eigenvalues_nonconvergence)
  856. signature = 'D->D' if isComplexType(t) else 'd->D'
  857. w = _umath_linalg.eigvals(a, signature=signature, extobj=extobj)
  858. if not isComplexType(t):
  859. if all(w.imag == 0):
  860. w = w.real
  861. result_t = _realType(result_t)
  862. else:
  863. result_t = _complexType(result_t)
  864. return w.astype(result_t, copy=False)
  865. def _eigvalsh_dispatcher(a, UPLO=None):
  866. return (a,)
  867. @array_function_dispatch(_eigvalsh_dispatcher)
  868. def eigvalsh(a, UPLO='L'):
  869. """
  870. Compute the eigenvalues of a complex Hermitian or real symmetric matrix.
  871. Main difference from eigh: the eigenvectors are not computed.
  872. Parameters
  873. ----------
  874. a : (..., M, M) array_like
  875. A complex- or real-valued matrix whose eigenvalues are to be
  876. computed.
  877. UPLO : {'L', 'U'}, optional
  878. Specifies whether the calculation is done with the lower triangular
  879. part of `a` ('L', default) or the upper triangular part ('U').
  880. Irrespective of this value only the real parts of the diagonal will
  881. be considered in the computation to preserve the notion of a Hermitian
  882. matrix. It therefore follows that the imaginary part of the diagonal
  883. will always be treated as zero.
  884. Returns
  885. -------
  886. w : (..., M,) ndarray
  887. The eigenvalues in ascending order, each repeated according to
  888. its multiplicity.
  889. Raises
  890. ------
  891. LinAlgError
  892. If the eigenvalue computation does not converge.
  893. See Also
  894. --------
  895. eigh : eigenvalues and eigenvectors of real symmetric or complex Hermitian
  896. (conjugate symmetric) arrays.
  897. eigvals : eigenvalues of general real or complex arrays.
  898. eig : eigenvalues and right eigenvectors of general real or complex
  899. arrays.
  900. scipy.linalg.eigvalsh : Similar function in SciPy.
  901. Notes
  902. -----
  903. .. versionadded:: 1.8.0
  904. Broadcasting rules apply, see the `numpy.linalg` documentation for
  905. details.
  906. The eigenvalues are computed using LAPACK routines ``_syevd``, ``_heevd``.
  907. Examples
  908. --------
  909. >>> from numpy import linalg as LA
  910. >>> a = np.array([[1, -2j], [2j, 5]])
  911. >>> LA.eigvalsh(a)
  912. array([ 0.17157288, 5.82842712]) # may vary
  913. >>> # demonstrate the treatment of the imaginary part of the diagonal
  914. >>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
  915. >>> a
  916. array([[5.+2.j, 9.-2.j],
  917. [0.+2.j, 2.-1.j]])
  918. >>> # with UPLO='L' this is numerically equivalent to using LA.eigvals()
  919. >>> # with:
  920. >>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
  921. >>> b
  922. array([[5.+0.j, 0.-2.j],
  923. [0.+2.j, 2.+0.j]])
  924. >>> wa = LA.eigvalsh(a)
  925. >>> wb = LA.eigvals(b)
  926. >>> wa; wb
  927. array([1., 6.])
  928. array([6.+0.j, 1.+0.j])
  929. """
  930. UPLO = UPLO.upper()
  931. if UPLO not in ('L', 'U'):
  932. raise ValueError("UPLO argument must be 'L' or 'U'")
  933. extobj = get_linalg_error_extobj(
  934. _raise_linalgerror_eigenvalues_nonconvergence)
  935. if UPLO == 'L':
  936. gufunc = _umath_linalg.eigvalsh_lo
  937. else:
  938. gufunc = _umath_linalg.eigvalsh_up
  939. a, wrap = _makearray(a)
  940. _assert_stacked_2d(a)
  941. _assert_stacked_square(a)
  942. t, result_t = _commonType(a)
  943. signature = 'D->d' if isComplexType(t) else 'd->d'
  944. w = gufunc(a, signature=signature, extobj=extobj)
  945. return w.astype(_realType(result_t), copy=False)
  946. def _convertarray(a):
  947. t, result_t = _commonType(a)
  948. a = a.astype(t).T.copy()
  949. return a, t, result_t
  950. # Eigenvectors
  951. @array_function_dispatch(_unary_dispatcher)
  952. def eig(a):
  953. """
  954. Compute the eigenvalues and right eigenvectors of a square array.
  955. Parameters
  956. ----------
  957. a : (..., M, M) array
  958. Matrices for which the eigenvalues and right eigenvectors will
  959. be computed
  960. Returns
  961. -------
  962. A namedtuple with the following attributes:
  963. eigenvalues : (..., M) array
  964. The eigenvalues, each repeated according to its multiplicity.
  965. The eigenvalues are not necessarily ordered. The resulting
  966. array will be of complex type, unless the imaginary part is
  967. zero in which case it will be cast to a real type. When `a`
  968. is real the resulting eigenvalues will be real (0 imaginary
  969. part) or occur in conjugate pairs
  970. eigenvectors : (..., M, M) array
  971. The normalized (unit "length") eigenvectors, such that the
  972. column ``eigenvectors[:,i]`` is the eigenvector corresponding to the
  973. eigenvalue ``eigenvalues[i]``.
  974. Raises
  975. ------
  976. LinAlgError
  977. If the eigenvalue computation does not converge.
  978. See Also
  979. --------
  980. eigvals : eigenvalues of a non-symmetric array.
  981. eigh : eigenvalues and eigenvectors of a real symmetric or complex
  982. Hermitian (conjugate symmetric) array.
  983. eigvalsh : eigenvalues of a real symmetric or complex Hermitian
  984. (conjugate symmetric) array.
  985. scipy.linalg.eig : Similar function in SciPy that also solves the
  986. generalized eigenvalue problem.
  987. scipy.linalg.schur : Best choice for unitary and other non-Hermitian
  988. normal matrices.
  989. Notes
  990. -----
  991. .. versionadded:: 1.8.0
  992. Broadcasting rules apply, see the `numpy.linalg` documentation for
  993. details.
  994. This is implemented using the ``_geev`` LAPACK routines which compute
  995. the eigenvalues and eigenvectors of general square arrays.
  996. The number `w` is an eigenvalue of `a` if there exists a vector `v` such
  997. that ``a @ v = w * v``. Thus, the arrays `a`, `eigenvalues`, and
  998. `eigenvectors` satisfy the equations ``a @ eigenvectors[:,i] =
  999. eigenvalues[i] * eigenvalues[:,i]`` for :math:`i \\in \\{0,...,M-1\\}`.
  1000. The array `eigenvectors` may not be of maximum rank, that is, some of the
  1001. columns may be linearly dependent, although round-off error may obscure
  1002. that fact. If the eigenvalues are all different, then theoretically the
  1003. eigenvectors are linearly independent and `a` can be diagonalized by a
  1004. similarity transformation using `eigenvectors`, i.e, ``inv(eigenvectors) @
  1005. a @ eigenvectors`` is diagonal.
  1006. For non-Hermitian normal matrices the SciPy function `scipy.linalg.schur`
  1007. is preferred because the matrix `eigenvectors` is guaranteed to be
  1008. unitary, which is not the case when using `eig`. The Schur factorization
  1009. produces an upper triangular matrix rather than a diagonal matrix, but for
  1010. normal matrices only the diagonal of the upper triangular matrix is
  1011. needed, the rest is roundoff error.
  1012. Finally, it is emphasized that `eigenvectors` consists of the *right* (as
  1013. in right-hand side) eigenvectors of `a`. A vector `y` satisfying ``y.T @ a
  1014. = z * y.T`` for some number `z` is called a *left* eigenvector of `a`,
  1015. and, in general, the left and right eigenvectors of a matrix are not
  1016. necessarily the (perhaps conjugate) transposes of each other.
  1017. References
  1018. ----------
  1019. G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando, FL,
  1020. Academic Press, Inc., 1980, Various pp.
  1021. Examples
  1022. --------
  1023. >>> from numpy import linalg as LA
  1024. (Almost) trivial example with real eigenvalues and eigenvectors.
  1025. >>> eigenvalues, eigenvectors = LA.eig(np.diag((1, 2, 3)))
  1026. >>> eigenvalues
  1027. array([1., 2., 3.])
  1028. >>> eigenvectors
  1029. array([[1., 0., 0.],
  1030. [0., 1., 0.],
  1031. [0., 0., 1.]])
  1032. Real matrix possessing complex eigenvalues and eigenvectors; note that the
  1033. eigenvalues are complex conjugates of each other.
  1034. >>> eigenvalues, eigenvectors = LA.eig(np.array([[1, -1], [1, 1]]))
  1035. >>> eigenvalues
  1036. array([1.+1.j, 1.-1.j])
  1037. >>> eigenvectors
  1038. array([[0.70710678+0.j , 0.70710678-0.j ],
  1039. [0. -0.70710678j, 0. +0.70710678j]])
  1040. Complex-valued matrix with real eigenvalues (but complex-valued eigenvectors);
  1041. note that ``a.conj().T == a``, i.e., `a` is Hermitian.
  1042. >>> a = np.array([[1, 1j], [-1j, 1]])
  1043. >>> eigenvalues, eigenvectors = LA.eig(a)
  1044. >>> eigenvalues
  1045. array([2.+0.j, 0.+0.j])
  1046. >>> eigenvectors
  1047. array([[ 0. +0.70710678j, 0.70710678+0.j ], # may vary
  1048. [ 0.70710678+0.j , -0. +0.70710678j]])
  1049. Be careful about round-off error!
  1050. >>> a = np.array([[1 + 1e-9, 0], [0, 1 - 1e-9]])
  1051. >>> # Theor. eigenvalues are 1 +/- 1e-9
  1052. >>> eigenvalues, eigenvectors = LA.eig(a)
  1053. >>> eigenvalues
  1054. array([1., 1.])
  1055. >>> eigenvectors
  1056. array([[1., 0.],
  1057. [0., 1.]])
  1058. """
  1059. a, wrap = _makearray(a)
  1060. _assert_stacked_2d(a)
  1061. _assert_stacked_square(a)
  1062. _assert_finite(a)
  1063. t, result_t = _commonType(a)
  1064. extobj = get_linalg_error_extobj(
  1065. _raise_linalgerror_eigenvalues_nonconvergence)
  1066. signature = 'D->DD' if isComplexType(t) else 'd->DD'
  1067. w, vt = _umath_linalg.eig(a, signature=signature, extobj=extobj)
  1068. if not isComplexType(t) and all(w.imag == 0.0):
  1069. w = w.real
  1070. vt = vt.real
  1071. result_t = _realType(result_t)
  1072. else:
  1073. result_t = _complexType(result_t)
  1074. vt = vt.astype(result_t, copy=False)
  1075. return EigResult(w.astype(result_t, copy=False), wrap(vt))
  1076. @array_function_dispatch(_eigvalsh_dispatcher)
  1077. def eigh(a, UPLO='L'):
  1078. """
  1079. Return the eigenvalues and eigenvectors of a complex Hermitian
  1080. (conjugate symmetric) or a real symmetric matrix.
  1081. Returns two objects, a 1-D array containing the eigenvalues of `a`, and
  1082. a 2-D square array or matrix (depending on the input type) of the
  1083. corresponding eigenvectors (in columns).
  1084. Parameters
  1085. ----------
  1086. a : (..., M, M) array
  1087. Hermitian or real symmetric matrices whose eigenvalues and
  1088. eigenvectors are to be computed.
  1089. UPLO : {'L', 'U'}, optional
  1090. Specifies whether the calculation is done with the lower triangular
  1091. part of `a` ('L', default) or the upper triangular part ('U').
  1092. Irrespective of this value only the real parts of the diagonal will
  1093. be considered in the computation to preserve the notion of a Hermitian
  1094. matrix. It therefore follows that the imaginary part of the diagonal
  1095. will always be treated as zero.
  1096. Returns
  1097. -------
  1098. A namedtuple with the following attributes:
  1099. eigenvalues : (..., M) ndarray
  1100. The eigenvalues in ascending order, each repeated according to
  1101. its multiplicity.
  1102. eigenvectors : {(..., M, M) ndarray, (..., M, M) matrix}
  1103. The column ``eigenvectors[:, i]`` is the normalized eigenvector
  1104. corresponding to the eigenvalue ``eigenvalues[i]``. Will return a
  1105. matrix object if `a` is a matrix object.
  1106. Raises
  1107. ------
  1108. LinAlgError
  1109. If the eigenvalue computation does not converge.
  1110. See Also
  1111. --------
  1112. eigvalsh : eigenvalues of real symmetric or complex Hermitian
  1113. (conjugate symmetric) arrays.
  1114. eig : eigenvalues and right eigenvectors for non-symmetric arrays.
  1115. eigvals : eigenvalues of non-symmetric arrays.
  1116. scipy.linalg.eigh : Similar function in SciPy (but also solves the
  1117. generalized eigenvalue problem).
  1118. Notes
  1119. -----
  1120. .. versionadded:: 1.8.0
  1121. Broadcasting rules apply, see the `numpy.linalg` documentation for
  1122. details.
  1123. The eigenvalues/eigenvectors are computed using LAPACK routines ``_syevd``,
  1124. ``_heevd``.
  1125. The eigenvalues of real symmetric or complex Hermitian matrices are always
  1126. real. [1]_ The array `eigenvalues` of (column) eigenvectors is unitary and
  1127. `a`, `eigenvalues`, and `eigenvectors` satisfy the equations ``dot(a,
  1128. eigenvectors[:, i]) = eigenvalues[i] * eigenvectors[:, i]``.
  1129. References
  1130. ----------
  1131. .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
  1132. FL, Academic Press, Inc., 1980, pg. 222.
  1133. Examples
  1134. --------
  1135. >>> from numpy import linalg as LA
  1136. >>> a = np.array([[1, -2j], [2j, 5]])
  1137. >>> a
  1138. array([[ 1.+0.j, -0.-2.j],
  1139. [ 0.+2.j, 5.+0.j]])
  1140. >>> eigenvalues, eigenvectors = LA.eigh(a)
  1141. >>> eigenvalues
  1142. array([0.17157288, 5.82842712])
  1143. >>> eigenvectors
  1144. array([[-0.92387953+0.j , -0.38268343+0.j ], # may vary
  1145. [ 0. +0.38268343j, 0. -0.92387953j]])
  1146. >>> np.dot(a, eigenvectors[:, 0]) - eigenvalues[0] * eigenvectors[:, 0] # verify 1st eigenval/vec pair
  1147. array([5.55111512e-17+0.0000000e+00j, 0.00000000e+00+1.2490009e-16j])
  1148. >>> np.dot(a, eigenvectors[:, 1]) - eigenvalues[1] * eigenvectors[:, 1] # verify 2nd eigenval/vec pair
  1149. array([0.+0.j, 0.+0.j])
  1150. >>> A = np.matrix(a) # what happens if input is a matrix object
  1151. >>> A
  1152. matrix([[ 1.+0.j, -0.-2.j],
  1153. [ 0.+2.j, 5.+0.j]])
  1154. >>> eigenvalues, eigenvectors = LA.eigh(A)
  1155. >>> eigenvalues
  1156. array([0.17157288, 5.82842712])
  1157. >>> eigenvectors
  1158. matrix([[-0.92387953+0.j , -0.38268343+0.j ], # may vary
  1159. [ 0. +0.38268343j, 0. -0.92387953j]])
  1160. >>> # demonstrate the treatment of the imaginary part of the diagonal
  1161. >>> a = np.array([[5+2j, 9-2j], [0+2j, 2-1j]])
  1162. >>> a
  1163. array([[5.+2.j, 9.-2.j],
  1164. [0.+2.j, 2.-1.j]])
  1165. >>> # with UPLO='L' this is numerically equivalent to using LA.eig() with:
  1166. >>> b = np.array([[5.+0.j, 0.-2.j], [0.+2.j, 2.-0.j]])
  1167. >>> b
  1168. array([[5.+0.j, 0.-2.j],
  1169. [0.+2.j, 2.+0.j]])
  1170. >>> wa, va = LA.eigh(a)
  1171. >>> wb, vb = LA.eig(b)
  1172. >>> wa; wb
  1173. array([1., 6.])
  1174. array([6.+0.j, 1.+0.j])
  1175. >>> va; vb
  1176. array([[-0.4472136 +0.j , -0.89442719+0.j ], # may vary
  1177. [ 0. +0.89442719j, 0. -0.4472136j ]])
  1178. array([[ 0.89442719+0.j , -0. +0.4472136j],
  1179. [-0. +0.4472136j, 0.89442719+0.j ]])
  1180. """
  1181. UPLO = UPLO.upper()
  1182. if UPLO not in ('L', 'U'):
  1183. raise ValueError("UPLO argument must be 'L' or 'U'")
  1184. a, wrap = _makearray(a)
  1185. _assert_stacked_2d(a)
  1186. _assert_stacked_square(a)
  1187. t, result_t = _commonType(a)
  1188. extobj = get_linalg_error_extobj(
  1189. _raise_linalgerror_eigenvalues_nonconvergence)
  1190. if UPLO == 'L':
  1191. gufunc = _umath_linalg.eigh_lo
  1192. else:
  1193. gufunc = _umath_linalg.eigh_up
  1194. signature = 'D->dD' if isComplexType(t) else 'd->dd'
  1195. w, vt = gufunc(a, signature=signature, extobj=extobj)
  1196. w = w.astype(_realType(result_t), copy=False)
  1197. vt = vt.astype(result_t, copy=False)
  1198. return EighResult(w, wrap(vt))
  1199. # Singular value decomposition
  1200. def _svd_dispatcher(a, full_matrices=None, compute_uv=None, hermitian=None):
  1201. return (a,)
  1202. @array_function_dispatch(_svd_dispatcher)
  1203. def svd(a, full_matrices=True, compute_uv=True, hermitian=False):
  1204. """
  1205. Singular Value Decomposition.
  1206. When `a` is a 2D array, and ``full_matrices=False``, then it is
  1207. factorized as ``u @ np.diag(s) @ vh = (u * s) @ vh``, where
  1208. `u` and the Hermitian transpose of `vh` are 2D arrays with
  1209. orthonormal columns and `s` is a 1D array of `a`'s singular
  1210. values. When `a` is higher-dimensional, SVD is applied in
  1211. stacked mode as explained below.
  1212. Parameters
  1213. ----------
  1214. a : (..., M, N) array_like
  1215. A real or complex array with ``a.ndim >= 2``.
  1216. full_matrices : bool, optional
  1217. If True (default), `u` and `vh` have the shapes ``(..., M, M)`` and
  1218. ``(..., N, N)``, respectively. Otherwise, the shapes are
  1219. ``(..., M, K)`` and ``(..., K, N)``, respectively, where
  1220. ``K = min(M, N)``.
  1221. compute_uv : bool, optional
  1222. Whether or not to compute `u` and `vh` in addition to `s`. True
  1223. by default.
  1224. hermitian : bool, optional
  1225. If True, `a` is assumed to be Hermitian (symmetric if real-valued),
  1226. enabling a more efficient method for finding singular values.
  1227. Defaults to False.
  1228. .. versionadded:: 1.17.0
  1229. Returns
  1230. -------
  1231. When `compute_uv` is True, the result is a namedtuple with the following
  1232. attribute names:
  1233. U : { (..., M, M), (..., M, K) } array
  1234. Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
  1235. size as those of the input `a`. The size of the last two dimensions
  1236. depends on the value of `full_matrices`. Only returned when
  1237. `compute_uv` is True.
  1238. S : (..., K) array
  1239. Vector(s) with the singular values, within each vector sorted in
  1240. descending order. The first ``a.ndim - 2`` dimensions have the same
  1241. size as those of the input `a`.
  1242. Vh : { (..., N, N), (..., K, N) } array
  1243. Unitary array(s). The first ``a.ndim - 2`` dimensions have the same
  1244. size as those of the input `a`. The size of the last two dimensions
  1245. depends on the value of `full_matrices`. Only returned when
  1246. `compute_uv` is True.
  1247. Raises
  1248. ------
  1249. LinAlgError
  1250. If SVD computation does not converge.
  1251. See Also
  1252. --------
  1253. scipy.linalg.svd : Similar function in SciPy.
  1254. scipy.linalg.svdvals : Compute singular values of a matrix.
  1255. Notes
  1256. -----
  1257. .. versionchanged:: 1.8.0
  1258. Broadcasting rules apply, see the `numpy.linalg` documentation for
  1259. details.
  1260. The decomposition is performed using LAPACK routine ``_gesdd``.
  1261. SVD is usually described for the factorization of a 2D matrix :math:`A`.
  1262. The higher-dimensional case will be discussed below. In the 2D case, SVD is
  1263. written as :math:`A = U S V^H`, where :math:`A = a`, :math:`U= u`,
  1264. :math:`S= \\mathtt{np.diag}(s)` and :math:`V^H = vh`. The 1D array `s`
  1265. contains the singular values of `a` and `u` and `vh` are unitary. The rows
  1266. of `vh` are the eigenvectors of :math:`A^H A` and the columns of `u` are
  1267. the eigenvectors of :math:`A A^H`. In both cases the corresponding
  1268. (possibly non-zero) eigenvalues are given by ``s**2``.
  1269. If `a` has more than two dimensions, then broadcasting rules apply, as
  1270. explained in :ref:`routines.linalg-broadcasting`. This means that SVD is
  1271. working in "stacked" mode: it iterates over all indices of the first
  1272. ``a.ndim - 2`` dimensions and for each combination SVD is applied to the
  1273. last two indices. The matrix `a` can be reconstructed from the
  1274. decomposition with either ``(u * s[..., None, :]) @ vh`` or
  1275. ``u @ (s[..., None] * vh)``. (The ``@`` operator can be replaced by the
  1276. function ``np.matmul`` for python versions below 3.5.)
  1277. If `a` is a ``matrix`` object (as opposed to an ``ndarray``), then so are
  1278. all the return values.
  1279. Examples
  1280. --------
  1281. >>> a = np.random.randn(9, 6) + 1j*np.random.randn(9, 6)
  1282. >>> b = np.random.randn(2, 7, 8, 3) + 1j*np.random.randn(2, 7, 8, 3)
  1283. Reconstruction based on full SVD, 2D case:
  1284. >>> U, S, Vh = np.linalg.svd(a, full_matrices=True)
  1285. >>> U.shape, S.shape, Vh.shape
  1286. ((9, 9), (6,), (6, 6))
  1287. >>> np.allclose(a, np.dot(U[:, :6] * S, Vh))
  1288. True
  1289. >>> smat = np.zeros((9, 6), dtype=complex)
  1290. >>> smat[:6, :6] = np.diag(S)
  1291. >>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
  1292. True
  1293. Reconstruction based on reduced SVD, 2D case:
  1294. >>> U, S, Vh = np.linalg.svd(a, full_matrices=False)
  1295. >>> U.shape, S.shape, Vh.shape
  1296. ((9, 6), (6,), (6, 6))
  1297. >>> np.allclose(a, np.dot(U * S, Vh))
  1298. True
  1299. >>> smat = np.diag(S)
  1300. >>> np.allclose(a, np.dot(U, np.dot(smat, Vh)))
  1301. True
  1302. Reconstruction based on full SVD, 4D case:
  1303. >>> U, S, Vh = np.linalg.svd(b, full_matrices=True)
  1304. >>> U.shape, S.shape, Vh.shape
  1305. ((2, 7, 8, 8), (2, 7, 3), (2, 7, 3, 3))
  1306. >>> np.allclose(b, np.matmul(U[..., :3] * S[..., None, :], Vh))
  1307. True
  1308. >>> np.allclose(b, np.matmul(U[..., :3], S[..., None] * Vh))
  1309. True
  1310. Reconstruction based on reduced SVD, 4D case:
  1311. >>> U, S, Vh = np.linalg.svd(b, full_matrices=False)
  1312. >>> U.shape, S.shape, Vh.shape
  1313. ((2, 7, 8, 3), (2, 7, 3), (2, 7, 3, 3))
  1314. >>> np.allclose(b, np.matmul(U * S[..., None, :], Vh))
  1315. True
  1316. >>> np.allclose(b, np.matmul(U, S[..., None] * Vh))
  1317. True
  1318. """
  1319. import numpy as _nx
  1320. a, wrap = _makearray(a)
  1321. if hermitian:
  1322. # note: lapack svd returns eigenvalues with s ** 2 sorted descending,
  1323. # but eig returns s sorted ascending, so we re-order the eigenvalues
  1324. # and related arrays to have the correct order
  1325. if compute_uv:
  1326. s, u = eigh(a)
  1327. sgn = sign(s)
  1328. s = abs(s)
  1329. sidx = argsort(s)[..., ::-1]
  1330. sgn = _nx.take_along_axis(sgn, sidx, axis=-1)
  1331. s = _nx.take_along_axis(s, sidx, axis=-1)
  1332. u = _nx.take_along_axis(u, sidx[..., None, :], axis=-1)
  1333. # singular values are unsigned, move the sign into v
  1334. vt = transpose(u * sgn[..., None, :]).conjugate()
  1335. return SVDResult(wrap(u), s, wrap(vt))
  1336. else:
  1337. s = eigvalsh(a)
  1338. s = abs(s)
  1339. return sort(s)[..., ::-1]
  1340. _assert_stacked_2d(a)
  1341. t, result_t = _commonType(a)
  1342. extobj = get_linalg_error_extobj(_raise_linalgerror_svd_nonconvergence)
  1343. m, n = a.shape[-2:]
  1344. if compute_uv:
  1345. if full_matrices:
  1346. if m < n:
  1347. gufunc = _umath_linalg.svd_m_f
  1348. else:
  1349. gufunc = _umath_linalg.svd_n_f
  1350. else:
  1351. if m < n:
  1352. gufunc = _umath_linalg.svd_m_s
  1353. else:
  1354. gufunc = _umath_linalg.svd_n_s
  1355. signature = 'D->DdD' if isComplexType(t) else 'd->ddd'
  1356. u, s, vh = gufunc(a, signature=signature, extobj=extobj)
  1357. u = u.astype(result_t, copy=False)
  1358. s = s.astype(_realType(result_t), copy=False)
  1359. vh = vh.astype(result_t, copy=False)
  1360. return SVDResult(wrap(u), s, wrap(vh))
  1361. else:
  1362. if m < n:
  1363. gufunc = _umath_linalg.svd_m
  1364. else:
  1365. gufunc = _umath_linalg.svd_n
  1366. signature = 'D->d' if isComplexType(t) else 'd->d'
  1367. s = gufunc(a, signature=signature, extobj=extobj)
  1368. s = s.astype(_realType(result_t), copy=False)
  1369. return s
  1370. def _cond_dispatcher(x, p=None):
  1371. return (x,)
  1372. @array_function_dispatch(_cond_dispatcher)
  1373. def cond(x, p=None):
  1374. """
  1375. Compute the condition number of a matrix.
  1376. This function is capable of returning the condition number using
  1377. one of seven different norms, depending on the value of `p` (see
  1378. Parameters below).
  1379. Parameters
  1380. ----------
  1381. x : (..., M, N) array_like
  1382. The matrix whose condition number is sought.
  1383. p : {None, 1, -1, 2, -2, inf, -inf, 'fro'}, optional
  1384. Order of the norm used in the condition number computation:
  1385. ===== ============================
  1386. p norm for matrices
  1387. ===== ============================
  1388. None 2-norm, computed directly using the ``SVD``
  1389. 'fro' Frobenius norm
  1390. inf max(sum(abs(x), axis=1))
  1391. -inf min(sum(abs(x), axis=1))
  1392. 1 max(sum(abs(x), axis=0))
  1393. -1 min(sum(abs(x), axis=0))
  1394. 2 2-norm (largest sing. value)
  1395. -2 smallest singular value
  1396. ===== ============================
  1397. inf means the `numpy.inf` object, and the Frobenius norm is
  1398. the root-of-sum-of-squares norm.
  1399. Returns
  1400. -------
  1401. c : {float, inf}
  1402. The condition number of the matrix. May be infinite.
  1403. See Also
  1404. --------
  1405. numpy.linalg.norm
  1406. Notes
  1407. -----
  1408. The condition number of `x` is defined as the norm of `x` times the
  1409. norm of the inverse of `x` [1]_; the norm can be the usual L2-norm
  1410. (root-of-sum-of-squares) or one of a number of other matrix norms.
  1411. References
  1412. ----------
  1413. .. [1] G. Strang, *Linear Algebra and Its Applications*, Orlando, FL,
  1414. Academic Press, Inc., 1980, pg. 285.
  1415. Examples
  1416. --------
  1417. >>> from numpy import linalg as LA
  1418. >>> a = np.array([[1, 0, -1], [0, 1, 0], [1, 0, 1]])
  1419. >>> a
  1420. array([[ 1, 0, -1],
  1421. [ 0, 1, 0],
  1422. [ 1, 0, 1]])
  1423. >>> LA.cond(a)
  1424. 1.4142135623730951
  1425. >>> LA.cond(a, 'fro')
  1426. 3.1622776601683795
  1427. >>> LA.cond(a, np.inf)
  1428. 2.0
  1429. >>> LA.cond(a, -np.inf)
  1430. 1.0
  1431. >>> LA.cond(a, 1)
  1432. 2.0
  1433. >>> LA.cond(a, -1)
  1434. 1.0
  1435. >>> LA.cond(a, 2)
  1436. 1.4142135623730951
  1437. >>> LA.cond(a, -2)
  1438. 0.70710678118654746 # may vary
  1439. >>> min(LA.svd(a, compute_uv=False))*min(LA.svd(LA.inv(a), compute_uv=False))
  1440. 0.70710678118654746 # may vary
  1441. """
  1442. x = asarray(x) # in case we have a matrix
  1443. if _is_empty_2d(x):
  1444. raise LinAlgError("cond is not defined on empty arrays")
  1445. if p is None or p == 2 or p == -2:
  1446. s = svd(x, compute_uv=False)
  1447. with errstate(all='ignore'):
  1448. if p == -2:
  1449. r = s[..., -1] / s[..., 0]
  1450. else:
  1451. r = s[..., 0] / s[..., -1]
  1452. else:
  1453. # Call inv(x) ignoring errors. The result array will
  1454. # contain nans in the entries where inversion failed.
  1455. _assert_stacked_2d(x)
  1456. _assert_stacked_square(x)
  1457. t, result_t = _commonType(x)
  1458. signature = 'D->D' if isComplexType(t) else 'd->d'
  1459. with errstate(all='ignore'):
  1460. invx = _umath_linalg.inv(x, signature=signature)
  1461. r = norm(x, p, axis=(-2, -1)) * norm(invx, p, axis=(-2, -1))
  1462. r = r.astype(result_t, copy=False)
  1463. # Convert nans to infs unless the original array had nan entries
  1464. r = asarray(r)
  1465. nan_mask = isnan(r)
  1466. if nan_mask.any():
  1467. nan_mask &= ~isnan(x).any(axis=(-2, -1))
  1468. if r.ndim > 0:
  1469. r[nan_mask] = Inf
  1470. elif nan_mask:
  1471. r[()] = Inf
  1472. # Convention is to return scalars instead of 0d arrays
  1473. if r.ndim == 0:
  1474. r = r[()]
  1475. return r
  1476. def _matrix_rank_dispatcher(A, tol=None, hermitian=None):
  1477. return (A,)
  1478. @array_function_dispatch(_matrix_rank_dispatcher)
  1479. def matrix_rank(A, tol=None, hermitian=False):
  1480. """
  1481. Return matrix rank of array using SVD method
  1482. Rank of the array is the number of singular values of the array that are
  1483. greater than `tol`.
  1484. .. versionchanged:: 1.14
  1485. Can now operate on stacks of matrices
  1486. Parameters
  1487. ----------
  1488. A : {(M,), (..., M, N)} array_like
  1489. Input vector or stack of matrices.
  1490. tol : (...) array_like, float, optional
  1491. Threshold below which SVD values are considered zero. If `tol` is
  1492. None, and ``S`` is an array with singular values for `M`, and
  1493. ``eps`` is the epsilon value for datatype of ``S``, then `tol` is
  1494. set to ``S.max() * max(M, N) * eps``.
  1495. .. versionchanged:: 1.14
  1496. Broadcasted against the stack of matrices
  1497. hermitian : bool, optional
  1498. If True, `A` is assumed to be Hermitian (symmetric if real-valued),
  1499. enabling a more efficient method for finding singular values.
  1500. Defaults to False.
  1501. .. versionadded:: 1.14
  1502. Returns
  1503. -------
  1504. rank : (...) array_like
  1505. Rank of A.
  1506. Notes
  1507. -----
  1508. The default threshold to detect rank deficiency is a test on the magnitude
  1509. of the singular values of `A`. By default, we identify singular values less
  1510. than ``S.max() * max(M, N) * eps`` as indicating rank deficiency (with
  1511. the symbols defined above). This is the algorithm MATLAB uses [1]. It also
  1512. appears in *Numerical recipes* in the discussion of SVD solutions for linear
  1513. least squares [2].
  1514. This default threshold is designed to detect rank deficiency accounting for
  1515. the numerical errors of the SVD computation. Imagine that there is a column
  1516. in `A` that is an exact (in floating point) linear combination of other
  1517. columns in `A`. Computing the SVD on `A` will not produce a singular value
  1518. exactly equal to 0 in general: any difference of the smallest SVD value from
  1519. 0 will be caused by numerical imprecision in the calculation of the SVD.
  1520. Our threshold for small SVD values takes this numerical imprecision into
  1521. account, and the default threshold will detect such numerical rank
  1522. deficiency. The threshold may declare a matrix `A` rank deficient even if
  1523. the linear combination of some columns of `A` is not exactly equal to
  1524. another column of `A` but only numerically very close to another column of
  1525. `A`.
  1526. We chose our default threshold because it is in wide use. Other thresholds
  1527. are possible. For example, elsewhere in the 2007 edition of *Numerical
  1528. recipes* there is an alternative threshold of ``S.max() *
  1529. np.finfo(A.dtype).eps / 2. * np.sqrt(m + n + 1.)``. The authors describe
  1530. this threshold as being based on "expected roundoff error" (p 71).
  1531. The thresholds above deal with floating point roundoff error in the
  1532. calculation of the SVD. However, you may have more information about the
  1533. sources of error in `A` that would make you consider other tolerance values
  1534. to detect *effective* rank deficiency. The most useful measure of the
  1535. tolerance depends on the operations you intend to use on your matrix. For
  1536. example, if your data come from uncertain measurements with uncertainties
  1537. greater than floating point epsilon, choosing a tolerance near that
  1538. uncertainty may be preferable. The tolerance may be absolute if the
  1539. uncertainties are absolute rather than relative.
  1540. References
  1541. ----------
  1542. .. [1] MATLAB reference documentation, "Rank"
  1543. https://www.mathworks.com/help/techdoc/ref/rank.html
  1544. .. [2] W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery,
  1545. "Numerical Recipes (3rd edition)", Cambridge University Press, 2007,
  1546. page 795.
  1547. Examples
  1548. --------
  1549. >>> from numpy.linalg import matrix_rank
  1550. >>> matrix_rank(np.eye(4)) # Full rank matrix
  1551. 4
  1552. >>> I=np.eye(4); I[-1,-1] = 0. # rank deficient matrix
  1553. >>> matrix_rank(I)
  1554. 3
  1555. >>> matrix_rank(np.ones((4,))) # 1 dimension - rank 1 unless all 0
  1556. 1
  1557. >>> matrix_rank(np.zeros((4,)))
  1558. 0
  1559. """
  1560. A = asarray(A)
  1561. if A.ndim < 2:
  1562. return int(not all(A==0))
  1563. S = svd(A, compute_uv=False, hermitian=hermitian)
  1564. if tol is None:
  1565. tol = S.max(axis=-1, keepdims=True) * max(A.shape[-2:]) * finfo(S.dtype).eps
  1566. else:
  1567. tol = asarray(tol)[..., newaxis]
  1568. return count_nonzero(S > tol, axis=-1)
  1569. # Generalized inverse
  1570. def _pinv_dispatcher(a, rcond=None, hermitian=None):
  1571. return (a,)
  1572. @array_function_dispatch(_pinv_dispatcher)
  1573. def pinv(a, rcond=1e-15, hermitian=False):
  1574. """
  1575. Compute the (Moore-Penrose) pseudo-inverse of a matrix.
  1576. Calculate the generalized inverse of a matrix using its
  1577. singular-value decomposition (SVD) and including all
  1578. *large* singular values.
  1579. .. versionchanged:: 1.14
  1580. Can now operate on stacks of matrices
  1581. Parameters
  1582. ----------
  1583. a : (..., M, N) array_like
  1584. Matrix or stack of matrices to be pseudo-inverted.
  1585. rcond : (...) array_like of float
  1586. Cutoff for small singular values.
  1587. Singular values less than or equal to
  1588. ``rcond * largest_singular_value`` are set to zero.
  1589. Broadcasts against the stack of matrices.
  1590. hermitian : bool, optional
  1591. If True, `a` is assumed to be Hermitian (symmetric if real-valued),
  1592. enabling a more efficient method for finding singular values.
  1593. Defaults to False.
  1594. .. versionadded:: 1.17.0
  1595. Returns
  1596. -------
  1597. B : (..., N, M) ndarray
  1598. The pseudo-inverse of `a`. If `a` is a `matrix` instance, then so
  1599. is `B`.
  1600. Raises
  1601. ------
  1602. LinAlgError
  1603. If the SVD computation does not converge.
  1604. See Also
  1605. --------
  1606. scipy.linalg.pinv : Similar function in SciPy.
  1607. scipy.linalg.pinvh : Compute the (Moore-Penrose) pseudo-inverse of a
  1608. Hermitian matrix.
  1609. Notes
  1610. -----
  1611. The pseudo-inverse of a matrix A, denoted :math:`A^+`, is
  1612. defined as: "the matrix that 'solves' [the least-squares problem]
  1613. :math:`Ax = b`," i.e., if :math:`\\bar{x}` is said solution, then
  1614. :math:`A^+` is that matrix such that :math:`\\bar{x} = A^+b`.
  1615. It can be shown that if :math:`Q_1 \\Sigma Q_2^T = A` is the singular
  1616. value decomposition of A, then
  1617. :math:`A^+ = Q_2 \\Sigma^+ Q_1^T`, where :math:`Q_{1,2}` are
  1618. orthogonal matrices, :math:`\\Sigma` is a diagonal matrix consisting
  1619. of A's so-called singular values, (followed, typically, by
  1620. zeros), and then :math:`\\Sigma^+` is simply the diagonal matrix
  1621. consisting of the reciprocals of A's singular values
  1622. (again, followed by zeros). [1]_
  1623. References
  1624. ----------
  1625. .. [1] G. Strang, *Linear Algebra and Its Applications*, 2nd Ed., Orlando,
  1626. FL, Academic Press, Inc., 1980, pp. 139-142.
  1627. Examples
  1628. --------
  1629. The following example checks that ``a * a+ * a == a`` and
  1630. ``a+ * a * a+ == a+``:
  1631. >>> a = np.random.randn(9, 6)
  1632. >>> B = np.linalg.pinv(a)
  1633. >>> np.allclose(a, np.dot(a, np.dot(B, a)))
  1634. True
  1635. >>> np.allclose(B, np.dot(B, np.dot(a, B)))
  1636. True
  1637. """
  1638. a, wrap = _makearray(a)
  1639. rcond = asarray(rcond)
  1640. if _is_empty_2d(a):
  1641. m, n = a.shape[-2:]
  1642. res = empty(a.shape[:-2] + (n, m), dtype=a.dtype)
  1643. return wrap(res)
  1644. a = a.conjugate()
  1645. u, s, vt = svd(a, full_matrices=False, hermitian=hermitian)
  1646. # discard small singular values
  1647. cutoff = rcond[..., newaxis] * amax(s, axis=-1, keepdims=True)
  1648. large = s > cutoff
  1649. s = divide(1, s, where=large, out=s)
  1650. s[~large] = 0
  1651. res = matmul(transpose(vt), multiply(s[..., newaxis], transpose(u)))
  1652. return wrap(res)
  1653. # Determinant
  1654. @array_function_dispatch(_unary_dispatcher)
  1655. def slogdet(a):
  1656. """
  1657. Compute the sign and (natural) logarithm of the determinant of an array.
  1658. If an array has a very small or very large determinant, then a call to
  1659. `det` may overflow or underflow. This routine is more robust against such
  1660. issues, because it computes the logarithm of the determinant rather than
  1661. the determinant itself.
  1662. Parameters
  1663. ----------
  1664. a : (..., M, M) array_like
  1665. Input array, has to be a square 2-D array.
  1666. Returns
  1667. -------
  1668. A namedtuple with the following attributes:
  1669. sign : (...) array_like
  1670. A number representing the sign of the determinant. For a real matrix,
  1671. this is 1, 0, or -1. For a complex matrix, this is a complex number
  1672. with absolute value 1 (i.e., it is on the unit circle), or else 0.
  1673. logabsdet : (...) array_like
  1674. The natural log of the absolute value of the determinant.
  1675. If the determinant is zero, then `sign` will be 0 and `logabsdet` will be
  1676. -Inf. In all cases, the determinant is equal to ``sign * np.exp(logabsdet)``.
  1677. See Also
  1678. --------
  1679. det
  1680. Notes
  1681. -----
  1682. .. versionadded:: 1.8.0
  1683. Broadcasting rules apply, see the `numpy.linalg` documentation for
  1684. details.
  1685. .. versionadded:: 1.6.0
  1686. The determinant is computed via LU factorization using the LAPACK
  1687. routine ``z/dgetrf``.
  1688. Examples
  1689. --------
  1690. The determinant of a 2-D array ``[[a, b], [c, d]]`` is ``ad - bc``:
  1691. >>> a = np.array([[1, 2], [3, 4]])
  1692. >>> (sign, logabsdet) = np.linalg.slogdet(a)
  1693. >>> (sign, logabsdet)
  1694. (-1, 0.69314718055994529) # may vary
  1695. >>> sign * np.exp(logabsdet)
  1696. -2.0
  1697. Computing log-determinants for a stack of matrices:
  1698. >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
  1699. >>> a.shape
  1700. (3, 2, 2)
  1701. >>> sign, logabsdet = np.linalg.slogdet(a)
  1702. >>> (sign, logabsdet)
  1703. (array([-1., -1., -1.]), array([ 0.69314718, 1.09861229, 2.07944154]))
  1704. >>> sign * np.exp(logabsdet)
  1705. array([-2., -3., -8.])
  1706. This routine succeeds where ordinary `det` does not:
  1707. >>> np.linalg.det(np.eye(500) * 0.1)
  1708. 0.0
  1709. >>> np.linalg.slogdet(np.eye(500) * 0.1)
  1710. (1, -1151.2925464970228)
  1711. """
  1712. a = asarray(a)
  1713. _assert_stacked_2d(a)
  1714. _assert_stacked_square(a)
  1715. t, result_t = _commonType(a)
  1716. real_t = _realType(result_t)
  1717. signature = 'D->Dd' if isComplexType(t) else 'd->dd'
  1718. sign, logdet = _umath_linalg.slogdet(a, signature=signature)
  1719. sign = sign.astype(result_t, copy=False)
  1720. logdet = logdet.astype(real_t, copy=False)
  1721. return SlogdetResult(sign, logdet)
  1722. @array_function_dispatch(_unary_dispatcher)
  1723. def det(a):
  1724. """
  1725. Compute the determinant of an array.
  1726. Parameters
  1727. ----------
  1728. a : (..., M, M) array_like
  1729. Input array to compute determinants for.
  1730. Returns
  1731. -------
  1732. det : (...) array_like
  1733. Determinant of `a`.
  1734. See Also
  1735. --------
  1736. slogdet : Another way to represent the determinant, more suitable
  1737. for large matrices where underflow/overflow may occur.
  1738. scipy.linalg.det : Similar function in SciPy.
  1739. Notes
  1740. -----
  1741. .. versionadded:: 1.8.0
  1742. Broadcasting rules apply, see the `numpy.linalg` documentation for
  1743. details.
  1744. The determinant is computed via LU factorization using the LAPACK
  1745. routine ``z/dgetrf``.
  1746. Examples
  1747. --------
  1748. The determinant of a 2-D array [[a, b], [c, d]] is ad - bc:
  1749. >>> a = np.array([[1, 2], [3, 4]])
  1750. >>> np.linalg.det(a)
  1751. -2.0 # may vary
  1752. Computing determinants for a stack of matrices:
  1753. >>> a = np.array([ [[1, 2], [3, 4]], [[1, 2], [2, 1]], [[1, 3], [3, 1]] ])
  1754. >>> a.shape
  1755. (3, 2, 2)
  1756. >>> np.linalg.det(a)
  1757. array([-2., -3., -8.])
  1758. """
  1759. a = asarray(a)
  1760. _assert_stacked_2d(a)
  1761. _assert_stacked_square(a)
  1762. t, result_t = _commonType(a)
  1763. signature = 'D->D' if isComplexType(t) else 'd->d'
  1764. r = _umath_linalg.det(a, signature=signature)
  1765. r = r.astype(result_t, copy=False)
  1766. return r
  1767. # Linear Least Squares
  1768. def _lstsq_dispatcher(a, b, rcond=None):
  1769. return (a, b)
  1770. @array_function_dispatch(_lstsq_dispatcher)
  1771. def lstsq(a, b, rcond="warn"):
  1772. r"""
  1773. Return the least-squares solution to a linear matrix equation.
  1774. Computes the vector `x` that approximately solves the equation
  1775. ``a @ x = b``. The equation may be under-, well-, or over-determined
  1776. (i.e., the number of linearly independent rows of `a` can be less than,
  1777. equal to, or greater than its number of linearly independent columns).
  1778. If `a` is square and of full rank, then `x` (but for round-off error)
  1779. is the "exact" solution of the equation. Else, `x` minimizes the
  1780. Euclidean 2-norm :math:`||b - ax||`. If there are multiple minimizing
  1781. solutions, the one with the smallest 2-norm :math:`||x||` is returned.
  1782. Parameters
  1783. ----------
  1784. a : (M, N) array_like
  1785. "Coefficient" matrix.
  1786. b : {(M,), (M, K)} array_like
  1787. Ordinate or "dependent variable" values. If `b` is two-dimensional,
  1788. the least-squares solution is calculated for each of the `K` columns
  1789. of `b`.
  1790. rcond : float, optional
  1791. Cut-off ratio for small singular values of `a`.
  1792. For the purposes of rank determination, singular values are treated
  1793. as zero if they are smaller than `rcond` times the largest singular
  1794. value of `a`.
  1795. .. versionchanged:: 1.14.0
  1796. If not set, a FutureWarning is given. The previous default
  1797. of ``-1`` will use the machine precision as `rcond` parameter,
  1798. the new default will use the machine precision times `max(M, N)`.
  1799. To silence the warning and use the new default, use ``rcond=None``,
  1800. to keep using the old behavior, use ``rcond=-1``.
  1801. Returns
  1802. -------
  1803. x : {(N,), (N, K)} ndarray
  1804. Least-squares solution. If `b` is two-dimensional,
  1805. the solutions are in the `K` columns of `x`.
  1806. residuals : {(1,), (K,), (0,)} ndarray
  1807. Sums of squared residuals: Squared Euclidean 2-norm for each column in
  1808. ``b - a @ x``.
  1809. If the rank of `a` is < N or M <= N, this is an empty array.
  1810. If `b` is 1-dimensional, this is a (1,) shape array.
  1811. Otherwise the shape is (K,).
  1812. rank : int
  1813. Rank of matrix `a`.
  1814. s : (min(M, N),) ndarray
  1815. Singular values of `a`.
  1816. Raises
  1817. ------
  1818. LinAlgError
  1819. If computation does not converge.
  1820. See Also
  1821. --------
  1822. scipy.linalg.lstsq : Similar function in SciPy.
  1823. Notes
  1824. -----
  1825. If `b` is a matrix, then all array results are returned as matrices.
  1826. Examples
  1827. --------
  1828. Fit a line, ``y = mx + c``, through some noisy data-points:
  1829. >>> x = np.array([0, 1, 2, 3])
  1830. >>> y = np.array([-1, 0.2, 0.9, 2.1])
  1831. By examining the coefficients, we see that the line should have a
  1832. gradient of roughly 1 and cut the y-axis at, more or less, -1.
  1833. We can rewrite the line equation as ``y = Ap``, where ``A = [[x 1]]``
  1834. and ``p = [[m], [c]]``. Now use `lstsq` to solve for `p`:
  1835. >>> A = np.vstack([x, np.ones(len(x))]).T
  1836. >>> A
  1837. array([[ 0., 1.],
  1838. [ 1., 1.],
  1839. [ 2., 1.],
  1840. [ 3., 1.]])
  1841. >>> m, c = np.linalg.lstsq(A, y, rcond=None)[0]
  1842. >>> m, c
  1843. (1.0 -0.95) # may vary
  1844. Plot the data along with the fitted line:
  1845. >>> import matplotlib.pyplot as plt
  1846. >>> _ = plt.plot(x, y, 'o', label='Original data', markersize=10)
  1847. >>> _ = plt.plot(x, m*x + c, 'r', label='Fitted line')
  1848. >>> _ = plt.legend()
  1849. >>> plt.show()
  1850. """
  1851. a, _ = _makearray(a)
  1852. b, wrap = _makearray(b)
  1853. is_1d = b.ndim == 1
  1854. if is_1d:
  1855. b = b[:, newaxis]
  1856. _assert_2d(a, b)
  1857. m, n = a.shape[-2:]
  1858. m2, n_rhs = b.shape[-2:]
  1859. if m != m2:
  1860. raise LinAlgError('Incompatible dimensions')
  1861. t, result_t = _commonType(a, b)
  1862. result_real_t = _realType(result_t)
  1863. # Determine default rcond value
  1864. if rcond == "warn":
  1865. # 2017-08-19, 1.14.0
  1866. warnings.warn("`rcond` parameter will change to the default of "
  1867. "machine precision times ``max(M, N)`` where M and N "
  1868. "are the input matrix dimensions.\n"
  1869. "To use the future default and silence this warning "
  1870. "we advise to pass `rcond=None`, to keep using the old, "
  1871. "explicitly pass `rcond=-1`.",
  1872. FutureWarning, stacklevel=2)
  1873. rcond = -1
  1874. if rcond is None:
  1875. rcond = finfo(t).eps * max(n, m)
  1876. if m <= n:
  1877. gufunc = _umath_linalg.lstsq_m
  1878. else:
  1879. gufunc = _umath_linalg.lstsq_n
  1880. signature = 'DDd->Ddid' if isComplexType(t) else 'ddd->ddid'
  1881. extobj = get_linalg_error_extobj(_raise_linalgerror_lstsq)
  1882. if n_rhs == 0:
  1883. # lapack can't handle n_rhs = 0 - so allocate the array one larger in that axis
  1884. b = zeros(b.shape[:-2] + (m, n_rhs + 1), dtype=b.dtype)
  1885. x, resids, rank, s = gufunc(a, b, rcond, signature=signature, extobj=extobj)
  1886. if m == 0:
  1887. x[...] = 0
  1888. if n_rhs == 0:
  1889. # remove the item we added
  1890. x = x[..., :n_rhs]
  1891. resids = resids[..., :n_rhs]
  1892. # remove the axis we added
  1893. if is_1d:
  1894. x = x.squeeze(axis=-1)
  1895. # we probably should squeeze resids too, but we can't
  1896. # without breaking compatibility.
  1897. # as documented
  1898. if rank != n or m <= n:
  1899. resids = array([], result_real_t)
  1900. # coerce output arrays
  1901. s = s.astype(result_real_t, copy=False)
  1902. resids = resids.astype(result_real_t, copy=False)
  1903. x = x.astype(result_t, copy=True) # Copying lets the memory in r_parts be freed
  1904. return wrap(x), wrap(resids), rank, s
  1905. def _multi_svd_norm(x, row_axis, col_axis, op):
  1906. """Compute a function of the singular values of the 2-D matrices in `x`.
  1907. This is a private utility function used by `numpy.linalg.norm()`.
  1908. Parameters
  1909. ----------
  1910. x : ndarray
  1911. row_axis, col_axis : int
  1912. The axes of `x` that hold the 2-D matrices.
  1913. op : callable
  1914. This should be either numpy.amin or `numpy.amax` or `numpy.sum`.
  1915. Returns
  1916. -------
  1917. result : float or ndarray
  1918. If `x` is 2-D, the return values is a float.
  1919. Otherwise, it is an array with ``x.ndim - 2`` dimensions.
  1920. The return values are either the minimum or maximum or sum of the
  1921. singular values of the matrices, depending on whether `op`
  1922. is `numpy.amin` or `numpy.amax` or `numpy.sum`.
  1923. """
  1924. y = moveaxis(x, (row_axis, col_axis), (-2, -1))
  1925. result = op(svd(y, compute_uv=False), axis=-1)
  1926. return result
  1927. def _norm_dispatcher(x, ord=None, axis=None, keepdims=None):
  1928. return (x,)
  1929. @array_function_dispatch(_norm_dispatcher)
  1930. def norm(x, ord=None, axis=None, keepdims=False):
  1931. """
  1932. Matrix or vector norm.
  1933. This function is able to return one of eight different matrix norms,
  1934. or one of an infinite number of vector norms (described below), depending
  1935. on the value of the ``ord`` parameter.
  1936. Parameters
  1937. ----------
  1938. x : array_like
  1939. Input array. If `axis` is None, `x` must be 1-D or 2-D, unless `ord`
  1940. is None. If both `axis` and `ord` are None, the 2-norm of
  1941. ``x.ravel`` will be returned.
  1942. ord : {non-zero int, inf, -inf, 'fro', 'nuc'}, optional
  1943. Order of the norm (see table under ``Notes``). inf means numpy's
  1944. `inf` object. The default is None.
  1945. axis : {None, int, 2-tuple of ints}, optional.
  1946. If `axis` is an integer, it specifies the axis of `x` along which to
  1947. compute the vector norms. If `axis` is a 2-tuple, it specifies the
  1948. axes that hold 2-D matrices, and the matrix norms of these matrices
  1949. are computed. If `axis` is None then either a vector norm (when `x`
  1950. is 1-D) or a matrix norm (when `x` is 2-D) is returned. The default
  1951. is None.
  1952. .. versionadded:: 1.8.0
  1953. keepdims : bool, optional
  1954. If this is set to True, the axes which are normed over are left in the
  1955. result as dimensions with size one. With this option the result will
  1956. broadcast correctly against the original `x`.
  1957. .. versionadded:: 1.10.0
  1958. Returns
  1959. -------
  1960. n : float or ndarray
  1961. Norm of the matrix or vector(s).
  1962. See Also
  1963. --------
  1964. scipy.linalg.norm : Similar function in SciPy.
  1965. Notes
  1966. -----
  1967. For values of ``ord < 1``, the result is, strictly speaking, not a
  1968. mathematical 'norm', but it may still be useful for various numerical
  1969. purposes.
  1970. The following norms can be calculated:
  1971. ===== ============================ ==========================
  1972. ord norm for matrices norm for vectors
  1973. ===== ============================ ==========================
  1974. None Frobenius norm 2-norm
  1975. 'fro' Frobenius norm --
  1976. 'nuc' nuclear norm --
  1977. inf max(sum(abs(x), axis=1)) max(abs(x))
  1978. -inf min(sum(abs(x), axis=1)) min(abs(x))
  1979. 0 -- sum(x != 0)
  1980. 1 max(sum(abs(x), axis=0)) as below
  1981. -1 min(sum(abs(x), axis=0)) as below
  1982. 2 2-norm (largest sing. value) as below
  1983. -2 smallest singular value as below
  1984. other -- sum(abs(x)**ord)**(1./ord)
  1985. ===== ============================ ==========================
  1986. The Frobenius norm is given by [1]_:
  1987. :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
  1988. The nuclear norm is the sum of the singular values.
  1989. Both the Frobenius and nuclear norm orders are only defined for
  1990. matrices and raise a ValueError when ``x.ndim != 2``.
  1991. References
  1992. ----------
  1993. .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
  1994. Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
  1995. Examples
  1996. --------
  1997. >>> from numpy import linalg as LA
  1998. >>> a = np.arange(9) - 4
  1999. >>> a
  2000. array([-4, -3, -2, ..., 2, 3, 4])
  2001. >>> b = a.reshape((3, 3))
  2002. >>> b
  2003. array([[-4, -3, -2],
  2004. [-1, 0, 1],
  2005. [ 2, 3, 4]])
  2006. >>> LA.norm(a)
  2007. 7.745966692414834
  2008. >>> LA.norm(b)
  2009. 7.745966692414834
  2010. >>> LA.norm(b, 'fro')
  2011. 7.745966692414834
  2012. >>> LA.norm(a, np.inf)
  2013. 4.0
  2014. >>> LA.norm(b, np.inf)
  2015. 9.0
  2016. >>> LA.norm(a, -np.inf)
  2017. 0.0
  2018. >>> LA.norm(b, -np.inf)
  2019. 2.0
  2020. >>> LA.norm(a, 1)
  2021. 20.0
  2022. >>> LA.norm(b, 1)
  2023. 7.0
  2024. >>> LA.norm(a, -1)
  2025. -4.6566128774142013e-010
  2026. >>> LA.norm(b, -1)
  2027. 6.0
  2028. >>> LA.norm(a, 2)
  2029. 7.745966692414834
  2030. >>> LA.norm(b, 2)
  2031. 7.3484692283495345
  2032. >>> LA.norm(a, -2)
  2033. 0.0
  2034. >>> LA.norm(b, -2)
  2035. 1.8570331885190563e-016 # may vary
  2036. >>> LA.norm(a, 3)
  2037. 5.8480354764257312 # may vary
  2038. >>> LA.norm(a, -3)
  2039. 0.0
  2040. Using the `axis` argument to compute vector norms:
  2041. >>> c = np.array([[ 1, 2, 3],
  2042. ... [-1, 1, 4]])
  2043. >>> LA.norm(c, axis=0)
  2044. array([ 1.41421356, 2.23606798, 5. ])
  2045. >>> LA.norm(c, axis=1)
  2046. array([ 3.74165739, 4.24264069])
  2047. >>> LA.norm(c, ord=1, axis=1)
  2048. array([ 6., 6.])
  2049. Using the `axis` argument to compute matrix norms:
  2050. >>> m = np.arange(8).reshape(2,2,2)
  2051. >>> LA.norm(m, axis=(1,2))
  2052. array([ 3.74165739, 11.22497216])
  2053. >>> LA.norm(m[0, :, :]), LA.norm(m[1, :, :])
  2054. (3.7416573867739413, 11.224972160321824)
  2055. """
  2056. x = asarray(x)
  2057. if not issubclass(x.dtype.type, (inexact, object_)):
  2058. x = x.astype(float)
  2059. # Immediately handle some default, simple, fast, and common cases.
  2060. if axis is None:
  2061. ndim = x.ndim
  2062. if ((ord is None) or
  2063. (ord in ('f', 'fro') and ndim == 2) or
  2064. (ord == 2 and ndim == 1)):
  2065. x = x.ravel(order='K')
  2066. if isComplexType(x.dtype.type):
  2067. x_real = x.real
  2068. x_imag = x.imag
  2069. sqnorm = x_real.dot(x_real) + x_imag.dot(x_imag)
  2070. else:
  2071. sqnorm = x.dot(x)
  2072. ret = sqrt(sqnorm)
  2073. if keepdims:
  2074. ret = ret.reshape(ndim*[1])
  2075. return ret
  2076. # Normalize the `axis` argument to a tuple.
  2077. nd = x.ndim
  2078. if axis is None:
  2079. axis = tuple(range(nd))
  2080. elif not isinstance(axis, tuple):
  2081. try:
  2082. axis = int(axis)
  2083. except Exception as e:
  2084. raise TypeError("'axis' must be None, an integer or a tuple of integers") from e
  2085. axis = (axis,)
  2086. if len(axis) == 1:
  2087. if ord == Inf:
  2088. return abs(x).max(axis=axis, keepdims=keepdims)
  2089. elif ord == -Inf:
  2090. return abs(x).min(axis=axis, keepdims=keepdims)
  2091. elif ord == 0:
  2092. # Zero norm
  2093. return (x != 0).astype(x.real.dtype).sum(axis=axis, keepdims=keepdims)
  2094. elif ord == 1:
  2095. # special case for speedup
  2096. return add.reduce(abs(x), axis=axis, keepdims=keepdims)
  2097. elif ord is None or ord == 2:
  2098. # special case for speedup
  2099. s = (x.conj() * x).real
  2100. return sqrt(add.reduce(s, axis=axis, keepdims=keepdims))
  2101. # None of the str-type keywords for ord ('fro', 'nuc')
  2102. # are valid for vectors
  2103. elif isinstance(ord, str):
  2104. raise ValueError(f"Invalid norm order '{ord}' for vectors")
  2105. else:
  2106. absx = abs(x)
  2107. absx **= ord
  2108. ret = add.reduce(absx, axis=axis, keepdims=keepdims)
  2109. ret **= reciprocal(ord, dtype=ret.dtype)
  2110. return ret
  2111. elif len(axis) == 2:
  2112. row_axis, col_axis = axis
  2113. row_axis = normalize_axis_index(row_axis, nd)
  2114. col_axis = normalize_axis_index(col_axis, nd)
  2115. if row_axis == col_axis:
  2116. raise ValueError('Duplicate axes given.')
  2117. if ord == 2:
  2118. ret = _multi_svd_norm(x, row_axis, col_axis, amax)
  2119. elif ord == -2:
  2120. ret = _multi_svd_norm(x, row_axis, col_axis, amin)
  2121. elif ord == 1:
  2122. if col_axis > row_axis:
  2123. col_axis -= 1
  2124. ret = add.reduce(abs(x), axis=row_axis).max(axis=col_axis)
  2125. elif ord == Inf:
  2126. if row_axis > col_axis:
  2127. row_axis -= 1
  2128. ret = add.reduce(abs(x), axis=col_axis).max(axis=row_axis)
  2129. elif ord == -1:
  2130. if col_axis > row_axis:
  2131. col_axis -= 1
  2132. ret = add.reduce(abs(x), axis=row_axis).min(axis=col_axis)
  2133. elif ord == -Inf:
  2134. if row_axis > col_axis:
  2135. row_axis -= 1
  2136. ret = add.reduce(abs(x), axis=col_axis).min(axis=row_axis)
  2137. elif ord in [None, 'fro', 'f']:
  2138. ret = sqrt(add.reduce((x.conj() * x).real, axis=axis))
  2139. elif ord == 'nuc':
  2140. ret = _multi_svd_norm(x, row_axis, col_axis, sum)
  2141. else:
  2142. raise ValueError("Invalid norm order for matrices.")
  2143. if keepdims:
  2144. ret_shape = list(x.shape)
  2145. ret_shape[axis[0]] = 1
  2146. ret_shape[axis[1]] = 1
  2147. ret = ret.reshape(ret_shape)
  2148. return ret
  2149. else:
  2150. raise ValueError("Improper number of dimensions to norm.")
  2151. # multi_dot
  2152. def _multidot_dispatcher(arrays, *, out=None):
  2153. yield from arrays
  2154. yield out
  2155. @array_function_dispatch(_multidot_dispatcher)
  2156. def multi_dot(arrays, *, out=None):
  2157. """
  2158. Compute the dot product of two or more arrays in a single function call,
  2159. while automatically selecting the fastest evaluation order.
  2160. `multi_dot` chains `numpy.dot` and uses optimal parenthesization
  2161. of the matrices [1]_ [2]_. Depending on the shapes of the matrices,
  2162. this can speed up the multiplication a lot.
  2163. If the first argument is 1-D it is treated as a row vector.
  2164. If the last argument is 1-D it is treated as a column vector.
  2165. The other arguments must be 2-D.
  2166. Think of `multi_dot` as::
  2167. def multi_dot(arrays): return functools.reduce(np.dot, arrays)
  2168. Parameters
  2169. ----------
  2170. arrays : sequence of array_like
  2171. If the first argument is 1-D it is treated as row vector.
  2172. If the last argument is 1-D it is treated as column vector.
  2173. The other arguments must be 2-D.
  2174. out : ndarray, optional
  2175. Output argument. This must have the exact kind that would be returned
  2176. if it was not used. In particular, it must have the right type, must be
  2177. C-contiguous, and its dtype must be the dtype that would be returned
  2178. for `dot(a, b)`. This is a performance feature. Therefore, if these
  2179. conditions are not met, an exception is raised, instead of attempting
  2180. to be flexible.
  2181. .. versionadded:: 1.19.0
  2182. Returns
  2183. -------
  2184. output : ndarray
  2185. Returns the dot product of the supplied arrays.
  2186. See Also
  2187. --------
  2188. numpy.dot : dot multiplication with two arguments.
  2189. References
  2190. ----------
  2191. .. [1] Cormen, "Introduction to Algorithms", Chapter 15.2, p. 370-378
  2192. .. [2] https://en.wikipedia.org/wiki/Matrix_chain_multiplication
  2193. Examples
  2194. --------
  2195. `multi_dot` allows you to write::
  2196. >>> from numpy.linalg import multi_dot
  2197. >>> # Prepare some data
  2198. >>> A = np.random.random((10000, 100))
  2199. >>> B = np.random.random((100, 1000))
  2200. >>> C = np.random.random((1000, 5))
  2201. >>> D = np.random.random((5, 333))
  2202. >>> # the actual dot multiplication
  2203. >>> _ = multi_dot([A, B, C, D])
  2204. instead of::
  2205. >>> _ = np.dot(np.dot(np.dot(A, B), C), D)
  2206. >>> # or
  2207. >>> _ = A.dot(B).dot(C).dot(D)
  2208. Notes
  2209. -----
  2210. The cost for a matrix multiplication can be calculated with the
  2211. following function::
  2212. def cost(A, B):
  2213. return A.shape[0] * A.shape[1] * B.shape[1]
  2214. Assume we have three matrices
  2215. :math:`A_{10x100}, B_{100x5}, C_{5x50}`.
  2216. The costs for the two different parenthesizations are as follows::
  2217. cost((AB)C) = 10*100*5 + 10*5*50 = 5000 + 2500 = 7500
  2218. cost(A(BC)) = 10*100*50 + 100*5*50 = 50000 + 25000 = 75000
  2219. """
  2220. n = len(arrays)
  2221. # optimization only makes sense for len(arrays) > 2
  2222. if n < 2:
  2223. raise ValueError("Expecting at least two arrays.")
  2224. elif n == 2:
  2225. return dot(arrays[0], arrays[1], out=out)
  2226. arrays = [asanyarray(a) for a in arrays]
  2227. # save original ndim to reshape the result array into the proper form later
  2228. ndim_first, ndim_last = arrays[0].ndim, arrays[-1].ndim
  2229. # Explicitly convert vectors to 2D arrays to keep the logic of the internal
  2230. # _multi_dot_* functions as simple as possible.
  2231. if arrays[0].ndim == 1:
  2232. arrays[0] = atleast_2d(arrays[0])
  2233. if arrays[-1].ndim == 1:
  2234. arrays[-1] = atleast_2d(arrays[-1]).T
  2235. _assert_2d(*arrays)
  2236. # _multi_dot_three is much faster than _multi_dot_matrix_chain_order
  2237. if n == 3:
  2238. result = _multi_dot_three(arrays[0], arrays[1], arrays[2], out=out)
  2239. else:
  2240. order = _multi_dot_matrix_chain_order(arrays)
  2241. result = _multi_dot(arrays, order, 0, n - 1, out=out)
  2242. # return proper shape
  2243. if ndim_first == 1 and ndim_last == 1:
  2244. return result[0, 0] # scalar
  2245. elif ndim_first == 1 or ndim_last == 1:
  2246. return result.ravel() # 1-D
  2247. else:
  2248. return result
  2249. def _multi_dot_three(A, B, C, out=None):
  2250. """
  2251. Find the best order for three arrays and do the multiplication.
  2252. For three arguments `_multi_dot_three` is approximately 15 times faster
  2253. than `_multi_dot_matrix_chain_order`
  2254. """
  2255. a0, a1b0 = A.shape
  2256. b1c0, c1 = C.shape
  2257. # cost1 = cost((AB)C) = a0*a1b0*b1c0 + a0*b1c0*c1
  2258. cost1 = a0 * b1c0 * (a1b0 + c1)
  2259. # cost2 = cost(A(BC)) = a1b0*b1c0*c1 + a0*a1b0*c1
  2260. cost2 = a1b0 * c1 * (a0 + b1c0)
  2261. if cost1 < cost2:
  2262. return dot(dot(A, B), C, out=out)
  2263. else:
  2264. return dot(A, dot(B, C), out=out)
  2265. def _multi_dot_matrix_chain_order(arrays, return_costs=False):
  2266. """
  2267. Return a np.array that encodes the optimal order of mutiplications.
  2268. The optimal order array is then used by `_multi_dot()` to do the
  2269. multiplication.
  2270. Also return the cost matrix if `return_costs` is `True`
  2271. The implementation CLOSELY follows Cormen, "Introduction to Algorithms",
  2272. Chapter 15.2, p. 370-378. Note that Cormen uses 1-based indices.
  2273. cost[i, j] = min([
  2274. cost[prefix] + cost[suffix] + cost_mult(prefix, suffix)
  2275. for k in range(i, j)])
  2276. """
  2277. n = len(arrays)
  2278. # p stores the dimensions of the matrices
  2279. # Example for p: A_{10x100}, B_{100x5}, C_{5x50} --> p = [10, 100, 5, 50]
  2280. p = [a.shape[0] for a in arrays] + [arrays[-1].shape[1]]
  2281. # m is a matrix of costs of the subproblems
  2282. # m[i,j]: min number of scalar multiplications needed to compute A_{i..j}
  2283. m = zeros((n, n), dtype=double)
  2284. # s is the actual ordering
  2285. # s[i, j] is the value of k at which we split the product A_i..A_j
  2286. s = empty((n, n), dtype=intp)
  2287. for l in range(1, n):
  2288. for i in range(n - l):
  2289. j = i + l
  2290. m[i, j] = Inf
  2291. for k in range(i, j):
  2292. q = m[i, k] + m[k+1, j] + p[i]*p[k+1]*p[j+1]
  2293. if q < m[i, j]:
  2294. m[i, j] = q
  2295. s[i, j] = k # Note that Cormen uses 1-based index
  2296. return (s, m) if return_costs else s
  2297. def _multi_dot(arrays, order, i, j, out=None):
  2298. """Actually do the multiplication with the given order."""
  2299. if i == j:
  2300. # the initial call with non-None out should never get here
  2301. assert out is None
  2302. return arrays[i]
  2303. else:
  2304. return dot(_multi_dot(arrays, order, i, order[i, j]),
  2305. _multi_dot(arrays, order, order[i, j] + 1, j),
  2306. out=out)