test_matfuncs.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. #
  2. # Created by: Pearu Peterson, March 2002
  3. #
  4. """ Test functions for scipy.linalg.matfuncs module
  5. """
  6. from __future__ import division, print_function, absolute_import
  7. import math
  8. import numpy as np
  9. from numpy import array, eye, exp, random
  10. from numpy.linalg import matrix_power
  11. from numpy.testing import (
  12. assert_allclose, assert_, assert_array_almost_equal, assert_equal,
  13. assert_array_almost_equal_nulp)
  14. from scipy._lib._numpy_compat import suppress_warnings
  15. from scipy.sparse import csc_matrix, SparseEfficiencyWarning
  16. from scipy.sparse.construct import eye as speye
  17. from scipy.sparse.linalg.matfuncs import (expm, _expm,
  18. ProductOperator, MatrixPowerOperator,
  19. _onenorm_matrix_power_nnm)
  20. from scipy.linalg import logm
  21. from scipy.special import factorial, binom
  22. import scipy.sparse
  23. import scipy.sparse.linalg
  24. def _burkardt_13_power(n, p):
  25. """
  26. A helper function for testing matrix functions.
  27. Parameters
  28. ----------
  29. n : integer greater than 1
  30. Order of the square matrix to be returned.
  31. p : non-negative integer
  32. Power of the matrix.
  33. Returns
  34. -------
  35. out : ndarray representing a square matrix
  36. A Forsythe matrix of order n, raised to the power p.
  37. """
  38. # Input validation.
  39. if n != int(n) or n < 2:
  40. raise ValueError('n must be an integer greater than 1')
  41. n = int(n)
  42. if p != int(p) or p < 0:
  43. raise ValueError('p must be a non-negative integer')
  44. p = int(p)
  45. # Construct the matrix explicitly.
  46. a, b = divmod(p, n)
  47. large = np.power(10.0, -n*a)
  48. small = large * np.power(10.0, -n)
  49. return np.diag([large]*(n-b), b) + np.diag([small]*b, b-n)
  50. def test_onenorm_matrix_power_nnm():
  51. np.random.seed(1234)
  52. for n in range(1, 5):
  53. for p in range(5):
  54. M = np.random.random((n, n))
  55. Mp = np.linalg.matrix_power(M, p)
  56. observed = _onenorm_matrix_power_nnm(M, p)
  57. expected = np.linalg.norm(Mp, 1)
  58. assert_allclose(observed, expected)
  59. class TestExpM(object):
  60. def test_zero_ndarray(self):
  61. a = array([[0.,0],[0,0]])
  62. assert_array_almost_equal(expm(a),[[1,0],[0,1]])
  63. def test_zero_sparse(self):
  64. a = csc_matrix([[0.,0],[0,0]])
  65. assert_array_almost_equal(expm(a).toarray(),[[1,0],[0,1]])
  66. def test_zero_matrix(self):
  67. a = np.matrix([[0.,0],[0,0]])
  68. assert_array_almost_equal(expm(a),[[1,0],[0,1]])
  69. def test_misc_types(self):
  70. A = expm(np.array([[1]]))
  71. assert_allclose(expm(((1,),)), A)
  72. assert_allclose(expm([[1]]), A)
  73. assert_allclose(expm(np.matrix([[1]])), A)
  74. assert_allclose(expm(np.array([[1]])), A)
  75. assert_allclose(expm(csc_matrix([[1]])).A, A)
  76. B = expm(np.array([[1j]]))
  77. assert_allclose(expm(((1j,),)), B)
  78. assert_allclose(expm([[1j]]), B)
  79. assert_allclose(expm(np.matrix([[1j]])), B)
  80. assert_allclose(expm(csc_matrix([[1j]])).A, B)
  81. def test_bidiagonal_sparse(self):
  82. A = csc_matrix([
  83. [1, 3, 0],
  84. [0, 1, 5],
  85. [0, 0, 2]], dtype=float)
  86. e1 = math.exp(1)
  87. e2 = math.exp(2)
  88. expected = np.array([
  89. [e1, 3*e1, 15*(e2 - 2*e1)],
  90. [0, e1, 5*(e2 - e1)],
  91. [0, 0, e2]], dtype=float)
  92. observed = expm(A).toarray()
  93. assert_array_almost_equal(observed, expected)
  94. def test_padecases_dtype_float(self):
  95. for dtype in [np.float32, np.float64]:
  96. for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
  97. A = scale * eye(3, dtype=dtype)
  98. observed = expm(A)
  99. expected = exp(scale) * eye(3, dtype=dtype)
  100. assert_array_almost_equal_nulp(observed, expected, nulp=100)
  101. def test_padecases_dtype_complex(self):
  102. for dtype in [np.complex64, np.complex128]:
  103. for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
  104. A = scale * eye(3, dtype=dtype)
  105. observed = expm(A)
  106. expected = exp(scale) * eye(3, dtype=dtype)
  107. assert_array_almost_equal_nulp(observed, expected, nulp=100)
  108. def test_padecases_dtype_sparse_float(self):
  109. # float32 and complex64 lead to errors in spsolve/UMFpack
  110. dtype = np.float64
  111. for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
  112. a = scale * speye(3, 3, dtype=dtype, format='csc')
  113. e = exp(scale) * eye(3, dtype=dtype)
  114. with suppress_warnings() as sup:
  115. sup.filter(SparseEfficiencyWarning,
  116. "Changing the sparsity structure of a csc_matrix is expensive.")
  117. exact_onenorm = _expm(a, use_exact_onenorm=True).toarray()
  118. inexact_onenorm = _expm(a, use_exact_onenorm=False).toarray()
  119. assert_array_almost_equal_nulp(exact_onenorm, e, nulp=100)
  120. assert_array_almost_equal_nulp(inexact_onenorm, e, nulp=100)
  121. def test_padecases_dtype_sparse_complex(self):
  122. # float32 and complex64 lead to errors in spsolve/UMFpack
  123. dtype = np.complex128
  124. for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
  125. a = scale * speye(3, 3, dtype=dtype, format='csc')
  126. e = exp(scale) * eye(3, dtype=dtype)
  127. with suppress_warnings() as sup:
  128. sup.filter(SparseEfficiencyWarning,
  129. "Changing the sparsity structure of a csc_matrix is expensive.")
  130. assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
  131. def test_logm_consistency(self):
  132. random.seed(1234)
  133. for dtype in [np.float64, np.complex128]:
  134. for n in range(1, 10):
  135. for scale in [1e-4, 1e-3, 1e-2, 1e-1, 1, 1e1, 1e2]:
  136. # make logm(A) be of a given scale
  137. A = (eye(n) + random.rand(n, n) * scale).astype(dtype)
  138. if np.iscomplexobj(A):
  139. A = A + 1j * random.rand(n, n) * scale
  140. assert_array_almost_equal(expm(logm(A)), A)
  141. def test_integer_matrix(self):
  142. Q = np.array([
  143. [-3, 1, 1, 1],
  144. [1, -3, 1, 1],
  145. [1, 1, -3, 1],
  146. [1, 1, 1, -3]])
  147. assert_allclose(expm(Q), expm(1.0 * Q))
  148. def test_integer_matrix_2(self):
  149. # Check for integer overflows
  150. Q = np.array([[-500, 500, 0, 0],
  151. [0, -550, 360, 190],
  152. [0, 630, -630, 0],
  153. [0, 0, 0, 0]], dtype=np.int16)
  154. assert_allclose(expm(Q), expm(1.0 * Q))
  155. Q = csc_matrix(Q)
  156. assert_allclose(expm(Q).A, expm(1.0 * Q).A)
  157. def test_triangularity_perturbation(self):
  158. # Experiment (1) of
  159. # Awad H. Al-Mohy and Nicholas J. Higham (2012)
  160. # Improved Inverse Scaling and Squaring Algorithms
  161. # for the Matrix Logarithm.
  162. A = np.array([
  163. [3.2346e-1, 3e4, 3e4, 3e4],
  164. [0, 3.0089e-1, 3e4, 3e4],
  165. [0, 0, 3.221e-1, 3e4],
  166. [0, 0, 0, 3.0744e-1]],
  167. dtype=float)
  168. A_logm = np.array([
  169. [-1.12867982029050462e+00, 9.61418377142025565e+04,
  170. -4.52485573953179264e+09, 2.92496941103871812e+14],
  171. [0.00000000000000000e+00, -1.20101052953082288e+00,
  172. 9.63469687211303099e+04, -4.68104828911105442e+09],
  173. [0.00000000000000000e+00, 0.00000000000000000e+00,
  174. -1.13289322264498393e+00, 9.53249183094775653e+04],
  175. [0.00000000000000000e+00, 0.00000000000000000e+00,
  176. 0.00000000000000000e+00, -1.17947533272554850e+00]],
  177. dtype=float)
  178. assert_allclose(expm(A_logm), A, rtol=1e-4)
  179. # Perturb the upper triangular matrix by tiny amounts,
  180. # so that it becomes technically not upper triangular.
  181. random.seed(1234)
  182. tiny = 1e-17
  183. A_logm_perturbed = A_logm.copy()
  184. A_logm_perturbed[1, 0] = tiny
  185. with suppress_warnings() as sup:
  186. sup.filter(RuntimeWarning, "Ill-conditioned.*")
  187. A_expm_logm_perturbed = expm(A_logm_perturbed)
  188. rtol = 1e-4
  189. atol = 100 * tiny
  190. assert_(not np.allclose(A_expm_logm_perturbed, A, rtol=rtol, atol=atol))
  191. def test_burkardt_1(self):
  192. # This matrix is diagonal.
  193. # The calculation of the matrix exponential is simple.
  194. #
  195. # This is the first of a series of matrix exponential tests
  196. # collected by John Burkardt from the following sources.
  197. #
  198. # Alan Laub,
  199. # Review of "Linear System Theory" by Joao Hespanha,
  200. # SIAM Review,
  201. # Volume 52, Number 4, December 2010, pages 779--781.
  202. #
  203. # Cleve Moler and Charles Van Loan,
  204. # Nineteen Dubious Ways to Compute the Exponential of a Matrix,
  205. # Twenty-Five Years Later,
  206. # SIAM Review,
  207. # Volume 45, Number 1, March 2003, pages 3--49.
  208. #
  209. # Cleve Moler,
  210. # Cleve's Corner: A Balancing Act for the Matrix Exponential,
  211. # 23 July 2012.
  212. #
  213. # Robert Ward,
  214. # Numerical computation of the matrix exponential
  215. # with accuracy estimate,
  216. # SIAM Journal on Numerical Analysis,
  217. # Volume 14, Number 4, September 1977, pages 600--610.
  218. exp1 = np.exp(1)
  219. exp2 = np.exp(2)
  220. A = np.array([
  221. [1, 0],
  222. [0, 2],
  223. ], dtype=float)
  224. desired = np.array([
  225. [exp1, 0],
  226. [0, exp2],
  227. ], dtype=float)
  228. actual = expm(A)
  229. assert_allclose(actual, desired)
  230. def test_burkardt_2(self):
  231. # This matrix is symmetric.
  232. # The calculation of the matrix exponential is straightforward.
  233. A = np.array([
  234. [1, 3],
  235. [3, 2],
  236. ], dtype=float)
  237. desired = np.array([
  238. [39.322809708033859, 46.166301438885753],
  239. [46.166301438885768, 54.711576854329110],
  240. ], dtype=float)
  241. actual = expm(A)
  242. assert_allclose(actual, desired)
  243. def test_burkardt_3(self):
  244. # This example is due to Laub.
  245. # This matrix is ill-suited for the Taylor series approach.
  246. # As powers of A are computed, the entries blow up too quickly.
  247. exp1 = np.exp(1)
  248. exp39 = np.exp(39)
  249. A = np.array([
  250. [0, 1],
  251. [-39, -40],
  252. ], dtype=float)
  253. desired = np.array([
  254. [
  255. 39/(38*exp1) - 1/(38*exp39),
  256. -np.expm1(-38) / (38*exp1)],
  257. [
  258. 39*np.expm1(-38) / (38*exp1),
  259. -1/(38*exp1) + 39/(38*exp39)],
  260. ], dtype=float)
  261. actual = expm(A)
  262. assert_allclose(actual, desired)
  263. def test_burkardt_4(self):
  264. # This example is due to Moler and Van Loan.
  265. # The example will cause problems for the series summation approach,
  266. # as well as for diagonal Pade approximations.
  267. A = np.array([
  268. [-49, 24],
  269. [-64, 31],
  270. ], dtype=float)
  271. U = np.array([[3, 1], [4, 2]], dtype=float)
  272. V = np.array([[1, -1/2], [-2, 3/2]], dtype=float)
  273. w = np.array([-17, -1], dtype=float)
  274. desired = np.dot(U * np.exp(w), V)
  275. actual = expm(A)
  276. assert_allclose(actual, desired)
  277. def test_burkardt_5(self):
  278. # This example is due to Moler and Van Loan.
  279. # This matrix is strictly upper triangular
  280. # All powers of A are zero beyond some (low) limit.
  281. # This example will cause problems for Pade approximations.
  282. A = np.array([
  283. [0, 6, 0, 0],
  284. [0, 0, 6, 0],
  285. [0, 0, 0, 6],
  286. [0, 0, 0, 0],
  287. ], dtype=float)
  288. desired = np.array([
  289. [1, 6, 18, 36],
  290. [0, 1, 6, 18],
  291. [0, 0, 1, 6],
  292. [0, 0, 0, 1],
  293. ], dtype=float)
  294. actual = expm(A)
  295. assert_allclose(actual, desired)
  296. def test_burkardt_6(self):
  297. # This example is due to Moler and Van Loan.
  298. # This matrix does not have a complete set of eigenvectors.
  299. # That means the eigenvector approach will fail.
  300. exp1 = np.exp(1)
  301. A = np.array([
  302. [1, 1],
  303. [0, 1],
  304. ], dtype=float)
  305. desired = np.array([
  306. [exp1, exp1],
  307. [0, exp1],
  308. ], dtype=float)
  309. actual = expm(A)
  310. assert_allclose(actual, desired)
  311. def test_burkardt_7(self):
  312. # This example is due to Moler and Van Loan.
  313. # This matrix is very close to example 5.
  314. # Mathematically, it has a complete set of eigenvectors.
  315. # Numerically, however, the calculation will be suspect.
  316. exp1 = np.exp(1)
  317. eps = np.spacing(1)
  318. A = np.array([
  319. [1 + eps, 1],
  320. [0, 1 - eps],
  321. ], dtype=float)
  322. desired = np.array([
  323. [exp1, exp1],
  324. [0, exp1],
  325. ], dtype=float)
  326. actual = expm(A)
  327. assert_allclose(actual, desired)
  328. def test_burkardt_8(self):
  329. # This matrix was an example in Wikipedia.
  330. exp4 = np.exp(4)
  331. exp16 = np.exp(16)
  332. A = np.array([
  333. [21, 17, 6],
  334. [-5, -1, -6],
  335. [4, 4, 16],
  336. ], dtype=float)
  337. desired = np.array([
  338. [13*exp16 - exp4, 13*exp16 - 5*exp4, 2*exp16 - 2*exp4],
  339. [-9*exp16 + exp4, -9*exp16 + 5*exp4, -2*exp16 + 2*exp4],
  340. [16*exp16, 16*exp16, 4*exp16],
  341. ], dtype=float) * 0.25
  342. actual = expm(A)
  343. assert_allclose(actual, desired)
  344. def test_burkardt_9(self):
  345. # This matrix is due to the NAG Library.
  346. # It is an example for function F01ECF.
  347. A = np.array([
  348. [1, 2, 2, 2],
  349. [3, 1, 1, 2],
  350. [3, 2, 1, 2],
  351. [3, 3, 3, 1],
  352. ], dtype=float)
  353. desired = np.array([
  354. [740.7038, 610.8500, 542.2743, 549.1753],
  355. [731.2510, 603.5524, 535.0884, 542.2743],
  356. [823.7630, 679.4257, 603.5524, 610.8500],
  357. [998.4355, 823.7630, 731.2510, 740.7038],
  358. ], dtype=float)
  359. actual = expm(A)
  360. assert_allclose(actual, desired)
  361. def test_burkardt_10(self):
  362. # This is Ward's example #1.
  363. # It is defective and nonderogatory.
  364. A = np.array([
  365. [4, 2, 0],
  366. [1, 4, 1],
  367. [1, 1, 4],
  368. ], dtype=float)
  369. assert_allclose(sorted(scipy.linalg.eigvals(A)), (3, 3, 6))
  370. desired = np.array([
  371. [147.8666224463699, 183.7651386463682, 71.79703239999647],
  372. [127.7810855231823, 183.7651386463682, 91.88256932318415],
  373. [127.7810855231824, 163.6796017231806, 111.9681062463718],
  374. ], dtype=float)
  375. actual = expm(A)
  376. assert_allclose(actual, desired)
  377. def test_burkardt_11(self):
  378. # This is Ward's example #2.
  379. # It is a symmetric matrix.
  380. A = np.array([
  381. [29.87942128909879, 0.7815750847907159, -2.289519314033932],
  382. [0.7815750847907159, 25.72656945571064, 8.680737820540137],
  383. [-2.289519314033932, 8.680737820540137, 34.39400925519054],
  384. ], dtype=float)
  385. assert_allclose(scipy.linalg.eigvalsh(A), (20, 30, 40))
  386. desired = np.array([
  387. [
  388. 5.496313853692378E+15,
  389. -1.823188097200898E+16,
  390. -3.047577080858001E+16],
  391. [
  392. -1.823188097200899E+16,
  393. 6.060522870222108E+16,
  394. 1.012918429302482E+17],
  395. [
  396. -3.047577080858001E+16,
  397. 1.012918429302482E+17,
  398. 1.692944112408493E+17],
  399. ], dtype=float)
  400. actual = expm(A)
  401. assert_allclose(actual, desired)
  402. def test_burkardt_12(self):
  403. # This is Ward's example #3.
  404. # Ward's algorithm has difficulty estimating the accuracy
  405. # of its results.
  406. A = np.array([
  407. [-131, 19, 18],
  408. [-390, 56, 54],
  409. [-387, 57, 52],
  410. ], dtype=float)
  411. assert_allclose(sorted(scipy.linalg.eigvals(A)), (-20, -2, -1))
  412. desired = np.array([
  413. [-1.509644158793135, 0.3678794391096522, 0.1353352811751005],
  414. [-5.632570799891469, 1.471517758499875, 0.4060058435250609],
  415. [-4.934938326088363, 1.103638317328798, 0.5413411267617766],
  416. ], dtype=float)
  417. actual = expm(A)
  418. assert_allclose(actual, desired)
  419. def test_burkardt_13(self):
  420. # This is Ward's example #4.
  421. # This is a version of the Forsythe matrix.
  422. # The eigenvector problem is badly conditioned.
  423. # Ward's algorithm has difficulty esimating the accuracy
  424. # of its results for this problem.
  425. #
  426. # Check the construction of one instance of this family of matrices.
  427. A4_actual = _burkardt_13_power(4, 1)
  428. A4_desired = [[0, 1, 0, 0],
  429. [0, 0, 1, 0],
  430. [0, 0, 0, 1],
  431. [1e-4, 0, 0, 0]]
  432. assert_allclose(A4_actual, A4_desired)
  433. # Check the expm for a few instances.
  434. for n in (2, 3, 4, 10):
  435. # Approximate expm using Taylor series.
  436. # This works well for this matrix family
  437. # because each matrix in the summation,
  438. # even before dividing by the factorial,
  439. # is entrywise positive with max entry 10**(-floor(p/n)*n).
  440. k = max(1, int(np.ceil(16/n)))
  441. desired = np.zeros((n, n), dtype=float)
  442. for p in range(n*k):
  443. Ap = _burkardt_13_power(n, p)
  444. assert_equal(np.min(Ap), 0)
  445. assert_allclose(np.max(Ap), np.power(10, -np.floor(p/n)*n))
  446. desired += Ap / factorial(p)
  447. actual = expm(_burkardt_13_power(n, 1))
  448. assert_allclose(actual, desired)
  449. def test_burkardt_14(self):
  450. # This is Moler's example.
  451. # This badly scaled matrix caused problems for MATLAB's expm().
  452. A = np.array([
  453. [0, 1e-8, 0],
  454. [-(2e10 + 4e8/6.), -3, 2e10],
  455. [200./3., 0, -200./3.],
  456. ], dtype=float)
  457. desired = np.array([
  458. [0.446849468283175, 1.54044157383952e-09, 0.462811453558774],
  459. [-5743067.77947947, -0.0152830038686819, -4526542.71278401],
  460. [0.447722977849494, 1.54270484519591e-09, 0.463480648837651],
  461. ], dtype=float)
  462. actual = expm(A)
  463. assert_allclose(actual, desired)
  464. def test_pascal(self):
  465. # Test pascal triangle.
  466. # Nilpotent exponential, used to trigger a failure (gh-8029)
  467. for scale in [1.0, 1e-3, 1e-6]:
  468. for n in range(120):
  469. A = np.diag(np.arange(1, n + 1), -1) * scale
  470. B = expm(A)
  471. sc = scale**np.arange(n, -1, -1)
  472. if np.any(sc < 1e-300):
  473. continue
  474. got = B
  475. expected = binom(np.arange(n + 1)[:,None],
  476. np.arange(n + 1)[None,:]) * sc[None,:] / sc[:,None]
  477. err = abs(expected - got).max()
  478. atol = 1e-13 * abs(expected).max()
  479. assert_allclose(got, expected, atol=atol)
  480. def test_matrix_input(self):
  481. # Large np.matrix inputs should work, gh-5546
  482. A = np.zeros((200, 200))
  483. A[-1,0] = 1
  484. B0 = expm(A)
  485. with suppress_warnings() as sup:
  486. sup.filter(DeprecationWarning, "the matrix subclass.*")
  487. sup.filter(PendingDeprecationWarning, "the matrix subclass.*")
  488. B = expm(np.matrix(A))
  489. assert_allclose(B, B0)
  490. class TestOperators(object):
  491. def test_product_operator(self):
  492. random.seed(1234)
  493. n = 5
  494. k = 2
  495. nsamples = 10
  496. for i in range(nsamples):
  497. A = np.random.randn(n, n)
  498. B = np.random.randn(n, n)
  499. C = np.random.randn(n, n)
  500. D = np.random.randn(n, k)
  501. op = ProductOperator(A, B, C)
  502. assert_allclose(op.matmat(D), A.dot(B).dot(C).dot(D))
  503. assert_allclose(op.T.matmat(D), (A.dot(B).dot(C)).T.dot(D))
  504. def test_matrix_power_operator(self):
  505. random.seed(1234)
  506. n = 5
  507. k = 2
  508. p = 3
  509. nsamples = 10
  510. for i in range(nsamples):
  511. A = np.random.randn(n, n)
  512. B = np.random.randn(n, k)
  513. op = MatrixPowerOperator(A, p)
  514. assert_allclose(op.matmat(B), matrix_power(A, p).dot(B))
  515. assert_allclose(op.T.matmat(B), matrix_power(A, p).T.dot(B))