linalg.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. """
  2. Linear algebra
  3. --------------
  4. Linear equations
  5. ................
  6. Basic linear algebra is implemented; you can for example solve the linear
  7. equation system::
  8. x + 2*y = -10
  9. 3*x + 4*y = 10
  10. using ``lu_solve``::
  11. >>> from mpmath import *
  12. >>> mp.pretty = False
  13. >>> A = matrix([[1, 2], [3, 4]])
  14. >>> b = matrix([-10, 10])
  15. >>> x = lu_solve(A, b)
  16. >>> x
  17. matrix(
  18. [['30.0'],
  19. ['-20.0']])
  20. If you don't trust the result, use ``residual`` to calculate the residual ||A*x-b||::
  21. >>> residual(A, x, b)
  22. matrix(
  23. [['3.46944695195361e-18'],
  24. ['3.46944695195361e-18']])
  25. >>> str(eps)
  26. '2.22044604925031e-16'
  27. As you can see, the solution is quite accurate. The error is caused by the
  28. inaccuracy of the internal floating point arithmetic. Though, it's even smaller
  29. than the current machine epsilon, which basically means you can trust the
  30. result.
  31. If you need more speed, use NumPy, or ``fp.lu_solve`` for a floating-point computation.
  32. >>> fp.lu_solve(A, b) # doctest: +ELLIPSIS
  33. matrix(...)
  34. ``lu_solve`` accepts overdetermined systems. It is usually not possible to solve
  35. such systems, so the residual is minimized instead. Internally this is done
  36. using Cholesky decomposition to compute a least squares approximation. This means
  37. that that ``lu_solve`` will square the errors. If you can't afford this, use
  38. ``qr_solve`` instead. It is twice as slow but more accurate, and it calculates
  39. the residual automatically.
  40. Matrix factorization
  41. ....................
  42. The function ``lu`` computes an explicit LU factorization of a matrix::
  43. >>> P, L, U = lu(matrix([[0,2,3],[4,5,6],[7,8,9]]))
  44. >>> print(P)
  45. [0.0 0.0 1.0]
  46. [1.0 0.0 0.0]
  47. [0.0 1.0 0.0]
  48. >>> print(L)
  49. [ 1.0 0.0 0.0]
  50. [ 0.0 1.0 0.0]
  51. [0.571428571428571 0.214285714285714 1.0]
  52. >>> print(U)
  53. [7.0 8.0 9.0]
  54. [0.0 2.0 3.0]
  55. [0.0 0.0 0.214285714285714]
  56. >>> print(P.T*L*U)
  57. [0.0 2.0 3.0]
  58. [4.0 5.0 6.0]
  59. [7.0 8.0 9.0]
  60. Interval matrices
  61. -----------------
  62. Matrices may contain interval elements. This allows one to perform
  63. basic linear algebra operations such as matrix multiplication
  64. and equation solving with rigorous error bounds::
  65. >>> a = iv.matrix([['0.1','0.3','1.0'],
  66. ... ['7.1','5.5','4.8'],
  67. ... ['3.2','4.4','5.6']])
  68. >>>
  69. >>> b = iv.matrix(['4','0.6','0.5'])
  70. >>> c = iv.lu_solve(a, b)
  71. >>> print(c)
  72. [ [5.2582327113062568605927528666, 5.25823271130625686059275702219]]
  73. [[-13.1550493962678375411635581388, -13.1550493962678375411635540152]]
  74. [ [7.42069154774972557628979076189, 7.42069154774972557628979190734]]
  75. >>> print(a*c)
  76. [ [3.99999999999999999999999844904, 4.00000000000000000000000155096]]
  77. [[0.599999999999999999999968898009, 0.600000000000000000000031763736]]
  78. [[0.499999999999999999999979320485, 0.500000000000000000000020679515]]
  79. """
  80. # TODO:
  81. # *implement high-level qr()
  82. # *test unitvector
  83. # *iterative solving
  84. from copy import copy
  85. from ..libmp.backend import xrange
  86. class LinearAlgebraMethods(object):
  87. def LU_decomp(ctx, A, overwrite=False, use_cache=True):
  88. """
  89. LU-factorization of a n*n matrix using the Gauss algorithm.
  90. Returns L and U in one matrix and the pivot indices.
  91. Use overwrite to specify whether A will be overwritten with L and U.
  92. """
  93. if not A.rows == A.cols:
  94. raise ValueError('need n*n matrix')
  95. # get from cache if possible
  96. if use_cache and isinstance(A, ctx.matrix) and A._LU:
  97. return A._LU
  98. if not overwrite:
  99. orig = A
  100. A = A.copy()
  101. tol = ctx.absmin(ctx.mnorm(A,1) * ctx.eps) # each pivot element has to be bigger
  102. n = A.rows
  103. p = [None]*(n - 1)
  104. for j in xrange(n - 1):
  105. # pivoting, choose max(abs(reciprocal row sum)*abs(pivot element))
  106. biggest = 0
  107. for k in xrange(j, n):
  108. s = ctx.fsum([ctx.absmin(A[k,l]) for l in xrange(j, n)])
  109. if ctx.absmin(s) <= tol:
  110. raise ZeroDivisionError('matrix is numerically singular')
  111. current = 1/s * ctx.absmin(A[k,j])
  112. if current > biggest: # TODO: what if equal?
  113. biggest = current
  114. p[j] = k
  115. # swap rows according to p
  116. ctx.swap_row(A, j, p[j])
  117. if ctx.absmin(A[j,j]) <= tol:
  118. raise ZeroDivisionError('matrix is numerically singular')
  119. # calculate elimination factors and add rows
  120. for i in xrange(j + 1, n):
  121. A[i,j] /= A[j,j]
  122. for k in xrange(j + 1, n):
  123. A[i,k] -= A[i,j]*A[j,k]
  124. if ctx.absmin(A[n - 1,n - 1]) <= tol:
  125. raise ZeroDivisionError('matrix is numerically singular')
  126. # cache decomposition
  127. if not overwrite and isinstance(orig, ctx.matrix):
  128. orig._LU = (A, p)
  129. return A, p
  130. def L_solve(ctx, L, b, p=None):
  131. """
  132. Solve the lower part of a LU factorized matrix for y.
  133. """
  134. if L.rows != L.cols:
  135. raise RuntimeError("need n*n matrix")
  136. n = L.rows
  137. if len(b) != n:
  138. raise ValueError("Value should be equal to n")
  139. b = copy(b)
  140. if p: # swap b according to p
  141. for k in xrange(0, len(p)):
  142. ctx.swap_row(b, k, p[k])
  143. # solve
  144. for i in xrange(1, n):
  145. for j in xrange(i):
  146. b[i] -= L[i,j] * b[j]
  147. return b
  148. def U_solve(ctx, U, y):
  149. """
  150. Solve the upper part of a LU factorized matrix for x.
  151. """
  152. if U.rows != U.cols:
  153. raise RuntimeError("need n*n matrix")
  154. n = U.rows
  155. if len(y) != n:
  156. raise ValueError("Value should be equal to n")
  157. x = copy(y)
  158. for i in xrange(n - 1, -1, -1):
  159. for j in xrange(i + 1, n):
  160. x[i] -= U[i,j] * x[j]
  161. x[i] /= U[i,i]
  162. return x
  163. def lu_solve(ctx, A, b, **kwargs):
  164. """
  165. Ax = b => x
  166. Solve a determined or overdetermined linear equations system.
  167. Fast LU decomposition is used, which is less accurate than QR decomposition
  168. (especially for overdetermined systems), but it's twice as efficient.
  169. Use qr_solve if you want more precision or have to solve a very ill-
  170. conditioned system.
  171. If you specify real=True, it does not check for overdeterminded complex
  172. systems.
  173. """
  174. prec = ctx.prec
  175. try:
  176. ctx.prec += 10
  177. # do not overwrite A nor b
  178. A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy()
  179. if A.rows < A.cols:
  180. raise ValueError('cannot solve underdetermined system')
  181. if A.rows > A.cols:
  182. # use least-squares method if overdetermined
  183. # (this increases errors)
  184. AH = A.H
  185. A = AH * A
  186. b = AH * b
  187. if (kwargs.get('real', False) or
  188. not sum(type(i) is ctx.mpc for i in A)):
  189. # TODO: necessary to check also b?
  190. x = ctx.cholesky_solve(A, b)
  191. else:
  192. x = ctx.lu_solve(A, b)
  193. else:
  194. # LU factorization
  195. A, p = ctx.LU_decomp(A)
  196. b = ctx.L_solve(A, b, p)
  197. x = ctx.U_solve(A, b)
  198. finally:
  199. ctx.prec = prec
  200. return x
  201. def improve_solution(ctx, A, x, b, maxsteps=1):
  202. """
  203. Improve a solution to a linear equation system iteratively.
  204. This re-uses the LU decomposition and is thus cheap.
  205. Usually 3 up to 4 iterations are giving the maximal improvement.
  206. """
  207. if A.rows != A.cols:
  208. raise RuntimeError("need n*n matrix") # TODO: really?
  209. for _ in xrange(maxsteps):
  210. r = ctx.residual(A, x, b)
  211. if ctx.norm(r, 2) < 10*ctx.eps:
  212. break
  213. # this uses cached LU decomposition and is thus cheap
  214. dx = ctx.lu_solve(A, -r)
  215. x += dx
  216. return x
  217. def lu(ctx, A):
  218. """
  219. A -> P, L, U
  220. LU factorisation of a square matrix A. L is the lower, U the upper part.
  221. P is the permutation matrix indicating the row swaps.
  222. P*A = L*U
  223. If you need efficiency, use the low-level method LU_decomp instead, it's
  224. much more memory efficient.
  225. """
  226. # get factorization
  227. A, p = ctx.LU_decomp(A)
  228. n = A.rows
  229. L = ctx.matrix(n)
  230. U = ctx.matrix(n)
  231. for i in xrange(n):
  232. for j in xrange(n):
  233. if i > j:
  234. L[i,j] = A[i,j]
  235. elif i == j:
  236. L[i,j] = 1
  237. U[i,j] = A[i,j]
  238. else:
  239. U[i,j] = A[i,j]
  240. # calculate permutation matrix
  241. P = ctx.eye(n)
  242. for k in xrange(len(p)):
  243. ctx.swap_row(P, k, p[k])
  244. return P, L, U
  245. def unitvector(ctx, n, i):
  246. """
  247. Return the i-th n-dimensional unit vector.
  248. """
  249. assert 0 < i <= n, 'this unit vector does not exist'
  250. return [ctx.zero]*(i-1) + [ctx.one] + [ctx.zero]*(n-i)
  251. def inverse(ctx, A, **kwargs):
  252. """
  253. Calculate the inverse of a matrix.
  254. If you want to solve an equation system Ax = b, it's recommended to use
  255. solve(A, b) instead, it's about 3 times more efficient.
  256. """
  257. prec = ctx.prec
  258. try:
  259. ctx.prec += 10
  260. # do not overwrite A
  261. A = ctx.matrix(A, **kwargs).copy()
  262. n = A.rows
  263. # get LU factorisation
  264. A, p = ctx.LU_decomp(A)
  265. cols = []
  266. # calculate unit vectors and solve corresponding system to get columns
  267. for i in xrange(1, n + 1):
  268. e = ctx.unitvector(n, i)
  269. y = ctx.L_solve(A, e, p)
  270. cols.append(ctx.U_solve(A, y))
  271. # convert columns to matrix
  272. inv = []
  273. for i in xrange(n):
  274. row = []
  275. for j in xrange(n):
  276. row.append(cols[j][i])
  277. inv.append(row)
  278. result = ctx.matrix(inv, **kwargs)
  279. finally:
  280. ctx.prec = prec
  281. return result
  282. def householder(ctx, A):
  283. """
  284. (A|b) -> H, p, x, res
  285. (A|b) is the coefficient matrix with left hand side of an optionally
  286. overdetermined linear equation system.
  287. H and p contain all information about the transformation matrices.
  288. x is the solution, res the residual.
  289. """
  290. if not isinstance(A, ctx.matrix):
  291. raise TypeError("A should be a type of ctx.matrix")
  292. m = A.rows
  293. n = A.cols
  294. if m < n - 1:
  295. raise RuntimeError("Columns should not be less than rows")
  296. # calculate Householder matrix
  297. p = []
  298. for j in xrange(0, n - 1):
  299. s = ctx.fsum(abs(A[i,j])**2 for i in xrange(j, m))
  300. if not abs(s) > ctx.eps:
  301. raise ValueError('matrix is numerically singular')
  302. p.append(-ctx.sign(ctx.re(A[j,j])) * ctx.sqrt(s))
  303. kappa = ctx.one / (s - p[j] * A[j,j])
  304. A[j,j] -= p[j]
  305. for k in xrange(j+1, n):
  306. y = ctx.fsum(ctx.conj(A[i,j]) * A[i,k] for i in xrange(j, m)) * kappa
  307. for i in xrange(j, m):
  308. A[i,k] -= A[i,j] * y
  309. # solve Rx = c1
  310. x = [A[i,n - 1] for i in xrange(n - 1)]
  311. for i in xrange(n - 2, -1, -1):
  312. x[i] -= ctx.fsum(A[i,j] * x[j] for j in xrange(i + 1, n - 1))
  313. x[i] /= p[i]
  314. # calculate residual
  315. if not m == n - 1:
  316. r = [A[m-1-i, n-1] for i in xrange(m - n + 1)]
  317. else:
  318. # determined system, residual should be 0
  319. r = [0]*m # maybe a bad idea, changing r[i] will change all elements
  320. return A, p, x, r
  321. #def qr(ctx, A):
  322. # """
  323. # A -> Q, R
  324. #
  325. # QR factorisation of a square matrix A using Householder decomposition.
  326. # Q is orthogonal, this leads to very few numerical errors.
  327. #
  328. # A = Q*R
  329. # """
  330. # H, p, x, res = householder(A)
  331. # TODO: implement this
  332. def residual(ctx, A, x, b, **kwargs):
  333. """
  334. Calculate the residual of a solution to a linear equation system.
  335. r = A*x - b for A*x = b
  336. """
  337. oldprec = ctx.prec
  338. try:
  339. ctx.prec *= 2
  340. A, x, b = ctx.matrix(A, **kwargs), ctx.matrix(x, **kwargs), ctx.matrix(b, **kwargs)
  341. return A*x - b
  342. finally:
  343. ctx.prec = oldprec
  344. def qr_solve(ctx, A, b, norm=None, **kwargs):
  345. """
  346. Ax = b => x, ||Ax - b||
  347. Solve a determined or overdetermined linear equations system and
  348. calculate the norm of the residual (error).
  349. QR decomposition using Householder factorization is applied, which gives very
  350. accurate results even for ill-conditioned matrices. qr_solve is twice as
  351. efficient.
  352. """
  353. if norm is None:
  354. norm = ctx.norm
  355. prec = ctx.prec
  356. try:
  357. ctx.prec += 10
  358. # do not overwrite A nor b
  359. A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy()
  360. if A.rows < A.cols:
  361. raise ValueError('cannot solve underdetermined system')
  362. H, p, x, r = ctx.householder(ctx.extend(A, b))
  363. res = ctx.norm(r)
  364. # calculate residual "manually" for determined systems
  365. if res == 0:
  366. res = ctx.norm(ctx.residual(A, x, b))
  367. return ctx.matrix(x, **kwargs), res
  368. finally:
  369. ctx.prec = prec
  370. def cholesky(ctx, A, tol=None):
  371. r"""
  372. Cholesky decomposition of a symmetric positive-definite matrix `A`.
  373. Returns a lower triangular matrix `L` such that `A = L \times L^T`.
  374. More generally, for a complex Hermitian positive-definite matrix,
  375. a Cholesky decomposition satisfying `A = L \times L^H` is returned.
  376. The Cholesky decomposition can be used to solve linear equation
  377. systems twice as efficiently as LU decomposition, or to
  378. test whether `A` is positive-definite.
  379. The optional parameter ``tol`` determines the tolerance for
  380. verifying positive-definiteness.
  381. **Examples**
  382. Cholesky decomposition of a positive-definite symmetric matrix::
  383. >>> from mpmath import *
  384. >>> mp.dps = 25; mp.pretty = True
  385. >>> A = eye(3) + hilbert(3)
  386. >>> nprint(A)
  387. [ 2.0 0.5 0.333333]
  388. [ 0.5 1.33333 0.25]
  389. [0.333333 0.25 1.2]
  390. >>> L = cholesky(A)
  391. >>> nprint(L)
  392. [ 1.41421 0.0 0.0]
  393. [0.353553 1.09924 0.0]
  394. [0.235702 0.15162 1.05899]
  395. >>> chop(A - L*L.T)
  396. [0.0 0.0 0.0]
  397. [0.0 0.0 0.0]
  398. [0.0 0.0 0.0]
  399. Cholesky decomposition of a Hermitian matrix::
  400. >>> A = eye(3) + matrix([[0,0.25j,-0.5j],[-0.25j,0,0],[0.5j,0,0]])
  401. >>> L = cholesky(A)
  402. >>> nprint(L)
  403. [ 1.0 0.0 0.0]
  404. [(0.0 - 0.25j) (0.968246 + 0.0j) 0.0]
  405. [ (0.0 + 0.5j) (0.129099 + 0.0j) (0.856349 + 0.0j)]
  406. >>> chop(A - L*L.H)
  407. [0.0 0.0 0.0]
  408. [0.0 0.0 0.0]
  409. [0.0 0.0 0.0]
  410. Attempted Cholesky decomposition of a matrix that is not positive
  411. definite::
  412. >>> A = -eye(3) + hilbert(3)
  413. >>> L = cholesky(A)
  414. Traceback (most recent call last):
  415. ...
  416. ValueError: matrix is not positive-definite
  417. **References**
  418. 1. [Wikipedia]_ http://en.wikipedia.org/wiki/Cholesky_decomposition
  419. """
  420. if not isinstance(A, ctx.matrix):
  421. raise RuntimeError("A should be a type of ctx.matrix")
  422. if not A.rows == A.cols:
  423. raise ValueError('need n*n matrix')
  424. if tol is None:
  425. tol = +ctx.eps
  426. n = A.rows
  427. L = ctx.matrix(n)
  428. for j in xrange(n):
  429. c = ctx.re(A[j,j])
  430. if abs(c-A[j,j]) > tol:
  431. raise ValueError('matrix is not Hermitian')
  432. s = c - ctx.fsum((L[j,k] for k in xrange(j)),
  433. absolute=True, squared=True)
  434. if s < tol:
  435. raise ValueError('matrix is not positive-definite')
  436. L[j,j] = ctx.sqrt(s)
  437. for i in xrange(j, n):
  438. it1 = (L[i,k] for k in xrange(j))
  439. it2 = (L[j,k] for k in xrange(j))
  440. t = ctx.fdot(it1, it2, conjugate=True)
  441. L[i,j] = (A[i,j] - t) / L[j,j]
  442. return L
  443. def cholesky_solve(ctx, A, b, **kwargs):
  444. """
  445. Ax = b => x
  446. Solve a symmetric positive-definite linear equation system.
  447. This is twice as efficient as lu_solve.
  448. Typical use cases:
  449. * A.T*A
  450. * Hessian matrix
  451. * differential equations
  452. """
  453. prec = ctx.prec
  454. try:
  455. ctx.prec += 10
  456. # do not overwrite A nor b
  457. A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy()
  458. if A.rows != A.cols:
  459. raise ValueError('can only solve determined system')
  460. # Cholesky factorization
  461. L = ctx.cholesky(A)
  462. # solve
  463. n = L.rows
  464. if len(b) != n:
  465. raise ValueError("Value should be equal to n")
  466. for i in xrange(n):
  467. b[i] -= ctx.fsum(L[i,j] * b[j] for j in xrange(i))
  468. b[i] /= L[i,i]
  469. x = ctx.U_solve(L.T, b)
  470. return x
  471. finally:
  472. ctx.prec = prec
  473. def det(ctx, A):
  474. """
  475. Calculate the determinant of a matrix.
  476. """
  477. prec = ctx.prec
  478. try:
  479. # do not overwrite A
  480. A = ctx.matrix(A).copy()
  481. # use LU factorization to calculate determinant
  482. try:
  483. R, p = ctx.LU_decomp(A)
  484. except ZeroDivisionError:
  485. return 0
  486. z = 1
  487. for i, e in enumerate(p):
  488. if i != e:
  489. z *= -1
  490. for i in xrange(A.rows):
  491. z *= R[i,i]
  492. return z
  493. finally:
  494. ctx.prec = prec
  495. def cond(ctx, A, norm=None):
  496. """
  497. Calculate the condition number of a matrix using a specified matrix norm.
  498. The condition number estimates the sensitivity of a matrix to errors.
  499. Example: small input errors for ill-conditioned coefficient matrices
  500. alter the solution of the system dramatically.
  501. For ill-conditioned matrices it's recommended to use qr_solve() instead
  502. of lu_solve(). This does not help with input errors however, it just avoids
  503. to add additional errors.
  504. Definition: cond(A) = ||A|| * ||A**-1||
  505. """
  506. if norm is None:
  507. norm = lambda x: ctx.mnorm(x,1)
  508. return norm(A) * norm(ctx.inverse(A))
  509. def lu_solve_mat(ctx, a, b):
  510. """Solve a * x = b where a and b are matrices."""
  511. r = ctx.matrix(a.rows, b.cols)
  512. for i in range(b.cols):
  513. c = ctx.lu_solve(a, b.column(i))
  514. for j in range(len(c)):
  515. r[j, i] = c[j]
  516. return r
  517. def qr(ctx, A, mode = 'full', edps = 10):
  518. """
  519. Compute a QR factorization $A = QR$ where
  520. A is an m x n matrix of real or complex numbers where m >= n
  521. mode has following meanings:
  522. (1) mode = 'raw' returns two matrixes (A, tau) in the
  523. internal format used by LAPACK
  524. (2) mode = 'skinny' returns the leading n columns of Q
  525. and n rows of R
  526. (3) Any other value returns the leading m columns of Q
  527. and m rows of R
  528. edps is the increase in mp precision used for calculations
  529. **Examples**
  530. >>> from mpmath import *
  531. >>> mp.dps = 15
  532. >>> mp.pretty = True
  533. >>> A = matrix([[1, 2], [3, 4], [1, 1]])
  534. >>> Q, R = qr(A)
  535. >>> Q
  536. [-0.301511344577764 0.861640436855329 0.408248290463863]
  537. [-0.904534033733291 -0.123091490979333 -0.408248290463863]
  538. [-0.301511344577764 -0.492365963917331 0.816496580927726]
  539. >>> R
  540. [-3.3166247903554 -4.52267016866645]
  541. [ 0.0 0.738548945875996]
  542. [ 0.0 0.0]
  543. >>> Q * R
  544. [1.0 2.0]
  545. [3.0 4.0]
  546. [1.0 1.0]
  547. >>> chop(Q.T * Q)
  548. [1.0 0.0 0.0]
  549. [0.0 1.0 0.0]
  550. [0.0 0.0 1.0]
  551. >>> B = matrix([[1+0j, 2-3j], [3+j, 4+5j]])
  552. >>> Q, R = qr(B)
  553. >>> nprint(Q)
  554. [ (-0.301511 + 0.0j) (0.0695795 - 0.95092j)]
  555. [(-0.904534 - 0.301511j) (-0.115966 + 0.278318j)]
  556. >>> nprint(R)
  557. [(-3.31662 + 0.0j) (-5.72872 - 2.41209j)]
  558. [ 0.0 (3.91965 + 0.0j)]
  559. >>> Q * R
  560. [(1.0 + 0.0j) (2.0 - 3.0j)]
  561. [(3.0 + 1.0j) (4.0 + 5.0j)]
  562. >>> chop(Q.T * Q.conjugate())
  563. [1.0 0.0]
  564. [0.0 1.0]
  565. """
  566. # check values before continuing
  567. assert isinstance(A, ctx.matrix)
  568. m = A.rows
  569. n = A.cols
  570. assert n >= 0
  571. assert m >= n
  572. assert edps >= 0
  573. # check for complex data type
  574. cmplx = any(type(x) is ctx.mpc for x in A)
  575. # temporarily increase the precision and initialize
  576. with ctx.extradps(edps):
  577. tau = ctx.matrix(n,1)
  578. A = A.copy()
  579. # ---------------
  580. # FACTOR MATRIX A
  581. # ---------------
  582. if cmplx:
  583. one = ctx.mpc('1.0', '0.0')
  584. zero = ctx.mpc('0.0', '0.0')
  585. rzero = ctx.mpf('0.0')
  586. # main loop to factor A (complex)
  587. for j in xrange(0, n):
  588. alpha = A[j,j]
  589. alphr = ctx.re(alpha)
  590. alphi = ctx.im(alpha)
  591. if (m-j) >= 2:
  592. xnorm = ctx.fsum( A[i,j]*ctx.conj(A[i,j]) for i in xrange(j+1, m) )
  593. xnorm = ctx.re( ctx.sqrt(xnorm) )
  594. else:
  595. xnorm = rzero
  596. if (xnorm == rzero) and (alphi == rzero):
  597. tau[j] = zero
  598. continue
  599. if alphr < rzero:
  600. beta = ctx.sqrt(alphr**2 + alphi**2 + xnorm**2)
  601. else:
  602. beta = -ctx.sqrt(alphr**2 + alphi**2 + xnorm**2)
  603. tau[j] = ctx.mpc( (beta - alphr) / beta, -alphi / beta )
  604. t = -ctx.conj(tau[j])
  605. za = one / (alpha - beta)
  606. for i in xrange(j+1, m):
  607. A[i,j] *= za
  608. A[j,j] = one
  609. for k in xrange(j+1, n):
  610. y = ctx.fsum(A[i,j] * ctx.conj(A[i,k]) for i in xrange(j, m))
  611. temp = t * ctx.conj(y)
  612. for i in xrange(j, m):
  613. A[i,k] += A[i,j] * temp
  614. A[j,j] = ctx.mpc(beta, '0.0')
  615. else:
  616. one = ctx.mpf('1.0')
  617. zero = ctx.mpf('0.0')
  618. # main loop to factor A (real)
  619. for j in xrange(0, n):
  620. alpha = A[j,j]
  621. if (m-j) > 2:
  622. xnorm = ctx.fsum( (A[i,j])**2 for i in xrange(j+1, m) )
  623. xnorm = ctx.sqrt(xnorm)
  624. elif (m-j) == 2:
  625. xnorm = abs( A[m-1,j] )
  626. else:
  627. xnorm = zero
  628. if xnorm == zero:
  629. tau[j] = zero
  630. continue
  631. if alpha < zero:
  632. beta = ctx.sqrt(alpha**2 + xnorm**2)
  633. else:
  634. beta = -ctx.sqrt(alpha**2 + xnorm**2)
  635. tau[j] = (beta - alpha) / beta
  636. t = -tau[j]
  637. da = one / (alpha - beta)
  638. for i in xrange(j+1, m):
  639. A[i,j] *= da
  640. A[j,j] = one
  641. for k in xrange(j+1, n):
  642. y = ctx.fsum( A[i,j] * A[i,k] for i in xrange(j, m) )
  643. temp = t * y
  644. for i in xrange(j,m):
  645. A[i,k] += A[i,j] * temp
  646. A[j,j] = beta
  647. # return factorization in same internal format as LAPACK
  648. if (mode == 'raw') or (mode == 'RAW'):
  649. return A, tau
  650. # ----------------------------------
  651. # FORM Q USING BACKWARD ACCUMULATION
  652. # ----------------------------------
  653. # form R before the values are overwritten
  654. R = A.copy()
  655. for j in xrange(0, n):
  656. for i in xrange(j+1, m):
  657. R[i,j] = zero
  658. # set the value of p (number of columns of Q to return)
  659. p = m
  660. if (mode == 'skinny') or (mode == 'SKINNY'):
  661. p = n
  662. # add columns to A if needed and initialize
  663. A.cols += (p-n)
  664. for j in xrange(0, p):
  665. A[j,j] = one
  666. for i in xrange(0, j):
  667. A[i,j] = zero
  668. # main loop to form Q
  669. for j in xrange(n-1, -1, -1):
  670. t = -tau[j]
  671. A[j,j] += t
  672. for k in xrange(j+1, p):
  673. if cmplx:
  674. y = ctx.fsum(A[i,j] * ctx.conj(A[i,k]) for i in xrange(j+1, m))
  675. temp = t * ctx.conj(y)
  676. else:
  677. y = ctx.fsum(A[i,j] * A[i,k] for i in xrange(j+1, m))
  678. temp = t * y
  679. A[j,k] = temp
  680. for i in xrange(j+1, m):
  681. A[i,k] += A[i,j] * temp
  682. for i in xrange(j+1, m):
  683. A[i, j] *= t
  684. return A, R[0:p,0:n]
  685. # ------------------
  686. # END OF FUNCTION QR
  687. # ------------------