_linalg.py 112 KB

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