test_linalg.py 83 KB

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