test_linalg.py 76 KB

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