m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2092 lines
73 KiB

6 months ago
  1. """ Test functions for linalg module
  2. """
  3. import os
  4. import sys
  5. import itertools
  6. import traceback
  7. import textwrap
  8. import subprocess
  9. import pytest
  10. import numpy as np
  11. from numpy import array, single, double, csingle, cdouble, dot, identity, matmul
  12. from numpy import multiply, atleast_2d, inf, asarray
  13. from numpy import linalg
  14. from numpy.linalg import matrix_power, norm, matrix_rank, multi_dot, LinAlgError
  15. from numpy.linalg.linalg import _multi_dot_matrix_chain_order
  16. from numpy.testing import (
  17. assert_, assert_equal, assert_raises, assert_array_equal,
  18. assert_almost_equal, assert_allclose, suppress_warnings,
  19. assert_raises_regex, HAS_LAPACK64,
  20. )
  21. from numpy.testing._private.utils import requires_memory
  22. def consistent_subclass(out, in_):
  23. # For ndarray subclass input, our output should have the same subclass
  24. # (non-ndarray input gets converted to ndarray).
  25. return type(out) is (type(in_) if isinstance(in_, np.ndarray)
  26. else np.ndarray)
  27. old_assert_almost_equal = assert_almost_equal
  28. def assert_almost_equal(a, b, single_decimal=6, double_decimal=12, **kw):
  29. if asarray(a).dtype.type in (single, csingle):
  30. decimal = single_decimal
  31. else:
  32. decimal = double_decimal
  33. old_assert_almost_equal(a, b, decimal=decimal, **kw)
  34. def get_real_dtype(dtype):
  35. return {single: single, double: double,
  36. csingle: single, cdouble: double}[dtype]
  37. def get_complex_dtype(dtype):
  38. return {single: csingle, double: cdouble,
  39. csingle: csingle, cdouble: cdouble}[dtype]
  40. def get_rtol(dtype):
  41. # Choose a safe rtol
  42. if dtype in (single, csingle):
  43. return 1e-5
  44. else:
  45. return 1e-11
  46. # used to categorize tests
  47. all_tags = {
  48. 'square', 'nonsquare', 'hermitian', # mutually exclusive
  49. 'generalized', 'size-0', 'strided' # optional additions
  50. }
  51. class LinalgCase:
  52. def __init__(self, name, a, b, tags=set()):
  53. """
  54. A bundle of arguments to be passed to a test case, with an identifying
  55. name, the operands a and b, and a set of tags to filter the tests
  56. """
  57. assert_(isinstance(name, str))
  58. self.name = name
  59. self.a = a
  60. self.b = b
  61. self.tags = frozenset(tags) # prevent shared tags
  62. def check(self, do):
  63. """
  64. Run the function `do` on this test case, expanding arguments
  65. """
  66. do(self.a, self.b, tags=self.tags)
  67. def __repr__(self):
  68. return f'<LinalgCase: {self.name}>'
  69. def apply_tag(tag, cases):
  70. """
  71. Add the given tag (a string) to each of the cases (a list of LinalgCase
  72. objects)
  73. """
  74. assert tag in all_tags, "Invalid tag"
  75. for case in cases:
  76. case.tags = case.tags | {tag}
  77. return cases
  78. #
  79. # Base test cases
  80. #
  81. np.random.seed(1234)
  82. CASES = []
  83. # square test cases
  84. CASES += apply_tag('square', [
  85. LinalgCase("single",
  86. array([[1., 2.], [3., 4.]], dtype=single),
  87. array([2., 1.], dtype=single)),
  88. LinalgCase("double",
  89. array([[1., 2.], [3., 4.]], dtype=double),
  90. array([2., 1.], dtype=double)),
  91. LinalgCase("double_2",
  92. array([[1., 2.], [3., 4.]], dtype=double),
  93. array([[2., 1., 4.], [3., 4., 6.]], dtype=double)),
  94. LinalgCase("csingle",
  95. array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=csingle),
  96. array([2. + 1j, 1. + 2j], dtype=csingle)),
  97. LinalgCase("cdouble",
  98. array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=cdouble),
  99. array([2. + 1j, 1. + 2j], dtype=cdouble)),
  100. LinalgCase("cdouble_2",
  101. array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=cdouble),
  102. array([[2. + 1j, 1. + 2j, 1 + 3j], [1 - 2j, 1 - 3j, 1 - 6j]], dtype=cdouble)),
  103. LinalgCase("0x0",
  104. np.empty((0, 0), dtype=double),
  105. np.empty((0,), dtype=double),
  106. tags={'size-0'}),
  107. LinalgCase("8x8",
  108. np.random.rand(8, 8),
  109. np.random.rand(8)),
  110. LinalgCase("1x1",
  111. np.random.rand(1, 1),
  112. np.random.rand(1)),
  113. LinalgCase("nonarray",
  114. [[1, 2], [3, 4]],
  115. [2, 1]),
  116. ])
  117. # non-square test-cases
  118. CASES += apply_tag('nonsquare', [
  119. LinalgCase("single_nsq_1",
  120. array([[1., 2., 3.], [3., 4., 6.]], dtype=single),
  121. array([2., 1.], dtype=single)),
  122. LinalgCase("single_nsq_2",
  123. array([[1., 2.], [3., 4.], [5., 6.]], dtype=single),
  124. array([2., 1., 3.], dtype=single)),
  125. LinalgCase("double_nsq_1",
  126. array([[1., 2., 3.], [3., 4., 6.]], dtype=double),
  127. array([2., 1.], dtype=double)),
  128. LinalgCase("double_nsq_2",
  129. array([[1., 2.], [3., 4.], [5., 6.]], dtype=double),
  130. array([2., 1., 3.], dtype=double)),
  131. LinalgCase("csingle_nsq_1",
  132. array(
  133. [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=csingle),
  134. array([2. + 1j, 1. + 2j], dtype=csingle)),
  135. LinalgCase("csingle_nsq_2",
  136. array(
  137. [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=csingle),
  138. array([2. + 1j, 1. + 2j, 3. - 3j], dtype=csingle)),
  139. LinalgCase("cdouble_nsq_1",
  140. array(
  141. [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble),
  142. array([2. + 1j, 1. + 2j], dtype=cdouble)),
  143. LinalgCase("cdouble_nsq_2",
  144. array(
  145. [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=cdouble),
  146. array([2. + 1j, 1. + 2j, 3. - 3j], dtype=cdouble)),
  147. LinalgCase("cdouble_nsq_1_2",
  148. array(
  149. [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble),
  150. array([[2. + 1j, 1. + 2j], [1 - 1j, 2 - 2j]], dtype=cdouble)),
  151. LinalgCase("cdouble_nsq_2_2",
  152. array(
  153. [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=cdouble),
  154. array([[2. + 1j, 1. + 2j], [1 - 1j, 2 - 2j], [1 - 1j, 2 - 2j]], dtype=cdouble)),
  155. LinalgCase("8x11",
  156. np.random.rand(8, 11),
  157. np.random.rand(8)),
  158. LinalgCase("1x5",
  159. np.random.rand(1, 5),
  160. np.random.rand(1)),
  161. LinalgCase("5x1",
  162. np.random.rand(5, 1),
  163. np.random.rand(5)),
  164. LinalgCase("0x4",
  165. np.random.rand(0, 4),
  166. np.random.rand(0),
  167. tags={'size-0'}),
  168. LinalgCase("4x0",
  169. np.random.rand(4, 0),
  170. np.random.rand(4),
  171. tags={'size-0'}),
  172. ])
  173. # hermitian test-cases
  174. CASES += apply_tag('hermitian', [
  175. LinalgCase("hsingle",
  176. array([[1., 2.], [2., 1.]], dtype=single),
  177. None),
  178. LinalgCase("hdouble",
  179. array([[1., 2.], [2., 1.]], dtype=double),
  180. None),
  181. LinalgCase("hcsingle",
  182. array([[1., 2 + 3j], [2 - 3j, 1]], dtype=csingle),
  183. None),
  184. LinalgCase("hcdouble",
  185. array([[1., 2 + 3j], [2 - 3j, 1]], dtype=cdouble),
  186. None),
  187. LinalgCase("hempty",
  188. np.empty((0, 0), dtype=double),
  189. None,
  190. tags={'size-0'}),
  191. LinalgCase("hnonarray",
  192. [[1, 2], [2, 1]],
  193. None),
  194. LinalgCase("matrix_b_only",
  195. array([[1., 2.], [2., 1.]]),
  196. None),
  197. LinalgCase("hmatrix_1x1",
  198. np.random.rand(1, 1),
  199. None),
  200. ])
  201. #
  202. # Gufunc test cases
  203. #
  204. def _make_generalized_cases():
  205. new_cases = []
  206. for case in CASES:
  207. if not isinstance(case.a, np.ndarray):
  208. continue
  209. a = np.array([case.a, 2 * case.a, 3 * case.a])
  210. if case.b is None:
  211. b = None
  212. else:
  213. b = np.array([case.b, 7 * case.b, 6 * case.b])
  214. new_case = LinalgCase(case.name + "_tile3", a, b,
  215. tags=case.tags | {'generalized'})
  216. new_cases.append(new_case)
  217. a = np.array([case.a] * 2 * 3).reshape((3, 2) + case.a.shape)
  218. if case.b is None:
  219. b = None
  220. else:
  221. b = np.array([case.b] * 2 * 3).reshape((3, 2) + case.b.shape)
  222. new_case = LinalgCase(case.name + "_tile213", a, b,
  223. tags=case.tags | {'generalized'})
  224. new_cases.append(new_case)
  225. return new_cases
  226. CASES += _make_generalized_cases()
  227. #
  228. # Generate stride combination variations of the above
  229. #
  230. def _stride_comb_iter(x):
  231. """
  232. Generate cartesian product of strides for all axes
  233. """
  234. if not isinstance(x, np.ndarray):
  235. yield x, "nop"
  236. return
  237. stride_set = [(1,)] * x.ndim
  238. stride_set[-1] = (1, 3, -4)
  239. if x.ndim > 1:
  240. stride_set[-2] = (1, 3, -4)
  241. if x.ndim > 2:
  242. stride_set[-3] = (1, -4)
  243. for repeats in itertools.product(*tuple(stride_set)):
  244. new_shape = [abs(a * b) for a, b in zip(x.shape, repeats)]
  245. slices = tuple([slice(None, None, repeat) for repeat in repeats])
  246. # new array with different strides, but same data
  247. xi = np.empty(new_shape, dtype=x.dtype)
  248. xi.view(np.uint32).fill(0xdeadbeef)
  249. xi = xi[slices]
  250. xi[...] = x
  251. xi = xi.view(x.__class__)
  252. assert_(np.all(xi == x))
  253. yield xi, "stride_" + "_".join(["%+d" % j for j in repeats])
  254. # generate also zero strides if possible
  255. if x.ndim >= 1 and x.shape[-1] == 1:
  256. s = list(x.strides)
  257. s[-1] = 0
  258. xi = np.lib.stride_tricks.as_strided(x, strides=s)
  259. yield xi, "stride_xxx_0"
  260. if x.ndim >= 2 and x.shape[-2] == 1:
  261. s = list(x.strides)
  262. s[-2] = 0
  263. xi = np.lib.stride_tricks.as_strided(x, strides=s)
  264. yield xi, "stride_xxx_0_x"
  265. if x.ndim >= 2 and x.shape[:-2] == (1, 1):
  266. s = list(x.strides)
  267. s[-1] = 0
  268. s[-2] = 0
  269. xi = np.lib.stride_tricks.as_strided(x, strides=s)
  270. yield xi, "stride_xxx_0_0"
  271. def _make_strided_cases():
  272. new_cases = []
  273. for case in CASES:
  274. for a, a_label in _stride_comb_iter(case.a):
  275. for b, b_label in _stride_comb_iter(case.b):
  276. new_case = LinalgCase(case.name + "_" + a_label + "_" + b_label, a, b,
  277. tags=case.tags | {'strided'})
  278. new_cases.append(new_case)
  279. return new_cases
  280. CASES += _make_strided_cases()
  281. #
  282. # Test different routines against the above cases
  283. #
  284. class LinalgTestCase:
  285. TEST_CASES = CASES
  286. def check_cases(self, require=set(), exclude=set()):
  287. """
  288. Run func on each of the cases with all of the tags in require, and none
  289. of the tags in exclude
  290. """
  291. for case in self.TEST_CASES:
  292. # filter by require and exclude
  293. if case.tags & require != require:
  294. continue
  295. if case.tags & exclude:
  296. continue
  297. try:
  298. case.check(self.do)
  299. except Exception as e:
  300. msg = f'In test case: {case!r}\n\n'
  301. msg += traceback.format_exc()
  302. raise AssertionError(msg) from e
  303. class LinalgSquareTestCase(LinalgTestCase):
  304. def test_sq_cases(self):
  305. self.check_cases(require={'square'},
  306. exclude={'generalized', 'size-0'})
  307. def test_empty_sq_cases(self):
  308. self.check_cases(require={'square', 'size-0'},
  309. exclude={'generalized'})
  310. class LinalgNonsquareTestCase(LinalgTestCase):
  311. def test_nonsq_cases(self):
  312. self.check_cases(require={'nonsquare'},
  313. exclude={'generalized', 'size-0'})
  314. def test_empty_nonsq_cases(self):
  315. self.check_cases(require={'nonsquare', 'size-0'},
  316. exclude={'generalized'})
  317. class HermitianTestCase(LinalgTestCase):
  318. def test_herm_cases(self):
  319. self.check_cases(require={'hermitian'},
  320. exclude={'generalized', 'size-0'})
  321. def test_empty_herm_cases(self):
  322. self.check_cases(require={'hermitian', 'size-0'},
  323. exclude={'generalized'})
  324. class LinalgGeneralizedSquareTestCase(LinalgTestCase):
  325. @pytest.mark.slow
  326. def test_generalized_sq_cases(self):
  327. self.check_cases(require={'generalized', 'square'},
  328. exclude={'size-0'})
  329. @pytest.mark.slow
  330. def test_generalized_empty_sq_cases(self):
  331. self.check_cases(require={'generalized', 'square', 'size-0'})
  332. class LinalgGeneralizedNonsquareTestCase(LinalgTestCase):
  333. @pytest.mark.slow
  334. def test_generalized_nonsq_cases(self):
  335. self.check_cases(require={'generalized', 'nonsquare'},
  336. exclude={'size-0'})
  337. @pytest.mark.slow
  338. def test_generalized_empty_nonsq_cases(self):
  339. self.check_cases(require={'generalized', 'nonsquare', 'size-0'})
  340. class HermitianGeneralizedTestCase(LinalgTestCase):
  341. @pytest.mark.slow
  342. def test_generalized_herm_cases(self):
  343. self.check_cases(require={'generalized', 'hermitian'},
  344. exclude={'size-0'})
  345. @pytest.mark.slow
  346. def test_generalized_empty_herm_cases(self):
  347. self.check_cases(require={'generalized', 'hermitian', 'size-0'},
  348. exclude={'none'})
  349. def dot_generalized(a, b):
  350. a = asarray(a)
  351. if a.ndim >= 3:
  352. if a.ndim == b.ndim:
  353. # matrix x matrix
  354. new_shape = a.shape[:-1] + b.shape[-1:]
  355. elif a.ndim == b.ndim + 1:
  356. # matrix x vector
  357. new_shape = a.shape[:-1]
  358. else:
  359. raise ValueError("Not implemented...")
  360. r = np.empty(new_shape, dtype=np.common_type(a, b))
  361. for c in itertools.product(*map(range, a.shape[:-2])):
  362. r[c] = dot(a[c], b[c])
  363. return r
  364. else:
  365. return dot(a, b)
  366. def identity_like_generalized(a):
  367. a = asarray(a)
  368. if a.ndim >= 3:
  369. r = np.empty(a.shape, dtype=a.dtype)
  370. r[...] = identity(a.shape[-2])
  371. return r
  372. else:
  373. return identity(a.shape[0])
  374. class SolveCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
  375. # kept apart from TestSolve for use for testing with matrices.
  376. def do(self, a, b, tags):
  377. x = linalg.solve(a, b)
  378. assert_almost_equal(b, dot_generalized(a, x))
  379. assert_(consistent_subclass(x, b))
  380. class TestSolve(SolveCases):
  381. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  382. def test_types(self, dtype):
  383. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  384. assert_equal(linalg.solve(x, x).dtype, dtype)
  385. def test_0_size(self):
  386. class ArraySubclass(np.ndarray):
  387. pass
  388. # Test system of 0x0 matrices
  389. a = np.arange(8).reshape(2, 2, 2)
  390. b = np.arange(6).reshape(1, 2, 3).view(ArraySubclass)
  391. expected = linalg.solve(a, b)[:, 0:0, :]
  392. result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, :])
  393. assert_array_equal(result, expected)
  394. assert_(isinstance(result, ArraySubclass))
  395. # Test errors for non-square and only b's dimension being 0
  396. assert_raises(linalg.LinAlgError, linalg.solve, a[:, 0:0, 0:1], b)
  397. assert_raises(ValueError, linalg.solve, a, b[:, 0:0, :])
  398. # Test broadcasting error
  399. b = np.arange(6).reshape(1, 3, 2) # broadcasting error
  400. assert_raises(ValueError, linalg.solve, a, b)
  401. assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
  402. # Test zero "single equations" with 0x0 matrices.
  403. b = np.arange(2).reshape(1, 2).view(ArraySubclass)
  404. expected = linalg.solve(a, b)[:, 0:0]
  405. result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0])
  406. assert_array_equal(result, expected)
  407. assert_(isinstance(result, ArraySubclass))
  408. b = np.arange(3).reshape(1, 3)
  409. assert_raises(ValueError, linalg.solve, a, b)
  410. assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
  411. assert_raises(ValueError, linalg.solve, a[:, 0:0, 0:0], b)
  412. def test_0_size_k(self):
  413. # test zero multiple equation (K=0) case.
  414. class ArraySubclass(np.ndarray):
  415. pass
  416. a = np.arange(4).reshape(1, 2, 2)
  417. b = np.arange(6).reshape(3, 2, 1).view(ArraySubclass)
  418. expected = linalg.solve(a, b)[:, :, 0:0]
  419. result = linalg.solve(a, b[:, :, 0:0])
  420. assert_array_equal(result, expected)
  421. assert_(isinstance(result, ArraySubclass))
  422. # test both zero.
  423. expected = linalg.solve(a, b)[:, 0:0, 0:0]
  424. result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, 0:0])
  425. assert_array_equal(result, expected)
  426. assert_(isinstance(result, ArraySubclass))
  427. class InvCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
  428. def do(self, a, b, tags):
  429. a_inv = linalg.inv(a)
  430. assert_almost_equal(dot_generalized(a, a_inv),
  431. identity_like_generalized(a))
  432. assert_(consistent_subclass(a_inv, a))
  433. class TestInv(InvCases):
  434. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  435. def test_types(self, dtype):
  436. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  437. assert_equal(linalg.inv(x).dtype, dtype)
  438. def test_0_size(self):
  439. # Check that all kinds of 0-sized arrays work
  440. class ArraySubclass(np.ndarray):
  441. pass
  442. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  443. res = linalg.inv(a)
  444. assert_(res.dtype.type is np.float64)
  445. assert_equal(a.shape, res.shape)
  446. assert_(isinstance(res, ArraySubclass))
  447. a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
  448. res = linalg.inv(a)
  449. assert_(res.dtype.type is np.complex64)
  450. assert_equal(a.shape, res.shape)
  451. assert_(isinstance(res, ArraySubclass))
  452. class EigvalsCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
  453. def do(self, a, b, tags):
  454. ev = linalg.eigvals(a)
  455. evalues, evectors = linalg.eig(a)
  456. assert_almost_equal(ev, evalues)
  457. class TestEigvals(EigvalsCases):
  458. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  459. def test_types(self, dtype):
  460. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  461. assert_equal(linalg.eigvals(x).dtype, dtype)
  462. x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
  463. assert_equal(linalg.eigvals(x).dtype, get_complex_dtype(dtype))
  464. def test_0_size(self):
  465. # Check that all kinds of 0-sized arrays work
  466. class ArraySubclass(np.ndarray):
  467. pass
  468. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  469. res = linalg.eigvals(a)
  470. assert_(res.dtype.type is np.float64)
  471. assert_equal((0, 1), res.shape)
  472. # This is just for documentation, it might make sense to change:
  473. assert_(isinstance(res, np.ndarray))
  474. a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
  475. res = linalg.eigvals(a)
  476. assert_(res.dtype.type is np.complex64)
  477. assert_equal((0,), res.shape)
  478. # This is just for documentation, it might make sense to change:
  479. assert_(isinstance(res, np.ndarray))
  480. class EigCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
  481. def do(self, a, b, tags):
  482. evalues, evectors = linalg.eig(a)
  483. assert_allclose(dot_generalized(a, evectors),
  484. np.asarray(evectors) * np.asarray(evalues)[..., None, :],
  485. rtol=get_rtol(evalues.dtype))
  486. assert_(consistent_subclass(evectors, a))
  487. class TestEig(EigCases):
  488. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  489. def test_types(self, dtype):
  490. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  491. w, v = np.linalg.eig(x)
  492. assert_equal(w.dtype, dtype)
  493. assert_equal(v.dtype, dtype)
  494. x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
  495. w, v = np.linalg.eig(x)
  496. assert_equal(w.dtype, get_complex_dtype(dtype))
  497. assert_equal(v.dtype, get_complex_dtype(dtype))
  498. def test_0_size(self):
  499. # Check that all kinds of 0-sized arrays work
  500. class ArraySubclass(np.ndarray):
  501. pass
  502. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  503. res, res_v = linalg.eig(a)
  504. assert_(res_v.dtype.type is np.float64)
  505. assert_(res.dtype.type is np.float64)
  506. assert_equal(a.shape, res_v.shape)
  507. assert_equal((0, 1), res.shape)
  508. # This is just for documentation, it might make sense to change:
  509. assert_(isinstance(a, np.ndarray))
  510. a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
  511. res, res_v = linalg.eig(a)
  512. assert_(res_v.dtype.type is np.complex64)
  513. assert_(res.dtype.type is np.complex64)
  514. assert_equal(a.shape, res_v.shape)
  515. assert_equal((0,), res.shape)
  516. # This is just for documentation, it might make sense to change:
  517. assert_(isinstance(a, np.ndarray))
  518. class SVDBaseTests:
  519. hermitian = False
  520. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  521. def test_types(self, dtype):
  522. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  523. u, s, vh = linalg.svd(x)
  524. assert_equal(u.dtype, dtype)
  525. assert_equal(s.dtype, get_real_dtype(dtype))
  526. assert_equal(vh.dtype, dtype)
  527. s = linalg.svd(x, compute_uv=False, hermitian=self.hermitian)
  528. assert_equal(s.dtype, get_real_dtype(dtype))
  529. class SVDCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
  530. def do(self, a, b, tags):
  531. u, s, vt = linalg.svd(a, False)
  532. assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[..., None, :],
  533. np.asarray(vt)),
  534. rtol=get_rtol(u.dtype))
  535. assert_(consistent_subclass(u, a))
  536. assert_(consistent_subclass(vt, a))
  537. class TestSVD(SVDCases, SVDBaseTests):
  538. def test_empty_identity(self):
  539. """ Empty input should put an identity matrix in u or vh """
  540. x = np.empty((4, 0))
  541. u, s, vh = linalg.svd(x, compute_uv=True, hermitian=self.hermitian)
  542. assert_equal(u.shape, (4, 4))
  543. assert_equal(vh.shape, (0, 0))
  544. assert_equal(u, np.eye(4))
  545. x = np.empty((0, 4))
  546. u, s, vh = linalg.svd(x, compute_uv=True, hermitian=self.hermitian)
  547. assert_equal(u.shape, (0, 0))
  548. assert_equal(vh.shape, (4, 4))
  549. assert_equal(vh, np.eye(4))
  550. class SVDHermitianCases(HermitianTestCase, HermitianGeneralizedTestCase):
  551. def do(self, a, b, tags):
  552. u, s, vt = linalg.svd(a, False, hermitian=True)
  553. assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[..., None, :],
  554. np.asarray(vt)),
  555. rtol=get_rtol(u.dtype))
  556. def hermitian(mat):
  557. axes = list(range(mat.ndim))
  558. axes[-1], axes[-2] = axes[-2], axes[-1]
  559. return np.conj(np.transpose(mat, axes=axes))
  560. assert_almost_equal(np.matmul(u, hermitian(u)), np.broadcast_to(np.eye(u.shape[-1]), u.shape))
  561. assert_almost_equal(np.matmul(vt, hermitian(vt)), np.broadcast_to(np.eye(vt.shape[-1]), vt.shape))
  562. assert_equal(np.sort(s)[..., ::-1], s)
  563. assert_(consistent_subclass(u, a))
  564. assert_(consistent_subclass(vt, a))
  565. class TestSVDHermitian(SVDHermitianCases, SVDBaseTests):
  566. hermitian = True
  567. class CondCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
  568. # cond(x, p) for p in (None, 2, -2)
  569. def do(self, a, b, tags):
  570. c = asarray(a) # a might be a matrix
  571. if 'size-0' in tags:
  572. assert_raises(LinAlgError, linalg.cond, c)
  573. return
  574. # +-2 norms
  575. s = linalg.svd(c, compute_uv=False)
  576. assert_almost_equal(
  577. linalg.cond(a), s[..., 0] / s[..., -1],
  578. single_decimal=5, double_decimal=11)
  579. assert_almost_equal(
  580. linalg.cond(a, 2), s[..., 0] / s[..., -1],
  581. single_decimal=5, double_decimal=11)
  582. assert_almost_equal(
  583. linalg.cond(a, -2), s[..., -1] / s[..., 0],
  584. single_decimal=5, double_decimal=11)
  585. # Other norms
  586. cinv = np.linalg.inv(c)
  587. assert_almost_equal(
  588. linalg.cond(a, 1),
  589. abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1),
  590. single_decimal=5, double_decimal=11)
  591. assert_almost_equal(
  592. linalg.cond(a, -1),
  593. abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1),
  594. single_decimal=5, double_decimal=11)
  595. assert_almost_equal(
  596. linalg.cond(a, np.inf),
  597. abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1),
  598. single_decimal=5, double_decimal=11)
  599. assert_almost_equal(
  600. linalg.cond(a, -np.inf),
  601. abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1),
  602. single_decimal=5, double_decimal=11)
  603. assert_almost_equal(
  604. linalg.cond(a, 'fro'),
  605. np.sqrt((abs(c)**2).sum(-1).sum(-1)
  606. * (abs(cinv)**2).sum(-1).sum(-1)),
  607. single_decimal=5, double_decimal=11)
  608. class TestCond(CondCases):
  609. def test_basic_nonsvd(self):
  610. # Smoketest the non-svd norms
  611. A = array([[1., 0, 1], [0, -2., 0], [0, 0, 3.]])
  612. assert_almost_equal(linalg.cond(A, inf), 4)
  613. assert_almost_equal(linalg.cond(A, -inf), 2/3)
  614. assert_almost_equal(linalg.cond(A, 1), 4)
  615. assert_almost_equal(linalg.cond(A, -1), 0.5)
  616. assert_almost_equal(linalg.cond(A, 'fro'), np.sqrt(265 / 12))
  617. def test_singular(self):
  618. # Singular matrices have infinite condition number for
  619. # positive norms, and negative norms shouldn't raise
  620. # exceptions
  621. As = [np.zeros((2, 2)), np.ones((2, 2))]
  622. p_pos = [None, 1, 2, 'fro']
  623. p_neg = [-1, -2]
  624. for A, p in itertools.product(As, p_pos):
  625. # Inversion may not hit exact infinity, so just check the
  626. # number is large
  627. assert_(linalg.cond(A, p) > 1e15)
  628. for A, p in itertools.product(As, p_neg):
  629. linalg.cond(A, p)
  630. @pytest.mark.xfail(True, run=False,
  631. reason="Platform/LAPACK-dependent failure, "
  632. "see gh-18914")
  633. def test_nan(self):
  634. # nans should be passed through, not converted to infs
  635. ps = [None, 1, -1, 2, -2, 'fro']
  636. p_pos = [None, 1, 2, 'fro']
  637. A = np.ones((2, 2))
  638. A[0,1] = np.nan
  639. for p in ps:
  640. c = linalg.cond(A, p)
  641. assert_(isinstance(c, np.float_))
  642. assert_(np.isnan(c))
  643. A = np.ones((3, 2, 2))
  644. A[1,0,1] = np.nan
  645. for p in ps:
  646. c = linalg.cond(A, p)
  647. assert_(np.isnan(c[1]))
  648. if p in p_pos:
  649. assert_(c[0] > 1e15)
  650. assert_(c[2] > 1e15)
  651. else:
  652. assert_(not np.isnan(c[0]))
  653. assert_(not np.isnan(c[2]))
  654. def test_stacked_singular(self):
  655. # Check behavior when only some of the stacked matrices are
  656. # singular
  657. np.random.seed(1234)
  658. A = np.random.rand(2, 2, 2, 2)
  659. A[0,0] = 0
  660. A[1,1] = 0
  661. for p in (None, 1, 2, 'fro', -1, -2):
  662. c = linalg.cond(A, p)
  663. assert_equal(c[0,0], np.inf)
  664. assert_equal(c[1,1], np.inf)
  665. assert_(np.isfinite(c[0,1]))
  666. assert_(np.isfinite(c[1,0]))
  667. class PinvCases(LinalgSquareTestCase,
  668. LinalgNonsquareTestCase,
  669. LinalgGeneralizedSquareTestCase,
  670. LinalgGeneralizedNonsquareTestCase):
  671. def do(self, a, b, tags):
  672. a_ginv = linalg.pinv(a)
  673. # `a @ a_ginv == I` does not hold if a is singular
  674. dot = dot_generalized
  675. assert_almost_equal(dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11)
  676. assert_(consistent_subclass(a_ginv, a))
  677. class TestPinv(PinvCases):
  678. pass
  679. class PinvHermitianCases(HermitianTestCase, HermitianGeneralizedTestCase):
  680. def do(self, a, b, tags):
  681. a_ginv = linalg.pinv(a, hermitian=True)
  682. # `a @ a_ginv == I` does not hold if a is singular
  683. dot = dot_generalized
  684. assert_almost_equal(dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11)
  685. assert_(consistent_subclass(a_ginv, a))
  686. class TestPinvHermitian(PinvHermitianCases):
  687. pass
  688. class DetCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
  689. def do(self, a, b, tags):
  690. d = linalg.det(a)
  691. (s, ld) = linalg.slogdet(a)
  692. if asarray(a).dtype.type in (single, double):
  693. ad = asarray(a).astype(double)
  694. else:
  695. ad = asarray(a).astype(cdouble)
  696. ev = linalg.eigvals(ad)
  697. assert_almost_equal(d, multiply.reduce(ev, axis=-1))
  698. assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1))
  699. s = np.atleast_1d(s)
  700. ld = np.atleast_1d(ld)
  701. m = (s != 0)
  702. assert_almost_equal(np.abs(s[m]), 1)
  703. assert_equal(ld[~m], -inf)
  704. class TestDet(DetCases):
  705. def test_zero(self):
  706. assert_equal(linalg.det([[0.0]]), 0.0)
  707. assert_equal(type(linalg.det([[0.0]])), double)
  708. assert_equal(linalg.det([[0.0j]]), 0.0)
  709. assert_equal(type(linalg.det([[0.0j]])), cdouble)
  710. assert_equal(linalg.slogdet([[0.0]]), (0.0, -inf))
  711. assert_equal(type(linalg.slogdet([[0.0]])[0]), double)
  712. assert_equal(type(linalg.slogdet([[0.0]])[1]), double)
  713. assert_equal(linalg.slogdet([[0.0j]]), (0.0j, -inf))
  714. assert_equal(type(linalg.slogdet([[0.0j]])[0]), cdouble)
  715. assert_equal(type(linalg.slogdet([[0.0j]])[1]), double)
  716. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  717. def test_types(self, dtype):
  718. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  719. assert_equal(np.linalg.det(x).dtype, dtype)
  720. ph, s = np.linalg.slogdet(x)
  721. assert_equal(s.dtype, get_real_dtype(dtype))
  722. assert_equal(ph.dtype, dtype)
  723. def test_0_size(self):
  724. a = np.zeros((0, 0), dtype=np.complex64)
  725. res = linalg.det(a)
  726. assert_equal(res, 1.)
  727. assert_(res.dtype.type is np.complex64)
  728. res = linalg.slogdet(a)
  729. assert_equal(res, (1, 0))
  730. assert_(res[0].dtype.type is np.complex64)
  731. assert_(res[1].dtype.type is np.float32)
  732. a = np.zeros((0, 0), dtype=np.float64)
  733. res = linalg.det(a)
  734. assert_equal(res, 1.)
  735. assert_(res.dtype.type is np.float64)
  736. res = linalg.slogdet(a)
  737. assert_equal(res, (1, 0))
  738. assert_(res[0].dtype.type is np.float64)
  739. assert_(res[1].dtype.type is np.float64)
  740. class LstsqCases(LinalgSquareTestCase, LinalgNonsquareTestCase):
  741. def do(self, a, b, tags):
  742. arr = np.asarray(a)
  743. m, n = arr.shape
  744. u, s, vt = linalg.svd(a, False)
  745. x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
  746. if m == 0:
  747. assert_((x == 0).all())
  748. if m <= n:
  749. assert_almost_equal(b, dot(a, x))
  750. assert_equal(rank, m)
  751. else:
  752. assert_equal(rank, n)
  753. assert_almost_equal(sv, sv.__array_wrap__(s))
  754. if rank == n and m > n:
  755. expect_resids = (
  756. np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
  757. expect_resids = np.asarray(expect_resids)
  758. if np.asarray(b).ndim == 1:
  759. expect_resids.shape = (1,)
  760. assert_equal(residuals.shape, expect_resids.shape)
  761. else:
  762. expect_resids = np.array([]).view(type(x))
  763. assert_almost_equal(residuals, expect_resids)
  764. assert_(np.issubdtype(residuals.dtype, np.floating))
  765. assert_(consistent_subclass(x, b))
  766. assert_(consistent_subclass(residuals, b))
  767. class TestLstsq(LstsqCases):
  768. def test_future_rcond(self):
  769. a = np.array([[0., 1., 0., 1., 2., 0.],
  770. [0., 2., 0., 0., 1., 0.],
  771. [1., 0., 1., 0., 0., 4.],
  772. [0., 0., 0., 2., 3., 0.]]).T
  773. b = np.array([1, 0, 0, 0, 0, 0])
  774. with suppress_warnings() as sup:
  775. w = sup.record(FutureWarning, "`rcond` parameter will change")
  776. x, residuals, rank, s = linalg.lstsq(a, b)
  777. assert_(rank == 4)
  778. x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
  779. assert_(rank == 4)
  780. x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
  781. assert_(rank == 3)
  782. # Warning should be raised exactly once (first command)
  783. assert_(len(w) == 1)
  784. @pytest.mark.parametrize(["m", "n", "n_rhs"], [
  785. (4, 2, 2),
  786. (0, 4, 1),
  787. (0, 4, 2),
  788. (4, 0, 1),
  789. (4, 0, 2),
  790. (4, 2, 0),
  791. (0, 0, 0)
  792. ])
  793. def test_empty_a_b(self, m, n, n_rhs):
  794. a = np.arange(m * n).reshape(m, n)
  795. b = np.ones((m, n_rhs))
  796. x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
  797. if m == 0:
  798. assert_((x == 0).all())
  799. assert_equal(x.shape, (n, n_rhs))
  800. assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
  801. if m > n and n_rhs > 0:
  802. # residuals are exactly the squared norms of b's columns
  803. r = b - np.dot(a, x)
  804. assert_almost_equal(residuals, (r * r).sum(axis=-2))
  805. assert_equal(rank, min(m, n))
  806. assert_equal(s.shape, (min(m, n),))
  807. def test_incompatible_dims(self):
  808. # use modified version of docstring example
  809. x = np.array([0, 1, 2, 3])
  810. y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
  811. A = np.vstack([x, np.ones(len(x))]).T
  812. with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
  813. linalg.lstsq(A, y, rcond=None)
  814. @pytest.mark.parametrize('dt', [np.dtype(c) for c in '?bBhHiIqQefdgFDGO'])
  815. class TestMatrixPower:
  816. rshft_0 = np.eye(4)
  817. rshft_1 = rshft_0[[3, 0, 1, 2]]
  818. rshft_2 = rshft_0[[2, 3, 0, 1]]
  819. rshft_3 = rshft_0[[1, 2, 3, 0]]
  820. rshft_all = [rshft_0, rshft_1, rshft_2, rshft_3]
  821. noninv = array([[1, 0], [0, 0]])
  822. stacked = np.block([[[rshft_0]]]*2)
  823. #FIXME the 'e' dtype might work in future
  824. dtnoinv = [object, np.dtype('e'), np.dtype('g'), np.dtype('G')]
  825. def test_large_power(self, dt):
  826. rshft = self.rshft_1.astype(dt)
  827. assert_equal(
  828. matrix_power(rshft, 2**100 + 2**10 + 2**5 + 0), self.rshft_0)
  829. assert_equal(
  830. matrix_power(rshft, 2**100 + 2**10 + 2**5 + 1), self.rshft_1)
  831. assert_equal(
  832. matrix_power(rshft, 2**100 + 2**10 + 2**5 + 2), self.rshft_2)
  833. assert_equal(
  834. matrix_power(rshft, 2**100 + 2**10 + 2**5 + 3), self.rshft_3)
  835. def test_power_is_zero(self, dt):
  836. def tz(M):
  837. mz = matrix_power(M, 0)
  838. assert_equal(mz, identity_like_generalized(M))
  839. assert_equal(mz.dtype, M.dtype)
  840. for mat in self.rshft_all:
  841. tz(mat.astype(dt))
  842. if dt != object:
  843. tz(self.stacked.astype(dt))
  844. def test_power_is_one(self, dt):
  845. def tz(mat):
  846. mz = matrix_power(mat, 1)
  847. assert_equal(mz, mat)
  848. assert_equal(mz.dtype, mat.dtype)
  849. for mat in self.rshft_all:
  850. tz(mat.astype(dt))
  851. if dt != object:
  852. tz(self.stacked.astype(dt))
  853. def test_power_is_two(self, dt):
  854. def tz(mat):
  855. mz = matrix_power(mat, 2)
  856. mmul = matmul if mat.dtype != object else dot
  857. assert_equal(mz, mmul(mat, mat))
  858. assert_equal(mz.dtype, mat.dtype)
  859. for mat in self.rshft_all:
  860. tz(mat.astype(dt))
  861. if dt != object:
  862. tz(self.stacked.astype(dt))
  863. def test_power_is_minus_one(self, dt):
  864. def tz(mat):
  865. invmat = matrix_power(mat, -1)
  866. mmul = matmul if mat.dtype != object else dot
  867. assert_almost_equal(
  868. mmul(invmat, mat), identity_like_generalized(mat))
  869. for mat in self.rshft_all:
  870. if dt not in self.dtnoinv:
  871. tz(mat.astype(dt))
  872. def test_exceptions_bad_power(self, dt):
  873. mat = self.rshft_0.astype(dt)
  874. assert_raises(TypeError, matrix_power, mat, 1.5)
  875. assert_raises(TypeError, matrix_power, mat, [1])
  876. def test_exceptions_non_square(self, dt):
  877. assert_raises(LinAlgError, matrix_power, np.array([1], dt), 1)
  878. assert_raises(LinAlgError, matrix_power, np.array([[1], [2]], dt), 1)
  879. assert_raises(LinAlgError, matrix_power, np.ones((4, 3, 2), dt), 1)
  880. def test_exceptions_not_invertible(self, dt):
  881. if dt in self.dtnoinv:
  882. return
  883. mat = self.noninv.astype(dt)
  884. assert_raises(LinAlgError, matrix_power, mat, -1)
  885. class TestEigvalshCases(HermitianTestCase, HermitianGeneralizedTestCase):
  886. def do(self, a, b, tags):
  887. # note that eigenvalue arrays returned by eig must be sorted since
  888. # their order isn't guaranteed.
  889. ev = linalg.eigvalsh(a, 'L')
  890. evalues, evectors = linalg.eig(a)
  891. evalues.sort(axis=-1)
  892. assert_allclose(ev, evalues, rtol=get_rtol(ev.dtype))
  893. ev2 = linalg.eigvalsh(a, 'U')
  894. assert_allclose(ev2, evalues, rtol=get_rtol(ev.dtype))
  895. class TestEigvalsh:
  896. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  897. def test_types(self, dtype):
  898. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  899. w = np.linalg.eigvalsh(x)
  900. assert_equal(w.dtype, get_real_dtype(dtype))
  901. def test_invalid(self):
  902. x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
  903. assert_raises(ValueError, np.linalg.eigvalsh, x, UPLO="lrong")
  904. assert_raises(ValueError, np.linalg.eigvalsh, x, "lower")
  905. assert_raises(ValueError, np.linalg.eigvalsh, x, "upper")
  906. def test_UPLO(self):
  907. Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
  908. Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
  909. tgt = np.array([-1, 1], dtype=np.double)
  910. rtol = get_rtol(np.double)
  911. # Check default is 'L'
  912. w = np.linalg.eigvalsh(Klo)
  913. assert_allclose(w, tgt, rtol=rtol)
  914. # Check 'L'
  915. w = np.linalg.eigvalsh(Klo, UPLO='L')
  916. assert_allclose(w, tgt, rtol=rtol)
  917. # Check 'l'
  918. w = np.linalg.eigvalsh(Klo, UPLO='l')
  919. assert_allclose(w, tgt, rtol=rtol)
  920. # Check 'U'
  921. w = np.linalg.eigvalsh(Kup, UPLO='U')
  922. assert_allclose(w, tgt, rtol=rtol)
  923. # Check 'u'
  924. w = np.linalg.eigvalsh(Kup, UPLO='u')
  925. assert_allclose(w, tgt, rtol=rtol)
  926. def test_0_size(self):
  927. # Check that all kinds of 0-sized arrays work
  928. class ArraySubclass(np.ndarray):
  929. pass
  930. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  931. res = linalg.eigvalsh(a)
  932. assert_(res.dtype.type is np.float64)
  933. assert_equal((0, 1), res.shape)
  934. # This is just for documentation, it might make sense to change:
  935. assert_(isinstance(res, np.ndarray))
  936. a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
  937. res = linalg.eigvalsh(a)
  938. assert_(res.dtype.type is np.float32)
  939. assert_equal((0,), res.shape)
  940. # This is just for documentation, it might make sense to change:
  941. assert_(isinstance(res, np.ndarray))
  942. class TestEighCases(HermitianTestCase, HermitianGeneralizedTestCase):
  943. def do(self, a, b, tags):
  944. # note that eigenvalue arrays returned by eig must be sorted since
  945. # their order isn't guaranteed.
  946. ev, evc = linalg.eigh(a)
  947. evalues, evectors = linalg.eig(a)
  948. evalues.sort(axis=-1)
  949. assert_almost_equal(ev, evalues)
  950. assert_allclose(dot_generalized(a, evc),
  951. np.asarray(ev)[..., None, :] * np.asarray(evc),
  952. rtol=get_rtol(ev.dtype))
  953. ev2, evc2 = linalg.eigh(a, 'U')
  954. assert_almost_equal(ev2, evalues)
  955. assert_allclose(dot_generalized(a, evc2),
  956. np.asarray(ev2)[..., None, :] * np.asarray(evc2),
  957. rtol=get_rtol(ev.dtype), err_msg=repr(a))
  958. class TestEigh:
  959. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  960. def test_types(self, dtype):
  961. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  962. w, v = np.linalg.eigh(x)
  963. assert_equal(w.dtype, get_real_dtype(dtype))
  964. assert_equal(v.dtype, dtype)
  965. def test_invalid(self):
  966. x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
  967. assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
  968. assert_raises(ValueError, np.linalg.eigh, x, "lower")
  969. assert_raises(ValueError, np.linalg.eigh, x, "upper")
  970. def test_UPLO(self):
  971. Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
  972. Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
  973. tgt = np.array([-1, 1], dtype=np.double)
  974. rtol = get_rtol(np.double)
  975. # Check default is 'L'
  976. w, v = np.linalg.eigh(Klo)
  977. assert_allclose(w, tgt, rtol=rtol)
  978. # Check 'L'
  979. w, v = np.linalg.eigh(Klo, UPLO='L')
  980. assert_allclose(w, tgt, rtol=rtol)
  981. # Check 'l'
  982. w, v = np.linalg.eigh(Klo, UPLO='l')
  983. assert_allclose(w, tgt, rtol=rtol)
  984. # Check 'U'
  985. w, v = np.linalg.eigh(Kup, UPLO='U')
  986. assert_allclose(w, tgt, rtol=rtol)
  987. # Check 'u'
  988. w, v = np.linalg.eigh(Kup, UPLO='u')
  989. assert_allclose(w, tgt, rtol=rtol)
  990. def test_0_size(self):
  991. # Check that all kinds of 0-sized arrays work
  992. class ArraySubclass(np.ndarray):
  993. pass
  994. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  995. res, res_v = linalg.eigh(a)
  996. assert_(res_v.dtype.type is np.float64)
  997. assert_(res.dtype.type is np.float64)
  998. assert_equal(a.shape, res_v.shape)
  999. assert_equal((0, 1), res.shape)
  1000. # This is just for documentation, it might make sense to change:
  1001. assert_(isinstance(a, np.ndarray))
  1002. a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
  1003. res, res_v = linalg.eigh(a)
  1004. assert_(res_v.dtype.type is np.complex64)
  1005. assert_(res.dtype.type is np.float32)
  1006. assert_equal(a.shape, res_v.shape)
  1007. assert_equal((0,), res.shape)
  1008. # This is just for documentation, it might make sense to change:
  1009. assert_(isinstance(a, np.ndarray))
  1010. class _TestNormBase:
  1011. dt = None
  1012. dec = None
  1013. class _TestNormGeneral(_TestNormBase):
  1014. def test_empty(self):
  1015. assert_equal(norm([]), 0.0)
  1016. assert_equal(norm(array([], dtype=self.dt)), 0.0)
  1017. assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0)
  1018. def test_vector_return_type(self):
  1019. a = np.array([1, 0, 1])
  1020. exact_types = np.typecodes['AllInteger']
  1021. inexact_types = np.typecodes['AllFloat']
  1022. all_types = exact_types + inexact_types
  1023. for each_inexact_types in all_types:
  1024. at = a.astype(each_inexact_types)
  1025. an = norm(at, -np.inf)
  1026. assert_(issubclass(an.dtype.type, np.floating))
  1027. assert_almost_equal(an, 0.0)
  1028. with suppress_warnings() as sup:
  1029. sup.filter(RuntimeWarning, "divide by zero encountered")
  1030. an = norm(at, -1)
  1031. assert_(issubclass(an.dtype.type, np.floating))
  1032. assert_almost_equal(an, 0.0)
  1033. an = norm(at, 0)
  1034. assert_(issubclass(an.dtype.type, np.floating))
  1035. assert_almost_equal(an, 2)
  1036. an = norm(at, 1)
  1037. assert_(issubclass(an.dtype.type, np.floating))
  1038. assert_almost_equal(an, 2.0)
  1039. an = norm(at, 2)
  1040. assert_(issubclass(an.dtype.type, np.floating))
  1041. assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/2.0))
  1042. an = norm(at, 4)
  1043. assert_(issubclass(an.dtype.type, np.floating))
  1044. assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/4.0))
  1045. an = norm(at, np.inf)
  1046. assert_(issubclass(an.dtype.type, np.floating))
  1047. assert_almost_equal(an, 1.0)
  1048. def test_vector(self):
  1049. a = [1, 2, 3, 4]
  1050. b = [-1, -2, -3, -4]
  1051. c = [-1, 2, -3, 4]
  1052. def _test(v):
  1053. np.testing.assert_almost_equal(norm(v), 30 ** 0.5,
  1054. decimal=self.dec)
  1055. np.testing.assert_almost_equal(norm(v, inf), 4.0,
  1056. decimal=self.dec)
  1057. np.testing.assert_almost_equal(norm(v, -inf), 1.0,
  1058. decimal=self.dec)
  1059. np.testing.assert_almost_equal(norm(v, 1), 10.0,
  1060. decimal=self.dec)
  1061. np.testing.assert_almost_equal(norm(v, -1), 12.0 / 25,
  1062. decimal=self.dec)
  1063. np.testing.assert_almost_equal(norm(v, 2), 30 ** 0.5,
  1064. decimal=self.dec)
  1065. np.testing.assert_almost_equal(norm(v, -2), ((205. / 144) ** -0.5),
  1066. decimal=self.dec)
  1067. np.testing.assert_almost_equal(norm(v, 0), 4,
  1068. decimal=self.dec)
  1069. for v in (a, b, c,):
  1070. _test(v)
  1071. for v in (array(a, dtype=self.dt), array(b, dtype=self.dt),
  1072. array(c, dtype=self.dt)):
  1073. _test(v)
  1074. def test_axis(self):
  1075. # Vector norms.
  1076. # Compare the use of `axis` with computing the norm of each row
  1077. # or column separately.
  1078. A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
  1079. for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
  1080. expected0 = [norm(A[:, k], ord=order) for k in range(A.shape[1])]
  1081. assert_almost_equal(norm(A, ord=order, axis=0), expected0)
  1082. expected1 = [norm(A[k, :], ord=order) for k in range(A.shape[0])]
  1083. assert_almost_equal(norm(A, ord=order, axis=1), expected1)
  1084. # Matrix norms.
  1085. B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
  1086. nd = B.ndim
  1087. for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro']:
  1088. for axis in itertools.combinations(range(-nd, nd), 2):
  1089. row_axis, col_axis = axis
  1090. if row_axis < 0:
  1091. row_axis += nd
  1092. if col_axis < 0:
  1093. col_axis += nd
  1094. if row_axis == col_axis:
  1095. assert_raises(ValueError, norm, B, ord=order, axis=axis)
  1096. else:
  1097. n = norm(B, ord=order, axis=axis)
  1098. # The logic using k_index only works for nd = 3.
  1099. # This has to be changed if nd is increased.
  1100. k_index = nd - (row_axis + col_axis)
  1101. if row_axis < col_axis:
  1102. expected = [norm(B[:].take(k, axis=k_index), ord=order)
  1103. for k in range(B.shape[k_index])]
  1104. else:
  1105. expected = [norm(B[:].take(k, axis=k_index).T, ord=order)
  1106. for k in range(B.shape[k_index])]
  1107. assert_almost_equal(n, expected)
  1108. def test_keepdims(self):
  1109. A = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
  1110. allclose_err = 'order {0}, axis = {1}'
  1111. shape_err = 'Shape mismatch found {0}, expected {1}, order={2}, axis={3}'
  1112. # check the order=None, axis=None case
  1113. expected = norm(A, ord=None, axis=None)
  1114. found = norm(A, ord=None, axis=None, keepdims=True)
  1115. assert_allclose(np.squeeze(found), expected,
  1116. err_msg=allclose_err.format(None, None))
  1117. expected_shape = (1, 1, 1)
  1118. assert_(found.shape == expected_shape,
  1119. shape_err.format(found.shape, expected_shape, None, None))
  1120. # Vector norms.
  1121. for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
  1122. for k in range(A.ndim):
  1123. expected = norm(A, ord=order, axis=k)
  1124. found = norm(A, ord=order, axis=k, keepdims=True)
  1125. assert_allclose(np.squeeze(found), expected,
  1126. err_msg=allclose_err.format(order, k))
  1127. expected_shape = list(A.shape)
  1128. expected_shape[k] = 1
  1129. expected_shape = tuple(expected_shape)
  1130. assert_(found.shape == expected_shape,
  1131. shape_err.format(found.shape, expected_shape, order, k))
  1132. # Matrix norms.
  1133. for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro', 'nuc']:
  1134. for k in itertools.permutations(range(A.ndim), 2):
  1135. expected = norm(A, ord=order, axis=k)
  1136. found = norm(A, ord=order, axis=k, keepdims=True)
  1137. assert_allclose(np.squeeze(found), expected,
  1138. err_msg=allclose_err.format(order, k))
  1139. expected_shape = list(A.shape)
  1140. expected_shape[k[0]] = 1
  1141. expected_shape[k[1]] = 1
  1142. expected_shape = tuple(expected_shape)
  1143. assert_(found.shape == expected_shape,
  1144. shape_err.format(found.shape, expected_shape, order, k))
  1145. class _TestNorm2D(_TestNormBase):
  1146. # Define the part for 2d arrays separately, so we can subclass this
  1147. # and run the tests using np.matrix in matrixlib.tests.test_matrix_linalg.
  1148. array = np.array
  1149. def test_matrix_empty(self):
  1150. assert_equal(norm(self.array([[]], dtype=self.dt)), 0.0)
  1151. def test_matrix_return_type(self):
  1152. a = self.array([[1, 0, 1], [0, 1, 1]])
  1153. exact_types = np.typecodes['AllInteger']
  1154. # float32, complex64, float64, complex128 types are the only types
  1155. # allowed by `linalg`, which performs the matrix operations used
  1156. # within `norm`.
  1157. inexact_types = 'fdFD'
  1158. all_types = exact_types + inexact_types
  1159. for each_inexact_types in all_types:
  1160. at = a.astype(each_inexact_types)
  1161. an = norm(at, -np.inf)
  1162. assert_(issubclass(an.dtype.type, np.floating))
  1163. assert_almost_equal(an, 2.0)
  1164. with suppress_warnings() as sup:
  1165. sup.filter(RuntimeWarning, "divide by zero encountered")
  1166. an = norm(at, -1)
  1167. assert_(issubclass(an.dtype.type, np.floating))
  1168. assert_almost_equal(an, 1.0)
  1169. an = norm(at, 1)
  1170. assert_(issubclass(an.dtype.type, np.floating))
  1171. assert_almost_equal(an, 2.0)
  1172. an = norm(at, 2)
  1173. assert_(issubclass(an.dtype.type, np.floating))
  1174. assert_almost_equal(an, 3.0**(1.0/2.0))
  1175. an = norm(at, -2)
  1176. assert_(issubclass(an.dtype.type, np.floating))
  1177. assert_almost_equal(an, 1.0)
  1178. an = norm(at, np.inf)
  1179. assert_(issubclass(an.dtype.type, np.floating))
  1180. assert_almost_equal(an, 2.0)
  1181. an = norm(at, 'fro')
  1182. assert_(issubclass(an.dtype.type, np.floating))
  1183. assert_almost_equal(an, 2.0)
  1184. an = norm(at, 'nuc')
  1185. assert_(issubclass(an.dtype.type, np.floating))
  1186. # Lower bar needed to support low precision floats.
  1187. # They end up being off by 1 in the 7th place.
  1188. np.testing.assert_almost_equal(an, 2.7320508075688772, decimal=6)
  1189. def test_matrix_2x2(self):
  1190. A = self.array([[1, 3], [5, 7]], dtype=self.dt)
  1191. assert_almost_equal(norm(A), 84 ** 0.5)
  1192. assert_almost_equal(norm(A, 'fro'), 84 ** 0.5)
  1193. assert_almost_equal(norm(A, 'nuc'), 10.0)
  1194. assert_almost_equal(norm(A, inf), 12.0)
  1195. assert_almost_equal(norm(A, -inf), 4.0)
  1196. assert_almost_equal(norm(A, 1), 10.0)
  1197. assert_almost_equal(norm(A, -1), 6.0)
  1198. assert_almost_equal(norm(A, 2), 9.1231056256176615)
  1199. assert_almost_equal(norm(A, -2), 0.87689437438234041)
  1200. assert_raises(ValueError, norm, A, 'nofro')
  1201. assert_raises(ValueError, norm, A, -3)
  1202. assert_raises(ValueError, norm, A, 0)
  1203. def test_matrix_3x3(self):
  1204. # This test has been added because the 2x2 example
  1205. # happened to have equal nuclear norm and induced 1-norm.
  1206. # The 1/10 scaling factor accommodates the absolute tolerance
  1207. # used in assert_almost_equal.
  1208. A = (1 / 10) * \
  1209. self.array([[1, 2, 3], [6, 0, 5], [3, 2, 1]], dtype=self.dt)
  1210. assert_almost_equal(norm(A), (1 / 10) * 89 ** 0.5)
  1211. assert_almost_equal(norm(A, 'fro'), (1 / 10) * 89 ** 0.5)
  1212. assert_almost_equal(norm(A, 'nuc'), 1.3366836911774836)
  1213. assert_almost_equal(norm(A, inf), 1.1)
  1214. assert_almost_equal(norm(A, -inf), 0.6)
  1215. assert_almost_equal(norm(A, 1), 1.0)
  1216. assert_almost_equal(norm(A, -1), 0.4)
  1217. assert_almost_equal(norm(A, 2), 0.88722940323461277)
  1218. assert_almost_equal(norm(A, -2), 0.19456584790481812)
  1219. def test_bad_args(self):
  1220. # Check that bad arguments raise the appropriate exceptions.
  1221. A = self.array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
  1222. B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
  1223. # Using `axis=<integer>` or passing in a 1-D array implies vector
  1224. # norms are being computed, so also using `ord='fro'`
  1225. # or `ord='nuc'` or any other string raises a ValueError.
  1226. assert_raises(ValueError, norm, A, 'fro', 0)
  1227. assert_raises(ValueError, norm, A, 'nuc', 0)
  1228. assert_raises(ValueError, norm, [3, 4], 'fro', None)
  1229. assert_raises(ValueError, norm, [3, 4], 'nuc', None)
  1230. assert_raises(ValueError, norm, [3, 4], 'test', None)
  1231. # Similarly, norm should raise an exception when ord is any finite
  1232. # number other than 1, 2, -1 or -2 when computing matrix norms.
  1233. for order in [0, 3]:
  1234. assert_raises(ValueError, norm, A, order, None)
  1235. assert_raises(ValueError, norm, A, order, (0, 1))
  1236. assert_raises(ValueError, norm, B, order, (1, 2))
  1237. # Invalid axis
  1238. assert_raises(np.AxisError, norm, B, None, 3)
  1239. assert_raises(np.AxisError, norm, B, None, (2, 3))
  1240. assert_raises(ValueError, norm, B, None, (0, 1, 2))
  1241. class _TestNorm(_TestNorm2D, _TestNormGeneral):
  1242. pass
  1243. class TestNorm_NonSystematic:
  1244. def test_longdouble_norm(self):
  1245. # Non-regression test: p-norm of longdouble would previously raise
  1246. # UnboundLocalError.
  1247. x = np.arange(10, dtype=np.longdouble)
  1248. old_assert_almost_equal(norm(x, ord=3), 12.65, decimal=2)
  1249. def test_intmin(self):
  1250. # Non-regression test: p-norm of signed integer would previously do
  1251. # float cast and abs in the wrong order.
  1252. x = np.array([-2 ** 31], dtype=np.int32)
  1253. old_assert_almost_equal(norm(x, ord=3), 2 ** 31, decimal=5)
  1254. def test_complex_high_ord(self):
  1255. # gh-4156
  1256. d = np.empty((2,), dtype=np.clongdouble)
  1257. d[0] = 6 + 7j
  1258. d[1] = -6 + 7j
  1259. res = 11.615898132184
  1260. old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=10)
  1261. d = d.astype(np.complex128)
  1262. old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=9)
  1263. d = d.astype(np.complex64)
  1264. old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=5)
  1265. # Separate definitions so we can use them for matrix tests.
  1266. class _TestNormDoubleBase(_TestNormBase):
  1267. dt = np.double
  1268. dec = 12
  1269. class _TestNormSingleBase(_TestNormBase):
  1270. dt = np.float32
  1271. dec = 6
  1272. class _TestNormInt64Base(_TestNormBase):
  1273. dt = np.int64
  1274. dec = 12
  1275. class TestNormDouble(_TestNorm, _TestNormDoubleBase):
  1276. pass
  1277. class TestNormSingle(_TestNorm, _TestNormSingleBase):
  1278. pass
  1279. class TestNormInt64(_TestNorm, _TestNormInt64Base):
  1280. pass
  1281. class TestMatrixRank:
  1282. def test_matrix_rank(self):
  1283. # Full rank matrix
  1284. assert_equal(4, matrix_rank(np.eye(4)))
  1285. # rank deficient matrix
  1286. I = np.eye(4)
  1287. I[-1, -1] = 0.
  1288. assert_equal(matrix_rank(I), 3)
  1289. # All zeros - zero rank
  1290. assert_equal(matrix_rank(np.zeros((4, 4))), 0)
  1291. # 1 dimension - rank 1 unless all 0
  1292. assert_equal(matrix_rank([1, 0, 0, 0]), 1)
  1293. assert_equal(matrix_rank(np.zeros((4,))), 0)
  1294. # accepts array-like
  1295. assert_equal(matrix_rank([1]), 1)
  1296. # greater than 2 dimensions treated as stacked matrices
  1297. ms = np.array([I, np.eye(4), np.zeros((4,4))])
  1298. assert_equal(matrix_rank(ms), np.array([3, 4, 0]))
  1299. # works on scalar
  1300. assert_equal(matrix_rank(1), 1)
  1301. def test_symmetric_rank(self):
  1302. assert_equal(4, matrix_rank(np.eye(4), hermitian=True))
  1303. assert_equal(1, matrix_rank(np.ones((4, 4)), hermitian=True))
  1304. assert_equal(0, matrix_rank(np.zeros((4, 4)), hermitian=True))
  1305. # rank deficient matrix
  1306. I = np.eye(4)
  1307. I[-1, -1] = 0.
  1308. assert_equal(3, matrix_rank(I, hermitian=True))
  1309. # manually supplied tolerance
  1310. I[-1, -1] = 1e-8
  1311. assert_equal(4, matrix_rank(I, hermitian=True, tol=0.99e-8))
  1312. assert_equal(3, matrix_rank(I, hermitian=True, tol=1.01e-8))
  1313. def test_reduced_rank():
  1314. # Test matrices with reduced rank
  1315. rng = np.random.RandomState(20120714)
  1316. for i in range(100):
  1317. # Make a rank deficient matrix
  1318. X = rng.normal(size=(40, 10))
  1319. X[:, 0] = X[:, 1] + X[:, 2]
  1320. # Assert that matrix_rank detected deficiency
  1321. assert_equal(matrix_rank(X), 9)
  1322. X[:, 3] = X[:, 4] + X[:, 5]
  1323. assert_equal(matrix_rank(X), 8)
  1324. class TestQR:
  1325. # Define the array class here, so run this on matrices elsewhere.
  1326. array = np.array
  1327. def check_qr(self, a):
  1328. # This test expects the argument `a` to be an ndarray or
  1329. # a subclass of an ndarray of inexact type.
  1330. a_type = type(a)
  1331. a_dtype = a.dtype
  1332. m, n = a.shape
  1333. k = min(m, n)
  1334. # mode == 'complete'
  1335. q, r = linalg.qr(a, mode='complete')
  1336. assert_(q.dtype == a_dtype)
  1337. assert_(r.dtype == a_dtype)
  1338. assert_(isinstance(q, a_type))
  1339. assert_(isinstance(r, a_type))
  1340. assert_(q.shape == (m, m))
  1341. assert_(r.shape == (m, n))
  1342. assert_almost_equal(dot(q, r), a)
  1343. assert_almost_equal(dot(q.T.conj(), q), np.eye(m))
  1344. assert_almost_equal(np.triu(r), r)
  1345. # mode == 'reduced'
  1346. q1, r1 = linalg.qr(a, mode='reduced')
  1347. assert_(q1.dtype == a_dtype)
  1348. assert_(r1.dtype == a_dtype)
  1349. assert_(isinstance(q1, a_type))
  1350. assert_(isinstance(r1, a_type))
  1351. assert_(q1.shape == (m, k))
  1352. assert_(r1.shape == (k, n))
  1353. assert_almost_equal(dot(q1, r1), a)
  1354. assert_almost_equal(dot(q1.T.conj(), q1), np.eye(k))
  1355. assert_almost_equal(np.triu(r1), r1)
  1356. # mode == 'r'
  1357. r2 = linalg.qr(a, mode='r')
  1358. assert_(r2.dtype == a_dtype)
  1359. assert_(isinstance(r2, a_type))
  1360. assert_almost_equal(r2, r1)
  1361. @pytest.mark.parametrize(["m", "n"], [
  1362. (3, 0),
  1363. (0, 3),
  1364. (0, 0)
  1365. ])
  1366. def test_qr_empty(self, m, n):
  1367. k = min(m, n)
  1368. a = np.empty((m, n))
  1369. self.check_qr(a)
  1370. h, tau = np.linalg.qr(a, mode='raw')
  1371. assert_equal(h.dtype, np.double)
  1372. assert_equal(tau.dtype, np.double)
  1373. assert_equal(h.shape, (n, m))
  1374. assert_equal(tau.shape, (k,))
  1375. def test_mode_raw(self):
  1376. # The factorization is not unique and varies between libraries,
  1377. # so it is not possible to check against known values. Functional
  1378. # testing is a possibility, but awaits the exposure of more
  1379. # of the functions in lapack_lite. Consequently, this test is
  1380. # very limited in scope. Note that the results are in FORTRAN
  1381. # order, hence the h arrays are transposed.
  1382. a = self.array([[1, 2], [3, 4], [5, 6]], dtype=np.double)
  1383. # Test double
  1384. h, tau = linalg.qr(a, mode='raw')
  1385. assert_(h.dtype == np.double)
  1386. assert_(tau.dtype == np.double)
  1387. assert_(h.shape == (2, 3))
  1388. assert_(tau.shape == (2,))
  1389. h, tau = linalg.qr(a.T, mode='raw')
  1390. assert_(h.dtype == np.double)
  1391. assert_(tau.dtype == np.double)
  1392. assert_(h.shape == (3, 2))
  1393. assert_(tau.shape == (2,))
  1394. def test_mode_all_but_economic(self):
  1395. a = self.array([[1, 2], [3, 4]])
  1396. b = self.array([[1, 2], [3, 4], [5, 6]])
  1397. for dt in "fd":
  1398. m1 = a.astype(dt)
  1399. m2 = b.astype(dt)
  1400. self.check_qr(m1)
  1401. self.check_qr(m2)
  1402. self.check_qr(m2.T)
  1403. for dt in "fd":
  1404. m1 = 1 + 1j * a.astype(dt)
  1405. m2 = 1 + 1j * b.astype(dt)
  1406. self.check_qr(m1)
  1407. self.check_qr(m2)
  1408. self.check_qr(m2.T)
  1409. class TestCholesky:
  1410. # TODO: are there no other tests for cholesky?
  1411. def test_basic_property(self):
  1412. # Check A = L L^H
  1413. shapes = [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)]
  1414. dtypes = (np.float32, np.float64, np.complex64, np.complex128)
  1415. for shape, dtype in itertools.product(shapes, dtypes):
  1416. np.random.seed(1)
  1417. a = np.random.randn(*shape)
  1418. if np.issubdtype(dtype, np.complexfloating):
  1419. a = a + 1j*np.random.randn(*shape)
  1420. t = list(range(len(shape)))
  1421. t[-2:] = -1, -2
  1422. a = np.matmul(a.transpose(t).conj(), a)
  1423. a = np.asarray(a, dtype=dtype)
  1424. c = np.linalg.cholesky(a)
  1425. b = np.matmul(c, c.transpose(t).conj())
  1426. assert_allclose(b, a,
  1427. err_msg=f'{shape} {dtype}\n{a}\n{c}',
  1428. atol=500 * a.shape[0] * np.finfo(dtype).eps)
  1429. def test_0_size(self):
  1430. class ArraySubclass(np.ndarray):
  1431. pass
  1432. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  1433. res = linalg.cholesky(a)
  1434. assert_equal(a.shape, res.shape)
  1435. assert_(res.dtype.type is np.float64)
  1436. # for documentation purpose:
  1437. assert_(isinstance(res, np.ndarray))
  1438. a = np.zeros((1, 0, 0), dtype=np.complex64).view(ArraySubclass)
  1439. res = linalg.cholesky(a)
  1440. assert_equal(a.shape, res.shape)
  1441. assert_(res.dtype.type is np.complex64)
  1442. assert_(isinstance(res, np.ndarray))
  1443. def test_byteorder_check():
  1444. # Byte order check should pass for native order
  1445. if sys.byteorder == 'little':
  1446. native = '<'
  1447. else:
  1448. native = '>'
  1449. for dtt in (np.float32, np.float64):
  1450. arr = np.eye(4, dtype=dtt)
  1451. n_arr = arr.newbyteorder(native)
  1452. sw_arr = arr.newbyteorder('S').byteswap()
  1453. assert_equal(arr.dtype.byteorder, '=')
  1454. for routine in (linalg.inv, linalg.det, linalg.pinv):
  1455. # Normal call
  1456. res = routine(arr)
  1457. # Native but not '='
  1458. assert_array_equal(res, routine(n_arr))
  1459. # Swapped
  1460. assert_array_equal(res, routine(sw_arr))
  1461. def test_generalized_raise_multiloop():
  1462. # It should raise an error even if the error doesn't occur in the
  1463. # last iteration of the ufunc inner loop
  1464. invertible = np.array([[1, 2], [3, 4]])
  1465. non_invertible = np.array([[1, 1], [1, 1]])
  1466. x = np.zeros([4, 4, 2, 2])[1::2]
  1467. x[...] = invertible
  1468. x[0, 0] = non_invertible
  1469. assert_raises(np.linalg.LinAlgError, np.linalg.inv, x)
  1470. def test_xerbla_override():
  1471. # Check that our xerbla has been successfully linked in. If it is not,
  1472. # the default xerbla routine is called, which prints a message to stdout
  1473. # and may, or may not, abort the process depending on the LAPACK package.
  1474. XERBLA_OK = 255
  1475. try:
  1476. pid = os.fork()
  1477. except (OSError, AttributeError):
  1478. # fork failed, or not running on POSIX
  1479. pytest.skip("Not POSIX or fork failed.")
  1480. if pid == 0:
  1481. # child; close i/o file handles
  1482. os.close(1)
  1483. os.close(0)
  1484. # Avoid producing core files.
  1485. import resource
  1486. resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
  1487. # These calls may abort.
  1488. try:
  1489. np.linalg.lapack_lite.xerbla()
  1490. except ValueError:
  1491. pass
  1492. except Exception:
  1493. os._exit(os.EX_CONFIG)
  1494. try:
  1495. a = np.array([[1.]])
  1496. np.linalg.lapack_lite.dorgqr(
  1497. 1, 1, 1, a,
  1498. 0, # <- invalid value
  1499. a, a, 0, 0)
  1500. except ValueError as e:
  1501. if "DORGQR parameter number 5" in str(e):
  1502. # success, reuse error code to mark success as
  1503. # FORTRAN STOP returns as success.
  1504. os._exit(XERBLA_OK)
  1505. # Did not abort, but our xerbla was not linked in.
  1506. os._exit(os.EX_CONFIG)
  1507. else:
  1508. # parent
  1509. pid, status = os.wait()
  1510. if os.WEXITSTATUS(status) != XERBLA_OK:
  1511. pytest.skip('Numpy xerbla not linked in.')
  1512. @pytest.mark.slow
  1513. def test_sdot_bug_8577():
  1514. # Regression test that loading certain other libraries does not
  1515. # result to wrong results in float32 linear algebra.
  1516. #
  1517. # There's a bug gh-8577 on OSX that can trigger this, and perhaps
  1518. # there are also other situations in which it occurs.
  1519. #
  1520. # Do the check in a separate process.
  1521. bad_libs = ['PyQt5.QtWidgets', 'IPython']
  1522. template = textwrap.dedent("""
  1523. import sys
  1524. {before}
  1525. try:
  1526. import {bad_lib}
  1527. except ImportError:
  1528. sys.exit(0)
  1529. {after}
  1530. x = np.ones(2, dtype=np.float32)
  1531. sys.exit(0 if np.allclose(x.dot(x), 2.0) else 1)
  1532. """)
  1533. for bad_lib in bad_libs:
  1534. code = template.format(before="import numpy as np", after="",
  1535. bad_lib=bad_lib)
  1536. subprocess.check_call([sys.executable, "-c", code])
  1537. # Swapped import order
  1538. code = template.format(after="import numpy as np", before="",
  1539. bad_lib=bad_lib)
  1540. subprocess.check_call([sys.executable, "-c", code])
  1541. class TestMultiDot:
  1542. def test_basic_function_with_three_arguments(self):
  1543. # multi_dot with three arguments uses a fast hand coded algorithm to
  1544. # determine the optimal order. Therefore test it separately.
  1545. A = np.random.random((6, 2))
  1546. B = np.random.random((2, 6))
  1547. C = np.random.random((6, 2))
  1548. assert_almost_equal(multi_dot([A, B, C]), A.dot(B).dot(C))
  1549. assert_almost_equal(multi_dot([A, B, C]), np.dot(A, np.dot(B, C)))
  1550. def test_basic_function_with_two_arguments(self):
  1551. # separate code path with two arguments
  1552. A = np.random.random((6, 2))
  1553. B = np.random.random((2, 6))
  1554. assert_almost_equal(multi_dot([A, B]), A.dot(B))
  1555. assert_almost_equal(multi_dot([A, B]), np.dot(A, B))
  1556. def test_basic_function_with_dynamic_programing_optimization(self):
  1557. # multi_dot with four or more arguments uses the dynamic programing
  1558. # optimization and therefore deserve a separate
  1559. A = np.random.random((6, 2))
  1560. B = np.random.random((2, 6))
  1561. C = np.random.random((6, 2))
  1562. D = np.random.random((2, 1))
  1563. assert_almost_equal(multi_dot([A, B, C, D]), A.dot(B).dot(C).dot(D))
  1564. def test_vector_as_first_argument(self):
  1565. # The first argument can be 1-D
  1566. A1d = np.random.random(2) # 1-D
  1567. B = np.random.random((2, 6))
  1568. C = np.random.random((6, 2))
  1569. D = np.random.random((2, 2))
  1570. # the result should be 1-D
  1571. assert_equal(multi_dot([A1d, B, C, D]).shape, (2,))
  1572. def test_vector_as_last_argument(self):
  1573. # The last argument can be 1-D
  1574. A = np.random.random((6, 2))
  1575. B = np.random.random((2, 6))
  1576. C = np.random.random((6, 2))
  1577. D1d = np.random.random(2) # 1-D
  1578. # the result should be 1-D
  1579. assert_equal(multi_dot([A, B, C, D1d]).shape, (6,))
  1580. def test_vector_as_first_and_last_argument(self):
  1581. # The first and last arguments can be 1-D
  1582. A1d = np.random.random(2) # 1-D
  1583. B = np.random.random((2, 6))
  1584. C = np.random.random((6, 2))
  1585. D1d = np.random.random(2) # 1-D
  1586. # the result should be a scalar
  1587. assert_equal(multi_dot([A1d, B, C, D1d]).shape, ())
  1588. def test_three_arguments_and_out(self):
  1589. # multi_dot with three arguments uses a fast hand coded algorithm to
  1590. # determine the optimal order. Therefore test it separately.
  1591. A = np.random.random((6, 2))
  1592. B = np.random.random((2, 6))
  1593. C = np.random.random((6, 2))
  1594. out = np.zeros((6, 2))
  1595. ret = multi_dot([A, B, C], out=out)
  1596. assert out is ret
  1597. assert_almost_equal(out, A.dot(B).dot(C))
  1598. assert_almost_equal(out, np.dot(A, np.dot(B, C)))
  1599. def test_two_arguments_and_out(self):
  1600. # separate code path with two arguments
  1601. A = np.random.random((6, 2))
  1602. B = np.random.random((2, 6))
  1603. out = np.zeros((6, 6))
  1604. ret = multi_dot([A, B], out=out)
  1605. assert out is ret
  1606. assert_almost_equal(out, A.dot(B))
  1607. assert_almost_equal(out, np.dot(A, B))
  1608. def test_dynamic_programing_optimization_and_out(self):
  1609. # multi_dot with four or more arguments uses the dynamic programing
  1610. # optimization and therefore deserve a separate test
  1611. A = np.random.random((6, 2))
  1612. B = np.random.random((2, 6))
  1613. C = np.random.random((6, 2))
  1614. D = np.random.random((2, 1))
  1615. out = np.zeros((6, 1))
  1616. ret = multi_dot([A, B, C, D], out=out)
  1617. assert out is ret
  1618. assert_almost_equal(out, A.dot(B).dot(C).dot(D))
  1619. def test_dynamic_programming_logic(self):
  1620. # Test for the dynamic programming part
  1621. # This test is directly taken from Cormen page 376.
  1622. arrays = [np.random.random((30, 35)),
  1623. np.random.random((35, 15)),
  1624. np.random.random((15, 5)),
  1625. np.random.random((5, 10)),
  1626. np.random.random((10, 20)),
  1627. np.random.random((20, 25))]
  1628. m_expected = np.array([[0., 15750., 7875., 9375., 11875., 15125.],
  1629. [0., 0., 2625., 4375., 7125., 10500.],
  1630. [0., 0., 0., 750., 2500., 5375.],
  1631. [0., 0., 0., 0., 1000., 3500.],
  1632. [0., 0., 0., 0., 0., 5000.],
  1633. [0., 0., 0., 0., 0., 0.]])
  1634. s_expected = np.array([[0, 1, 1, 3, 3, 3],
  1635. [0, 0, 2, 3, 3, 3],
  1636. [0, 0, 0, 3, 3, 3],
  1637. [0, 0, 0, 0, 4, 5],
  1638. [0, 0, 0, 0, 0, 5],
  1639. [0, 0, 0, 0, 0, 0]], dtype=int)
  1640. s_expected -= 1 # Cormen uses 1-based index, python does not.
  1641. s, m = _multi_dot_matrix_chain_order(arrays, return_costs=True)
  1642. # Only the upper triangular part (without the diagonal) is interesting.
  1643. assert_almost_equal(np.triu(s[:-1, 1:]),
  1644. np.triu(s_expected[:-1, 1:]))
  1645. assert_almost_equal(np.triu(m), np.triu(m_expected))
  1646. def test_too_few_input_arrays(self):
  1647. assert_raises(ValueError, multi_dot, [])
  1648. assert_raises(ValueError, multi_dot, [np.random.random((3, 3))])
  1649. class TestTensorinv:
  1650. @pytest.mark.parametrize("arr, ind", [
  1651. (np.ones((4, 6, 8, 2)), 2),
  1652. (np.ones((3, 3, 2)), 1),
  1653. ])
  1654. def test_non_square_handling(self, arr, ind):
  1655. with assert_raises(LinAlgError):
  1656. linalg.tensorinv(arr, ind=ind)
  1657. @pytest.mark.parametrize("shape, ind", [
  1658. # examples from docstring
  1659. ((4, 6, 8, 3), 2),
  1660. ((24, 8, 3), 1),
  1661. ])
  1662. def test_tensorinv_shape(self, shape, ind):
  1663. a = np.eye(24)
  1664. a.shape = shape
  1665. ainv = linalg.tensorinv(a=a, ind=ind)
  1666. expected = a.shape[ind:] + a.shape[:ind]
  1667. actual = ainv.shape
  1668. assert_equal(actual, expected)
  1669. @pytest.mark.parametrize("ind", [
  1670. 0, -2,
  1671. ])
  1672. def test_tensorinv_ind_limit(self, ind):
  1673. a = np.eye(24)
  1674. a.shape = (4, 6, 8, 3)
  1675. with assert_raises(ValueError):
  1676. linalg.tensorinv(a=a, ind=ind)
  1677. def test_tensorinv_result(self):
  1678. # mimic a docstring example
  1679. a = np.eye(24)
  1680. a.shape = (24, 8, 3)
  1681. ainv = linalg.tensorinv(a, ind=1)
  1682. b = np.ones(24)
  1683. assert_allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
  1684. def test_unsupported_commontype():
  1685. # linalg gracefully handles unsupported type
  1686. arr = np.array([[1, -2], [2, 5]], dtype='float16')
  1687. with assert_raises_regex(TypeError, "unsupported in linalg"):
  1688. linalg.cholesky(arr)
  1689. @pytest.mark.slow
  1690. @pytest.mark.xfail(not HAS_LAPACK64, run=False,
  1691. reason="Numpy not compiled with 64-bit BLAS/LAPACK")
  1692. @requires_memory(free_bytes=16e9)
  1693. def test_blas64_dot():
  1694. n = 2**32
  1695. a = np.zeros([1, n], dtype=np.float32)
  1696. b = np.ones([1, 1], dtype=np.float32)
  1697. a[0,-1] = 1
  1698. c = np.dot(b, a)
  1699. assert_equal(c[0,-1], 1)
  1700. @pytest.mark.xfail(not HAS_LAPACK64,
  1701. reason="Numpy not compiled with 64-bit BLAS/LAPACK")
  1702. def test_blas64_geqrf_lwork_smoketest():
  1703. # Smoke test LAPACK geqrf lwork call with 64-bit integers
  1704. dtype = np.float64
  1705. lapack_routine = np.linalg.lapack_lite.dgeqrf
  1706. m = 2**32 + 1
  1707. n = 2**32 + 1
  1708. lda = m
  1709. # Dummy arrays, not referenced by the lapack routine, so don't
  1710. # need to be of the right size
  1711. a = np.zeros([1, 1], dtype=dtype)
  1712. work = np.zeros([1], dtype=dtype)
  1713. tau = np.zeros([1], dtype=dtype)
  1714. # Size query
  1715. results = lapack_routine(m, n, a, lda, tau, work, -1, 0)
  1716. assert_equal(results['info'], 0)
  1717. assert_equal(results['m'], m)
  1718. assert_equal(results['n'], m)
  1719. # Should result to an integer of a reasonable size
  1720. lwork = int(work.item())
  1721. assert_(2**32 < lwork < 2**42)