linalg.py 26 KB

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