test_linalg.py 81 KB

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