solvers.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. from sympy.core.function import expand_mul
  2. from sympy.core.symbol import Dummy, uniquely_named_symbol, symbols
  3. from sympy.utilities.iterables import numbered_symbols
  4. from .common import ShapeError, NonSquareMatrixError, NonInvertibleMatrixError
  5. from .eigen import _fuzzy_positive_definite
  6. from .utilities import _get_intermediate_simp, _iszero
  7. def _diagonal_solve(M, rhs):
  8. """Solves ``Ax = B`` efficiently, where A is a diagonal Matrix,
  9. with non-zero diagonal entries.
  10. Examples
  11. ========
  12. >>> from sympy import Matrix, eye
  13. >>> A = eye(2)*2
  14. >>> B = Matrix([[1, 2], [3, 4]])
  15. >>> A.diagonal_solve(B) == B/2
  16. True
  17. See Also
  18. ========
  19. sympy.matrices.dense.DenseMatrix.lower_triangular_solve
  20. sympy.matrices.dense.DenseMatrix.upper_triangular_solve
  21. gauss_jordan_solve
  22. cholesky_solve
  23. LDLsolve
  24. LUsolve
  25. QRsolve
  26. pinv_solve
  27. """
  28. if not M.is_diagonal():
  29. raise TypeError("Matrix should be diagonal")
  30. if rhs.rows != M.rows:
  31. raise TypeError("Size mis-match")
  32. return M._new(
  33. rhs.rows, rhs.cols, lambda i, j: rhs[i, j] / M[i, i])
  34. def _lower_triangular_solve(M, rhs):
  35. """Solves ``Ax = B``, where A is a lower triangular matrix.
  36. See Also
  37. ========
  38. upper_triangular_solve
  39. gauss_jordan_solve
  40. cholesky_solve
  41. diagonal_solve
  42. LDLsolve
  43. LUsolve
  44. QRsolve
  45. pinv_solve
  46. """
  47. from .dense import MutableDenseMatrix
  48. if not M.is_square:
  49. raise NonSquareMatrixError("Matrix must be square.")
  50. if rhs.rows != M.rows:
  51. raise ShapeError("Matrices size mismatch.")
  52. if not M.is_lower:
  53. raise ValueError("Matrix must be lower triangular.")
  54. dps = _get_intermediate_simp()
  55. X = MutableDenseMatrix.zeros(M.rows, rhs.cols)
  56. for j in range(rhs.cols):
  57. for i in range(M.rows):
  58. if M[i, i] == 0:
  59. raise TypeError("Matrix must be non-singular.")
  60. X[i, j] = dps((rhs[i, j] - sum(M[i, k]*X[k, j]
  61. for k in range(i))) / M[i, i])
  62. return M._new(X)
  63. def _lower_triangular_solve_sparse(M, rhs):
  64. """Solves ``Ax = B``, where A is a lower triangular matrix.
  65. See Also
  66. ========
  67. upper_triangular_solve
  68. gauss_jordan_solve
  69. cholesky_solve
  70. diagonal_solve
  71. LDLsolve
  72. LUsolve
  73. QRsolve
  74. pinv_solve
  75. """
  76. if not M.is_square:
  77. raise NonSquareMatrixError("Matrix must be square.")
  78. if rhs.rows != M.rows:
  79. raise ShapeError("Matrices size mismatch.")
  80. if not M.is_lower:
  81. raise ValueError("Matrix must be lower triangular.")
  82. dps = _get_intermediate_simp()
  83. rows = [[] for i in range(M.rows)]
  84. for i, j, v in M.row_list():
  85. if i > j:
  86. rows[i].append((j, v))
  87. X = rhs.as_mutable()
  88. for j in range(rhs.cols):
  89. for i in range(rhs.rows):
  90. for u, v in rows[i]:
  91. X[i, j] -= v*X[u, j]
  92. X[i, j] = dps(X[i, j] / M[i, i])
  93. return M._new(X)
  94. def _upper_triangular_solve(M, rhs):
  95. """Solves ``Ax = B``, where A is an upper triangular matrix.
  96. See Also
  97. ========
  98. lower_triangular_solve
  99. gauss_jordan_solve
  100. cholesky_solve
  101. diagonal_solve
  102. LDLsolve
  103. LUsolve
  104. QRsolve
  105. pinv_solve
  106. """
  107. from .dense import MutableDenseMatrix
  108. if not M.is_square:
  109. raise NonSquareMatrixError("Matrix must be square.")
  110. if rhs.rows != M.rows:
  111. raise ShapeError("Matrix size mismatch.")
  112. if not M.is_upper:
  113. raise TypeError("Matrix is not upper triangular.")
  114. dps = _get_intermediate_simp()
  115. X = MutableDenseMatrix.zeros(M.rows, rhs.cols)
  116. for j in range(rhs.cols):
  117. for i in reversed(range(M.rows)):
  118. if M[i, i] == 0:
  119. raise ValueError("Matrix must be non-singular.")
  120. X[i, j] = dps((rhs[i, j] - sum(M[i, k]*X[k, j]
  121. for k in range(i + 1, M.rows))) / M[i, i])
  122. return M._new(X)
  123. def _upper_triangular_solve_sparse(M, rhs):
  124. """Solves ``Ax = B``, where A is an upper triangular matrix.
  125. See Also
  126. ========
  127. lower_triangular_solve
  128. gauss_jordan_solve
  129. cholesky_solve
  130. diagonal_solve
  131. LDLsolve
  132. LUsolve
  133. QRsolve
  134. pinv_solve
  135. """
  136. if not M.is_square:
  137. raise NonSquareMatrixError("Matrix must be square.")
  138. if rhs.rows != M.rows:
  139. raise ShapeError("Matrix size mismatch.")
  140. if not M.is_upper:
  141. raise TypeError("Matrix is not upper triangular.")
  142. dps = _get_intermediate_simp()
  143. rows = [[] for i in range(M.rows)]
  144. for i, j, v in M.row_list():
  145. if i < j:
  146. rows[i].append((j, v))
  147. X = rhs.as_mutable()
  148. for j in range(rhs.cols):
  149. for i in reversed(range(rhs.rows)):
  150. for u, v in reversed(rows[i]):
  151. X[i, j] -= v*X[u, j]
  152. X[i, j] = dps(X[i, j] / M[i, i])
  153. return M._new(X)
  154. def _cholesky_solve(M, rhs):
  155. """Solves ``Ax = B`` using Cholesky decomposition,
  156. for a general square non-singular matrix.
  157. For a non-square matrix with rows > cols,
  158. the least squares solution is returned.
  159. See Also
  160. ========
  161. sympy.matrices.dense.DenseMatrix.lower_triangular_solve
  162. sympy.matrices.dense.DenseMatrix.upper_triangular_solve
  163. gauss_jordan_solve
  164. diagonal_solve
  165. LDLsolve
  166. LUsolve
  167. QRsolve
  168. pinv_solve
  169. """
  170. if M.rows < M.cols:
  171. raise NotImplementedError(
  172. 'Under-determined System. Try M.gauss_jordan_solve(rhs)')
  173. hermitian = True
  174. reform = False
  175. if M.is_symmetric():
  176. hermitian = False
  177. elif not M.is_hermitian:
  178. reform = True
  179. if reform or _fuzzy_positive_definite(M) is False:
  180. H = M.H
  181. M = H.multiply(M)
  182. rhs = H.multiply(rhs)
  183. hermitian = not M.is_symmetric()
  184. L = M.cholesky(hermitian=hermitian)
  185. Y = L.lower_triangular_solve(rhs)
  186. if hermitian:
  187. return (L.H).upper_triangular_solve(Y)
  188. else:
  189. return (L.T).upper_triangular_solve(Y)
  190. def _LDLsolve(M, rhs):
  191. """Solves ``Ax = B`` using LDL decomposition,
  192. for a general square and non-singular matrix.
  193. For a non-square matrix with rows > cols,
  194. the least squares solution is returned.
  195. Examples
  196. ========
  197. >>> from sympy import Matrix, eye
  198. >>> A = eye(2)*2
  199. >>> B = Matrix([[1, 2], [3, 4]])
  200. >>> A.LDLsolve(B) == B/2
  201. True
  202. See Also
  203. ========
  204. sympy.matrices.dense.DenseMatrix.LDLdecomposition
  205. sympy.matrices.dense.DenseMatrix.lower_triangular_solve
  206. sympy.matrices.dense.DenseMatrix.upper_triangular_solve
  207. gauss_jordan_solve
  208. cholesky_solve
  209. diagonal_solve
  210. LUsolve
  211. QRsolve
  212. pinv_solve
  213. """
  214. if M.rows < M.cols:
  215. raise NotImplementedError(
  216. 'Under-determined System. Try M.gauss_jordan_solve(rhs)')
  217. hermitian = True
  218. reform = False
  219. if M.is_symmetric():
  220. hermitian = False
  221. elif not M.is_hermitian:
  222. reform = True
  223. if reform or _fuzzy_positive_definite(M) is False:
  224. H = M.H
  225. M = H.multiply(M)
  226. rhs = H.multiply(rhs)
  227. hermitian = not M.is_symmetric()
  228. L, D = M.LDLdecomposition(hermitian=hermitian)
  229. Y = L.lower_triangular_solve(rhs)
  230. Z = D.diagonal_solve(Y)
  231. if hermitian:
  232. return (L.H).upper_triangular_solve(Z)
  233. else:
  234. return (L.T).upper_triangular_solve(Z)
  235. def _LUsolve(M, rhs, iszerofunc=_iszero):
  236. """Solve the linear system ``Ax = rhs`` for ``x`` where ``A = M``.
  237. This is for symbolic matrices, for real or complex ones use
  238. mpmath.lu_solve or mpmath.qr_solve.
  239. See Also
  240. ========
  241. sympy.matrices.dense.DenseMatrix.lower_triangular_solve
  242. sympy.matrices.dense.DenseMatrix.upper_triangular_solve
  243. gauss_jordan_solve
  244. cholesky_solve
  245. diagonal_solve
  246. LDLsolve
  247. QRsolve
  248. pinv_solve
  249. LUdecomposition
  250. """
  251. if rhs.rows != M.rows:
  252. raise ShapeError(
  253. "``M`` and ``rhs`` must have the same number of rows.")
  254. m = M.rows
  255. n = M.cols
  256. if m < n:
  257. raise NotImplementedError("Underdetermined systems not supported.")
  258. try:
  259. A, perm = M.LUdecomposition_Simple(
  260. iszerofunc=_iszero, rankcheck=True)
  261. except ValueError:
  262. raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
  263. dps = _get_intermediate_simp()
  264. b = rhs.permute_rows(perm).as_mutable()
  265. # forward substitution, all diag entries are scaled to 1
  266. for i in range(m):
  267. for j in range(min(i, n)):
  268. scale = A[i, j]
  269. b.zip_row_op(i, j, lambda x, y: dps(x - y * scale))
  270. # consistency check for overdetermined systems
  271. if m > n:
  272. for i in range(n, m):
  273. for j in range(b.cols):
  274. if not iszerofunc(b[i, j]):
  275. raise ValueError("The system is inconsistent.")
  276. b = b[0:n, :] # truncate zero rows if consistent
  277. # backward substitution
  278. for i in range(n - 1, -1, -1):
  279. for j in range(i + 1, n):
  280. scale = A[i, j]
  281. b.zip_row_op(i, j, lambda x, y: dps(x - y * scale))
  282. scale = A[i, i]
  283. b.row_op(i, lambda x, _: dps(x / scale))
  284. return rhs.__class__(b)
  285. def _QRsolve(M, b):
  286. """Solve the linear system ``Ax = b``.
  287. ``M`` is the matrix ``A``, the method argument is the vector
  288. ``b``. The method returns the solution vector ``x``. If ``b`` is a
  289. matrix, the system is solved for each column of ``b`` and the
  290. return value is a matrix of the same shape as ``b``.
  291. This method is slower (approximately by a factor of 2) but
  292. more stable for floating-point arithmetic than the LUsolve method.
  293. However, LUsolve usually uses an exact arithmetic, so you do not need
  294. to use QRsolve.
  295. This is mainly for educational purposes and symbolic matrices, for real
  296. (or complex) matrices use mpmath.qr_solve.
  297. See Also
  298. ========
  299. sympy.matrices.dense.DenseMatrix.lower_triangular_solve
  300. sympy.matrices.dense.DenseMatrix.upper_triangular_solve
  301. gauss_jordan_solve
  302. cholesky_solve
  303. diagonal_solve
  304. LDLsolve
  305. LUsolve
  306. pinv_solve
  307. QRdecomposition
  308. """
  309. dps = _get_intermediate_simp(expand_mul, expand_mul)
  310. Q, R = M.QRdecomposition()
  311. y = Q.T * b
  312. # back substitution to solve R*x = y:
  313. # We build up the result "backwards" in the vector 'x' and reverse it
  314. # only in the end.
  315. x = []
  316. n = R.rows
  317. for j in range(n - 1, -1, -1):
  318. tmp = y[j, :]
  319. for k in range(j + 1, n):
  320. tmp -= R[j, k] * x[n - 1 - k]
  321. tmp = dps(tmp)
  322. x.append(tmp / R[j, j])
  323. return M.vstack(*x[::-1])
  324. def _gauss_jordan_solve(M, B, freevar=False):
  325. """
  326. Solves ``Ax = B`` using Gauss Jordan elimination.
  327. There may be zero, one, or infinite solutions. If one solution
  328. exists, it will be returned. If infinite solutions exist, it will
  329. be returned parametrically. If no solutions exist, It will throw
  330. ValueError.
  331. Parameters
  332. ==========
  333. B : Matrix
  334. The right hand side of the equation to be solved for. Must have
  335. the same number of rows as matrix A.
  336. freevar : boolean, optional
  337. Flag, when set to `True` will return the indices of the free
  338. variables in the solutions (column Matrix), for a system that is
  339. undetermined (e.g. A has more columns than rows), for which
  340. infinite solutions are possible, in terms of arbitrary
  341. values of free variables. Default `False`.
  342. Returns
  343. =======
  344. x : Matrix
  345. The matrix that will satisfy ``Ax = B``. Will have as many rows as
  346. matrix A has columns, and as many columns as matrix B.
  347. params : Matrix
  348. If the system is underdetermined (e.g. A has more columns than
  349. rows), infinite solutions are possible, in terms of arbitrary
  350. parameters. These arbitrary parameters are returned as params
  351. Matrix.
  352. free_var_index : List, optional
  353. If the system is underdetermined (e.g. A has more columns than
  354. rows), infinite solutions are possible, in terms of arbitrary
  355. values of free variables. Then the indices of the free variables
  356. in the solutions (column Matrix) are returned by free_var_index,
  357. if the flag `freevar` is set to `True`.
  358. Examples
  359. ========
  360. >>> from sympy import Matrix
  361. >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]])
  362. >>> B = Matrix([7, 12, 4])
  363. >>> sol, params = A.gauss_jordan_solve(B)
  364. >>> sol
  365. Matrix([
  366. [-2*tau0 - 3*tau1 + 2],
  367. [ tau0],
  368. [ 2*tau1 + 5],
  369. [ tau1]])
  370. >>> params
  371. Matrix([
  372. [tau0],
  373. [tau1]])
  374. >>> taus_zeroes = { tau:0 for tau in params }
  375. >>> sol_unique = sol.xreplace(taus_zeroes)
  376. >>> sol_unique
  377. Matrix([
  378. [2],
  379. [0],
  380. [5],
  381. [0]])
  382. >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
  383. >>> B = Matrix([3, 6, 9])
  384. >>> sol, params = A.gauss_jordan_solve(B)
  385. >>> sol
  386. Matrix([
  387. [-1],
  388. [ 2],
  389. [ 0]])
  390. >>> params
  391. Matrix(0, 1, [])
  392. >>> A = Matrix([[2, -7], [-1, 4]])
  393. >>> B = Matrix([[-21, 3], [12, -2]])
  394. >>> sol, params = A.gauss_jordan_solve(B)
  395. >>> sol
  396. Matrix([
  397. [0, -2],
  398. [3, -1]])
  399. >>> params
  400. Matrix(0, 2, [])
  401. >>> from sympy import Matrix
  402. >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]])
  403. >>> B = Matrix([7, 12, 4])
  404. >>> sol, params, freevars = A.gauss_jordan_solve(B, freevar=True)
  405. >>> sol
  406. Matrix([
  407. [-2*tau0 - 3*tau1 + 2],
  408. [ tau0],
  409. [ 2*tau1 + 5],
  410. [ tau1]])
  411. >>> params
  412. Matrix([
  413. [tau0],
  414. [tau1]])
  415. >>> freevars
  416. [1, 3]
  417. See Also
  418. ========
  419. sympy.matrices.dense.DenseMatrix.lower_triangular_solve
  420. sympy.matrices.dense.DenseMatrix.upper_triangular_solve
  421. cholesky_solve
  422. diagonal_solve
  423. LDLsolve
  424. LUsolve
  425. QRsolve
  426. pinv
  427. References
  428. ==========
  429. .. [1] https://en.wikipedia.org/wiki/Gaussian_elimination
  430. """
  431. from sympy.matrices import Matrix, zeros
  432. cls = M.__class__
  433. aug = M.hstack(M.copy(), B.copy())
  434. B_cols = B.cols
  435. row, col = aug[:, :-B_cols].shape
  436. # solve by reduced row echelon form
  437. A, pivots = aug.rref(simplify=True)
  438. A, v = A[:, :-B_cols], A[:, -B_cols:]
  439. pivots = list(filter(lambda p: p < col, pivots))
  440. rank = len(pivots)
  441. # Get index of free symbols (free parameters)
  442. # non-pivots columns are free variables
  443. free_var_index = [c for c in range(A.cols) if c not in pivots]
  444. # Bring to block form
  445. permutation = Matrix(pivots + free_var_index).T
  446. # check for existence of solutions
  447. # rank of aug Matrix should be equal to rank of coefficient matrix
  448. if not v[rank:, :].is_zero_matrix:
  449. raise ValueError("Linear system has no solution")
  450. # Free parameters
  451. # what are current unnumbered free symbol names?
  452. name = uniquely_named_symbol('tau', aug,
  453. compare=lambda i: str(i).rstrip('1234567890'),
  454. modify=lambda s: '_' + s).name
  455. gen = numbered_symbols(name)
  456. tau = Matrix([next(gen) for k in range((col - rank)*B_cols)]).reshape(
  457. col - rank, B_cols)
  458. # Full parametric solution
  459. V = A[:rank, free_var_index]
  460. vt = v[:rank, :]
  461. free_sol = tau.vstack(vt - V * tau, tau)
  462. # Undo permutation
  463. sol = zeros(col, B_cols)
  464. for k in range(col):
  465. sol[permutation[k], :] = free_sol[k,:]
  466. sol, tau = cls(sol), cls(tau)
  467. if freevar:
  468. return sol, tau, free_var_index
  469. else:
  470. return sol, tau
  471. def _pinv_solve(M, B, arbitrary_matrix=None):
  472. """Solve ``Ax = B`` using the Moore-Penrose pseudoinverse.
  473. There may be zero, one, or infinite solutions. If one solution
  474. exists, it will be returned. If infinite solutions exist, one will
  475. be returned based on the value of arbitrary_matrix. If no solutions
  476. exist, the least-squares solution is returned.
  477. Parameters
  478. ==========
  479. B : Matrix
  480. The right hand side of the equation to be solved for. Must have
  481. the same number of rows as matrix A.
  482. arbitrary_matrix : Matrix
  483. If the system is underdetermined (e.g. A has more columns than
  484. rows), infinite solutions are possible, in terms of an arbitrary
  485. matrix. This parameter may be set to a specific matrix to use
  486. for that purpose; if so, it must be the same shape as x, with as
  487. many rows as matrix A has columns, and as many columns as matrix
  488. B. If left as None, an appropriate matrix containing dummy
  489. symbols in the form of ``wn_m`` will be used, with n and m being
  490. row and column position of each symbol.
  491. Returns
  492. =======
  493. x : Matrix
  494. The matrix that will satisfy ``Ax = B``. Will have as many rows as
  495. matrix A has columns, and as many columns as matrix B.
  496. Examples
  497. ========
  498. >>> from sympy import Matrix
  499. >>> A = Matrix([[1, 2, 3], [4, 5, 6]])
  500. >>> B = Matrix([7, 8])
  501. >>> A.pinv_solve(B)
  502. Matrix([
  503. [ _w0_0/6 - _w1_0/3 + _w2_0/6 - 55/18],
  504. [-_w0_0/3 + 2*_w1_0/3 - _w2_0/3 + 1/9],
  505. [ _w0_0/6 - _w1_0/3 + _w2_0/6 + 59/18]])
  506. >>> A.pinv_solve(B, arbitrary_matrix=Matrix([0, 0, 0]))
  507. Matrix([
  508. [-55/18],
  509. [ 1/9],
  510. [ 59/18]])
  511. See Also
  512. ========
  513. sympy.matrices.dense.DenseMatrix.lower_triangular_solve
  514. sympy.matrices.dense.DenseMatrix.upper_triangular_solve
  515. gauss_jordan_solve
  516. cholesky_solve
  517. diagonal_solve
  518. LDLsolve
  519. LUsolve
  520. QRsolve
  521. pinv
  522. Notes
  523. =====
  524. This may return either exact solutions or least squares solutions.
  525. To determine which, check ``A * A.pinv() * B == B``. It will be
  526. True if exact solutions exist, and False if only a least-squares
  527. solution exists. Be aware that the left hand side of that equation
  528. may need to be simplified to correctly compare to the right hand
  529. side.
  530. References
  531. ==========
  532. .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#Obtaining_all_solutions_of_a_linear_system
  533. """
  534. from sympy.matrices import eye
  535. A = M
  536. A_pinv = M.pinv()
  537. if arbitrary_matrix is None:
  538. rows, cols = A.cols, B.cols
  539. w = symbols('w:{}_:{}'.format(rows, cols), cls=Dummy)
  540. arbitrary_matrix = M.__class__(cols, rows, w).T
  541. return A_pinv.multiply(B) + (eye(A.cols) -
  542. A_pinv.multiply(A)).multiply(arbitrary_matrix)
  543. def _solve(M, rhs, method='GJ'):
  544. """Solves linear equation where the unique solution exists.
  545. Parameters
  546. ==========
  547. rhs : Matrix
  548. Vector representing the right hand side of the linear equation.
  549. method : string, optional
  550. If set to ``'GJ'`` or ``'GE'``, the Gauss-Jordan elimination will be
  551. used, which is implemented in the routine ``gauss_jordan_solve``.
  552. If set to ``'LU'``, ``LUsolve`` routine will be used.
  553. If set to ``'QR'``, ``QRsolve`` routine will be used.
  554. If set to ``'PINV'``, ``pinv_solve`` routine will be used.
  555. It also supports the methods available for special linear systems
  556. For positive definite systems:
  557. If set to ``'CH'``, ``cholesky_solve`` routine will be used.
  558. If set to ``'LDL'``, ``LDLsolve`` routine will be used.
  559. To use a different method and to compute the solution via the
  560. inverse, use a method defined in the .inv() docstring.
  561. Returns
  562. =======
  563. solutions : Matrix
  564. Vector representing the solution.
  565. Raises
  566. ======
  567. ValueError
  568. If there is not a unique solution then a ``ValueError`` will be
  569. raised.
  570. If ``M`` is not square, a ``ValueError`` and a different routine
  571. for solving the system will be suggested.
  572. """
  573. if method in ('GJ', 'GE'):
  574. try:
  575. soln, param = M.gauss_jordan_solve(rhs)
  576. if param:
  577. raise NonInvertibleMatrixError("Matrix det == 0; not invertible. "
  578. "Try ``M.gauss_jordan_solve(rhs)`` to obtain a parametric solution.")
  579. except ValueError:
  580. raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
  581. return soln
  582. elif method == 'LU':
  583. return M.LUsolve(rhs)
  584. elif method == 'CH':
  585. return M.cholesky_solve(rhs)
  586. elif method == 'QR':
  587. return M.QRsolve(rhs)
  588. elif method == 'LDL':
  589. return M.LDLsolve(rhs)
  590. elif method == 'PINV':
  591. return M.pinv_solve(rhs)
  592. else:
  593. return M.inv(method=method).multiply(rhs)
  594. def _solve_least_squares(M, rhs, method='CH'):
  595. """Return the least-square fit to the data.
  596. Parameters
  597. ==========
  598. rhs : Matrix
  599. Vector representing the right hand side of the linear equation.
  600. method : string or boolean, optional
  601. If set to ``'CH'``, ``cholesky_solve`` routine will be used.
  602. If set to ``'LDL'``, ``LDLsolve`` routine will be used.
  603. If set to ``'QR'``, ``QRsolve`` routine will be used.
  604. If set to ``'PINV'``, ``pinv_solve`` routine will be used.
  605. Otherwise, the conjugate of ``M`` will be used to create a system
  606. of equations that is passed to ``solve`` along with the hint
  607. defined by ``method``.
  608. Returns
  609. =======
  610. solutions : Matrix
  611. Vector representing the solution.
  612. Examples
  613. ========
  614. >>> from sympy import Matrix, ones
  615. >>> A = Matrix([1, 2, 3])
  616. >>> B = Matrix([2, 3, 4])
  617. >>> S = Matrix(A.row_join(B))
  618. >>> S
  619. Matrix([
  620. [1, 2],
  621. [2, 3],
  622. [3, 4]])
  623. If each line of S represent coefficients of Ax + By
  624. and x and y are [2, 3] then S*xy is:
  625. >>> r = S*Matrix([2, 3]); r
  626. Matrix([
  627. [ 8],
  628. [13],
  629. [18]])
  630. But let's add 1 to the middle value and then solve for the
  631. least-squares value of xy:
  632. >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy
  633. Matrix([
  634. [ 5/3],
  635. [10/3]])
  636. The error is given by S*xy - r:
  637. >>> S*xy - r
  638. Matrix([
  639. [1/3],
  640. [1/3],
  641. [1/3]])
  642. >>> _.norm().n(2)
  643. 0.58
  644. If a different xy is used, the norm will be higher:
  645. >>> xy += ones(2, 1)/10
  646. >>> (S*xy - r).norm().n(2)
  647. 1.5
  648. """
  649. if method == 'CH':
  650. return M.cholesky_solve(rhs)
  651. elif method == 'QR':
  652. return M.QRsolve(rhs)
  653. elif method == 'LDL':
  654. return M.LDLsolve(rhs)
  655. elif method == 'PINV':
  656. return M.pinv_solve(rhs)
  657. else:
  658. t = M.H
  659. return (t * M).solve(t * rhs, method=method)