test_onenormest.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. """Test functions for the sparse.linalg._onenormest module
  2. """
  3. import numpy as np
  4. from numpy.testing import assert_allclose, assert_equal, assert_
  5. import pytest
  6. import scipy.linalg
  7. import scipy.sparse.linalg
  8. from scipy.sparse.linalg._onenormest import _onenormest_core, _algorithm_2_2
  9. class MatrixProductOperator(scipy.sparse.linalg.LinearOperator):
  10. """
  11. This is purely for onenormest testing.
  12. """
  13. def __init__(self, A, B):
  14. if A.ndim != 2 or B.ndim != 2:
  15. raise ValueError('expected ndarrays representing matrices')
  16. if A.shape[1] != B.shape[0]:
  17. raise ValueError('incompatible shapes')
  18. self.A = A
  19. self.B = B
  20. self.ndim = 2
  21. self.shape = (A.shape[0], B.shape[1])
  22. def _matvec(self, x):
  23. return np.dot(self.A, np.dot(self.B, x))
  24. def _rmatvec(self, x):
  25. return np.dot(np.dot(x, self.A), self.B)
  26. def _matmat(self, X):
  27. return np.dot(self.A, np.dot(self.B, X))
  28. @property
  29. def T(self):
  30. return MatrixProductOperator(self.B.T, self.A.T)
  31. class TestOnenormest:
  32. @pytest.mark.xslow
  33. def test_onenormest_table_3_t_2(self):
  34. # This will take multiple seconds if your computer is slow like mine.
  35. # It is stochastic, so the tolerance could be too strict.
  36. np.random.seed(1234)
  37. t = 2
  38. n = 100
  39. itmax = 5
  40. nsamples = 5000
  41. observed = []
  42. expected = []
  43. nmult_list = []
  44. nresample_list = []
  45. for i in range(nsamples):
  46. A = scipy.linalg.inv(np.random.randn(n, n))
  47. est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax)
  48. observed.append(est)
  49. expected.append(scipy.linalg.norm(A, 1))
  50. nmult_list.append(nmults)
  51. nresample_list.append(nresamples)
  52. observed = np.array(observed, dtype=float)
  53. expected = np.array(expected, dtype=float)
  54. relative_errors = np.abs(observed - expected) / expected
  55. # check the mean underestimation ratio
  56. underestimation_ratio = observed / expected
  57. assert_(0.99 < np.mean(underestimation_ratio) < 1.0)
  58. # check the max and mean required column resamples
  59. assert_equal(np.max(nresample_list), 2)
  60. assert_(0.05 < np.mean(nresample_list) < 0.2)
  61. # check the proportion of norms computed exactly correctly
  62. nexact = np.count_nonzero(relative_errors < 1e-14)
  63. proportion_exact = nexact / float(nsamples)
  64. assert_(0.9 < proportion_exact < 0.95)
  65. # check the average number of matrix*vector multiplications
  66. assert_(3.5 < np.mean(nmult_list) < 4.5)
  67. @pytest.mark.xslow
  68. def test_onenormest_table_4_t_7(self):
  69. # This will take multiple seconds if your computer is slow like mine.
  70. # It is stochastic, so the tolerance could be too strict.
  71. np.random.seed(1234)
  72. t = 7
  73. n = 100
  74. itmax = 5
  75. nsamples = 5000
  76. observed = []
  77. expected = []
  78. nmult_list = []
  79. nresample_list = []
  80. for i in range(nsamples):
  81. A = np.random.randint(-1, 2, size=(n, n))
  82. est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax)
  83. observed.append(est)
  84. expected.append(scipy.linalg.norm(A, 1))
  85. nmult_list.append(nmults)
  86. nresample_list.append(nresamples)
  87. observed = np.array(observed, dtype=float)
  88. expected = np.array(expected, dtype=float)
  89. relative_errors = np.abs(observed - expected) / expected
  90. # check the mean underestimation ratio
  91. underestimation_ratio = observed / expected
  92. assert_(0.90 < np.mean(underestimation_ratio) < 0.99)
  93. # check the required column resamples
  94. assert_equal(np.max(nresample_list), 0)
  95. # check the proportion of norms computed exactly correctly
  96. nexact = np.count_nonzero(relative_errors < 1e-14)
  97. proportion_exact = nexact / float(nsamples)
  98. assert_(0.15 < proportion_exact < 0.25)
  99. # check the average number of matrix*vector multiplications
  100. assert_(3.5 < np.mean(nmult_list) < 4.5)
  101. def test_onenormest_table_5_t_1(self):
  102. # "note that there is no randomness and hence only one estimate for t=1"
  103. t = 1
  104. n = 100
  105. itmax = 5
  106. alpha = 1 - 1e-6
  107. A = -scipy.linalg.inv(np.identity(n) + alpha*np.eye(n, k=1))
  108. first_col = np.array([1] + [0]*(n-1))
  109. first_row = np.array([(-alpha)**i for i in range(n)])
  110. B = -scipy.linalg.toeplitz(first_col, first_row)
  111. assert_allclose(A, B)
  112. est, v, w, nmults, nresamples = _onenormest_core(B, B.T, t, itmax)
  113. exact_value = scipy.linalg.norm(B, 1)
  114. underest_ratio = est / exact_value
  115. assert_allclose(underest_ratio, 0.05, rtol=1e-4)
  116. assert_equal(nmults, 11)
  117. assert_equal(nresamples, 0)
  118. # check the non-underscored version of onenormest
  119. est_plain = scipy.sparse.linalg.onenormest(B, t=t, itmax=itmax)
  120. assert_allclose(est, est_plain)
  121. @pytest.mark.xslow
  122. def test_onenormest_table_6_t_1(self):
  123. #TODO this test seems to give estimates that match the table,
  124. #TODO even though no attempt has been made to deal with
  125. #TODO complex numbers in the one-norm estimation.
  126. # This will take multiple seconds if your computer is slow like mine.
  127. # It is stochastic, so the tolerance could be too strict.
  128. np.random.seed(1234)
  129. t = 1
  130. n = 100
  131. itmax = 5
  132. nsamples = 5000
  133. observed = []
  134. expected = []
  135. nmult_list = []
  136. nresample_list = []
  137. for i in range(nsamples):
  138. A_inv = np.random.rand(n, n) + 1j * np.random.rand(n, n)
  139. A = scipy.linalg.inv(A_inv)
  140. est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax)
  141. observed.append(est)
  142. expected.append(scipy.linalg.norm(A, 1))
  143. nmult_list.append(nmults)
  144. nresample_list.append(nresamples)
  145. observed = np.array(observed, dtype=float)
  146. expected = np.array(expected, dtype=float)
  147. relative_errors = np.abs(observed - expected) / expected
  148. # check the mean underestimation ratio
  149. underestimation_ratio = observed / expected
  150. underestimation_ratio_mean = np.mean(underestimation_ratio)
  151. assert_(0.90 < underestimation_ratio_mean < 0.99)
  152. # check the required column resamples
  153. max_nresamples = np.max(nresample_list)
  154. assert_equal(max_nresamples, 0)
  155. # check the proportion of norms computed exactly correctly
  156. nexact = np.count_nonzero(relative_errors < 1e-14)
  157. proportion_exact = nexact / float(nsamples)
  158. assert_(0.7 < proportion_exact < 0.8)
  159. # check the average number of matrix*vector multiplications
  160. mean_nmult = np.mean(nmult_list)
  161. assert_(4 < mean_nmult < 5)
  162. def _help_product_norm_slow(self, A, B):
  163. # for profiling
  164. C = np.dot(A, B)
  165. return scipy.linalg.norm(C, 1)
  166. def _help_product_norm_fast(self, A, B):
  167. # for profiling
  168. t = 2
  169. itmax = 5
  170. D = MatrixProductOperator(A, B)
  171. est, v, w, nmults, nresamples = _onenormest_core(D, D.T, t, itmax)
  172. return est
  173. @pytest.mark.slow
  174. def test_onenormest_linear_operator(self):
  175. # Define a matrix through its product A B.
  176. # Depending on the shapes of A and B,
  177. # it could be easy to multiply this product by a small matrix,
  178. # but it could be annoying to look at all of
  179. # the entries of the product explicitly.
  180. np.random.seed(1234)
  181. n = 6000
  182. k = 3
  183. A = np.random.randn(n, k)
  184. B = np.random.randn(k, n)
  185. fast_estimate = self._help_product_norm_fast(A, B)
  186. exact_value = self._help_product_norm_slow(A, B)
  187. assert_(fast_estimate <= exact_value <= 3*fast_estimate,
  188. 'fast: %g\nexact:%g' % (fast_estimate, exact_value))
  189. def test_returns(self):
  190. np.random.seed(1234)
  191. A = scipy.sparse.rand(50, 50, 0.1)
  192. s0 = scipy.linalg.norm(A.toarray(), 1)
  193. s1, v = scipy.sparse.linalg.onenormest(A, compute_v=True)
  194. s2, w = scipy.sparse.linalg.onenormest(A, compute_w=True)
  195. s3, v2, w2 = scipy.sparse.linalg.onenormest(A, compute_w=True, compute_v=True)
  196. assert_allclose(s1, s0, rtol=1e-9)
  197. assert_allclose(np.linalg.norm(A.dot(v), 1), s0*np.linalg.norm(v, 1), rtol=1e-9)
  198. assert_allclose(A.dot(v), w, rtol=1e-9)
  199. class TestAlgorithm_2_2:
  200. def test_randn_inv(self):
  201. np.random.seed(1234)
  202. n = 20
  203. nsamples = 100
  204. for i in range(nsamples):
  205. # Choose integer t uniformly between 1 and 3 inclusive.
  206. t = np.random.randint(1, 4)
  207. # Choose n uniformly between 10 and 40 inclusive.
  208. n = np.random.randint(10, 41)
  209. # Sample the inverse of a matrix with random normal entries.
  210. A = scipy.linalg.inv(np.random.randn(n, n))
  211. # Compute the 1-norm bounds.
  212. g, ind = _algorithm_2_2(A, A.T, t)