_linalg.py 112 KB

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