linalg.py 74 KB

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