test_linalg.py 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964
  1. """ Test functions for linalg module
  2. """
  3. from __future__ import division, absolute_import, print_function
  4. import os
  5. import sys
  6. import itertools
  7. import traceback
  8. import textwrap
  9. import subprocess
  10. import pytest
  11. import numpy as np
  12. from numpy import array, single, double, csingle, cdouble, dot, identity, matmul
  13. from numpy import multiply, atleast_2d, inf, asarray
  14. from numpy import linalg
  15. from numpy.linalg import matrix_power, norm, matrix_rank, multi_dot, LinAlgError
  16. from numpy.linalg.linalg import _multi_dot_matrix_chain_order
  17. from numpy.testing import (
  18. assert_, assert_equal, assert_raises, assert_array_equal,
  19. assert_almost_equal, assert_allclose, suppress_warnings,
  20. assert_raises_regex,
  21. )
  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(object):
  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 "<LinalgCase: %s>" % (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(object):
  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:
  300. msg = "In test case: %r\n\n" % case
  301. msg += traceback.format_exc()
  302. raise AssertionError(msg)
  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 SVDCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
  519. def do(self, a, b, tags):
  520. u, s, vt = linalg.svd(a, 0)
  521. assert_allclose(a, dot_generalized(np.asarray(u) * np.asarray(s)[..., None, :],
  522. np.asarray(vt)),
  523. rtol=get_rtol(u.dtype))
  524. assert_(consistent_subclass(u, a))
  525. assert_(consistent_subclass(vt, a))
  526. class TestSVD(SVDCases):
  527. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  528. def test_types(self, dtype):
  529. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  530. u, s, vh = linalg.svd(x)
  531. assert_equal(u.dtype, dtype)
  532. assert_equal(s.dtype, get_real_dtype(dtype))
  533. assert_equal(vh.dtype, dtype)
  534. s = linalg.svd(x, compute_uv=False)
  535. assert_equal(s.dtype, get_real_dtype(dtype))
  536. def test_empty_identity(self):
  537. """ Empty input should put an identity matrix in u or vh """
  538. x = np.empty((4, 0))
  539. u, s, vh = linalg.svd(x, compute_uv=True)
  540. assert_equal(u.shape, (4, 4))
  541. assert_equal(vh.shape, (0, 0))
  542. assert_equal(u, np.eye(4))
  543. x = np.empty((0, 4))
  544. u, s, vh = linalg.svd(x, compute_uv=True)
  545. assert_equal(u.shape, (0, 0))
  546. assert_equal(vh.shape, (4, 4))
  547. assert_equal(vh, np.eye(4))
  548. class CondCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
  549. # cond(x, p) for p in (None, 2, -2)
  550. def do(self, a, b, tags):
  551. c = asarray(a) # a might be a matrix
  552. if 'size-0' in tags:
  553. assert_raises(LinAlgError, linalg.cond, c)
  554. return
  555. # +-2 norms
  556. s = linalg.svd(c, compute_uv=False)
  557. assert_almost_equal(
  558. linalg.cond(a), s[..., 0] / s[..., -1],
  559. single_decimal=5, double_decimal=11)
  560. assert_almost_equal(
  561. linalg.cond(a, 2), s[..., 0] / s[..., -1],
  562. single_decimal=5, double_decimal=11)
  563. assert_almost_equal(
  564. linalg.cond(a, -2), s[..., -1] / s[..., 0],
  565. single_decimal=5, double_decimal=11)
  566. # Other norms
  567. cinv = np.linalg.inv(c)
  568. assert_almost_equal(
  569. linalg.cond(a, 1),
  570. abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1),
  571. single_decimal=5, double_decimal=11)
  572. assert_almost_equal(
  573. linalg.cond(a, -1),
  574. abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1),
  575. single_decimal=5, double_decimal=11)
  576. assert_almost_equal(
  577. linalg.cond(a, np.inf),
  578. abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1),
  579. single_decimal=5, double_decimal=11)
  580. assert_almost_equal(
  581. linalg.cond(a, -np.inf),
  582. abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1),
  583. single_decimal=5, double_decimal=11)
  584. assert_almost_equal(
  585. linalg.cond(a, 'fro'),
  586. np.sqrt((abs(c)**2).sum(-1).sum(-1)
  587. * (abs(cinv)**2).sum(-1).sum(-1)),
  588. single_decimal=5, double_decimal=11)
  589. class TestCond(CondCases):
  590. def test_basic_nonsvd(self):
  591. # Smoketest the non-svd norms
  592. A = array([[1., 0, 1], [0, -2., 0], [0, 0, 3.]])
  593. assert_almost_equal(linalg.cond(A, inf), 4)
  594. assert_almost_equal(linalg.cond(A, -inf), 2/3)
  595. assert_almost_equal(linalg.cond(A, 1), 4)
  596. assert_almost_equal(linalg.cond(A, -1), 0.5)
  597. assert_almost_equal(linalg.cond(A, 'fro'), np.sqrt(265 / 12))
  598. def test_singular(self):
  599. # Singular matrices have infinite condition number for
  600. # positive norms, and negative norms shouldn't raise
  601. # exceptions
  602. As = [np.zeros((2, 2)), np.ones((2, 2))]
  603. p_pos = [None, 1, 2, 'fro']
  604. p_neg = [-1, -2]
  605. for A, p in itertools.product(As, p_pos):
  606. # Inversion may not hit exact infinity, so just check the
  607. # number is large
  608. assert_(linalg.cond(A, p) > 1e15)
  609. for A, p in itertools.product(As, p_neg):
  610. linalg.cond(A, p)
  611. def test_nan(self):
  612. # nans should be passed through, not converted to infs
  613. ps = [None, 1, -1, 2, -2, 'fro']
  614. p_pos = [None, 1, 2, 'fro']
  615. A = np.ones((2, 2))
  616. A[0,1] = np.nan
  617. for p in ps:
  618. c = linalg.cond(A, p)
  619. assert_(isinstance(c, np.float_))
  620. assert_(np.isnan(c))
  621. A = np.ones((3, 2, 2))
  622. A[1,0,1] = np.nan
  623. for p in ps:
  624. c = linalg.cond(A, p)
  625. assert_(np.isnan(c[1]))
  626. if p in p_pos:
  627. assert_(c[0] > 1e15)
  628. assert_(c[2] > 1e15)
  629. else:
  630. assert_(not np.isnan(c[0]))
  631. assert_(not np.isnan(c[2]))
  632. def test_stacked_singular(self):
  633. # Check behavior when only some of the stacked matrices are
  634. # singular
  635. np.random.seed(1234)
  636. A = np.random.rand(2, 2, 2, 2)
  637. A[0,0] = 0
  638. A[1,1] = 0
  639. for p in (None, 1, 2, 'fro', -1, -2):
  640. c = linalg.cond(A, p)
  641. assert_equal(c[0,0], np.inf)
  642. assert_equal(c[1,1], np.inf)
  643. assert_(np.isfinite(c[0,1]))
  644. assert_(np.isfinite(c[1,0]))
  645. class PinvCases(LinalgSquareTestCase,
  646. LinalgNonsquareTestCase,
  647. LinalgGeneralizedSquareTestCase,
  648. LinalgGeneralizedNonsquareTestCase):
  649. def do(self, a, b, tags):
  650. a_ginv = linalg.pinv(a)
  651. # `a @ a_ginv == I` does not hold if a is singular
  652. dot = dot_generalized
  653. assert_almost_equal(dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11)
  654. assert_(consistent_subclass(a_ginv, a))
  655. class TestPinv(PinvCases):
  656. pass
  657. class DetCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
  658. def do(self, a, b, tags):
  659. d = linalg.det(a)
  660. (s, ld) = linalg.slogdet(a)
  661. if asarray(a).dtype.type in (single, double):
  662. ad = asarray(a).astype(double)
  663. else:
  664. ad = asarray(a).astype(cdouble)
  665. ev = linalg.eigvals(ad)
  666. assert_almost_equal(d, multiply.reduce(ev, axis=-1))
  667. assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1))
  668. s = np.atleast_1d(s)
  669. ld = np.atleast_1d(ld)
  670. m = (s != 0)
  671. assert_almost_equal(np.abs(s[m]), 1)
  672. assert_equal(ld[~m], -inf)
  673. class TestDet(DetCases):
  674. def test_zero(self):
  675. assert_equal(linalg.det([[0.0]]), 0.0)
  676. assert_equal(type(linalg.det([[0.0]])), double)
  677. assert_equal(linalg.det([[0.0j]]), 0.0)
  678. assert_equal(type(linalg.det([[0.0j]])), cdouble)
  679. assert_equal(linalg.slogdet([[0.0]]), (0.0, -inf))
  680. assert_equal(type(linalg.slogdet([[0.0]])[0]), double)
  681. assert_equal(type(linalg.slogdet([[0.0]])[1]), double)
  682. assert_equal(linalg.slogdet([[0.0j]]), (0.0j, -inf))
  683. assert_equal(type(linalg.slogdet([[0.0j]])[0]), cdouble)
  684. assert_equal(type(linalg.slogdet([[0.0j]])[1]), double)
  685. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  686. def test_types(self, dtype):
  687. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  688. assert_equal(np.linalg.det(x).dtype, dtype)
  689. ph, s = np.linalg.slogdet(x)
  690. assert_equal(s.dtype, get_real_dtype(dtype))
  691. assert_equal(ph.dtype, dtype)
  692. def test_0_size(self):
  693. a = np.zeros((0, 0), dtype=np.complex64)
  694. res = linalg.det(a)
  695. assert_equal(res, 1.)
  696. assert_(res.dtype.type is np.complex64)
  697. res = linalg.slogdet(a)
  698. assert_equal(res, (1, 0))
  699. assert_(res[0].dtype.type is np.complex64)
  700. assert_(res[1].dtype.type is np.float32)
  701. a = np.zeros((0, 0), dtype=np.float64)
  702. res = linalg.det(a)
  703. assert_equal(res, 1.)
  704. assert_(res.dtype.type is np.float64)
  705. res = linalg.slogdet(a)
  706. assert_equal(res, (1, 0))
  707. assert_(res[0].dtype.type is np.float64)
  708. assert_(res[1].dtype.type is np.float64)
  709. class LstsqCases(LinalgSquareTestCase, LinalgNonsquareTestCase):
  710. def do(self, a, b, tags):
  711. arr = np.asarray(a)
  712. m, n = arr.shape
  713. u, s, vt = linalg.svd(a, 0)
  714. x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
  715. if m == 0:
  716. assert_((x == 0).all())
  717. if m <= n:
  718. assert_almost_equal(b, dot(a, x))
  719. assert_equal(rank, m)
  720. else:
  721. assert_equal(rank, n)
  722. assert_almost_equal(sv, sv.__array_wrap__(s))
  723. if rank == n and m > n:
  724. expect_resids = (
  725. np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
  726. expect_resids = np.asarray(expect_resids)
  727. if np.asarray(b).ndim == 1:
  728. expect_resids.shape = (1,)
  729. assert_equal(residuals.shape, expect_resids.shape)
  730. else:
  731. expect_resids = np.array([]).view(type(x))
  732. assert_almost_equal(residuals, expect_resids)
  733. assert_(np.issubdtype(residuals.dtype, np.floating))
  734. assert_(consistent_subclass(x, b))
  735. assert_(consistent_subclass(residuals, b))
  736. class TestLstsq(LstsqCases):
  737. def test_future_rcond(self):
  738. a = np.array([[0., 1., 0., 1., 2., 0.],
  739. [0., 2., 0., 0., 1., 0.],
  740. [1., 0., 1., 0., 0., 4.],
  741. [0., 0., 0., 2., 3., 0.]]).T
  742. b = np.array([1, 0, 0, 0, 0, 0])
  743. with suppress_warnings() as sup:
  744. w = sup.record(FutureWarning, "`rcond` parameter will change")
  745. x, residuals, rank, s = linalg.lstsq(a, b)
  746. assert_(rank == 4)
  747. x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
  748. assert_(rank == 4)
  749. x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
  750. assert_(rank == 3)
  751. # Warning should be raised exactly once (first command)
  752. assert_(len(w) == 1)
  753. @pytest.mark.parametrize(["m", "n", "n_rhs"], [
  754. (4, 2, 2),
  755. (0, 4, 1),
  756. (0, 4, 2),
  757. (4, 0, 1),
  758. (4, 0, 2),
  759. (4, 2, 0),
  760. (0, 0, 0)
  761. ])
  762. def test_empty_a_b(self, m, n, n_rhs):
  763. a = np.arange(m * n).reshape(m, n)
  764. b = np.ones((m, n_rhs))
  765. x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
  766. if m == 0:
  767. assert_((x == 0).all())
  768. assert_equal(x.shape, (n, n_rhs))
  769. assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
  770. if m > n and n_rhs > 0:
  771. # residuals are exactly the squared norms of b's columns
  772. r = b - np.dot(a, x)
  773. assert_almost_equal(residuals, (r * r).sum(axis=-2))
  774. assert_equal(rank, min(m, n))
  775. assert_equal(s.shape, (min(m, n),))
  776. def test_incompatible_dims(self):
  777. # use modified version of docstring example
  778. x = np.array([0, 1, 2, 3])
  779. y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
  780. A = np.vstack([x, np.ones(len(x))]).T
  781. with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
  782. linalg.lstsq(A, y, rcond=None)
  783. @pytest.mark.parametrize('dt', [np.dtype(c) for c in '?bBhHiIqQefdgFDGO'])
  784. class TestMatrixPower(object):
  785. rshft_0 = np.eye(4)
  786. rshft_1 = rshft_0[[3, 0, 1, 2]]
  787. rshft_2 = rshft_0[[2, 3, 0, 1]]
  788. rshft_3 = rshft_0[[1, 2, 3, 0]]
  789. rshft_all = [rshft_0, rshft_1, rshft_2, rshft_3]
  790. noninv = array([[1, 0], [0, 0]])
  791. stacked = np.block([[[rshft_0]]]*2)
  792. #FIXME the 'e' dtype might work in future
  793. dtnoinv = [object, np.dtype('e'), np.dtype('g'), np.dtype('G')]
  794. def test_large_power(self, dt):
  795. rshft = self.rshft_1.astype(dt)
  796. assert_equal(
  797. matrix_power(rshft, 2**100 + 2**10 + 2**5 + 0), self.rshft_0)
  798. assert_equal(
  799. matrix_power(rshft, 2**100 + 2**10 + 2**5 + 1), self.rshft_1)
  800. assert_equal(
  801. matrix_power(rshft, 2**100 + 2**10 + 2**5 + 2), self.rshft_2)
  802. assert_equal(
  803. matrix_power(rshft, 2**100 + 2**10 + 2**5 + 3), self.rshft_3)
  804. def test_power_is_zero(self, dt):
  805. def tz(M):
  806. mz = matrix_power(M, 0)
  807. assert_equal(mz, identity_like_generalized(M))
  808. assert_equal(mz.dtype, M.dtype)
  809. for mat in self.rshft_all:
  810. tz(mat.astype(dt))
  811. if dt != object:
  812. tz(self.stacked.astype(dt))
  813. def test_power_is_one(self, dt):
  814. def tz(mat):
  815. mz = matrix_power(mat, 1)
  816. assert_equal(mz, mat)
  817. assert_equal(mz.dtype, mat.dtype)
  818. for mat in self.rshft_all:
  819. tz(mat.astype(dt))
  820. if dt != object:
  821. tz(self.stacked.astype(dt))
  822. def test_power_is_two(self, dt):
  823. def tz(mat):
  824. mz = matrix_power(mat, 2)
  825. mmul = matmul if mat.dtype != object else dot
  826. assert_equal(mz, mmul(mat, mat))
  827. assert_equal(mz.dtype, mat.dtype)
  828. for mat in self.rshft_all:
  829. tz(mat.astype(dt))
  830. if dt != object:
  831. tz(self.stacked.astype(dt))
  832. def test_power_is_minus_one(self, dt):
  833. def tz(mat):
  834. invmat = matrix_power(mat, -1)
  835. mmul = matmul if mat.dtype != object else dot
  836. assert_almost_equal(
  837. mmul(invmat, mat), identity_like_generalized(mat))
  838. for mat in self.rshft_all:
  839. if dt not in self.dtnoinv:
  840. tz(mat.astype(dt))
  841. def test_exceptions_bad_power(self, dt):
  842. mat = self.rshft_0.astype(dt)
  843. assert_raises(TypeError, matrix_power, mat, 1.5)
  844. assert_raises(TypeError, matrix_power, mat, [1])
  845. def test_exceptions_non_square(self, dt):
  846. assert_raises(LinAlgError, matrix_power, np.array([1], dt), 1)
  847. assert_raises(LinAlgError, matrix_power, np.array([[1], [2]], dt), 1)
  848. assert_raises(LinAlgError, matrix_power, np.ones((4, 3, 2), dt), 1)
  849. def test_exceptions_not_invertible(self, dt):
  850. if dt in self.dtnoinv:
  851. return
  852. mat = self.noninv.astype(dt)
  853. assert_raises(LinAlgError, matrix_power, mat, -1)
  854. class TestEigvalshCases(HermitianTestCase, HermitianGeneralizedTestCase):
  855. def do(self, a, b, tags):
  856. # note that eigenvalue arrays returned by eig must be sorted since
  857. # their order isn't guaranteed.
  858. ev = linalg.eigvalsh(a, 'L')
  859. evalues, evectors = linalg.eig(a)
  860. evalues.sort(axis=-1)
  861. assert_allclose(ev, evalues, rtol=get_rtol(ev.dtype))
  862. ev2 = linalg.eigvalsh(a, 'U')
  863. assert_allclose(ev2, evalues, rtol=get_rtol(ev.dtype))
  864. class TestEigvalsh(object):
  865. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  866. def test_types(self, dtype):
  867. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  868. w = np.linalg.eigvalsh(x)
  869. assert_equal(w.dtype, get_real_dtype(dtype))
  870. def test_invalid(self):
  871. x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
  872. assert_raises(ValueError, np.linalg.eigvalsh, x, UPLO="lrong")
  873. assert_raises(ValueError, np.linalg.eigvalsh, x, "lower")
  874. assert_raises(ValueError, np.linalg.eigvalsh, x, "upper")
  875. def test_UPLO(self):
  876. Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
  877. Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
  878. tgt = np.array([-1, 1], dtype=np.double)
  879. rtol = get_rtol(np.double)
  880. # Check default is 'L'
  881. w = np.linalg.eigvalsh(Klo)
  882. assert_allclose(w, tgt, rtol=rtol)
  883. # Check 'L'
  884. w = np.linalg.eigvalsh(Klo, UPLO='L')
  885. assert_allclose(w, tgt, rtol=rtol)
  886. # Check 'l'
  887. w = np.linalg.eigvalsh(Klo, UPLO='l')
  888. assert_allclose(w, tgt, rtol=rtol)
  889. # Check 'U'
  890. w = np.linalg.eigvalsh(Kup, UPLO='U')
  891. assert_allclose(w, tgt, rtol=rtol)
  892. # Check 'u'
  893. w = np.linalg.eigvalsh(Kup, UPLO='u')
  894. assert_allclose(w, tgt, rtol=rtol)
  895. def test_0_size(self):
  896. # Check that all kinds of 0-sized arrays work
  897. class ArraySubclass(np.ndarray):
  898. pass
  899. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  900. res = linalg.eigvalsh(a)
  901. assert_(res.dtype.type is np.float64)
  902. assert_equal((0, 1), res.shape)
  903. # This is just for documentation, it might make sense to change:
  904. assert_(isinstance(res, np.ndarray))
  905. a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
  906. res = linalg.eigvalsh(a)
  907. assert_(res.dtype.type is np.float32)
  908. assert_equal((0,), res.shape)
  909. # This is just for documentation, it might make sense to change:
  910. assert_(isinstance(res, np.ndarray))
  911. class TestEighCases(HermitianTestCase, HermitianGeneralizedTestCase):
  912. def do(self, a, b, tags):
  913. # note that eigenvalue arrays returned by eig must be sorted since
  914. # their order isn't guaranteed.
  915. ev, evc = linalg.eigh(a)
  916. evalues, evectors = linalg.eig(a)
  917. evalues.sort(axis=-1)
  918. assert_almost_equal(ev, evalues)
  919. assert_allclose(dot_generalized(a, evc),
  920. np.asarray(ev)[..., None, :] * np.asarray(evc),
  921. rtol=get_rtol(ev.dtype))
  922. ev2, evc2 = linalg.eigh(a, 'U')
  923. assert_almost_equal(ev2, evalues)
  924. assert_allclose(dot_generalized(a, evc2),
  925. np.asarray(ev2)[..., None, :] * np.asarray(evc2),
  926. rtol=get_rtol(ev.dtype), err_msg=repr(a))
  927. class TestEigh(object):
  928. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  929. def test_types(self, dtype):
  930. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  931. w, v = np.linalg.eigh(x)
  932. assert_equal(w.dtype, get_real_dtype(dtype))
  933. assert_equal(v.dtype, dtype)
  934. def test_invalid(self):
  935. x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
  936. assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
  937. assert_raises(ValueError, np.linalg.eigh, x, "lower")
  938. assert_raises(ValueError, np.linalg.eigh, x, "upper")
  939. def test_UPLO(self):
  940. Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
  941. Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
  942. tgt = np.array([-1, 1], dtype=np.double)
  943. rtol = get_rtol(np.double)
  944. # Check default is 'L'
  945. w, v = np.linalg.eigh(Klo)
  946. assert_allclose(w, tgt, rtol=rtol)
  947. # Check 'L'
  948. w, v = np.linalg.eigh(Klo, UPLO='L')
  949. assert_allclose(w, tgt, rtol=rtol)
  950. # Check 'l'
  951. w, v = np.linalg.eigh(Klo, UPLO='l')
  952. assert_allclose(w, tgt, rtol=rtol)
  953. # Check 'U'
  954. w, v = np.linalg.eigh(Kup, UPLO='U')
  955. assert_allclose(w, tgt, rtol=rtol)
  956. # Check 'u'
  957. w, v = np.linalg.eigh(Kup, UPLO='u')
  958. assert_allclose(w, tgt, rtol=rtol)
  959. def test_0_size(self):
  960. # Check that all kinds of 0-sized arrays work
  961. class ArraySubclass(np.ndarray):
  962. pass
  963. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  964. res, res_v = linalg.eigh(a)
  965. assert_(res_v.dtype.type is np.float64)
  966. assert_(res.dtype.type is np.float64)
  967. assert_equal(a.shape, res_v.shape)
  968. assert_equal((0, 1), res.shape)
  969. # This is just for documentation, it might make sense to change:
  970. assert_(isinstance(a, np.ndarray))
  971. a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
  972. res, res_v = linalg.eigh(a)
  973. assert_(res_v.dtype.type is np.complex64)
  974. assert_(res.dtype.type is np.float32)
  975. assert_equal(a.shape, res_v.shape)
  976. assert_equal((0,), res.shape)
  977. # This is just for documentation, it might make sense to change:
  978. assert_(isinstance(a, np.ndarray))
  979. class _TestNormBase(object):
  980. dt = None
  981. dec = None
  982. class _TestNormGeneral(_TestNormBase):
  983. def test_empty(self):
  984. assert_equal(norm([]), 0.0)
  985. assert_equal(norm(array([], dtype=self.dt)), 0.0)
  986. assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0)
  987. def test_vector_return_type(self):
  988. a = np.array([1, 0, 1])
  989. exact_types = np.typecodes['AllInteger']
  990. inexact_types = np.typecodes['AllFloat']
  991. all_types = exact_types + inexact_types
  992. for each_inexact_types in all_types:
  993. at = a.astype(each_inexact_types)
  994. an = norm(at, -np.inf)
  995. assert_(issubclass(an.dtype.type, np.floating))
  996. assert_almost_equal(an, 0.0)
  997. with suppress_warnings() as sup:
  998. sup.filter(RuntimeWarning, "divide by zero encountered")
  999. an = norm(at, -1)
  1000. assert_(issubclass(an.dtype.type, np.floating))
  1001. assert_almost_equal(an, 0.0)
  1002. an = norm(at, 0)
  1003. assert_(issubclass(an.dtype.type, np.floating))
  1004. assert_almost_equal(an, 2)
  1005. an = norm(at, 1)
  1006. assert_(issubclass(an.dtype.type, np.floating))
  1007. assert_almost_equal(an, 2.0)
  1008. an = norm(at, 2)
  1009. assert_(issubclass(an.dtype.type, np.floating))
  1010. assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/2.0))
  1011. an = norm(at, 4)
  1012. assert_(issubclass(an.dtype.type, np.floating))
  1013. assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/4.0))
  1014. an = norm(at, np.inf)
  1015. assert_(issubclass(an.dtype.type, np.floating))
  1016. assert_almost_equal(an, 1.0)
  1017. def test_vector(self):
  1018. a = [1, 2, 3, 4]
  1019. b = [-1, -2, -3, -4]
  1020. c = [-1, 2, -3, 4]
  1021. def _test(v):
  1022. np.testing.assert_almost_equal(norm(v), 30 ** 0.5,
  1023. decimal=self.dec)
  1024. np.testing.assert_almost_equal(norm(v, inf), 4.0,
  1025. decimal=self.dec)
  1026. np.testing.assert_almost_equal(norm(v, -inf), 1.0,
  1027. decimal=self.dec)
  1028. np.testing.assert_almost_equal(norm(v, 1), 10.0,
  1029. decimal=self.dec)
  1030. np.testing.assert_almost_equal(norm(v, -1), 12.0 / 25,
  1031. decimal=self.dec)
  1032. np.testing.assert_almost_equal(norm(v, 2), 30 ** 0.5,
  1033. decimal=self.dec)
  1034. np.testing.assert_almost_equal(norm(v, -2), ((205. / 144) ** -0.5),
  1035. decimal=self.dec)
  1036. np.testing.assert_almost_equal(norm(v, 0), 4,
  1037. decimal=self.dec)
  1038. for v in (a, b, c,):
  1039. _test(v)
  1040. for v in (array(a, dtype=self.dt), array(b, dtype=self.dt),
  1041. array(c, dtype=self.dt)):
  1042. _test(v)
  1043. def test_axis(self):
  1044. # Vector norms.
  1045. # Compare the use of `axis` with computing the norm of each row
  1046. # or column separately.
  1047. A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
  1048. for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
  1049. expected0 = [norm(A[:, k], ord=order) for k in range(A.shape[1])]
  1050. assert_almost_equal(norm(A, ord=order, axis=0), expected0)
  1051. expected1 = [norm(A[k, :], ord=order) for k in range(A.shape[0])]
  1052. assert_almost_equal(norm(A, ord=order, axis=1), expected1)
  1053. # Matrix norms.
  1054. B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
  1055. nd = B.ndim
  1056. for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro']:
  1057. for axis in itertools.combinations(range(-nd, nd), 2):
  1058. row_axis, col_axis = axis
  1059. if row_axis < 0:
  1060. row_axis += nd
  1061. if col_axis < 0:
  1062. col_axis += nd
  1063. if row_axis == col_axis:
  1064. assert_raises(ValueError, norm, B, ord=order, axis=axis)
  1065. else:
  1066. n = norm(B, ord=order, axis=axis)
  1067. # The logic using k_index only works for nd = 3.
  1068. # This has to be changed if nd is increased.
  1069. k_index = nd - (row_axis + col_axis)
  1070. if row_axis < col_axis:
  1071. expected = [norm(B[:].take(k, axis=k_index), ord=order)
  1072. for k in range(B.shape[k_index])]
  1073. else:
  1074. expected = [norm(B[:].take(k, axis=k_index).T, ord=order)
  1075. for k in range(B.shape[k_index])]
  1076. assert_almost_equal(n, expected)
  1077. def test_keepdims(self):
  1078. A = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
  1079. allclose_err = 'order {0}, axis = {1}'
  1080. shape_err = 'Shape mismatch found {0}, expected {1}, order={2}, axis={3}'
  1081. # check the order=None, axis=None case
  1082. expected = norm(A, ord=None, axis=None)
  1083. found = norm(A, ord=None, axis=None, keepdims=True)
  1084. assert_allclose(np.squeeze(found), expected,
  1085. err_msg=allclose_err.format(None, None))
  1086. expected_shape = (1, 1, 1)
  1087. assert_(found.shape == expected_shape,
  1088. shape_err.format(found.shape, expected_shape, None, None))
  1089. # Vector norms.
  1090. for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
  1091. for k in range(A.ndim):
  1092. expected = norm(A, ord=order, axis=k)
  1093. found = norm(A, ord=order, axis=k, keepdims=True)
  1094. assert_allclose(np.squeeze(found), expected,
  1095. err_msg=allclose_err.format(order, k))
  1096. expected_shape = list(A.shape)
  1097. expected_shape[k] = 1
  1098. expected_shape = tuple(expected_shape)
  1099. assert_(found.shape == expected_shape,
  1100. shape_err.format(found.shape, expected_shape, order, k))
  1101. # Matrix norms.
  1102. for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro', 'nuc']:
  1103. for k in itertools.permutations(range(A.ndim), 2):
  1104. expected = norm(A, ord=order, axis=k)
  1105. found = norm(A, ord=order, axis=k, keepdims=True)
  1106. assert_allclose(np.squeeze(found), expected,
  1107. err_msg=allclose_err.format(order, k))
  1108. expected_shape = list(A.shape)
  1109. expected_shape[k[0]] = 1
  1110. expected_shape[k[1]] = 1
  1111. expected_shape = tuple(expected_shape)
  1112. assert_(found.shape == expected_shape,
  1113. shape_err.format(found.shape, expected_shape, order, k))
  1114. class _TestNorm2D(_TestNormBase):
  1115. # Define the part for 2d arrays separately, so we can subclass this
  1116. # and run the tests using np.matrix in matrixlib.tests.test_matrix_linalg.
  1117. array = np.array
  1118. def test_matrix_empty(self):
  1119. assert_equal(norm(self.array([[]], dtype=self.dt)), 0.0)
  1120. def test_matrix_return_type(self):
  1121. a = self.array([[1, 0, 1], [0, 1, 1]])
  1122. exact_types = np.typecodes['AllInteger']
  1123. # float32, complex64, float64, complex128 types are the only types
  1124. # allowed by `linalg`, which performs the matrix operations used
  1125. # within `norm`.
  1126. inexact_types = 'fdFD'
  1127. all_types = exact_types + inexact_types
  1128. for each_inexact_types in all_types:
  1129. at = a.astype(each_inexact_types)
  1130. an = norm(at, -np.inf)
  1131. assert_(issubclass(an.dtype.type, np.floating))
  1132. assert_almost_equal(an, 2.0)
  1133. with suppress_warnings() as sup:
  1134. sup.filter(RuntimeWarning, "divide by zero encountered")
  1135. an = norm(at, -1)
  1136. assert_(issubclass(an.dtype.type, np.floating))
  1137. assert_almost_equal(an, 1.0)
  1138. an = norm(at, 1)
  1139. assert_(issubclass(an.dtype.type, np.floating))
  1140. assert_almost_equal(an, 2.0)
  1141. an = norm(at, 2)
  1142. assert_(issubclass(an.dtype.type, np.floating))
  1143. assert_almost_equal(an, 3.0**(1.0/2.0))
  1144. an = norm(at, -2)
  1145. assert_(issubclass(an.dtype.type, np.floating))
  1146. assert_almost_equal(an, 1.0)
  1147. an = norm(at, np.inf)
  1148. assert_(issubclass(an.dtype.type, np.floating))
  1149. assert_almost_equal(an, 2.0)
  1150. an = norm(at, 'fro')
  1151. assert_(issubclass(an.dtype.type, np.floating))
  1152. assert_almost_equal(an, 2.0)
  1153. an = norm(at, 'nuc')
  1154. assert_(issubclass(an.dtype.type, np.floating))
  1155. # Lower bar needed to support low precision floats.
  1156. # They end up being off by 1 in the 7th place.
  1157. np.testing.assert_almost_equal(an, 2.7320508075688772, decimal=6)
  1158. def test_matrix_2x2(self):
  1159. A = self.array([[1, 3], [5, 7]], dtype=self.dt)
  1160. assert_almost_equal(norm(A), 84 ** 0.5)
  1161. assert_almost_equal(norm(A, 'fro'), 84 ** 0.5)
  1162. assert_almost_equal(norm(A, 'nuc'), 10.0)
  1163. assert_almost_equal(norm(A, inf), 12.0)
  1164. assert_almost_equal(norm(A, -inf), 4.0)
  1165. assert_almost_equal(norm(A, 1), 10.0)
  1166. assert_almost_equal(norm(A, -1), 6.0)
  1167. assert_almost_equal(norm(A, 2), 9.1231056256176615)
  1168. assert_almost_equal(norm(A, -2), 0.87689437438234041)
  1169. assert_raises(ValueError, norm, A, 'nofro')
  1170. assert_raises(ValueError, norm, A, -3)
  1171. assert_raises(ValueError, norm, A, 0)
  1172. def test_matrix_3x3(self):
  1173. # This test has been added because the 2x2 example
  1174. # happened to have equal nuclear norm and induced 1-norm.
  1175. # The 1/10 scaling factor accommodates the absolute tolerance
  1176. # used in assert_almost_equal.
  1177. A = (1 / 10) * \
  1178. self.array([[1, 2, 3], [6, 0, 5], [3, 2, 1]], dtype=self.dt)
  1179. assert_almost_equal(norm(A), (1 / 10) * 89 ** 0.5)
  1180. assert_almost_equal(norm(A, 'fro'), (1 / 10) * 89 ** 0.5)
  1181. assert_almost_equal(norm(A, 'nuc'), 1.3366836911774836)
  1182. assert_almost_equal(norm(A, inf), 1.1)
  1183. assert_almost_equal(norm(A, -inf), 0.6)
  1184. assert_almost_equal(norm(A, 1), 1.0)
  1185. assert_almost_equal(norm(A, -1), 0.4)
  1186. assert_almost_equal(norm(A, 2), 0.88722940323461277)
  1187. assert_almost_equal(norm(A, -2), 0.19456584790481812)
  1188. def test_bad_args(self):
  1189. # Check that bad arguments raise the appropriate exceptions.
  1190. A = self.array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
  1191. B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
  1192. # Using `axis=<integer>` or passing in a 1-D array implies vector
  1193. # norms are being computed, so also using `ord='fro'`
  1194. # or `ord='nuc'` raises a ValueError.
  1195. assert_raises(ValueError, norm, A, 'fro', 0)
  1196. assert_raises(ValueError, norm, A, 'nuc', 0)
  1197. assert_raises(ValueError, norm, [3, 4], 'fro', None)
  1198. assert_raises(ValueError, norm, [3, 4], 'nuc', None)
  1199. # Similarly, norm should raise an exception when ord is any finite
  1200. # number other than 1, 2, -1 or -2 when computing matrix norms.
  1201. for order in [0, 3]:
  1202. assert_raises(ValueError, norm, A, order, None)
  1203. assert_raises(ValueError, norm, A, order, (0, 1))
  1204. assert_raises(ValueError, norm, B, order, (1, 2))
  1205. # Invalid axis
  1206. assert_raises(np.AxisError, norm, B, None, 3)
  1207. assert_raises(np.AxisError, norm, B, None, (2, 3))
  1208. assert_raises(ValueError, norm, B, None, (0, 1, 2))
  1209. class _TestNorm(_TestNorm2D, _TestNormGeneral):
  1210. pass
  1211. class TestNorm_NonSystematic(object):
  1212. def test_longdouble_norm(self):
  1213. # Non-regression test: p-norm of longdouble would previously raise
  1214. # UnboundLocalError.
  1215. x = np.arange(10, dtype=np.longdouble)
  1216. old_assert_almost_equal(norm(x, ord=3), 12.65, decimal=2)
  1217. def test_intmin(self):
  1218. # Non-regression test: p-norm of signed integer would previously do
  1219. # float cast and abs in the wrong order.
  1220. x = np.array([-2 ** 31], dtype=np.int32)
  1221. old_assert_almost_equal(norm(x, ord=3), 2 ** 31, decimal=5)
  1222. def test_complex_high_ord(self):
  1223. # gh-4156
  1224. d = np.empty((2,), dtype=np.clongdouble)
  1225. d[0] = 6 + 7j
  1226. d[1] = -6 + 7j
  1227. res = 11.615898132184
  1228. old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=10)
  1229. d = d.astype(np.complex128)
  1230. old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=9)
  1231. d = d.astype(np.complex64)
  1232. old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=5)
  1233. # Separate definitions so we can use them for matrix tests.
  1234. class _TestNormDoubleBase(_TestNormBase):
  1235. dt = np.double
  1236. dec = 12
  1237. class _TestNormSingleBase(_TestNormBase):
  1238. dt = np.float32
  1239. dec = 6
  1240. class _TestNormInt64Base(_TestNormBase):
  1241. dt = np.int64
  1242. dec = 12
  1243. class TestNormDouble(_TestNorm, _TestNormDoubleBase):
  1244. pass
  1245. class TestNormSingle(_TestNorm, _TestNormSingleBase):
  1246. pass
  1247. class TestNormInt64(_TestNorm, _TestNormInt64Base):
  1248. pass
  1249. class TestMatrixRank(object):
  1250. def test_matrix_rank(self):
  1251. # Full rank matrix
  1252. assert_equal(4, matrix_rank(np.eye(4)))
  1253. # rank deficient matrix
  1254. I = np.eye(4)
  1255. I[-1, -1] = 0.
  1256. assert_equal(matrix_rank(I), 3)
  1257. # All zeros - zero rank
  1258. assert_equal(matrix_rank(np.zeros((4, 4))), 0)
  1259. # 1 dimension - rank 1 unless all 0
  1260. assert_equal(matrix_rank([1, 0, 0, 0]), 1)
  1261. assert_equal(matrix_rank(np.zeros((4,))), 0)
  1262. # accepts array-like
  1263. assert_equal(matrix_rank([1]), 1)
  1264. # greater than 2 dimensions treated as stacked matrices
  1265. ms = np.array([I, np.eye(4), np.zeros((4,4))])
  1266. assert_equal(matrix_rank(ms), np.array([3, 4, 0]))
  1267. # works on scalar
  1268. assert_equal(matrix_rank(1), 1)
  1269. def test_symmetric_rank(self):
  1270. assert_equal(4, matrix_rank(np.eye(4), hermitian=True))
  1271. assert_equal(1, matrix_rank(np.ones((4, 4)), hermitian=True))
  1272. assert_equal(0, matrix_rank(np.zeros((4, 4)), hermitian=True))
  1273. # rank deficient matrix
  1274. I = np.eye(4)
  1275. I[-1, -1] = 0.
  1276. assert_equal(3, matrix_rank(I, hermitian=True))
  1277. # manually supplied tolerance
  1278. I[-1, -1] = 1e-8
  1279. assert_equal(4, matrix_rank(I, hermitian=True, tol=0.99e-8))
  1280. assert_equal(3, matrix_rank(I, hermitian=True, tol=1.01e-8))
  1281. def test_reduced_rank():
  1282. # Test matrices with reduced rank
  1283. rng = np.random.RandomState(20120714)
  1284. for i in range(100):
  1285. # Make a rank deficient matrix
  1286. X = rng.normal(size=(40, 10))
  1287. X[:, 0] = X[:, 1] + X[:, 2]
  1288. # Assert that matrix_rank detected deficiency
  1289. assert_equal(matrix_rank(X), 9)
  1290. X[:, 3] = X[:, 4] + X[:, 5]
  1291. assert_equal(matrix_rank(X), 8)
  1292. class TestQR(object):
  1293. # Define the array class here, so run this on matrices elsewhere.
  1294. array = np.array
  1295. def check_qr(self, a):
  1296. # This test expects the argument `a` to be an ndarray or
  1297. # a subclass of an ndarray of inexact type.
  1298. a_type = type(a)
  1299. a_dtype = a.dtype
  1300. m, n = a.shape
  1301. k = min(m, n)
  1302. # mode == 'complete'
  1303. q, r = linalg.qr(a, mode='complete')
  1304. assert_(q.dtype == a_dtype)
  1305. assert_(r.dtype == a_dtype)
  1306. assert_(isinstance(q, a_type))
  1307. assert_(isinstance(r, a_type))
  1308. assert_(q.shape == (m, m))
  1309. assert_(r.shape == (m, n))
  1310. assert_almost_equal(dot(q, r), a)
  1311. assert_almost_equal(dot(q.T.conj(), q), np.eye(m))
  1312. assert_almost_equal(np.triu(r), r)
  1313. # mode == 'reduced'
  1314. q1, r1 = linalg.qr(a, mode='reduced')
  1315. assert_(q1.dtype == a_dtype)
  1316. assert_(r1.dtype == a_dtype)
  1317. assert_(isinstance(q1, a_type))
  1318. assert_(isinstance(r1, a_type))
  1319. assert_(q1.shape == (m, k))
  1320. assert_(r1.shape == (k, n))
  1321. assert_almost_equal(dot(q1, r1), a)
  1322. assert_almost_equal(dot(q1.T.conj(), q1), np.eye(k))
  1323. assert_almost_equal(np.triu(r1), r1)
  1324. # mode == 'r'
  1325. r2 = linalg.qr(a, mode='r')
  1326. assert_(r2.dtype == a_dtype)
  1327. assert_(isinstance(r2, a_type))
  1328. assert_almost_equal(r2, r1)
  1329. @pytest.mark.parametrize(["m", "n"], [
  1330. (3, 0),
  1331. (0, 3),
  1332. (0, 0)
  1333. ])
  1334. def test_qr_empty(self, m, n):
  1335. k = min(m, n)
  1336. a = np.empty((m, n))
  1337. self.check_qr(a)
  1338. h, tau = np.linalg.qr(a, mode='raw')
  1339. assert_equal(h.dtype, np.double)
  1340. assert_equal(tau.dtype, np.double)
  1341. assert_equal(h.shape, (n, m))
  1342. assert_equal(tau.shape, (k,))
  1343. def test_mode_raw(self):
  1344. # The factorization is not unique and varies between libraries,
  1345. # so it is not possible to check against known values. Functional
  1346. # testing is a possibility, but awaits the exposure of more
  1347. # of the functions in lapack_lite. Consequently, this test is
  1348. # very limited in scope. Note that the results are in FORTRAN
  1349. # order, hence the h arrays are transposed.
  1350. a = self.array([[1, 2], [3, 4], [5, 6]], dtype=np.double)
  1351. # Test double
  1352. h, tau = linalg.qr(a, mode='raw')
  1353. assert_(h.dtype == np.double)
  1354. assert_(tau.dtype == np.double)
  1355. assert_(h.shape == (2, 3))
  1356. assert_(tau.shape == (2,))
  1357. h, tau = linalg.qr(a.T, mode='raw')
  1358. assert_(h.dtype == np.double)
  1359. assert_(tau.dtype == np.double)
  1360. assert_(h.shape == (3, 2))
  1361. assert_(tau.shape == (2,))
  1362. def test_mode_all_but_economic(self):
  1363. a = self.array([[1, 2], [3, 4]])
  1364. b = self.array([[1, 2], [3, 4], [5, 6]])
  1365. for dt in "fd":
  1366. m1 = a.astype(dt)
  1367. m2 = b.astype(dt)
  1368. self.check_qr(m1)
  1369. self.check_qr(m2)
  1370. self.check_qr(m2.T)
  1371. for dt in "fd":
  1372. m1 = 1 + 1j * a.astype(dt)
  1373. m2 = 1 + 1j * b.astype(dt)
  1374. self.check_qr(m1)
  1375. self.check_qr(m2)
  1376. self.check_qr(m2.T)
  1377. class TestCholesky(object):
  1378. # TODO: are there no other tests for cholesky?
  1379. def test_basic_property(self):
  1380. # Check A = L L^H
  1381. shapes = [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)]
  1382. dtypes = (np.float32, np.float64, np.complex64, np.complex128)
  1383. for shape, dtype in itertools.product(shapes, dtypes):
  1384. np.random.seed(1)
  1385. a = np.random.randn(*shape)
  1386. if np.issubdtype(dtype, np.complexfloating):
  1387. a = a + 1j*np.random.randn(*shape)
  1388. t = list(range(len(shape)))
  1389. t[-2:] = -1, -2
  1390. a = np.matmul(a.transpose(t).conj(), a)
  1391. a = np.asarray(a, dtype=dtype)
  1392. c = np.linalg.cholesky(a)
  1393. b = np.matmul(c, c.transpose(t).conj())
  1394. assert_allclose(b, a,
  1395. err_msg="{} {}\n{}\n{}".format(shape, dtype, a, c),
  1396. atol=500 * a.shape[0] * np.finfo(dtype).eps)
  1397. def test_0_size(self):
  1398. class ArraySubclass(np.ndarray):
  1399. pass
  1400. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  1401. res = linalg.cholesky(a)
  1402. assert_equal(a.shape, res.shape)
  1403. assert_(res.dtype.type is np.float64)
  1404. # for documentation purpose:
  1405. assert_(isinstance(res, np.ndarray))
  1406. a = np.zeros((1, 0, 0), dtype=np.complex64).view(ArraySubclass)
  1407. res = linalg.cholesky(a)
  1408. assert_equal(a.shape, res.shape)
  1409. assert_(res.dtype.type is np.complex64)
  1410. assert_(isinstance(res, np.ndarray))
  1411. def test_byteorder_check():
  1412. # Byte order check should pass for native order
  1413. if sys.byteorder == 'little':
  1414. native = '<'
  1415. else:
  1416. native = '>'
  1417. for dtt in (np.float32, np.float64):
  1418. arr = np.eye(4, dtype=dtt)
  1419. n_arr = arr.newbyteorder(native)
  1420. sw_arr = arr.newbyteorder('S').byteswap()
  1421. assert_equal(arr.dtype.byteorder, '=')
  1422. for routine in (linalg.inv, linalg.det, linalg.pinv):
  1423. # Normal call
  1424. res = routine(arr)
  1425. # Native but not '='
  1426. assert_array_equal(res, routine(n_arr))
  1427. # Swapped
  1428. assert_array_equal(res, routine(sw_arr))
  1429. def test_generalized_raise_multiloop():
  1430. # It should raise an error even if the error doesn't occur in the
  1431. # last iteration of the ufunc inner loop
  1432. invertible = np.array([[1, 2], [3, 4]])
  1433. non_invertible = np.array([[1, 1], [1, 1]])
  1434. x = np.zeros([4, 4, 2, 2])[1::2]
  1435. x[...] = invertible
  1436. x[0, 0] = non_invertible
  1437. assert_raises(np.linalg.LinAlgError, np.linalg.inv, x)
  1438. def test_xerbla_override():
  1439. # Check that our xerbla has been successfully linked in. If it is not,
  1440. # the default xerbla routine is called, which prints a message to stdout
  1441. # and may, or may not, abort the process depending on the LAPACK package.
  1442. XERBLA_OK = 255
  1443. try:
  1444. pid = os.fork()
  1445. except (OSError, AttributeError):
  1446. # fork failed, or not running on POSIX
  1447. pytest.skip("Not POSIX or fork failed.")
  1448. if pid == 0:
  1449. # child; close i/o file handles
  1450. os.close(1)
  1451. os.close(0)
  1452. # Avoid producing core files.
  1453. import resource
  1454. resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
  1455. # These calls may abort.
  1456. try:
  1457. np.linalg.lapack_lite.xerbla()
  1458. except ValueError:
  1459. pass
  1460. except Exception:
  1461. os._exit(os.EX_CONFIG)
  1462. try:
  1463. a = np.array([[1.]])
  1464. np.linalg.lapack_lite.dorgqr(
  1465. 1, 1, 1, a,
  1466. 0, # <- invalid value
  1467. a, a, 0, 0)
  1468. except ValueError as e:
  1469. if "DORGQR parameter number 5" in str(e):
  1470. # success, reuse error code to mark success as
  1471. # FORTRAN STOP returns as success.
  1472. os._exit(XERBLA_OK)
  1473. # Did not abort, but our xerbla was not linked in.
  1474. os._exit(os.EX_CONFIG)
  1475. else:
  1476. # parent
  1477. pid, status = os.wait()
  1478. if os.WEXITSTATUS(status) != XERBLA_OK:
  1479. pytest.skip('Numpy xerbla not linked in.')
  1480. def test_sdot_bug_8577():
  1481. # Regression test that loading certain other libraries does not
  1482. # result to wrong results in float32 linear algebra.
  1483. #
  1484. # There's a bug gh-8577 on OSX that can trigger this, and perhaps
  1485. # there are also other situations in which it occurs.
  1486. #
  1487. # Do the check in a separate process.
  1488. bad_libs = ['PyQt5.QtWidgets', 'IPython']
  1489. template = textwrap.dedent("""
  1490. import sys
  1491. {before}
  1492. try:
  1493. import {bad_lib}
  1494. except ImportError:
  1495. sys.exit(0)
  1496. {after}
  1497. x = np.ones(2, dtype=np.float32)
  1498. sys.exit(0 if np.allclose(x.dot(x), 2.0) else 1)
  1499. """)
  1500. for bad_lib in bad_libs:
  1501. code = template.format(before="import numpy as np", after="",
  1502. bad_lib=bad_lib)
  1503. subprocess.check_call([sys.executable, "-c", code])
  1504. # Swapped import order
  1505. code = template.format(after="import numpy as np", before="",
  1506. bad_lib=bad_lib)
  1507. subprocess.check_call([sys.executable, "-c", code])
  1508. class TestMultiDot(object):
  1509. def test_basic_function_with_three_arguments(self):
  1510. # multi_dot with three arguments uses a fast hand coded algorithm to
  1511. # determine the optimal order. Therefore test it separately.
  1512. A = np.random.random((6, 2))
  1513. B = np.random.random((2, 6))
  1514. C = np.random.random((6, 2))
  1515. assert_almost_equal(multi_dot([A, B, C]), A.dot(B).dot(C))
  1516. assert_almost_equal(multi_dot([A, B, C]), np.dot(A, np.dot(B, C)))
  1517. def test_basic_function_with_two_arguments(self):
  1518. # separate code path with two arguments
  1519. A = np.random.random((6, 2))
  1520. B = np.random.random((2, 6))
  1521. assert_almost_equal(multi_dot([A, B]), A.dot(B))
  1522. assert_almost_equal(multi_dot([A, B]), np.dot(A, B))
  1523. def test_basic_function_with_dynamic_programing_optimization(self):
  1524. # multi_dot with four or more arguments uses the dynamic programing
  1525. # optimization and therefore deserve a separate
  1526. A = np.random.random((6, 2))
  1527. B = np.random.random((2, 6))
  1528. C = np.random.random((6, 2))
  1529. D = np.random.random((2, 1))
  1530. assert_almost_equal(multi_dot([A, B, C, D]), A.dot(B).dot(C).dot(D))
  1531. def test_vector_as_first_argument(self):
  1532. # The first argument can be 1-D
  1533. A1d = np.random.random(2) # 1-D
  1534. B = np.random.random((2, 6))
  1535. C = np.random.random((6, 2))
  1536. D = np.random.random((2, 2))
  1537. # the result should be 1-D
  1538. assert_equal(multi_dot([A1d, B, C, D]).shape, (2,))
  1539. def test_vector_as_last_argument(self):
  1540. # The last argument can be 1-D
  1541. A = np.random.random((6, 2))
  1542. B = np.random.random((2, 6))
  1543. C = np.random.random((6, 2))
  1544. D1d = np.random.random(2) # 1-D
  1545. # the result should be 1-D
  1546. assert_equal(multi_dot([A, B, C, D1d]).shape, (6,))
  1547. def test_vector_as_first_and_last_argument(self):
  1548. # The first and last arguments can be 1-D
  1549. A1d = np.random.random(2) # 1-D
  1550. B = np.random.random((2, 6))
  1551. C = np.random.random((6, 2))
  1552. D1d = np.random.random(2) # 1-D
  1553. # the result should be a scalar
  1554. assert_equal(multi_dot([A1d, B, C, D1d]).shape, ())
  1555. def test_dynamic_programming_logic(self):
  1556. # Test for the dynamic programming part
  1557. # This test is directly taken from Cormen page 376.
  1558. arrays = [np.random.random((30, 35)),
  1559. np.random.random((35, 15)),
  1560. np.random.random((15, 5)),
  1561. np.random.random((5, 10)),
  1562. np.random.random((10, 20)),
  1563. np.random.random((20, 25))]
  1564. m_expected = np.array([[0., 15750., 7875., 9375., 11875., 15125.],
  1565. [0., 0., 2625., 4375., 7125., 10500.],
  1566. [0., 0., 0., 750., 2500., 5375.],
  1567. [0., 0., 0., 0., 1000., 3500.],
  1568. [0., 0., 0., 0., 0., 5000.],
  1569. [0., 0., 0., 0., 0., 0.]])
  1570. s_expected = np.array([[0, 1, 1, 3, 3, 3],
  1571. [0, 0, 2, 3, 3, 3],
  1572. [0, 0, 0, 3, 3, 3],
  1573. [0, 0, 0, 0, 4, 5],
  1574. [0, 0, 0, 0, 0, 5],
  1575. [0, 0, 0, 0, 0, 0]], dtype=int)
  1576. s_expected -= 1 # Cormen uses 1-based index, python does not.
  1577. s, m = _multi_dot_matrix_chain_order(arrays, return_costs=True)
  1578. # Only the upper triangular part (without the diagonal) is interesting.
  1579. assert_almost_equal(np.triu(s[:-1, 1:]),
  1580. np.triu(s_expected[:-1, 1:]))
  1581. assert_almost_equal(np.triu(m), np.triu(m_expected))
  1582. def test_too_few_input_arrays(self):
  1583. assert_raises(ValueError, multi_dot, [])
  1584. assert_raises(ValueError, multi_dot, [np.random.random((3, 3))])
  1585. class TestTensorinv(object):
  1586. @pytest.mark.parametrize("arr, ind", [
  1587. (np.ones((4, 6, 8, 2)), 2),
  1588. (np.ones((3, 3, 2)), 1),
  1589. ])
  1590. def test_non_square_handling(self, arr, ind):
  1591. with assert_raises(LinAlgError):
  1592. linalg.tensorinv(arr, ind=ind)
  1593. @pytest.mark.parametrize("shape, ind", [
  1594. # examples from docstring
  1595. ((4, 6, 8, 3), 2),
  1596. ((24, 8, 3), 1),
  1597. ])
  1598. def test_tensorinv_shape(self, shape, ind):
  1599. a = np.eye(24)
  1600. a.shape = shape
  1601. ainv = linalg.tensorinv(a=a, ind=ind)
  1602. expected = a.shape[ind:] + a.shape[:ind]
  1603. actual = ainv.shape
  1604. assert_equal(actual, expected)
  1605. @pytest.mark.parametrize("ind", [
  1606. 0, -2,
  1607. ])
  1608. def test_tensorinv_ind_limit(self, ind):
  1609. a = np.eye(24)
  1610. a.shape = (4, 6, 8, 3)
  1611. with assert_raises(ValueError):
  1612. linalg.tensorinv(a=a, ind=ind)
  1613. def test_tensorinv_result(self):
  1614. # mimic a docstring example
  1615. a = np.eye(24)
  1616. a.shape = (24, 8, 3)
  1617. ainv = linalg.tensorinv(a, ind=1)
  1618. b = np.ones(24)
  1619. assert_allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))