test_linalg.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186
  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.core import swapaxes
  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, HAS_LAPACK64, IS_WASM
  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:
  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. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  881. def test_exceptions_not_invertible(self, dt):
  882. if dt in self.dtnoinv:
  883. return
  884. mat = self.noninv.astype(dt)
  885. assert_raises(LinAlgError, matrix_power, mat, -1)
  886. class TestEigvalshCases(HermitianTestCase, HermitianGeneralizedTestCase):
  887. def do(self, a, b, tags):
  888. # note that eigenvalue arrays returned by eig must be sorted since
  889. # their order isn't guaranteed.
  890. ev = linalg.eigvalsh(a, 'L')
  891. evalues, evectors = linalg.eig(a)
  892. evalues.sort(axis=-1)
  893. assert_allclose(ev, evalues, rtol=get_rtol(ev.dtype))
  894. ev2 = linalg.eigvalsh(a, 'U')
  895. assert_allclose(ev2, evalues, rtol=get_rtol(ev.dtype))
  896. class TestEigvalsh:
  897. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  898. def test_types(self, dtype):
  899. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  900. w = np.linalg.eigvalsh(x)
  901. assert_equal(w.dtype, get_real_dtype(dtype))
  902. def test_invalid(self):
  903. x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
  904. assert_raises(ValueError, np.linalg.eigvalsh, x, UPLO="lrong")
  905. assert_raises(ValueError, np.linalg.eigvalsh, x, "lower")
  906. assert_raises(ValueError, np.linalg.eigvalsh, x, "upper")
  907. def test_UPLO(self):
  908. Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
  909. Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
  910. tgt = np.array([-1, 1], dtype=np.double)
  911. rtol = get_rtol(np.double)
  912. # Check default is 'L'
  913. w = np.linalg.eigvalsh(Klo)
  914. assert_allclose(w, tgt, rtol=rtol)
  915. # Check 'L'
  916. w = np.linalg.eigvalsh(Klo, UPLO='L')
  917. assert_allclose(w, tgt, rtol=rtol)
  918. # Check 'l'
  919. w = np.linalg.eigvalsh(Klo, UPLO='l')
  920. assert_allclose(w, tgt, rtol=rtol)
  921. # Check 'U'
  922. w = np.linalg.eigvalsh(Kup, UPLO='U')
  923. assert_allclose(w, tgt, rtol=rtol)
  924. # Check 'u'
  925. w = np.linalg.eigvalsh(Kup, UPLO='u')
  926. assert_allclose(w, tgt, rtol=rtol)
  927. def test_0_size(self):
  928. # Check that all kinds of 0-sized arrays work
  929. class ArraySubclass(np.ndarray):
  930. pass
  931. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  932. res = linalg.eigvalsh(a)
  933. assert_(res.dtype.type is np.float64)
  934. assert_equal((0, 1), res.shape)
  935. # This is just for documentation, it might make sense to change:
  936. assert_(isinstance(res, np.ndarray))
  937. a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
  938. res = linalg.eigvalsh(a)
  939. assert_(res.dtype.type is np.float32)
  940. assert_equal((0,), res.shape)
  941. # This is just for documentation, it might make sense to change:
  942. assert_(isinstance(res, np.ndarray))
  943. class TestEighCases(HermitianTestCase, HermitianGeneralizedTestCase):
  944. def do(self, a, b, tags):
  945. # note that eigenvalue arrays returned by eig must be sorted since
  946. # their order isn't guaranteed.
  947. ev, evc = linalg.eigh(a)
  948. evalues, evectors = linalg.eig(a)
  949. evalues.sort(axis=-1)
  950. assert_almost_equal(ev, evalues)
  951. assert_allclose(dot_generalized(a, evc),
  952. np.asarray(ev)[..., None, :] * np.asarray(evc),
  953. rtol=get_rtol(ev.dtype))
  954. ev2, evc2 = linalg.eigh(a, 'U')
  955. assert_almost_equal(ev2, evalues)
  956. assert_allclose(dot_generalized(a, evc2),
  957. np.asarray(ev2)[..., None, :] * np.asarray(evc2),
  958. rtol=get_rtol(ev.dtype), err_msg=repr(a))
  959. class TestEigh:
  960. @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
  961. def test_types(self, dtype):
  962. x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
  963. w, v = np.linalg.eigh(x)
  964. assert_equal(w.dtype, get_real_dtype(dtype))
  965. assert_equal(v.dtype, dtype)
  966. def test_invalid(self):
  967. x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
  968. assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
  969. assert_raises(ValueError, np.linalg.eigh, x, "lower")
  970. assert_raises(ValueError, np.linalg.eigh, x, "upper")
  971. def test_UPLO(self):
  972. Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
  973. Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
  974. tgt = np.array([-1, 1], dtype=np.double)
  975. rtol = get_rtol(np.double)
  976. # Check default is 'L'
  977. w, v = np.linalg.eigh(Klo)
  978. assert_allclose(w, tgt, rtol=rtol)
  979. # Check 'L'
  980. w, v = np.linalg.eigh(Klo, UPLO='L')
  981. assert_allclose(w, tgt, rtol=rtol)
  982. # Check 'l'
  983. w, v = np.linalg.eigh(Klo, UPLO='l')
  984. assert_allclose(w, tgt, rtol=rtol)
  985. # Check 'U'
  986. w, v = np.linalg.eigh(Kup, UPLO='U')
  987. assert_allclose(w, tgt, rtol=rtol)
  988. # Check 'u'
  989. w, v = np.linalg.eigh(Kup, UPLO='u')
  990. assert_allclose(w, tgt, rtol=rtol)
  991. def test_0_size(self):
  992. # Check that all kinds of 0-sized arrays work
  993. class ArraySubclass(np.ndarray):
  994. pass
  995. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  996. res, res_v = linalg.eigh(a)
  997. assert_(res_v.dtype.type is np.float64)
  998. assert_(res.dtype.type is np.float64)
  999. assert_equal(a.shape, res_v.shape)
  1000. assert_equal((0, 1), res.shape)
  1001. # This is just for documentation, it might make sense to change:
  1002. assert_(isinstance(a, np.ndarray))
  1003. a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
  1004. res, res_v = linalg.eigh(a)
  1005. assert_(res_v.dtype.type is np.complex64)
  1006. assert_(res.dtype.type is np.float32)
  1007. assert_equal(a.shape, res_v.shape)
  1008. assert_equal((0,), res.shape)
  1009. # This is just for documentation, it might make sense to change:
  1010. assert_(isinstance(a, np.ndarray))
  1011. class _TestNormBase:
  1012. dt = None
  1013. dec = None
  1014. @staticmethod
  1015. def check_dtype(x, res):
  1016. if issubclass(x.dtype.type, np.inexact):
  1017. assert_equal(res.dtype, x.real.dtype)
  1018. else:
  1019. # For integer input, don't have to test float precision of output.
  1020. assert_(issubclass(res.dtype.type, np.floating))
  1021. class _TestNormGeneral(_TestNormBase):
  1022. def test_empty(self):
  1023. assert_equal(norm([]), 0.0)
  1024. assert_equal(norm(array([], dtype=self.dt)), 0.0)
  1025. assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0)
  1026. def test_vector_return_type(self):
  1027. a = np.array([1, 0, 1])
  1028. exact_types = np.typecodes['AllInteger']
  1029. inexact_types = np.typecodes['AllFloat']
  1030. all_types = exact_types + inexact_types
  1031. for each_type in all_types:
  1032. at = a.astype(each_type)
  1033. an = norm(at, -np.inf)
  1034. self.check_dtype(at, an)
  1035. assert_almost_equal(an, 0.0)
  1036. with suppress_warnings() as sup:
  1037. sup.filter(RuntimeWarning, "divide by zero encountered")
  1038. an = norm(at, -1)
  1039. self.check_dtype(at, an)
  1040. assert_almost_equal(an, 0.0)
  1041. an = norm(at, 0)
  1042. self.check_dtype(at, an)
  1043. assert_almost_equal(an, 2)
  1044. an = norm(at, 1)
  1045. self.check_dtype(at, an)
  1046. assert_almost_equal(an, 2.0)
  1047. an = norm(at, 2)
  1048. self.check_dtype(at, an)
  1049. assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/2.0))
  1050. an = norm(at, 4)
  1051. self.check_dtype(at, an)
  1052. assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/4.0))
  1053. an = norm(at, np.inf)
  1054. self.check_dtype(at, an)
  1055. assert_almost_equal(an, 1.0)
  1056. def test_vector(self):
  1057. a = [1, 2, 3, 4]
  1058. b = [-1, -2, -3, -4]
  1059. c = [-1, 2, -3, 4]
  1060. def _test(v):
  1061. np.testing.assert_almost_equal(norm(v), 30 ** 0.5,
  1062. decimal=self.dec)
  1063. np.testing.assert_almost_equal(norm(v, inf), 4.0,
  1064. decimal=self.dec)
  1065. np.testing.assert_almost_equal(norm(v, -inf), 1.0,
  1066. decimal=self.dec)
  1067. np.testing.assert_almost_equal(norm(v, 1), 10.0,
  1068. decimal=self.dec)
  1069. np.testing.assert_almost_equal(norm(v, -1), 12.0 / 25,
  1070. decimal=self.dec)
  1071. np.testing.assert_almost_equal(norm(v, 2), 30 ** 0.5,
  1072. decimal=self.dec)
  1073. np.testing.assert_almost_equal(norm(v, -2), ((205. / 144) ** -0.5),
  1074. decimal=self.dec)
  1075. np.testing.assert_almost_equal(norm(v, 0), 4,
  1076. decimal=self.dec)
  1077. for v in (a, b, c,):
  1078. _test(v)
  1079. for v in (array(a, dtype=self.dt), array(b, dtype=self.dt),
  1080. array(c, dtype=self.dt)):
  1081. _test(v)
  1082. def test_axis(self):
  1083. # Vector norms.
  1084. # Compare the use of `axis` with computing the norm of each row
  1085. # or column separately.
  1086. A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
  1087. for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
  1088. expected0 = [norm(A[:, k], ord=order) for k in range(A.shape[1])]
  1089. assert_almost_equal(norm(A, ord=order, axis=0), expected0)
  1090. expected1 = [norm(A[k, :], ord=order) for k in range(A.shape[0])]
  1091. assert_almost_equal(norm(A, ord=order, axis=1), expected1)
  1092. # Matrix norms.
  1093. B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
  1094. nd = B.ndim
  1095. for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro']:
  1096. for axis in itertools.combinations(range(-nd, nd), 2):
  1097. row_axis, col_axis = axis
  1098. if row_axis < 0:
  1099. row_axis += nd
  1100. if col_axis < 0:
  1101. col_axis += nd
  1102. if row_axis == col_axis:
  1103. assert_raises(ValueError, norm, B, ord=order, axis=axis)
  1104. else:
  1105. n = norm(B, ord=order, axis=axis)
  1106. # The logic using k_index only works for nd = 3.
  1107. # This has to be changed if nd is increased.
  1108. k_index = nd - (row_axis + col_axis)
  1109. if row_axis < col_axis:
  1110. expected = [norm(B[:].take(k, axis=k_index), ord=order)
  1111. for k in range(B.shape[k_index])]
  1112. else:
  1113. expected = [norm(B[:].take(k, axis=k_index).T, ord=order)
  1114. for k in range(B.shape[k_index])]
  1115. assert_almost_equal(n, expected)
  1116. def test_keepdims(self):
  1117. A = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
  1118. allclose_err = 'order {0}, axis = {1}'
  1119. shape_err = 'Shape mismatch found {0}, expected {1}, order={2}, axis={3}'
  1120. # check the order=None, axis=None case
  1121. expected = norm(A, ord=None, axis=None)
  1122. found = norm(A, ord=None, axis=None, keepdims=True)
  1123. assert_allclose(np.squeeze(found), expected,
  1124. err_msg=allclose_err.format(None, None))
  1125. expected_shape = (1, 1, 1)
  1126. assert_(found.shape == expected_shape,
  1127. shape_err.format(found.shape, expected_shape, None, None))
  1128. # Vector norms.
  1129. for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]:
  1130. for k in range(A.ndim):
  1131. expected = norm(A, ord=order, axis=k)
  1132. found = norm(A, ord=order, axis=k, keepdims=True)
  1133. assert_allclose(np.squeeze(found), expected,
  1134. err_msg=allclose_err.format(order, k))
  1135. expected_shape = list(A.shape)
  1136. expected_shape[k] = 1
  1137. expected_shape = tuple(expected_shape)
  1138. assert_(found.shape == expected_shape,
  1139. shape_err.format(found.shape, expected_shape, order, k))
  1140. # Matrix norms.
  1141. for order in [None, -2, 2, -1, 1, np.Inf, -np.Inf, 'fro', 'nuc']:
  1142. for k in itertools.permutations(range(A.ndim), 2):
  1143. expected = norm(A, ord=order, axis=k)
  1144. found = norm(A, ord=order, axis=k, keepdims=True)
  1145. assert_allclose(np.squeeze(found), expected,
  1146. err_msg=allclose_err.format(order, k))
  1147. expected_shape = list(A.shape)
  1148. expected_shape[k[0]] = 1
  1149. expected_shape[k[1]] = 1
  1150. expected_shape = tuple(expected_shape)
  1151. assert_(found.shape == expected_shape,
  1152. shape_err.format(found.shape, expected_shape, order, k))
  1153. class _TestNorm2D(_TestNormBase):
  1154. # Define the part for 2d arrays separately, so we can subclass this
  1155. # and run the tests using np.matrix in matrixlib.tests.test_matrix_linalg.
  1156. array = np.array
  1157. def test_matrix_empty(self):
  1158. assert_equal(norm(self.array([[]], dtype=self.dt)), 0.0)
  1159. def test_matrix_return_type(self):
  1160. a = self.array([[1, 0, 1], [0, 1, 1]])
  1161. exact_types = np.typecodes['AllInteger']
  1162. # float32, complex64, float64, complex128 types are the only types
  1163. # allowed by `linalg`, which performs the matrix operations used
  1164. # within `norm`.
  1165. inexact_types = 'fdFD'
  1166. all_types = exact_types + inexact_types
  1167. for each_type in all_types:
  1168. at = a.astype(each_type)
  1169. an = norm(at, -np.inf)
  1170. self.check_dtype(at, an)
  1171. assert_almost_equal(an, 2.0)
  1172. with suppress_warnings() as sup:
  1173. sup.filter(RuntimeWarning, "divide by zero encountered")
  1174. an = norm(at, -1)
  1175. self.check_dtype(at, an)
  1176. assert_almost_equal(an, 1.0)
  1177. an = norm(at, 1)
  1178. self.check_dtype(at, an)
  1179. assert_almost_equal(an, 2.0)
  1180. an = norm(at, 2)
  1181. self.check_dtype(at, an)
  1182. assert_almost_equal(an, 3.0**(1.0/2.0))
  1183. an = norm(at, -2)
  1184. self.check_dtype(at, an)
  1185. assert_almost_equal(an, 1.0)
  1186. an = norm(at, np.inf)
  1187. self.check_dtype(at, an)
  1188. assert_almost_equal(an, 2.0)
  1189. an = norm(at, 'fro')
  1190. self.check_dtype(at, an)
  1191. assert_almost_equal(an, 2.0)
  1192. an = norm(at, 'nuc')
  1193. self.check_dtype(at, an)
  1194. # Lower bar needed to support low precision floats.
  1195. # They end up being off by 1 in the 7th place.
  1196. np.testing.assert_almost_equal(an, 2.7320508075688772, decimal=6)
  1197. def test_matrix_2x2(self):
  1198. A = self.array([[1, 3], [5, 7]], dtype=self.dt)
  1199. assert_almost_equal(norm(A), 84 ** 0.5)
  1200. assert_almost_equal(norm(A, 'fro'), 84 ** 0.5)
  1201. assert_almost_equal(norm(A, 'nuc'), 10.0)
  1202. assert_almost_equal(norm(A, inf), 12.0)
  1203. assert_almost_equal(norm(A, -inf), 4.0)
  1204. assert_almost_equal(norm(A, 1), 10.0)
  1205. assert_almost_equal(norm(A, -1), 6.0)
  1206. assert_almost_equal(norm(A, 2), 9.1231056256176615)
  1207. assert_almost_equal(norm(A, -2), 0.87689437438234041)
  1208. assert_raises(ValueError, norm, A, 'nofro')
  1209. assert_raises(ValueError, norm, A, -3)
  1210. assert_raises(ValueError, norm, A, 0)
  1211. def test_matrix_3x3(self):
  1212. # This test has been added because the 2x2 example
  1213. # happened to have equal nuclear norm and induced 1-norm.
  1214. # The 1/10 scaling factor accommodates the absolute tolerance
  1215. # used in assert_almost_equal.
  1216. A = (1 / 10) * \
  1217. self.array([[1, 2, 3], [6, 0, 5], [3, 2, 1]], dtype=self.dt)
  1218. assert_almost_equal(norm(A), (1 / 10) * 89 ** 0.5)
  1219. assert_almost_equal(norm(A, 'fro'), (1 / 10) * 89 ** 0.5)
  1220. assert_almost_equal(norm(A, 'nuc'), 1.3366836911774836)
  1221. assert_almost_equal(norm(A, inf), 1.1)
  1222. assert_almost_equal(norm(A, -inf), 0.6)
  1223. assert_almost_equal(norm(A, 1), 1.0)
  1224. assert_almost_equal(norm(A, -1), 0.4)
  1225. assert_almost_equal(norm(A, 2), 0.88722940323461277)
  1226. assert_almost_equal(norm(A, -2), 0.19456584790481812)
  1227. def test_bad_args(self):
  1228. # Check that bad arguments raise the appropriate exceptions.
  1229. A = self.array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
  1230. B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
  1231. # Using `axis=<integer>` or passing in a 1-D array implies vector
  1232. # norms are being computed, so also using `ord='fro'`
  1233. # or `ord='nuc'` or any other string raises a ValueError.
  1234. assert_raises(ValueError, norm, A, 'fro', 0)
  1235. assert_raises(ValueError, norm, A, 'nuc', 0)
  1236. assert_raises(ValueError, norm, [3, 4], 'fro', None)
  1237. assert_raises(ValueError, norm, [3, 4], 'nuc', None)
  1238. assert_raises(ValueError, norm, [3, 4], 'test', None)
  1239. # Similarly, norm should raise an exception when ord is any finite
  1240. # number other than 1, 2, -1 or -2 when computing matrix norms.
  1241. for order in [0, 3]:
  1242. assert_raises(ValueError, norm, A, order, None)
  1243. assert_raises(ValueError, norm, A, order, (0, 1))
  1244. assert_raises(ValueError, norm, B, order, (1, 2))
  1245. # Invalid axis
  1246. assert_raises(np.AxisError, norm, B, None, 3)
  1247. assert_raises(np.AxisError, norm, B, None, (2, 3))
  1248. assert_raises(ValueError, norm, B, None, (0, 1, 2))
  1249. class _TestNorm(_TestNorm2D, _TestNormGeneral):
  1250. pass
  1251. class TestNorm_NonSystematic:
  1252. def test_longdouble_norm(self):
  1253. # Non-regression test: p-norm of longdouble would previously raise
  1254. # UnboundLocalError.
  1255. x = np.arange(10, dtype=np.longdouble)
  1256. old_assert_almost_equal(norm(x, ord=3), 12.65, decimal=2)
  1257. def test_intmin(self):
  1258. # Non-regression test: p-norm of signed integer would previously do
  1259. # float cast and abs in the wrong order.
  1260. x = np.array([-2 ** 31], dtype=np.int32)
  1261. old_assert_almost_equal(norm(x, ord=3), 2 ** 31, decimal=5)
  1262. def test_complex_high_ord(self):
  1263. # gh-4156
  1264. d = np.empty((2,), dtype=np.clongdouble)
  1265. d[0] = 6 + 7j
  1266. d[1] = -6 + 7j
  1267. res = 11.615898132184
  1268. old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=10)
  1269. d = d.astype(np.complex128)
  1270. old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=9)
  1271. d = d.astype(np.complex64)
  1272. old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=5)
  1273. # Separate definitions so we can use them for matrix tests.
  1274. class _TestNormDoubleBase(_TestNormBase):
  1275. dt = np.double
  1276. dec = 12
  1277. class _TestNormSingleBase(_TestNormBase):
  1278. dt = np.float32
  1279. dec = 6
  1280. class _TestNormInt64Base(_TestNormBase):
  1281. dt = np.int64
  1282. dec = 12
  1283. class TestNormDouble(_TestNorm, _TestNormDoubleBase):
  1284. pass
  1285. class TestNormSingle(_TestNorm, _TestNormSingleBase):
  1286. pass
  1287. class TestNormInt64(_TestNorm, _TestNormInt64Base):
  1288. pass
  1289. class TestMatrixRank:
  1290. def test_matrix_rank(self):
  1291. # Full rank matrix
  1292. assert_equal(4, matrix_rank(np.eye(4)))
  1293. # rank deficient matrix
  1294. I = np.eye(4)
  1295. I[-1, -1] = 0.
  1296. assert_equal(matrix_rank(I), 3)
  1297. # All zeros - zero rank
  1298. assert_equal(matrix_rank(np.zeros((4, 4))), 0)
  1299. # 1 dimension - rank 1 unless all 0
  1300. assert_equal(matrix_rank([1, 0, 0, 0]), 1)
  1301. assert_equal(matrix_rank(np.zeros((4,))), 0)
  1302. # accepts array-like
  1303. assert_equal(matrix_rank([1]), 1)
  1304. # greater than 2 dimensions treated as stacked matrices
  1305. ms = np.array([I, np.eye(4), np.zeros((4,4))])
  1306. assert_equal(matrix_rank(ms), np.array([3, 4, 0]))
  1307. # works on scalar
  1308. assert_equal(matrix_rank(1), 1)
  1309. def test_symmetric_rank(self):
  1310. assert_equal(4, matrix_rank(np.eye(4), hermitian=True))
  1311. assert_equal(1, matrix_rank(np.ones((4, 4)), hermitian=True))
  1312. assert_equal(0, matrix_rank(np.zeros((4, 4)), hermitian=True))
  1313. # rank deficient matrix
  1314. I = np.eye(4)
  1315. I[-1, -1] = 0.
  1316. assert_equal(3, matrix_rank(I, hermitian=True))
  1317. # manually supplied tolerance
  1318. I[-1, -1] = 1e-8
  1319. assert_equal(4, matrix_rank(I, hermitian=True, tol=0.99e-8))
  1320. assert_equal(3, matrix_rank(I, hermitian=True, tol=1.01e-8))
  1321. def test_reduced_rank():
  1322. # Test matrices with reduced rank
  1323. rng = np.random.RandomState(20120714)
  1324. for i in range(100):
  1325. # Make a rank deficient matrix
  1326. X = rng.normal(size=(40, 10))
  1327. X[:, 0] = X[:, 1] + X[:, 2]
  1328. # Assert that matrix_rank detected deficiency
  1329. assert_equal(matrix_rank(X), 9)
  1330. X[:, 3] = X[:, 4] + X[:, 5]
  1331. assert_equal(matrix_rank(X), 8)
  1332. class TestQR:
  1333. # Define the array class here, so run this on matrices elsewhere.
  1334. array = np.array
  1335. def check_qr(self, a):
  1336. # This test expects the argument `a` to be an ndarray or
  1337. # a subclass of an ndarray of inexact type.
  1338. a_type = type(a)
  1339. a_dtype = a.dtype
  1340. m, n = a.shape
  1341. k = min(m, n)
  1342. # mode == 'complete'
  1343. q, r = linalg.qr(a, mode='complete')
  1344. assert_(q.dtype == a_dtype)
  1345. assert_(r.dtype == a_dtype)
  1346. assert_(isinstance(q, a_type))
  1347. assert_(isinstance(r, a_type))
  1348. assert_(q.shape == (m, m))
  1349. assert_(r.shape == (m, n))
  1350. assert_almost_equal(dot(q, r), a)
  1351. assert_almost_equal(dot(q.T.conj(), q), np.eye(m))
  1352. assert_almost_equal(np.triu(r), r)
  1353. # mode == 'reduced'
  1354. q1, r1 = linalg.qr(a, mode='reduced')
  1355. assert_(q1.dtype == a_dtype)
  1356. assert_(r1.dtype == a_dtype)
  1357. assert_(isinstance(q1, a_type))
  1358. assert_(isinstance(r1, a_type))
  1359. assert_(q1.shape == (m, k))
  1360. assert_(r1.shape == (k, n))
  1361. assert_almost_equal(dot(q1, r1), a)
  1362. assert_almost_equal(dot(q1.T.conj(), q1), np.eye(k))
  1363. assert_almost_equal(np.triu(r1), r1)
  1364. # mode == 'r'
  1365. r2 = linalg.qr(a, mode='r')
  1366. assert_(r2.dtype == a_dtype)
  1367. assert_(isinstance(r2, a_type))
  1368. assert_almost_equal(r2, r1)
  1369. @pytest.mark.parametrize(["m", "n"], [
  1370. (3, 0),
  1371. (0, 3),
  1372. (0, 0)
  1373. ])
  1374. def test_qr_empty(self, m, n):
  1375. k = min(m, n)
  1376. a = np.empty((m, n))
  1377. self.check_qr(a)
  1378. h, tau = np.linalg.qr(a, mode='raw')
  1379. assert_equal(h.dtype, np.double)
  1380. assert_equal(tau.dtype, np.double)
  1381. assert_equal(h.shape, (n, m))
  1382. assert_equal(tau.shape, (k,))
  1383. def test_mode_raw(self):
  1384. # The factorization is not unique and varies between libraries,
  1385. # so it is not possible to check against known values. Functional
  1386. # testing is a possibility, but awaits the exposure of more
  1387. # of the functions in lapack_lite. Consequently, this test is
  1388. # very limited in scope. Note that the results are in FORTRAN
  1389. # order, hence the h arrays are transposed.
  1390. a = self.array([[1, 2], [3, 4], [5, 6]], dtype=np.double)
  1391. # Test double
  1392. h, tau = linalg.qr(a, mode='raw')
  1393. assert_(h.dtype == np.double)
  1394. assert_(tau.dtype == np.double)
  1395. assert_(h.shape == (2, 3))
  1396. assert_(tau.shape == (2,))
  1397. h, tau = linalg.qr(a.T, mode='raw')
  1398. assert_(h.dtype == np.double)
  1399. assert_(tau.dtype == np.double)
  1400. assert_(h.shape == (3, 2))
  1401. assert_(tau.shape == (2,))
  1402. def test_mode_all_but_economic(self):
  1403. a = self.array([[1, 2], [3, 4]])
  1404. b = self.array([[1, 2], [3, 4], [5, 6]])
  1405. for dt in "fd":
  1406. m1 = a.astype(dt)
  1407. m2 = b.astype(dt)
  1408. self.check_qr(m1)
  1409. self.check_qr(m2)
  1410. self.check_qr(m2.T)
  1411. for dt in "fd":
  1412. m1 = 1 + 1j * a.astype(dt)
  1413. m2 = 1 + 1j * b.astype(dt)
  1414. self.check_qr(m1)
  1415. self.check_qr(m2)
  1416. self.check_qr(m2.T)
  1417. def check_qr_stacked(self, a):
  1418. # This test expects the argument `a` to be an ndarray or
  1419. # a subclass of an ndarray of inexact type.
  1420. a_type = type(a)
  1421. a_dtype = a.dtype
  1422. m, n = a.shape[-2:]
  1423. k = min(m, n)
  1424. # mode == 'complete'
  1425. q, r = linalg.qr(a, mode='complete')
  1426. assert_(q.dtype == a_dtype)
  1427. assert_(r.dtype == a_dtype)
  1428. assert_(isinstance(q, a_type))
  1429. assert_(isinstance(r, a_type))
  1430. assert_(q.shape[-2:] == (m, m))
  1431. assert_(r.shape[-2:] == (m, n))
  1432. assert_almost_equal(matmul(q, r), a)
  1433. I_mat = np.identity(q.shape[-1])
  1434. stack_I_mat = np.broadcast_to(I_mat,
  1435. q.shape[:-2] + (q.shape[-1],)*2)
  1436. assert_almost_equal(matmul(swapaxes(q, -1, -2).conj(), q), stack_I_mat)
  1437. assert_almost_equal(np.triu(r[..., :, :]), r)
  1438. # mode == 'reduced'
  1439. q1, r1 = linalg.qr(a, mode='reduced')
  1440. assert_(q1.dtype == a_dtype)
  1441. assert_(r1.dtype == a_dtype)
  1442. assert_(isinstance(q1, a_type))
  1443. assert_(isinstance(r1, a_type))
  1444. assert_(q1.shape[-2:] == (m, k))
  1445. assert_(r1.shape[-2:] == (k, n))
  1446. assert_almost_equal(matmul(q1, r1), a)
  1447. I_mat = np.identity(q1.shape[-1])
  1448. stack_I_mat = np.broadcast_to(I_mat,
  1449. q1.shape[:-2] + (q1.shape[-1],)*2)
  1450. assert_almost_equal(matmul(swapaxes(q1, -1, -2).conj(), q1),
  1451. stack_I_mat)
  1452. assert_almost_equal(np.triu(r1[..., :, :]), r1)
  1453. # mode == 'r'
  1454. r2 = linalg.qr(a, mode='r')
  1455. assert_(r2.dtype == a_dtype)
  1456. assert_(isinstance(r2, a_type))
  1457. assert_almost_equal(r2, r1)
  1458. @pytest.mark.parametrize("size", [
  1459. (3, 4), (4, 3), (4, 4),
  1460. (3, 0), (0, 3)])
  1461. @pytest.mark.parametrize("outer_size", [
  1462. (2, 2), (2,), (2, 3, 4)])
  1463. @pytest.mark.parametrize("dt", [
  1464. np.single, np.double,
  1465. np.csingle, np.cdouble])
  1466. def test_stacked_inputs(self, outer_size, size, dt):
  1467. A = np.random.normal(size=outer_size + size).astype(dt)
  1468. B = np.random.normal(size=outer_size + size).astype(dt)
  1469. self.check_qr_stacked(A)
  1470. self.check_qr_stacked(A + 1.j*B)
  1471. class TestCholesky:
  1472. # TODO: are there no other tests for cholesky?
  1473. @pytest.mark.parametrize(
  1474. 'shape', [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)]
  1475. )
  1476. @pytest.mark.parametrize(
  1477. 'dtype', (np.float32, np.float64, np.complex64, np.complex128)
  1478. )
  1479. def test_basic_property(self, shape, dtype):
  1480. # Check A = L L^H
  1481. np.random.seed(1)
  1482. a = np.random.randn(*shape)
  1483. if np.issubdtype(dtype, np.complexfloating):
  1484. a = a + 1j*np.random.randn(*shape)
  1485. t = list(range(len(shape)))
  1486. t[-2:] = -1, -2
  1487. a = np.matmul(a.transpose(t).conj(), a)
  1488. a = np.asarray(a, dtype=dtype)
  1489. c = np.linalg.cholesky(a)
  1490. b = np.matmul(c, c.transpose(t).conj())
  1491. with np._no_nep50_warning():
  1492. atol = 500 * a.shape[0] * np.finfo(dtype).eps
  1493. assert_allclose(b, a, atol=atol, err_msg=f'{shape} {dtype}\n{a}\n{c}')
  1494. def test_0_size(self):
  1495. class ArraySubclass(np.ndarray):
  1496. pass
  1497. a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
  1498. res = linalg.cholesky(a)
  1499. assert_equal(a.shape, res.shape)
  1500. assert_(res.dtype.type is np.float64)
  1501. # for documentation purpose:
  1502. assert_(isinstance(res, np.ndarray))
  1503. a = np.zeros((1, 0, 0), dtype=np.complex64).view(ArraySubclass)
  1504. res = linalg.cholesky(a)
  1505. assert_equal(a.shape, res.shape)
  1506. assert_(res.dtype.type is np.complex64)
  1507. assert_(isinstance(res, np.ndarray))
  1508. def test_byteorder_check():
  1509. # Byte order check should pass for native order
  1510. if sys.byteorder == 'little':
  1511. native = '<'
  1512. else:
  1513. native = '>'
  1514. for dtt in (np.float32, np.float64):
  1515. arr = np.eye(4, dtype=dtt)
  1516. n_arr = arr.newbyteorder(native)
  1517. sw_arr = arr.newbyteorder('S').byteswap()
  1518. assert_equal(arr.dtype.byteorder, '=')
  1519. for routine in (linalg.inv, linalg.det, linalg.pinv):
  1520. # Normal call
  1521. res = routine(arr)
  1522. # Native but not '='
  1523. assert_array_equal(res, routine(n_arr))
  1524. # Swapped
  1525. assert_array_equal(res, routine(sw_arr))
  1526. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  1527. def test_generalized_raise_multiloop():
  1528. # It should raise an error even if the error doesn't occur in the
  1529. # last iteration of the ufunc inner loop
  1530. invertible = np.array([[1, 2], [3, 4]])
  1531. non_invertible = np.array([[1, 1], [1, 1]])
  1532. x = np.zeros([4, 4, 2, 2])[1::2]
  1533. x[...] = invertible
  1534. x[0, 0] = non_invertible
  1535. assert_raises(np.linalg.LinAlgError, np.linalg.inv, x)
  1536. def test_xerbla_override():
  1537. # Check that our xerbla has been successfully linked in. If it is not,
  1538. # the default xerbla routine is called, which prints a message to stdout
  1539. # and may, or may not, abort the process depending on the LAPACK package.
  1540. XERBLA_OK = 255
  1541. try:
  1542. pid = os.fork()
  1543. except (OSError, AttributeError):
  1544. # fork failed, or not running on POSIX
  1545. pytest.skip("Not POSIX or fork failed.")
  1546. if pid == 0:
  1547. # child; close i/o file handles
  1548. os.close(1)
  1549. os.close(0)
  1550. # Avoid producing core files.
  1551. import resource
  1552. resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
  1553. # These calls may abort.
  1554. try:
  1555. np.linalg.lapack_lite.xerbla()
  1556. except ValueError:
  1557. pass
  1558. except Exception:
  1559. os._exit(os.EX_CONFIG)
  1560. try:
  1561. a = np.array([[1.]])
  1562. np.linalg.lapack_lite.dorgqr(
  1563. 1, 1, 1, a,
  1564. 0, # <- invalid value
  1565. a, a, 0, 0)
  1566. except ValueError as e:
  1567. if "DORGQR parameter number 5" in str(e):
  1568. # success, reuse error code to mark success as
  1569. # FORTRAN STOP returns as success.
  1570. os._exit(XERBLA_OK)
  1571. # Did not abort, but our xerbla was not linked in.
  1572. os._exit(os.EX_CONFIG)
  1573. else:
  1574. # parent
  1575. pid, status = os.wait()
  1576. if os.WEXITSTATUS(status) != XERBLA_OK:
  1577. pytest.skip('Numpy xerbla not linked in.')
  1578. @pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
  1579. @pytest.mark.slow
  1580. def test_sdot_bug_8577():
  1581. # Regression test that loading certain other libraries does not
  1582. # result to wrong results in float32 linear algebra.
  1583. #
  1584. # There's a bug gh-8577 on OSX that can trigger this, and perhaps
  1585. # there are also other situations in which it occurs.
  1586. #
  1587. # Do the check in a separate process.
  1588. bad_libs = ['PyQt5.QtWidgets', 'IPython']
  1589. template = textwrap.dedent("""
  1590. import sys
  1591. {before}
  1592. try:
  1593. import {bad_lib}
  1594. except ImportError:
  1595. sys.exit(0)
  1596. {after}
  1597. x = np.ones(2, dtype=np.float32)
  1598. sys.exit(0 if np.allclose(x.dot(x), 2.0) else 1)
  1599. """)
  1600. for bad_lib in bad_libs:
  1601. code = template.format(before="import numpy as np", after="",
  1602. bad_lib=bad_lib)
  1603. subprocess.check_call([sys.executable, "-c", code])
  1604. # Swapped import order
  1605. code = template.format(after="import numpy as np", before="",
  1606. bad_lib=bad_lib)
  1607. subprocess.check_call([sys.executable, "-c", code])
  1608. class TestMultiDot:
  1609. def test_basic_function_with_three_arguments(self):
  1610. # multi_dot with three arguments uses a fast hand coded algorithm to
  1611. # determine the optimal order. Therefore test it separately.
  1612. A = np.random.random((6, 2))
  1613. B = np.random.random((2, 6))
  1614. C = np.random.random((6, 2))
  1615. assert_almost_equal(multi_dot([A, B, C]), A.dot(B).dot(C))
  1616. assert_almost_equal(multi_dot([A, B, C]), np.dot(A, np.dot(B, C)))
  1617. def test_basic_function_with_two_arguments(self):
  1618. # separate code path with two arguments
  1619. A = np.random.random((6, 2))
  1620. B = np.random.random((2, 6))
  1621. assert_almost_equal(multi_dot([A, B]), A.dot(B))
  1622. assert_almost_equal(multi_dot([A, B]), np.dot(A, B))
  1623. def test_basic_function_with_dynamic_programming_optimization(self):
  1624. # multi_dot with four or more arguments uses the dynamic programming
  1625. # optimization and therefore deserve a separate
  1626. A = np.random.random((6, 2))
  1627. B = np.random.random((2, 6))
  1628. C = np.random.random((6, 2))
  1629. D = np.random.random((2, 1))
  1630. assert_almost_equal(multi_dot([A, B, C, D]), A.dot(B).dot(C).dot(D))
  1631. def test_vector_as_first_argument(self):
  1632. # The first argument can be 1-D
  1633. A1d = np.random.random(2) # 1-D
  1634. B = np.random.random((2, 6))
  1635. C = np.random.random((6, 2))
  1636. D = np.random.random((2, 2))
  1637. # the result should be 1-D
  1638. assert_equal(multi_dot([A1d, B, C, D]).shape, (2,))
  1639. def test_vector_as_last_argument(self):
  1640. # The last argument can be 1-D
  1641. A = np.random.random((6, 2))
  1642. B = np.random.random((2, 6))
  1643. C = np.random.random((6, 2))
  1644. D1d = np.random.random(2) # 1-D
  1645. # the result should be 1-D
  1646. assert_equal(multi_dot([A, B, C, D1d]).shape, (6,))
  1647. def test_vector_as_first_and_last_argument(self):
  1648. # The first and last arguments can be 1-D
  1649. A1d = np.random.random(2) # 1-D
  1650. B = np.random.random((2, 6))
  1651. C = np.random.random((6, 2))
  1652. D1d = np.random.random(2) # 1-D
  1653. # the result should be a scalar
  1654. assert_equal(multi_dot([A1d, B, C, D1d]).shape, ())
  1655. def test_three_arguments_and_out(self):
  1656. # multi_dot with three arguments uses a fast hand coded algorithm to
  1657. # determine the optimal order. Therefore test it separately.
  1658. A = np.random.random((6, 2))
  1659. B = np.random.random((2, 6))
  1660. C = np.random.random((6, 2))
  1661. out = np.zeros((6, 2))
  1662. ret = multi_dot([A, B, C], out=out)
  1663. assert out is ret
  1664. assert_almost_equal(out, A.dot(B).dot(C))
  1665. assert_almost_equal(out, np.dot(A, np.dot(B, C)))
  1666. def test_two_arguments_and_out(self):
  1667. # separate code path with two arguments
  1668. A = np.random.random((6, 2))
  1669. B = np.random.random((2, 6))
  1670. out = np.zeros((6, 6))
  1671. ret = multi_dot([A, B], out=out)
  1672. assert out is ret
  1673. assert_almost_equal(out, A.dot(B))
  1674. assert_almost_equal(out, np.dot(A, B))
  1675. def test_dynamic_programming_optimization_and_out(self):
  1676. # multi_dot with four or more arguments uses the dynamic programming
  1677. # optimization and therefore deserve a separate test
  1678. A = np.random.random((6, 2))
  1679. B = np.random.random((2, 6))
  1680. C = np.random.random((6, 2))
  1681. D = np.random.random((2, 1))
  1682. out = np.zeros((6, 1))
  1683. ret = multi_dot([A, B, C, D], out=out)
  1684. assert out is ret
  1685. assert_almost_equal(out, A.dot(B).dot(C).dot(D))
  1686. def test_dynamic_programming_logic(self):
  1687. # Test for the dynamic programming part
  1688. # This test is directly taken from Cormen page 376.
  1689. arrays = [np.random.random((30, 35)),
  1690. np.random.random((35, 15)),
  1691. np.random.random((15, 5)),
  1692. np.random.random((5, 10)),
  1693. np.random.random((10, 20)),
  1694. np.random.random((20, 25))]
  1695. m_expected = np.array([[0., 15750., 7875., 9375., 11875., 15125.],
  1696. [0., 0., 2625., 4375., 7125., 10500.],
  1697. [0., 0., 0., 750., 2500., 5375.],
  1698. [0., 0., 0., 0., 1000., 3500.],
  1699. [0., 0., 0., 0., 0., 5000.],
  1700. [0., 0., 0., 0., 0., 0.]])
  1701. s_expected = np.array([[0, 1, 1, 3, 3, 3],
  1702. [0, 0, 2, 3, 3, 3],
  1703. [0, 0, 0, 3, 3, 3],
  1704. [0, 0, 0, 0, 4, 5],
  1705. [0, 0, 0, 0, 0, 5],
  1706. [0, 0, 0, 0, 0, 0]], dtype=int)
  1707. s_expected -= 1 # Cormen uses 1-based index, python does not.
  1708. s, m = _multi_dot_matrix_chain_order(arrays, return_costs=True)
  1709. # Only the upper triangular part (without the diagonal) is interesting.
  1710. assert_almost_equal(np.triu(s[:-1, 1:]),
  1711. np.triu(s_expected[:-1, 1:]))
  1712. assert_almost_equal(np.triu(m), np.triu(m_expected))
  1713. def test_too_few_input_arrays(self):
  1714. assert_raises(ValueError, multi_dot, [])
  1715. assert_raises(ValueError, multi_dot, [np.random.random((3, 3))])
  1716. class TestTensorinv:
  1717. @pytest.mark.parametrize("arr, ind", [
  1718. (np.ones((4, 6, 8, 2)), 2),
  1719. (np.ones((3, 3, 2)), 1),
  1720. ])
  1721. def test_non_square_handling(self, arr, ind):
  1722. with assert_raises(LinAlgError):
  1723. linalg.tensorinv(arr, ind=ind)
  1724. @pytest.mark.parametrize("shape, ind", [
  1725. # examples from docstring
  1726. ((4, 6, 8, 3), 2),
  1727. ((24, 8, 3), 1),
  1728. ])
  1729. def test_tensorinv_shape(self, shape, ind):
  1730. a = np.eye(24)
  1731. a.shape = shape
  1732. ainv = linalg.tensorinv(a=a, ind=ind)
  1733. expected = a.shape[ind:] + a.shape[:ind]
  1734. actual = ainv.shape
  1735. assert_equal(actual, expected)
  1736. @pytest.mark.parametrize("ind", [
  1737. 0, -2,
  1738. ])
  1739. def test_tensorinv_ind_limit(self, ind):
  1740. a = np.eye(24)
  1741. a.shape = (4, 6, 8, 3)
  1742. with assert_raises(ValueError):
  1743. linalg.tensorinv(a=a, ind=ind)
  1744. def test_tensorinv_result(self):
  1745. # mimic a docstring example
  1746. a = np.eye(24)
  1747. a.shape = (24, 8, 3)
  1748. ainv = linalg.tensorinv(a, ind=1)
  1749. b = np.ones(24)
  1750. assert_allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
  1751. class TestTensorsolve:
  1752. @pytest.mark.parametrize("a, axes", [
  1753. (np.ones((4, 6, 8, 2)), None),
  1754. (np.ones((3, 3, 2)), (0, 2)),
  1755. ])
  1756. def test_non_square_handling(self, a, axes):
  1757. with assert_raises(LinAlgError):
  1758. b = np.ones(a.shape[:2])
  1759. linalg.tensorsolve(a, b, axes=axes)
  1760. @pytest.mark.parametrize("shape",
  1761. [(2, 3, 6), (3, 4, 4, 3), (0, 3, 3, 0)],
  1762. )
  1763. def test_tensorsolve_result(self, shape):
  1764. a = np.random.randn(*shape)
  1765. b = np.ones(a.shape[:2])
  1766. x = np.linalg.tensorsolve(a, b)
  1767. assert_allclose(np.tensordot(a, x, axes=len(x.shape)), b)
  1768. def test_unsupported_commontype():
  1769. # linalg gracefully handles unsupported type
  1770. arr = np.array([[1, -2], [2, 5]], dtype='float16')
  1771. with assert_raises_regex(TypeError, "unsupported in linalg"):
  1772. linalg.cholesky(arr)
  1773. #@pytest.mark.slow
  1774. #@pytest.mark.xfail(not HAS_LAPACK64, run=False,
  1775. # reason="Numpy not compiled with 64-bit BLAS/LAPACK")
  1776. #@requires_memory(free_bytes=16e9)
  1777. @pytest.mark.skip(reason="Bad memory reports lead to OOM in ci testing")
  1778. def test_blas64_dot():
  1779. n = 2**32
  1780. a = np.zeros([1, n], dtype=np.float32)
  1781. b = np.ones([1, 1], dtype=np.float32)
  1782. a[0,-1] = 1
  1783. c = np.dot(b, a)
  1784. assert_equal(c[0,-1], 1)
  1785. @pytest.mark.xfail(not HAS_LAPACK64,
  1786. reason="Numpy not compiled with 64-bit BLAS/LAPACK")
  1787. def test_blas64_geqrf_lwork_smoketest():
  1788. # Smoke test LAPACK geqrf lwork call with 64-bit integers
  1789. dtype = np.float64
  1790. lapack_routine = np.linalg.lapack_lite.dgeqrf
  1791. m = 2**32 + 1
  1792. n = 2**32 + 1
  1793. lda = m
  1794. # Dummy arrays, not referenced by the lapack routine, so don't
  1795. # need to be of the right size
  1796. a = np.zeros([1, 1], dtype=dtype)
  1797. work = np.zeros([1], dtype=dtype)
  1798. tau = np.zeros([1], dtype=dtype)
  1799. # Size query
  1800. results = lapack_routine(m, n, a, lda, tau, work, -1, 0)
  1801. assert_equal(results['info'], 0)
  1802. assert_equal(results['m'], m)
  1803. assert_equal(results['n'], m)
  1804. # Should result to an integer of a reasonable size
  1805. lwork = int(work.item())
  1806. assert_(2**32 < lwork < 2**42)