test_lapack.py 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616
  1. #
  2. # Created by: Pearu Peterson, September 2002
  3. #
  4. from functools import reduce
  5. import sysconfig
  6. from numpy.testing import (assert_equal, assert_array_almost_equal, assert_,
  7. assert_allclose, assert_almost_equal,
  8. assert_array_equal)
  9. import pytest
  10. from pytest import raises as assert_raises
  11. import numpy as np
  12. from numpy import (eye, ones, zeros, zeros_like, triu, tril, tril_indices,
  13. triu_indices)
  14. from scipy.linalg import (_flapack as flapack, lapack, inv, svd, cholesky,
  15. solve, ldl, norm, block_diag, qr, eigh, qz)
  16. from scipy.linalg._basic import _to_banded
  17. from scipy.linalg.lapack import _compute_lwork
  18. from scipy.stats import ortho_group, unitary_group
  19. import scipy.sparse as sps
  20. try:
  21. from scipy.linalg import _clapack as clapack
  22. except ImportError:
  23. clapack = None
  24. from scipy.linalg.lapack import get_lapack_funcs
  25. from scipy.linalg.blas import get_blas_funcs
  26. from scipy.__config__ import CONFIG
  27. blas_provider = blas_version = None
  28. blas_provider = CONFIG['Build Dependencies']['blas']['name']
  29. blas_version = CONFIG['Build Dependencies']['blas']['version']
  30. REAL_DTYPES = [np.float32, np.float64]
  31. COMPLEX_DTYPES = [np.complex64, np.complex128]
  32. DTYPES = REAL_DTYPES + COMPLEX_DTYPES
  33. def generate_random_dtype_array(shape, dtype, rng):
  34. # generates a random matrix of desired data type of shape
  35. if dtype in COMPLEX_DTYPES:
  36. return (rng.rand(*shape)
  37. + rng.rand(*shape)*1.0j).astype(dtype)
  38. return rng.rand(*shape).astype(dtype)
  39. def test_lapack_documented():
  40. """Test that all entries are in the doc."""
  41. if lapack.__doc__ is None: # just in case there is a python -OO
  42. pytest.skip('lapack.__doc__ is None')
  43. names = set(lapack.__doc__.split())
  44. ignore_list = {
  45. "absolute_import",
  46. "clapack",
  47. "division",
  48. "find_best_lapack_type",
  49. "flapack",
  50. "print_function",
  51. "HAS_ILP64",
  52. "np",
  53. }
  54. missing = list()
  55. for name in dir(lapack):
  56. if (not name.startswith('_') and name not in ignore_list and
  57. name not in names):
  58. missing.append(name)
  59. assert missing == [], 'Name(s) missing from lapack.__doc__ or ignore_list'
  60. def test_ilp64_blas_lapack_both_or_none():
  61. from scipy.linalg.blas import HAS_ILP64 as blas_has_ilp64
  62. from scipy.linalg.lapack import HAS_ILP64 as lapack_has_ilp64
  63. assert blas_has_ilp64 == lapack_has_ilp64
  64. class TestFlapackSimple:
  65. def test_gebal(self):
  66. a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  67. a1 = [[1, 0, 0, 3e-4],
  68. [4, 0, 0, 2e-3],
  69. [7, 1, 0, 0],
  70. [0, 1, 0, 0]]
  71. for p in 'sdzc':
  72. f = getattr(flapack, p+'gebal', None)
  73. if f is None:
  74. continue
  75. ba, lo, hi, pivscale, info = f(a)
  76. assert_(not info, repr(info))
  77. assert_array_almost_equal(ba, a)
  78. assert_equal((lo, hi), (0, len(a[0])-1))
  79. assert_array_almost_equal(pivscale, np.ones(len(a)))
  80. ba, lo, hi, pivscale, info = f(a1, permute=1, scale=1)
  81. assert_(not info, repr(info))
  82. # print(a1)
  83. # print(ba, lo, hi, pivscale)
  84. def test_gehrd(self):
  85. a = [[-149, -50, -154],
  86. [537, 180, 546],
  87. [-27, -9, -25]]
  88. for p in 'd':
  89. f = getattr(flapack, p+'gehrd', None)
  90. if f is None:
  91. continue
  92. ht, tau, info = f(a)
  93. assert_(not info, repr(info))
  94. def test_trsyl(self):
  95. a = np.array([[1, 2], [0, 4]])
  96. b = np.array([[5, 6], [0, 8]])
  97. c = np.array([[9, 10], [11, 12]])
  98. trans = 'T'
  99. # Test single and double implementations, including most
  100. # of the options
  101. for dtype in 'fdFD':
  102. a1, b1, c1 = a.astype(dtype), b.astype(dtype), c.astype(dtype)
  103. trsyl, = get_lapack_funcs(('trsyl',), (a1,))
  104. if dtype.isupper(): # is complex dtype
  105. a1[0] += 1j
  106. trans = 'C'
  107. x, scale, info = trsyl(a1, b1, c1)
  108. assert_array_almost_equal(np.dot(a1, x) + np.dot(x, b1),
  109. scale * c1)
  110. x, scale, info = trsyl(a1, b1, c1, trana=trans, tranb=trans)
  111. assert_array_almost_equal(
  112. np.dot(a1.conjugate().T, x) + np.dot(x, b1.conjugate().T),
  113. scale * c1, decimal=4)
  114. x, scale, info = trsyl(a1, b1, c1, isgn=-1)
  115. assert_array_almost_equal(np.dot(a1, x) - np.dot(x, b1),
  116. scale * c1, decimal=4)
  117. def test_lange(self):
  118. a = np.array([
  119. [-149, -50, -154],
  120. [537, 180, 546],
  121. [-27, -9, -25]])
  122. for dtype in 'fdFD':
  123. for norm_str in 'Mm1OoIiFfEe':
  124. a1 = a.astype(dtype)
  125. if dtype.isupper():
  126. # is complex dtype
  127. a1[0, 0] += 1j
  128. lange, = get_lapack_funcs(('lange',), (a1,))
  129. value = lange(norm_str, a1)
  130. if norm_str in 'FfEe':
  131. if dtype in 'Ff':
  132. decimal = 3
  133. else:
  134. decimal = 7
  135. ref = np.sqrt(np.sum(np.square(np.abs(a1))))
  136. assert_almost_equal(value, ref, decimal)
  137. else:
  138. if norm_str in 'Mm':
  139. ref = np.max(np.abs(a1))
  140. elif norm_str in '1Oo':
  141. ref = np.max(np.sum(np.abs(a1), axis=0))
  142. elif norm_str in 'Ii':
  143. ref = np.max(np.sum(np.abs(a1), axis=1))
  144. assert_equal(value, ref)
  145. class TestLapack:
  146. def test_flapack(self):
  147. if hasattr(flapack, 'empty_module'):
  148. # flapack module is empty
  149. pass
  150. def test_clapack(self):
  151. if hasattr(clapack, 'empty_module'):
  152. # clapack module is empty
  153. pass
  154. class TestLeastSquaresSolvers:
  155. def test_gels(self):
  156. rng = np.random.default_rng(1234)
  157. # Test fat/tall matrix argument handling - gh-issue #8329
  158. for ind, dtype in enumerate(DTYPES):
  159. m = 10
  160. n = 20
  161. nrhs = 1
  162. a1 = rng.random((m, n)).astype(dtype)
  163. b1 = rng.random(n).astype(dtype)
  164. gls, glslw = get_lapack_funcs(('gels', 'gels_lwork'), dtype=dtype)
  165. # Request of sizes
  166. lwork = _compute_lwork(glslw, m, n, nrhs)
  167. _, _, info = gls(a1, b1, lwork=lwork)
  168. assert_(info >= 0)
  169. _, _, info = gls(a1, b1, trans='TTCC'[ind], lwork=lwork)
  170. assert_(info >= 0)
  171. for dtype in REAL_DTYPES:
  172. a1 = np.array([[1.0, 2.0],
  173. [4.0, 5.0],
  174. [7.0, 8.0]], dtype=dtype)
  175. b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
  176. gels, gels_lwork, geqrf = get_lapack_funcs(
  177. ('gels', 'gels_lwork', 'geqrf'), (a1, b1))
  178. m, n = a1.shape
  179. if len(b1.shape) == 2:
  180. nrhs = b1.shape[1]
  181. else:
  182. nrhs = 1
  183. # Request of sizes
  184. lwork = _compute_lwork(gels_lwork, m, n, nrhs)
  185. lqr, x, info = gels(a1, b1, lwork=lwork)
  186. assert_allclose(x[:-1], np.array([-14.333333333333323,
  187. 14.999999999999991],
  188. dtype=dtype),
  189. rtol=25*np.finfo(dtype).eps)
  190. lqr_truth, _, _, _ = geqrf(a1)
  191. assert_array_equal(lqr, lqr_truth)
  192. for dtype in COMPLEX_DTYPES:
  193. a1 = np.array([[1.0+4.0j, 2.0],
  194. [4.0+0.5j, 5.0-3.0j],
  195. [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
  196. b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
  197. gels, gels_lwork, geqrf = get_lapack_funcs(
  198. ('gels', 'gels_lwork', 'geqrf'), (a1, b1))
  199. m, n = a1.shape
  200. if len(b1.shape) == 2:
  201. nrhs = b1.shape[1]
  202. else:
  203. nrhs = 1
  204. # Request of sizes
  205. lwork = _compute_lwork(gels_lwork, m, n, nrhs)
  206. lqr, x, info = gels(a1, b1, lwork=lwork)
  207. assert_allclose(x[:-1],
  208. np.array([1.161753632288328-1.901075709391912j,
  209. 1.735882340522193+1.521240901196909j],
  210. dtype=dtype), rtol=25*np.finfo(dtype).eps)
  211. lqr_truth, _, _, _ = geqrf(a1)
  212. assert_array_equal(lqr, lqr_truth)
  213. def test_gelsd(self):
  214. for dtype in REAL_DTYPES:
  215. a1 = np.array([[1.0, 2.0],
  216. [4.0, 5.0],
  217. [7.0, 8.0]], dtype=dtype)
  218. b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
  219. gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'),
  220. (a1, b1))
  221. m, n = a1.shape
  222. if len(b1.shape) == 2:
  223. nrhs = b1.shape[1]
  224. else:
  225. nrhs = 1
  226. # Request of sizes
  227. work, iwork, info = gelsd_lwork(m, n, nrhs, -1)
  228. lwork = int(np.real(work))
  229. iwork_size = iwork
  230. x, s, rank, info = gelsd(a1, b1, lwork, iwork_size,
  231. -1, False, False)
  232. assert_allclose(x[:-1], np.array([-14.333333333333323,
  233. 14.999999999999991],
  234. dtype=dtype),
  235. rtol=25*np.finfo(dtype).eps)
  236. assert_allclose(s, np.array([12.596017180511966,
  237. 0.583396253199685], dtype=dtype),
  238. rtol=25*np.finfo(dtype).eps)
  239. for dtype in COMPLEX_DTYPES:
  240. a1 = np.array([[1.0+4.0j, 2.0],
  241. [4.0+0.5j, 5.0-3.0j],
  242. [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
  243. b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
  244. gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'),
  245. (a1, b1))
  246. m, n = a1.shape
  247. if len(b1.shape) == 2:
  248. nrhs = b1.shape[1]
  249. else:
  250. nrhs = 1
  251. # Request of sizes
  252. work, rwork, iwork, info = gelsd_lwork(m, n, nrhs, -1)
  253. lwork = int(np.real(work))
  254. rwork_size = int(rwork)
  255. iwork_size = iwork
  256. x, s, rank, info = gelsd(a1, b1, lwork, rwork_size, iwork_size,
  257. -1, False, False)
  258. assert_allclose(x[:-1],
  259. np.array([1.161753632288328-1.901075709391912j,
  260. 1.735882340522193+1.521240901196909j],
  261. dtype=dtype), rtol=25*np.finfo(dtype).eps)
  262. assert_allclose(s,
  263. np.array([13.035514762572043, 4.337666985231382],
  264. dtype=dtype), rtol=25*np.finfo(dtype).eps)
  265. def test_gelss(self):
  266. for dtype in REAL_DTYPES:
  267. a1 = np.array([[1.0, 2.0],
  268. [4.0, 5.0],
  269. [7.0, 8.0]], dtype=dtype)
  270. b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
  271. gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'),
  272. (a1, b1))
  273. m, n = a1.shape
  274. if len(b1.shape) == 2:
  275. nrhs = b1.shape[1]
  276. else:
  277. nrhs = 1
  278. # Request of sizes
  279. work, info = gelss_lwork(m, n, nrhs, -1)
  280. lwork = int(np.real(work))
  281. v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False)
  282. assert_allclose(x[:-1], np.array([-14.333333333333323,
  283. 14.999999999999991],
  284. dtype=dtype),
  285. rtol=25*np.finfo(dtype).eps)
  286. assert_allclose(s, np.array([12.596017180511966,
  287. 0.583396253199685], dtype=dtype),
  288. rtol=25*np.finfo(dtype).eps)
  289. for dtype in COMPLEX_DTYPES:
  290. a1 = np.array([[1.0+4.0j, 2.0],
  291. [4.0+0.5j, 5.0-3.0j],
  292. [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
  293. b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
  294. gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'),
  295. (a1, b1))
  296. m, n = a1.shape
  297. if len(b1.shape) == 2:
  298. nrhs = b1.shape[1]
  299. else:
  300. nrhs = 1
  301. # Request of sizes
  302. work, info = gelss_lwork(m, n, nrhs, -1)
  303. lwork = int(np.real(work))
  304. v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False)
  305. assert_allclose(x[:-1],
  306. np.array([1.161753632288328-1.901075709391912j,
  307. 1.735882340522193+1.521240901196909j],
  308. dtype=dtype),
  309. rtol=25*np.finfo(dtype).eps)
  310. assert_allclose(s, np.array([13.035514762572043,
  311. 4.337666985231382], dtype=dtype),
  312. rtol=25*np.finfo(dtype).eps)
  313. def test_gelsy(self):
  314. for dtype in REAL_DTYPES:
  315. a1 = np.array([[1.0, 2.0],
  316. [4.0, 5.0],
  317. [7.0, 8.0]], dtype=dtype)
  318. b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
  319. gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'),
  320. (a1, b1))
  321. m, n = a1.shape
  322. if len(b1.shape) == 2:
  323. nrhs = b1.shape[1]
  324. else:
  325. nrhs = 1
  326. # Request of sizes
  327. work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps)
  328. lwork = int(np.real(work))
  329. jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
  330. v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps,
  331. lwork, False, False)
  332. assert_allclose(x[:-1], np.array([-14.333333333333323,
  333. 14.999999999999991],
  334. dtype=dtype),
  335. rtol=25*np.finfo(dtype).eps)
  336. for dtype in COMPLEX_DTYPES:
  337. a1 = np.array([[1.0+4.0j, 2.0],
  338. [4.0+0.5j, 5.0-3.0j],
  339. [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
  340. b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
  341. gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'),
  342. (a1, b1))
  343. m, n = a1.shape
  344. if len(b1.shape) == 2:
  345. nrhs = b1.shape[1]
  346. else:
  347. nrhs = 1
  348. # Request of sizes
  349. work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps)
  350. lwork = int(np.real(work))
  351. jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
  352. v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps,
  353. lwork, False, False)
  354. assert_allclose(x[:-1],
  355. np.array([1.161753632288328-1.901075709391912j,
  356. 1.735882340522193+1.521240901196909j],
  357. dtype=dtype),
  358. rtol=25*np.finfo(dtype).eps)
  359. @pytest.mark.parametrize('dtype', DTYPES)
  360. @pytest.mark.parametrize('shape', [(3, 4), (5, 2), (2**18, 2**18)])
  361. def test_geqrf_lwork(dtype, shape):
  362. geqrf_lwork = get_lapack_funcs(('geqrf_lwork'), dtype=dtype)
  363. m, n = shape
  364. lwork, info = geqrf_lwork(m=m, n=n)
  365. assert_equal(info, 0)
  366. class TestRegression:
  367. def test_ticket_1645(self):
  368. # Check that RQ routines have correct lwork
  369. for dtype in DTYPES:
  370. a = np.zeros((300, 2), dtype=dtype)
  371. gerqf, = get_lapack_funcs(['gerqf'], [a])
  372. assert_raises(Exception, gerqf, a, lwork=2)
  373. rq, tau, work, info = gerqf(a)
  374. if dtype in REAL_DTYPES:
  375. orgrq, = get_lapack_funcs(['orgrq'], [a])
  376. assert_raises(Exception, orgrq, rq[-2:], tau, lwork=1)
  377. orgrq(rq[-2:], tau, lwork=2)
  378. elif dtype in COMPLEX_DTYPES:
  379. ungrq, = get_lapack_funcs(['ungrq'], [a])
  380. assert_raises(Exception, ungrq, rq[-2:], tau, lwork=1)
  381. ungrq(rq[-2:], tau, lwork=2)
  382. class TestDpotr:
  383. # 'lower' argument of dportf/dpotri
  384. @pytest.mark.parametrize("lower", [True, False])
  385. @pytest.mark.parametrize("clean", [True, False])
  386. def test_gh_2691(self, lower, clean):
  387. rng = np.random.default_rng(42)
  388. x = rng.normal(size=(3, 3))
  389. a = x.dot(x.T)
  390. dpotrf, dpotri = get_lapack_funcs(("potrf", "potri"), (a, ))
  391. c, _ = dpotrf(a, lower, clean=clean)
  392. dpt = dpotri(c, lower)[0]
  393. if lower:
  394. assert_allclose(np.tril(dpt), np.tril(inv(a)))
  395. else:
  396. assert_allclose(np.triu(dpt), np.triu(inv(a)))
  397. class TestDlasd4:
  398. def test_sing_val_update(self):
  399. sigmas = np.array([4., 3., 2., 0])
  400. m_vec = np.array([3.12, 5.7, -4.8, -2.2])
  401. M = np.hstack((np.vstack((np.diag(sigmas[0:-1]),
  402. np.zeros((1, len(m_vec) - 1)))),
  403. m_vec[:, np.newaxis]))
  404. SM = svd(M, full_matrices=False, compute_uv=False, overwrite_a=False,
  405. check_finite=False)
  406. it_len = len(sigmas)
  407. sgm = np.concatenate((sigmas[::-1], [sigmas[0] + it_len*norm(m_vec)]))
  408. mvc = np.concatenate((m_vec[::-1], (0,)))
  409. lasd4 = get_lapack_funcs('lasd4', (sigmas,))
  410. roots = []
  411. for i in range(0, it_len):
  412. res = lasd4(i, sgm, mvc)
  413. roots.append(res[1])
  414. assert_(
  415. (res[3] <= 0),
  416. f"LAPACK root finding dlasd4 failed to find the singular value {i}"
  417. )
  418. roots = np.array(roots)[::-1]
  419. assert_((not np.any(np.isnan(roots)), "There are NaN roots"))
  420. assert_allclose(SM, roots, atol=100*np.finfo(np.float64).eps,
  421. rtol=100*np.finfo(np.float64).eps)
  422. class TestTbtrs:
  423. @pytest.mark.parametrize('dtype', DTYPES)
  424. def test_nag_example_f07vef_f07vsf(self, dtype):
  425. """Test real (f07vef) and complex (f07vsf) examples from NAG
  426. Examples available from:
  427. * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vef.html
  428. * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vsf.html
  429. """
  430. if dtype in REAL_DTYPES:
  431. ab = np.array([[-4.16, 4.78, 6.32, 0.16],
  432. [-2.25, 5.86, -4.82, 0]],
  433. dtype=dtype)
  434. b = np.array([[-16.64, -4.16],
  435. [-13.78, -16.59],
  436. [13.10, -4.94],
  437. [-14.14, -9.96]],
  438. dtype=dtype)
  439. x_out = np.array([[4, 1],
  440. [-1, -3],
  441. [3, 2],
  442. [2, -2]],
  443. dtype=dtype)
  444. elif dtype in COMPLEX_DTYPES:
  445. ab = np.array([[-1.94+4.43j, 4.12-4.27j, 0.43-2.66j, 0.44+0.1j],
  446. [-3.39+3.44j, -1.84+5.52j, 1.74 - 0.04j, 0],
  447. [1.62+3.68j, -2.77-1.93j, 0, 0]],
  448. dtype=dtype)
  449. b = np.array([[-8.86 - 3.88j, -24.09 - 5.27j],
  450. [-15.57 - 23.41j, -57.97 + 8.14j],
  451. [-7.63 + 22.78j, 19.09 - 29.51j],
  452. [-14.74 - 2.40j, 19.17 + 21.33j]],
  453. dtype=dtype)
  454. x_out = np.array([[2j, 1 + 5j],
  455. [1 - 3j, -7 - 2j],
  456. [-4.001887 - 4.988417j, 3.026830 + 4.003182j],
  457. [1.996158 - 1.045105j, -6.103357 - 8.986653j]],
  458. dtype=dtype)
  459. else:
  460. raise ValueError(f"Datatype {dtype} not understood.")
  461. tbtrs = get_lapack_funcs(('tbtrs'), dtype=dtype)
  462. x, info = tbtrs(ab=ab, b=b, uplo='L')
  463. assert_equal(info, 0)
  464. assert_allclose(x, x_out, rtol=0, atol=1e-5)
  465. @pytest.mark.parametrize('dtype,trans',
  466. [(dtype, trans)
  467. for dtype in DTYPES for trans in ['N', 'T', 'C']
  468. if not (trans == 'C' and dtype in REAL_DTYPES)])
  469. @pytest.mark.parametrize('uplo', ['U', 'L'])
  470. @pytest.mark.parametrize('diag', ['N', 'U'])
  471. def test_random_matrices(self, dtype, trans, uplo, diag):
  472. rng = np.random.RandomState(1724)
  473. # n, nrhs, kd are used to specify A and b.
  474. # A is of shape n x n with kd super/sub-diagonals
  475. # b is of shape n x nrhs matrix
  476. n, nrhs, kd = 4, 3, 2
  477. tbtrs = get_lapack_funcs('tbtrs', dtype=dtype)
  478. is_upper = (uplo == 'U')
  479. ku = kd * is_upper
  480. kl = kd - ku
  481. # Construct the diagonal and kd super/sub diagonals of A with
  482. # the corresponding offsets.
  483. band_offsets = range(ku, -kl - 1, -1)
  484. band_widths = [n - abs(x) for x in band_offsets]
  485. bands = [generate_random_dtype_array((width,), dtype, rng)
  486. for width in band_widths]
  487. if diag == 'U': # A must be unit triangular
  488. bands[ku] = np.ones(n, dtype=dtype)
  489. # Construct the diagonal banded matrix A from the bands and offsets.
  490. a = sps.diags(bands, band_offsets, format='dia')
  491. # Convert A into banded storage form
  492. ab = np.zeros((kd + 1, n), dtype)
  493. for row, k in enumerate(band_offsets):
  494. ab[row, max(k, 0):min(n+k, n)] = a.diagonal(k)
  495. # The RHS values.
  496. b = generate_random_dtype_array((n, nrhs), dtype, rng)
  497. x, info = tbtrs(ab=ab, b=b, uplo=uplo, trans=trans, diag=diag)
  498. assert_equal(info, 0)
  499. if trans == 'N':
  500. assert_allclose(a @ x, b, rtol=5e-5)
  501. elif trans == 'T':
  502. assert_allclose(a.T @ x, b, rtol=5e-5)
  503. elif trans == 'C':
  504. assert_allclose(a.T.conjugate() @ x, b, rtol=5e-5)
  505. else:
  506. raise ValueError('Invalid trans argument')
  507. @pytest.mark.parametrize('uplo,trans,diag',
  508. [['U', 'N', 'Invalid'],
  509. ['U', 'Invalid', 'N'],
  510. ['Invalid', 'N', 'N']])
  511. def test_invalid_argument_raises_exception(self, uplo, trans, diag):
  512. """Test if invalid values of uplo, trans and diag raise exceptions"""
  513. # Argument checks occur independently of used datatype.
  514. # This mean we must not parameterize all available datatypes.
  515. tbtrs = get_lapack_funcs('tbtrs', dtype=np.float64)
  516. rng = np.random.default_rng(1234)
  517. ab = rng.random((4, 2))
  518. b = rng.random((2, 4))
  519. assert_raises(Exception, tbtrs, ab, b, uplo, trans, diag)
  520. def test_zero_element_in_diagonal(self):
  521. """Test if a matrix with a zero diagonal element is singular
  522. If the i-th diagonal of A is zero, ?tbtrs should return `i` in `info`
  523. indicating the provided matrix is singular.
  524. Note that ?tbtrs requires the matrix A to be stored in banded form.
  525. In this form the diagonal corresponds to the last row."""
  526. ab = np.ones((3, 4), dtype=float)
  527. b = np.ones(4, dtype=float)
  528. tbtrs = get_lapack_funcs('tbtrs', dtype=float)
  529. ab[-1, 3] = 0
  530. _, info = tbtrs(ab=ab, b=b, uplo='U')
  531. assert_equal(info, 4)
  532. @pytest.mark.parametrize('ldab,n,ldb,nrhs', [
  533. (5, 5, 0, 5),
  534. (5, 5, 3, 5)
  535. ])
  536. def test_invalid_matrix_shapes(self, ldab, n, ldb, nrhs):
  537. """Test ?tbtrs fails correctly if shapes are invalid."""
  538. ab = np.ones((ldab, n), dtype=float)
  539. b = np.ones((ldb, nrhs), dtype=float)
  540. tbtrs = get_lapack_funcs('tbtrs', dtype=float)
  541. assert_raises(Exception, tbtrs, ab, b)
  542. @pytest.mark.parametrize('dtype', DTYPES)
  543. @pytest.mark.parametrize('norm', ['I', '1', 'O'])
  544. @pytest.mark.parametrize('uplo', ['U', 'L'])
  545. @pytest.mark.parametrize('diag', ['N', 'U'])
  546. @pytest.mark.parametrize('n', [3, 10])
  547. def test_trcon(dtype, norm, uplo, diag, n):
  548. # Simple way to get deterministic (unlike `hash`) seed based on arguments
  549. seed = list(f"{dtype}{norm}{uplo}{diag}{n}".encode())
  550. rng = np.random.default_rng(seed)
  551. A = rng.random(size=(n, n)) + rng.random(size=(n, n))*1j
  552. # make the condition numbers more interesting
  553. offset = rng.permuted(np.logspace(0, rng.integers(0, 10), n))
  554. A += offset
  555. A = A.real if np.issubdtype(dtype, np.floating) else A
  556. A = np.triu(A) if uplo == 'U' else np.tril(A)
  557. if diag == 'U':
  558. A /= np.diag(A)[:, np.newaxis]
  559. A = A.astype(dtype)
  560. trcon = get_lapack_funcs('trcon', (A,))
  561. res, _ = trcon(A, norm=norm, uplo=uplo, diag=diag)
  562. if norm == 'I':
  563. norm_A = np.linalg.norm(A, ord=np.inf)
  564. norm_inv_A = np.linalg.norm(np.linalg.inv(A), ord=np.inf)
  565. ref = 1 / (norm_A * norm_inv_A)
  566. else:
  567. anorm = np.linalg.norm(A, ord=1)
  568. gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,))
  569. lu, ipvt, info = getrf(A)
  570. ref, _ = gecon(lu, anorm, norm=norm)
  571. # This is an estimate of reciprocal condition number; we just need order of
  572. # magnitude. In testing, we observed that much smaller rtol is OK in almost
  573. # all cases... but sometimes it isn't.
  574. rtol = 1 # np.finfo(dtype).eps**0.75
  575. assert_allclose(res, ref, rtol=rtol)
  576. def test_lartg():
  577. for dtype in 'fdFD':
  578. lartg = get_lapack_funcs('lartg', dtype=dtype)
  579. f = np.array(3, dtype)
  580. g = np.array(4, dtype)
  581. if np.iscomplexobj(g):
  582. g *= 1j
  583. cs, sn, r = lartg(f, g)
  584. assert_allclose(cs, 3.0/5.0)
  585. assert_allclose(r, 5.0)
  586. if np.iscomplexobj(g):
  587. assert_allclose(sn, -4.0j/5.0)
  588. assert_(isinstance(r, complex))
  589. assert_(isinstance(cs, float))
  590. else:
  591. assert_allclose(sn, 4.0/5.0)
  592. def test_rot():
  593. # srot, drot from blas and crot and zrot from lapack.
  594. for dtype in 'fdFD':
  595. c = 0.6
  596. s = 0.8
  597. u = np.full(4, 3, dtype)
  598. v = np.full(4, 4, dtype)
  599. atol = 10**-(np.finfo(dtype).precision-1)
  600. if dtype in 'fd':
  601. rot = get_blas_funcs('rot', dtype=dtype)
  602. f = 4
  603. else:
  604. rot = get_lapack_funcs('rot', dtype=dtype)
  605. s *= -1j
  606. v *= 1j
  607. f = 4j
  608. assert_allclose(rot(u, v, c, s), [[5, 5, 5, 5],
  609. [0, 0, 0, 0]], atol=atol)
  610. assert_allclose(rot(u, v, c, s, n=2), [[5, 5, 3, 3],
  611. [0, 0, f, f]], atol=atol)
  612. assert_allclose(rot(u, v, c, s, offx=2, offy=2),
  613. [[3, 3, 5, 5], [f, f, 0, 0]], atol=atol)
  614. assert_allclose(rot(u, v, c, s, incx=2, offy=2, n=2),
  615. [[5, 3, 5, 3], [f, f, 0, 0]], atol=atol)
  616. assert_allclose(rot(u, v, c, s, offx=2, incy=2, n=2),
  617. [[3, 3, 5, 5], [0, f, 0, f]], atol=atol)
  618. assert_allclose(rot(u, v, c, s, offx=2, incx=2, offy=2, incy=2, n=1),
  619. [[3, 3, 5, 3], [f, f, 0, f]], atol=atol)
  620. assert_allclose(rot(u, v, c, s, incx=-2, incy=-2, n=2),
  621. [[5, 3, 5, 3], [0, f, 0, f]], atol=atol)
  622. a, b = rot(u, v, c, s, overwrite_x=1, overwrite_y=1)
  623. assert_(a is u)
  624. assert_(b is v)
  625. assert_allclose(a, [5, 5, 5, 5], atol=atol)
  626. assert_allclose(b, [0, 0, 0, 0], atol=atol)
  627. def test_larfg_larf():
  628. rng = np.random.default_rng(1234)
  629. a0 = rng.random((4, 4))
  630. a0 = a0.T.dot(a0)
  631. a0j = rng.random((4, 4)) + 1j*rng.random((4, 4))
  632. a0j = a0j.T.conj().dot(a0j)
  633. # our test here will be to do one step of reducing a hermetian matrix to
  634. # tridiagonal form using householder transforms.
  635. for dtype in 'fdFD':
  636. larfg, larf = get_lapack_funcs(['larfg', 'larf'], dtype=dtype)
  637. if dtype in 'FD':
  638. a = a0j.copy()
  639. else:
  640. a = a0.copy()
  641. # generate a householder transform to clear a[2:,0]
  642. alpha, x, tau = larfg(a.shape[0]-1, a[1, 0], a[2:, 0])
  643. # create expected output
  644. expected = np.zeros_like(a[:, 0])
  645. expected[0] = a[0, 0]
  646. expected[1] = alpha
  647. # assemble householder vector
  648. v = np.zeros_like(a[1:, 0])
  649. v[0] = 1.0
  650. v[1:] = x
  651. # apply transform from the left
  652. a[1:, :] = larf(v, tau.conjugate(), a[1:, :], np.zeros(a.shape[1]))
  653. # apply transform from the right
  654. a[:, 1:] = larf(v, tau, a[:, 1:], np.zeros(a.shape[0]), side='R')
  655. assert_allclose(a[:, 0], expected, atol=1e-5)
  656. assert_allclose(a[0, :], expected, atol=1e-5)
  657. def test_sgesdd_lwork_bug_workaround():
  658. # Test that SGESDD lwork is sufficiently large for LAPACK.
  659. #
  660. # This checks that _compute_lwork() correctly works around a bug in
  661. # LAPACK versions older than 3.10.1.
  662. sgesdd_lwork = get_lapack_funcs('gesdd_lwork', dtype=np.float32,
  663. ilp64='preferred')
  664. n = 9537
  665. lwork = _compute_lwork(sgesdd_lwork, n, n,
  666. compute_uv=True, full_matrices=True)
  667. # If we called the Fortran function SGESDD directly with IWORK=-1, the
  668. # LAPACK bug would result in lwork being 272929856, which was too small.
  669. # (The result was returned in a single precision float, which does not
  670. # have sufficient precision to represent the exact integer value that it
  671. # computed internally.) The work-around implemented in _compute_lwork()
  672. # will convert that to 272929888. If we are using LAPACK 3.10.1 or later
  673. # (such as in OpenBLAS 0.3.21 or later), the work-around will return
  674. # 272929920, because it does not know which version of LAPACK is being
  675. # used, so it always applies the correction to whatever it is given. We
  676. # will accept either 272929888 or 272929920.
  677. # Note that the acceptable values are a LAPACK implementation detail.
  678. # If a future version of LAPACK changes how SGESDD works, and therefore
  679. # changes the required LWORK size, the acceptable values might have to
  680. # be updated.
  681. assert lwork == 272929888 or lwork == 272929920
  682. class TestSytrd:
  683. @pytest.mark.parametrize('dtype', REAL_DTYPES)
  684. def test_sytrd_with_zero_dim_array(self, dtype):
  685. # Assert that a 0x0 matrix raises an error
  686. A = np.zeros((0, 0), dtype=dtype)
  687. sytrd = get_lapack_funcs('sytrd', (A,))
  688. assert_raises(ValueError, sytrd, A)
  689. @pytest.mark.parametrize('dtype', REAL_DTYPES)
  690. @pytest.mark.parametrize('n', (1, 3))
  691. def test_sytrd(self, dtype, n):
  692. A = np.zeros((n, n), dtype=dtype)
  693. sytrd, sytrd_lwork = \
  694. get_lapack_funcs(('sytrd', 'sytrd_lwork'), (A,))
  695. # some upper triangular array
  696. A[np.triu_indices_from(A)] = \
  697. np.arange(1, n*(n+1)//2+1, dtype=dtype)
  698. # query lwork
  699. lwork, info = sytrd_lwork(n)
  700. assert_equal(info, 0)
  701. # check lower=1 behavior (shouldn't do much since the matrix is
  702. # upper triangular)
  703. data, d, e, tau, info = sytrd(A, lower=1, lwork=lwork)
  704. assert_equal(info, 0)
  705. assert_allclose(data, A, atol=5*np.finfo(dtype).eps, rtol=1.0)
  706. assert_allclose(d, np.diag(A))
  707. assert_allclose(e, 0.0)
  708. assert_allclose(tau, 0.0)
  709. # and now for the proper test (lower=0 is the default)
  710. data, d, e, tau, info = sytrd(A, lwork=lwork)
  711. assert_equal(info, 0)
  712. # assert Q^T*A*Q = tridiag(e, d, e)
  713. # build tridiagonal matrix
  714. T = np.zeros_like(A, dtype=dtype)
  715. k = np.arange(A.shape[0])
  716. T[k, k] = d
  717. k2 = np.arange(A.shape[0]-1)
  718. T[k2+1, k2] = e
  719. T[k2, k2+1] = e
  720. # build Q
  721. Q = np.eye(n, n, dtype=dtype)
  722. for i in range(n-1):
  723. v = np.zeros(n, dtype=dtype)
  724. v[:i] = data[:i, i+1]
  725. v[i] = 1.0
  726. H = np.eye(n, n, dtype=dtype) - tau[i] * np.outer(v, v)
  727. Q = np.dot(H, Q)
  728. # Make matrix fully symmetric
  729. i_lower = np.tril_indices(n, -1)
  730. A[i_lower] = A.T[i_lower]
  731. QTAQ = np.dot(Q.T, np.dot(A, Q))
  732. # disable rtol here since some values in QTAQ and T are very close
  733. # to 0.
  734. assert_allclose(QTAQ, T, atol=5*np.finfo(dtype).eps, rtol=1.0)
  735. class TestHetrd:
  736. @pytest.mark.parametrize('complex_dtype', COMPLEX_DTYPES)
  737. def test_hetrd_with_zero_dim_array(self, complex_dtype):
  738. # Assert that a 0x0 matrix raises an error
  739. A = np.zeros((0, 0), dtype=complex_dtype)
  740. hetrd = get_lapack_funcs('hetrd', (A,))
  741. assert_raises(ValueError, hetrd, A)
  742. @pytest.mark.parametrize('real_dtype,complex_dtype',
  743. zip(REAL_DTYPES, COMPLEX_DTYPES))
  744. @pytest.mark.parametrize('n', (1, 3))
  745. def test_hetrd(self, n, real_dtype, complex_dtype):
  746. A = np.zeros((n, n), dtype=complex_dtype)
  747. hetrd, hetrd_lwork = \
  748. get_lapack_funcs(('hetrd', 'hetrd_lwork'), (A,))
  749. # some upper triangular array
  750. A[np.triu_indices_from(A)] = (
  751. np.arange(1, n*(n+1)//2+1, dtype=real_dtype)
  752. + 1j * np.arange(1, n*(n+1)//2+1, dtype=real_dtype)
  753. )
  754. np.fill_diagonal(A, np.real(np.diag(A)))
  755. # test query lwork
  756. for x in [0, 1]:
  757. _, info = hetrd_lwork(n, lower=x)
  758. assert_equal(info, 0)
  759. # lwork returns complex which segfaults hetrd call (gh-10388)
  760. # use the safe and recommended option
  761. lwork = _compute_lwork(hetrd_lwork, n)
  762. # check lower=1 behavior (shouldn't do much since the matrix is
  763. # upper triangular)
  764. data, d, e, tau, info = hetrd(A, lower=1, lwork=lwork)
  765. assert_equal(info, 0)
  766. assert_allclose(data, A, atol=5*np.finfo(real_dtype).eps, rtol=1.0)
  767. assert_allclose(d, np.real(np.diag(A)))
  768. assert_allclose(e, 0.0)
  769. assert_allclose(tau, 0.0)
  770. # and now for the proper test (lower=0 is the default)
  771. data, d, e, tau, info = hetrd(A, lwork=lwork)
  772. assert_equal(info, 0)
  773. # assert Q^T*A*Q = tridiag(e, d, e)
  774. # build tridiagonal matrix
  775. T = np.zeros_like(A, dtype=real_dtype)
  776. k = np.arange(A.shape[0], dtype=int)
  777. T[k, k] = d
  778. k2 = np.arange(A.shape[0]-1, dtype=int)
  779. T[k2+1, k2] = e
  780. T[k2, k2+1] = e
  781. # build Q
  782. Q = np.eye(n, n, dtype=complex_dtype)
  783. for i in range(n-1):
  784. v = np.zeros(n, dtype=complex_dtype)
  785. v[:i] = data[:i, i+1]
  786. v[i] = 1.0
  787. H = np.eye(n, n, dtype=complex_dtype) \
  788. - tau[i] * np.outer(v, np.conj(v))
  789. Q = np.dot(H, Q)
  790. # Make matrix fully Hermitian
  791. i_lower = np.tril_indices(n, -1)
  792. A[i_lower] = np.conj(A.T[i_lower])
  793. QHAQ = np.dot(np.conj(Q.T), np.dot(A, Q))
  794. # disable rtol here since some values in QTAQ and T are very close
  795. # to 0.
  796. assert_allclose(
  797. QHAQ, T, atol=10*np.finfo(real_dtype).eps, rtol=1.0
  798. )
  799. def test_gglse():
  800. # Example data taken from NAG manual
  801. for ind, dtype in enumerate(DTYPES):
  802. # DTYPES = <s,d,c,z> gglse
  803. func, func_lwork = get_lapack_funcs(('gglse', 'gglse_lwork'),
  804. dtype=dtype)
  805. lwork = _compute_lwork(func_lwork, m=6, n=4, p=2)
  806. # For <s,d>gglse
  807. if ind < 2:
  808. a = np.array([[-0.57, -1.28, -0.39, 0.25],
  809. [-1.93, 1.08, -0.31, -2.14],
  810. [2.30, 0.24, 0.40, -0.35],
  811. [-1.93, 0.64, -0.66, 0.08],
  812. [0.15, 0.30, 0.15, -2.13],
  813. [-0.02, 1.03, -1.43, 0.50]], dtype=dtype)
  814. c = np.array([-1.50, -2.14, 1.23, -0.54, -1.68, 0.82], dtype=dtype)
  815. d = np.array([0., 0.], dtype=dtype)
  816. # For <s,d>gglse
  817. else:
  818. a = np.array([[0.96-0.81j, -0.03+0.96j, -0.91+2.06j, -0.05+0.41j],
  819. [-0.98+1.98j, -1.20+0.19j, -0.66+0.42j, -0.81+0.56j],
  820. [0.62-0.46j, 1.01+0.02j, 0.63-0.17j, -1.11+0.60j],
  821. [0.37+0.38j, 0.19-0.54j, -0.98-0.36j, 0.22-0.20j],
  822. [0.83+0.51j, 0.20+0.01j, -0.17-0.46j, 1.47+1.59j],
  823. [1.08-0.28j, 0.20-0.12j, -0.07+1.23j, 0.26+0.26j]])
  824. c = np.array([[-2.54+0.09j],
  825. [1.65-2.26j],
  826. [-2.11-3.96j],
  827. [1.82+3.30j],
  828. [-6.41+3.77j],
  829. [2.07+0.66j]])
  830. d = np.zeros(2, dtype=dtype)
  831. b = np.array([[1., 0., -1., 0.], [0., 1., 0., -1.]], dtype=dtype)
  832. _, _, _, result, _ = func(a, b, c, d, lwork=lwork)
  833. if ind < 2:
  834. expected = np.array([0.48904455,
  835. 0.99754786,
  836. 0.48904455,
  837. 0.99754786])
  838. else:
  839. expected = np.array([1.08742917-1.96205783j,
  840. -0.74093902+3.72973919j,
  841. 1.08742917-1.96205759j,
  842. -0.74093896+3.72973895j])
  843. assert_array_almost_equal(result, expected, decimal=4)
  844. def test_sycon_hecon():
  845. rng = np.random.default_rng(1234)
  846. for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
  847. # DTYPES + COMPLEX DTYPES = <s,d,c,z> sycon + <c,z>hecon
  848. n = 10
  849. # For <s,d,c,z>sycon
  850. if ind < 4:
  851. func_lwork = get_lapack_funcs('sytrf_lwork', dtype=dtype)
  852. funcon, functrf = get_lapack_funcs(('sycon', 'sytrf'), dtype=dtype)
  853. A = (rng.random((n, n))).astype(dtype)
  854. # For <c,z>hecon
  855. else:
  856. func_lwork = get_lapack_funcs('hetrf_lwork', dtype=dtype)
  857. funcon, functrf = get_lapack_funcs(('hecon', 'hetrf'), dtype=dtype)
  858. A = (rng.random((n, n)) + rng.random((n, n))*1j).astype(dtype)
  859. # Since sycon only refers to upper/lower part, conj() is safe here.
  860. A = (A + A.conj().T)/2 + 2*np.eye(n, dtype=dtype)
  861. anorm = norm(A, 1)
  862. lwork = _compute_lwork(func_lwork, n)
  863. ldu, ipiv, _ = functrf(A, lwork=lwork, lower=1)
  864. rcond, _ = funcon(a=ldu, ipiv=ipiv, anorm=anorm, lower=1)
  865. # The error is at most 1-fold
  866. assert_(abs(1/rcond - np.linalg.cond(A, p=1))*rcond < 1)
  867. def test_sygst():
  868. rng = np.random.default_rng(1234)
  869. for ind, dtype in enumerate(REAL_DTYPES):
  870. # DTYPES = <s,d> sygst
  871. n = 10
  872. potrf, sygst, syevd, sygvd = get_lapack_funcs(('potrf', 'sygst',
  873. 'syevd', 'sygvd'),
  874. dtype=dtype)
  875. A = rng.random((n, n)).astype(dtype)
  876. A = (A + A.T)/2
  877. # B must be positive definite
  878. B = rng.random((n, n)).astype(dtype)
  879. B = (B + B.T)/2 + 2 * np.eye(n, dtype=dtype)
  880. # Perform eig (sygvd)
  881. eig_gvd, _, info = sygvd(A, B)
  882. assert_(info == 0)
  883. # Convert to std problem potrf
  884. b, info = potrf(B)
  885. assert_(info == 0)
  886. a, info = sygst(A, b)
  887. assert_(info == 0)
  888. eig, _, info = syevd(a)
  889. assert_(info == 0)
  890. assert_allclose(eig, eig_gvd, rtol=1.2e-4)
  891. def test_hegst():
  892. rng = np.random.default_rng(1234)
  893. for ind, dtype in enumerate(COMPLEX_DTYPES):
  894. # DTYPES = <c,z> hegst
  895. n = 10
  896. potrf, hegst, heevd, hegvd = get_lapack_funcs(('potrf', 'hegst',
  897. 'heevd', 'hegvd'),
  898. dtype=dtype)
  899. A = rng.random((n, n)).astype(dtype) + 1j * rng.random((n, n)).astype(dtype)
  900. A = (A + A.conj().T)/2
  901. # B must be positive definite
  902. B = rng.random((n, n)).astype(dtype) + 1j * rng.random((n, n)).astype(dtype)
  903. B = (B + B.conj().T)/2 + 2 * np.eye(n, dtype=dtype)
  904. # Perform eig (hegvd)
  905. eig_gvd, _, info = hegvd(A, B)
  906. assert_(info == 0)
  907. # Convert to std problem potrf
  908. b, info = potrf(B)
  909. assert_(info == 0)
  910. a, info = hegst(A, b)
  911. assert_(info == 0)
  912. eig, _, info = heevd(a)
  913. assert_(info == 0)
  914. assert_allclose(eig, eig_gvd, rtol=1e-4)
  915. def test_tzrzf():
  916. """
  917. This test performs an RZ decomposition in which an m x n upper trapezoidal
  918. array M (m <= n) is factorized as M = [R 0] * Z where R is upper triangular
  919. and Z is unitary.
  920. """
  921. rng = np.random.RandomState(1234)
  922. m, n = 10, 15
  923. for ind, dtype in enumerate(DTYPES):
  924. tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'),
  925. dtype=dtype)
  926. lwork = _compute_lwork(tzrzf_lw, m, n)
  927. if ind < 2:
  928. A = triu(rng.rand(m, n).astype(dtype))
  929. else:
  930. A = triu((rng.rand(m, n) + rng.rand(m, n)*1j).astype(dtype))
  931. # assert wrong shape arg, f2py returns generic error
  932. assert_raises(Exception, tzrzf, A.T)
  933. rz, tau, info = tzrzf(A, lwork=lwork)
  934. # Check success
  935. assert_(info == 0)
  936. # Get Z manually for comparison
  937. R = np.hstack((rz[:, :m], np.zeros((m, n-m), dtype=dtype)))
  938. V = np.hstack((np.eye(m, dtype=dtype), rz[:, m:]))
  939. Id = np.eye(n, dtype=dtype)
  940. ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(m)]
  941. Z = reduce(np.dot, ref)
  942. assert_allclose(R.dot(Z) - A, zeros_like(A, dtype=dtype),
  943. atol=10*np.spacing(dtype(1.0).real), rtol=0.)
  944. def test_tfsm():
  945. """
  946. Test for solving a linear system with the coefficient matrix is a
  947. triangular array stored in Full Packed (RFP) format.
  948. """
  949. rng = np.random.RandomState(1234)
  950. for ind, dtype in enumerate(DTYPES):
  951. n = 20
  952. if ind > 1:
  953. A = triu(rng.rand(n, n) + rng.rand(n, n)*1j + eye(n)).astype(dtype)
  954. trans = 'C'
  955. else:
  956. A = triu(rng.rand(n, n) + eye(n)).astype(dtype)
  957. trans = 'T'
  958. trttf, tfttr, tfsm = get_lapack_funcs(('trttf', 'tfttr', 'tfsm'),
  959. dtype=dtype)
  960. Afp, _ = trttf(A)
  961. B = rng.rand(n, 2).astype(dtype)
  962. soln = tfsm(-1, Afp, B)
  963. assert_array_almost_equal(soln, solve(-A, B),
  964. decimal=4 if ind % 2 == 0 else 6)
  965. soln = tfsm(-1, Afp, B, trans=trans)
  966. assert_array_almost_equal(soln, solve(-A.conj().T, B),
  967. decimal=4 if ind % 2 == 0 else 6)
  968. # Make A, unit diagonal
  969. A[np.arange(n), np.arange(n)] = dtype(1.)
  970. soln = tfsm(-1, Afp, B, trans=trans, diag='U')
  971. assert_array_almost_equal(soln, solve(-A.conj().T, B),
  972. decimal=4 if ind % 2 == 0 else 6)
  973. # Change side
  974. B2 = rng.rand(3, n).astype(dtype)
  975. soln = tfsm(-1, Afp, B2, trans=trans, diag='U', side='R')
  976. assert_array_almost_equal(soln, solve(-A, B2.T).conj().T,
  977. decimal=4 if ind % 2 == 0 else 6)
  978. def test_ormrz_unmrz():
  979. """
  980. This test performs a matrix multiplication with an arbitrary m x n matrix C
  981. and a unitary matrix Q without explicitly forming the array. The array data
  982. is encoded in the rectangular part of A which is obtained from ?TZRZF. Q
  983. size is inferred by m, n, side keywords.
  984. """
  985. rng = np.random.RandomState(1234)
  986. qm, qn, cn = 10, 15, 15
  987. for ind, dtype in enumerate(DTYPES):
  988. tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'),
  989. dtype=dtype)
  990. lwork_rz = _compute_lwork(tzrzf_lw, qm, qn)
  991. if ind < 2:
  992. A = triu(rng.random((qm, qn)).astype(dtype))
  993. C = rng.random((cn, cn)).astype(dtype)
  994. orun_mrz, orun_mrz_lw = get_lapack_funcs(('ormrz', 'ormrz_lwork'),
  995. dtype=dtype)
  996. else:
  997. A = triu((rng.random((qm, qn)) + rng.random((qm, qn))*1j).astype(dtype))
  998. C = (rng.random((cn, cn)) + rng.random((cn, cn))*1j).astype(dtype)
  999. orun_mrz, orun_mrz_lw = get_lapack_funcs(('unmrz', 'unmrz_lwork'),
  1000. dtype=dtype)
  1001. lwork_mrz = _compute_lwork(orun_mrz_lw, cn, cn)
  1002. rz, tau, info = tzrzf(A, lwork=lwork_rz)
  1003. # Get Q manually for comparison
  1004. V = np.hstack((np.eye(qm, dtype=dtype), rz[:, qm:]))
  1005. Id = np.eye(qn, dtype=dtype)
  1006. ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(qm)]
  1007. Q = reduce(np.dot, ref)
  1008. # Now that we have Q, we can test whether lapack results agree with
  1009. # each case of CQ, CQ^H, QC, and QC^H
  1010. trans = 'T' if ind < 2 else 'C'
  1011. tol = 10*np.spacing(dtype(1.0).real)
  1012. cq, info = orun_mrz(rz, tau, C, lwork=lwork_mrz)
  1013. assert_(info == 0)
  1014. assert_allclose(cq - Q.dot(C), zeros_like(C), atol=tol, rtol=0.)
  1015. cq, info = orun_mrz(rz, tau, C, trans=trans, lwork=lwork_mrz)
  1016. assert_(info == 0)
  1017. assert_allclose(cq - Q.conj().T.dot(C), zeros_like(C), atol=tol,
  1018. rtol=0.)
  1019. cq, info = orun_mrz(rz, tau, C, side='R', lwork=lwork_mrz)
  1020. assert_(info == 0)
  1021. assert_allclose(cq - C.dot(Q), zeros_like(C), atol=tol, rtol=0.)
  1022. cq, info = orun_mrz(rz, tau, C, side='R', trans=trans, lwork=lwork_mrz)
  1023. assert_(info == 0)
  1024. assert_allclose(cq - C.dot(Q.conj().T), zeros_like(C), atol=tol,
  1025. rtol=0.)
  1026. def test_tfttr_trttf():
  1027. """
  1028. Test conversion routines between the Rectangular Full Packed (RFP) format
  1029. and Standard Triangular Array (TR)
  1030. """
  1031. rng = np.random.RandomState(1234)
  1032. for ind, dtype in enumerate(DTYPES):
  1033. n = 20
  1034. if ind > 1:
  1035. A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1036. transr = 'C'
  1037. else:
  1038. A_full = (rng.rand(n, n)).astype(dtype)
  1039. transr = 'T'
  1040. trttf, tfttr = get_lapack_funcs(('trttf', 'tfttr'), dtype=dtype)
  1041. A_tf_U, info = trttf(A_full)
  1042. assert_(info == 0)
  1043. A_tf_L, info = trttf(A_full, uplo='L')
  1044. assert_(info == 0)
  1045. A_tf_U_T, info = trttf(A_full, transr=transr, uplo='U')
  1046. assert_(info == 0)
  1047. A_tf_L_T, info = trttf(A_full, transr=transr, uplo='L')
  1048. assert_(info == 0)
  1049. # Create the RFP array manually (n is even!)
  1050. A_tf_U_m = zeros((n+1, n//2), dtype=dtype)
  1051. A_tf_U_m[:-1, :] = triu(A_full)[:, n//2:]
  1052. A_tf_U_m[n//2+1:, :] += triu(A_full)[:n//2, :n//2].conj().T
  1053. A_tf_L_m = zeros((n+1, n//2), dtype=dtype)
  1054. A_tf_L_m[1:, :] = tril(A_full)[:, :n//2]
  1055. A_tf_L_m[:n//2, :] += tril(A_full)[n//2:, n//2:].conj().T
  1056. assert_array_almost_equal(A_tf_U, A_tf_U_m.reshape(-1, order='F'))
  1057. assert_array_almost_equal(A_tf_U_T,
  1058. A_tf_U_m.conj().T.reshape(-1, order='F'))
  1059. assert_array_almost_equal(A_tf_L, A_tf_L_m.reshape(-1, order='F'))
  1060. assert_array_almost_equal(A_tf_L_T,
  1061. A_tf_L_m.conj().T.reshape(-1, order='F'))
  1062. # Get the original array from RFP
  1063. A_tr_U, info = tfttr(n, A_tf_U)
  1064. assert_(info == 0)
  1065. A_tr_L, info = tfttr(n, A_tf_L, uplo='L')
  1066. assert_(info == 0)
  1067. A_tr_U_T, info = tfttr(n, A_tf_U_T, transr=transr, uplo='U')
  1068. assert_(info == 0)
  1069. A_tr_L_T, info = tfttr(n, A_tf_L_T, transr=transr, uplo='L')
  1070. assert_(info == 0)
  1071. assert_array_almost_equal(A_tr_U, triu(A_full))
  1072. assert_array_almost_equal(A_tr_U_T, triu(A_full))
  1073. assert_array_almost_equal(A_tr_L, tril(A_full))
  1074. assert_array_almost_equal(A_tr_L_T, tril(A_full))
  1075. def test_tpttr_trttp():
  1076. """
  1077. Test conversion routines between the Rectangular Full Packed (RFP) format
  1078. and Standard Triangular Array (TR)
  1079. """
  1080. rng = np.random.RandomState(1234)
  1081. for ind, dtype in enumerate(DTYPES):
  1082. n = 20
  1083. if ind > 1:
  1084. A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1085. else:
  1086. A_full = (rng.rand(n, n)).astype(dtype)
  1087. trttp, tpttr = get_lapack_funcs(('trttp', 'tpttr'), dtype=dtype)
  1088. A_tp_U, info = trttp(A_full)
  1089. assert_(info == 0)
  1090. A_tp_L, info = trttp(A_full, uplo='L')
  1091. assert_(info == 0)
  1092. # Create the TP array manually
  1093. inds = tril_indices(n)
  1094. A_tp_U_m = zeros(n*(n+1)//2, dtype=dtype)
  1095. A_tp_U_m[:] = (triu(A_full).T)[inds]
  1096. inds = triu_indices(n)
  1097. A_tp_L_m = zeros(n*(n+1)//2, dtype=dtype)
  1098. A_tp_L_m[:] = (tril(A_full).T)[inds]
  1099. assert_array_almost_equal(A_tp_U, A_tp_U_m)
  1100. assert_array_almost_equal(A_tp_L, A_tp_L_m)
  1101. # Get the original array from TP
  1102. A_tr_U, info = tpttr(n, A_tp_U)
  1103. assert_(info == 0)
  1104. A_tr_L, info = tpttr(n, A_tp_L, uplo='L')
  1105. assert_(info == 0)
  1106. assert_array_almost_equal(A_tr_U, triu(A_full))
  1107. assert_array_almost_equal(A_tr_L, tril(A_full))
  1108. def test_pftrf():
  1109. """
  1110. Test Cholesky factorization of a positive definite Rectangular Full
  1111. Packed (RFP) format array
  1112. """
  1113. rng = np.random.RandomState(1234)
  1114. for ind, dtype in enumerate(DTYPES):
  1115. n = 20
  1116. if ind > 1:
  1117. A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1118. A = A + A.conj().T + n*eye(n)
  1119. else:
  1120. A = (rng.rand(n, n)).astype(dtype)
  1121. A = A + A.T + n*eye(n)
  1122. pftrf, trttf, tfttr = get_lapack_funcs(('pftrf', 'trttf', 'tfttr'),
  1123. dtype=dtype)
  1124. # Get the original array from TP
  1125. Afp, info = trttf(A)
  1126. Achol_rfp, info = pftrf(n, Afp)
  1127. assert_(info == 0)
  1128. A_chol_r, _ = tfttr(n, Achol_rfp)
  1129. Achol = cholesky(A)
  1130. assert_array_almost_equal(A_chol_r, Achol)
  1131. def test_pftri():
  1132. """
  1133. Test Cholesky factorization of a positive definite Rectangular Full
  1134. Packed (RFP) format array to find its inverse
  1135. """
  1136. rng = np.random.RandomState(1234)
  1137. for ind, dtype in enumerate(DTYPES):
  1138. n = 20
  1139. if ind > 1:
  1140. A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1141. A = A + A.conj().T + n*eye(n)
  1142. else:
  1143. A = (rng.rand(n, n)).astype(dtype)
  1144. A = A + A.T + n*eye(n)
  1145. pftri, pftrf, trttf, tfttr = get_lapack_funcs(('pftri',
  1146. 'pftrf',
  1147. 'trttf',
  1148. 'tfttr'),
  1149. dtype=dtype)
  1150. # Get the original array from TP
  1151. Afp, info = trttf(A)
  1152. A_chol_rfp, info = pftrf(n, Afp)
  1153. A_inv_rfp, info = pftri(n, A_chol_rfp)
  1154. assert_(info == 0)
  1155. A_inv_r, _ = tfttr(n, A_inv_rfp)
  1156. Ainv = inv(A)
  1157. assert_array_almost_equal(A_inv_r, triu(Ainv),
  1158. decimal=4 if ind % 2 == 0 else 6)
  1159. def test_pftrs():
  1160. """
  1161. Test Cholesky factorization of a positive definite Rectangular Full
  1162. Packed (RFP) format array and solve a linear system
  1163. """
  1164. rng = np.random.RandomState(1234)
  1165. for ind, dtype in enumerate(DTYPES):
  1166. n = 20
  1167. if ind > 1:
  1168. A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1169. A = A + A.conj().T + n*eye(n)
  1170. else:
  1171. A = (rng.rand(n, n)).astype(dtype)
  1172. A = A + A.T + n*eye(n)
  1173. B = ones((n, 3), dtype=dtype)
  1174. Bf1 = ones((n+2, 3), dtype=dtype)
  1175. Bf2 = ones((n-2, 3), dtype=dtype)
  1176. pftrs, pftrf, trttf, tfttr = get_lapack_funcs(('pftrs',
  1177. 'pftrf',
  1178. 'trttf',
  1179. 'tfttr'),
  1180. dtype=dtype)
  1181. # Get the original array from TP
  1182. Afp, info = trttf(A)
  1183. A_chol_rfp, info = pftrf(n, Afp)
  1184. # larger B arrays shouldn't segfault
  1185. soln, info = pftrs(n, A_chol_rfp, Bf1)
  1186. assert_(info == 0)
  1187. assert_raises(Exception, pftrs, n, A_chol_rfp, Bf2)
  1188. soln, info = pftrs(n, A_chol_rfp, B)
  1189. assert_(info == 0)
  1190. assert_array_almost_equal(solve(A, B), soln,
  1191. decimal=4 if ind % 2 == 0 else 6)
  1192. def test_sfrk_hfrk():
  1193. """
  1194. Test for performing a symmetric rank-k operation for matrix in RFP format.
  1195. """
  1196. rng = np.random.RandomState(1234)
  1197. for ind, dtype in enumerate(DTYPES):
  1198. n = 20
  1199. if ind > 1:
  1200. A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1201. A = A + A.conj().T + n*eye(n)
  1202. else:
  1203. A = (rng.rand(n, n)).astype(dtype)
  1204. A = A + A.T + n*eye(n)
  1205. prefix = 's'if ind < 2 else 'h'
  1206. trttf, tfttr, shfrk = get_lapack_funcs(('trttf', 'tfttr', f'{prefix}frk'),
  1207. dtype=dtype)
  1208. Afp, _ = trttf(A)
  1209. C = rng.rand(n, 2).astype(dtype)
  1210. Afp_out = shfrk(n, 2, -1, C, 2, Afp)
  1211. A_out, _ = tfttr(n, Afp_out)
  1212. assert_array_almost_equal(A_out, triu(-C.dot(C.conj().T) + 2*A),
  1213. decimal=4 if ind % 2 == 0 else 6)
  1214. def test_syconv():
  1215. """
  1216. Test for going back and forth between the returned format of he/sytrf to
  1217. L and D factors/permutations.
  1218. """
  1219. rng = np.random.RandomState(1234)
  1220. for ind, dtype in enumerate(DTYPES):
  1221. n = 10
  1222. if ind > 1:
  1223. A = (rng.randint(-30, 30, (n, n)) +
  1224. rng.randint(-30, 30, (n, n))*1j).astype(dtype)
  1225. A = A + A.conj().T
  1226. else:
  1227. A = rng.randint(-30, 30, (n, n)).astype(dtype)
  1228. A = A + A.T + n*eye(n)
  1229. tol = 100*np.spacing(dtype(1.0).real)
  1230. syconv, trf, trf_lwork = get_lapack_funcs(('syconv', 'sytrf',
  1231. 'sytrf_lwork'), dtype=dtype)
  1232. lw = _compute_lwork(trf_lwork, n, lower=1)
  1233. L, D, perm = ldl(A, lower=1, hermitian=False)
  1234. lw = _compute_lwork(trf_lwork, n, lower=1)
  1235. ldu, ipiv, info = trf(A, lower=1, lwork=lw)
  1236. a, e, info = syconv(ldu, ipiv, lower=1)
  1237. assert_allclose(tril(a, -1,), tril(L[perm, :], -1), atol=tol, rtol=0.)
  1238. # Test also upper
  1239. U, D, perm = ldl(A, lower=0, hermitian=False)
  1240. ldu, ipiv, info = trf(A, lower=0)
  1241. a, e, info = syconv(ldu, ipiv, lower=0)
  1242. assert_allclose(triu(a, 1), triu(U[perm, :], 1), atol=tol, rtol=0.)
  1243. class TestBlockedQR:
  1244. """
  1245. Tests for the blocked QR factorization, namely through geqrt, gemqrt, tpqrt
  1246. and tpmqr.
  1247. """
  1248. def test_geqrt_gemqrt(self):
  1249. rng = np.random.RandomState(1234)
  1250. for ind, dtype in enumerate(DTYPES):
  1251. n = 20
  1252. if ind > 1:
  1253. A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1254. else:
  1255. A = (rng.rand(n, n)).astype(dtype)
  1256. tol = 100*np.spacing(dtype(1.0).real)
  1257. geqrt, gemqrt = get_lapack_funcs(('geqrt', 'gemqrt'), dtype=dtype)
  1258. a, t, info = geqrt(n, A)
  1259. assert info == 0
  1260. # Extract elementary reflectors from lower triangle, adding the
  1261. # main diagonal of ones.
  1262. v = np.tril(a, -1) + np.eye(n, dtype=dtype)
  1263. # Generate the block Householder transform I - VTV^H
  1264. Q = np.eye(n, dtype=dtype) - v @ t @ v.T.conj()
  1265. R = np.triu(a)
  1266. # Test columns of Q are orthogonal
  1267. assert_allclose(Q.T.conj() @ Q, np.eye(n, dtype=dtype), atol=tol,
  1268. rtol=0.)
  1269. assert_allclose(Q @ R, A, atol=tol, rtol=0.)
  1270. if ind > 1:
  1271. C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1272. transpose = 'C'
  1273. else:
  1274. C = (rng.rand(n, n)).astype(dtype)
  1275. transpose = 'T'
  1276. for side in ('L', 'R'):
  1277. for trans in ('N', transpose):
  1278. c, info = gemqrt(a, t, C, side=side, trans=trans)
  1279. assert info == 0
  1280. if trans == transpose:
  1281. q = Q.T.conj()
  1282. else:
  1283. q = Q
  1284. if side == 'L':
  1285. qC = q @ C
  1286. else:
  1287. qC = C @ q
  1288. assert_allclose(c, qC, atol=tol, rtol=0.)
  1289. # Test default arguments
  1290. if (side, trans) == ('L', 'N'):
  1291. c_default, info = gemqrt(a, t, C)
  1292. assert info == 0
  1293. assert_equal(c_default, c)
  1294. # Test invalid side/trans
  1295. assert_raises(Exception, gemqrt, a, t, C, side='A')
  1296. assert_raises(Exception, gemqrt, a, t, C, trans='A')
  1297. def test_tpqrt_tpmqrt(self):
  1298. rng = np.random.RandomState(1234)
  1299. for ind, dtype in enumerate(DTYPES):
  1300. n = 20
  1301. if ind > 1:
  1302. A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1303. B = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1304. else:
  1305. A = (rng.rand(n, n)).astype(dtype)
  1306. B = (rng.rand(n, n)).astype(dtype)
  1307. tol = 100*np.spacing(dtype(1.0).real)
  1308. tpqrt, tpmqrt = get_lapack_funcs(('tpqrt', 'tpmqrt'), dtype=dtype)
  1309. # Test for the range of pentagonal B, from square to upper
  1310. # triangular
  1311. for l in (0, n // 2, n):
  1312. a, b, t, info = tpqrt(l, n, A, B)
  1313. assert info == 0
  1314. # Check that lower triangular part of A has not been modified
  1315. assert_equal(np.tril(a, -1), np.tril(A, -1))
  1316. # Check that elements not part of the pentagonal portion of B
  1317. # have not been modified.
  1318. assert_equal(np.tril(b, l - n - 1), np.tril(B, l - n - 1))
  1319. # Extract pentagonal portion of B
  1320. B_pent, b_pent = np.triu(B, l - n), np.triu(b, l - n)
  1321. # Generate elementary reflectors
  1322. v = np.concatenate((np.eye(n, dtype=dtype), b_pent))
  1323. # Generate the block Householder transform I - VTV^H
  1324. Q = np.eye(2 * n, dtype=dtype) - v @ t @ v.T.conj()
  1325. R = np.concatenate((np.triu(a), np.zeros_like(a)))
  1326. # Test columns of Q are orthogonal
  1327. assert_allclose(Q.T.conj() @ Q, np.eye(2 * n, dtype=dtype),
  1328. atol=tol, rtol=0.)
  1329. assert_allclose(Q @ R, np.concatenate((np.triu(A), B_pent)),
  1330. atol=tol, rtol=0.)
  1331. if ind > 1:
  1332. C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1333. D = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
  1334. transpose = 'C'
  1335. else:
  1336. C = (rng.rand(n, n)).astype(dtype)
  1337. D = (rng.rand(n, n)).astype(dtype)
  1338. transpose = 'T'
  1339. for side in ('L', 'R'):
  1340. for trans in ('N', transpose):
  1341. c, d, info = tpmqrt(l, b, t, C, D, side=side,
  1342. trans=trans)
  1343. assert info == 0
  1344. if trans == transpose:
  1345. q = Q.T.conj()
  1346. else:
  1347. q = Q
  1348. if side == 'L':
  1349. cd = np.concatenate((c, d), axis=0)
  1350. CD = np.concatenate((C, D), axis=0)
  1351. qCD = q @ CD
  1352. else:
  1353. cd = np.concatenate((c, d), axis=1)
  1354. CD = np.concatenate((C, D), axis=1)
  1355. qCD = CD @ q
  1356. assert_allclose(cd, qCD, atol=tol, rtol=0.)
  1357. if (side, trans) == ('L', 'N'):
  1358. c_default, d_default, info = tpmqrt(l, b, t, C, D)
  1359. assert info == 0
  1360. assert_equal(c_default, c)
  1361. assert_equal(d_default, d)
  1362. # Test invalid side/trans
  1363. assert_raises(Exception, tpmqrt, l, b, t, C, D, side='A')
  1364. assert_raises(Exception, tpmqrt, l, b, t, C, D, trans='A')
  1365. def test_pstrf():
  1366. rng = np.random.RandomState(1234)
  1367. for ind, dtype in enumerate(DTYPES):
  1368. # DTYPES = <s, d, c, z> pstrf
  1369. n = 10
  1370. r = 2
  1371. pstrf = get_lapack_funcs('pstrf', dtype=dtype)
  1372. # Create positive semidefinite A
  1373. if ind > 1:
  1374. A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype)
  1375. A = A @ A.conj().T
  1376. else:
  1377. A = rng.rand(n, n-r).astype(dtype)
  1378. A = A @ A.T
  1379. c, piv, r_c, info = pstrf(A)
  1380. U = triu(c)
  1381. U[r_c - n:, r_c - n:] = 0.
  1382. assert_equal(info, 1)
  1383. # python-dbg 3.5.2 runs cause trouble with the following assertion.
  1384. # assert_equal(r_c, n - r)
  1385. single_atol = 1000 * np.finfo(np.float32).eps
  1386. double_atol = 1000 * np.finfo(np.float64).eps
  1387. atol = single_atol if ind in [0, 2] else double_atol
  1388. assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol)
  1389. c, piv, r_c, info = pstrf(A, lower=1)
  1390. L = tril(c)
  1391. L[r_c - n:, r_c - n:] = 0.
  1392. assert_equal(info, 1)
  1393. # assert_equal(r_c, n - r)
  1394. single_atol = 1000 * np.finfo(np.float32).eps
  1395. double_atol = 1000 * np.finfo(np.float64).eps
  1396. atol = single_atol if ind in [0, 2] else double_atol
  1397. assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol)
  1398. def test_pstf2():
  1399. rng = np.random.RandomState(1234)
  1400. for ind, dtype in enumerate(DTYPES):
  1401. # DTYPES = <s, d, c, z> pstf2
  1402. n = 10
  1403. r = 2
  1404. pstf2 = get_lapack_funcs('pstf2', dtype=dtype)
  1405. # Create positive semidefinite A
  1406. if ind > 1:
  1407. A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype)
  1408. A = A @ A.conj().T
  1409. else:
  1410. A = rng.rand(n, n-r).astype(dtype)
  1411. A = A @ A.T
  1412. c, piv, r_c, info = pstf2(A)
  1413. U = triu(c)
  1414. U[r_c - n:, r_c - n:] = 0.
  1415. assert_equal(info, 1)
  1416. # python-dbg 3.5.2 runs cause trouble with the commented assertions.
  1417. # assert_equal(r_c, n - r)
  1418. single_atol = 1000 * np.finfo(np.float32).eps
  1419. double_atol = 1000 * np.finfo(np.float64).eps
  1420. atol = single_atol if ind in [0, 2] else double_atol
  1421. assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol)
  1422. c, piv, r_c, info = pstf2(A, lower=1)
  1423. L = tril(c)
  1424. L[r_c - n:, r_c - n:] = 0.
  1425. assert_equal(info, 1)
  1426. # assert_equal(r_c, n - r)
  1427. single_atol = 1000 * np.finfo(np.float32).eps
  1428. double_atol = 1000 * np.finfo(np.float64).eps
  1429. atol = single_atol if ind in [0, 2] else double_atol
  1430. assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol)
  1431. def test_geequ():
  1432. desired_real = np.array([[0.6250, 1.0000, 0.0393, -0.4269],
  1433. [1.0000, -0.5619, -1.0000, -1.0000],
  1434. [0.5874, -1.0000, -0.0596, -0.5341],
  1435. [-1.0000, -0.5946, -0.0294, 0.9957]])
  1436. desired_cplx = np.array([[-0.2816+0.5359*1j,
  1437. 0.0812+0.9188*1j,
  1438. -0.7439-0.2561*1j],
  1439. [-0.3562-0.2954*1j,
  1440. 0.9566-0.0434*1j,
  1441. -0.0174+0.1555*1j],
  1442. [0.8607+0.1393*1j,
  1443. -0.2759+0.7241*1j,
  1444. -0.1642-0.1365*1j]])
  1445. for ind, dtype in enumerate(DTYPES):
  1446. if ind < 2:
  1447. # Use examples from the NAG documentation
  1448. A = np.array([[1.80e+10, 2.88e+10, 2.05e+00, -8.90e+09],
  1449. [5.25e+00, -2.95e+00, -9.50e-09, -3.80e+00],
  1450. [1.58e+00, -2.69e+00, -2.90e-10, -1.04e+00],
  1451. [-1.11e+00, -6.60e-01, -5.90e-11, 8.00e-01]])
  1452. A = A.astype(dtype)
  1453. else:
  1454. A = np.array([[-1.34e+00, 0.28e+10, -6.39e+00],
  1455. [-1.70e+00, 3.31e+10, -0.15e+00],
  1456. [2.41e-10, -0.56e+00, -0.83e-10]], dtype=dtype)
  1457. A += np.array([[2.55e+00, 3.17e+10, -2.20e+00],
  1458. [-1.41e+00, -0.15e+10, 1.34e+00],
  1459. [0.39e-10, 1.47e+00, -0.69e-10]])*1j
  1460. A = A.astype(dtype)
  1461. geequ = get_lapack_funcs('geequ', dtype=dtype)
  1462. r, c, rowcnd, colcnd, amax, info = geequ(A)
  1463. if ind < 2:
  1464. assert_allclose(desired_real.astype(dtype), r[:, None]*A*c,
  1465. rtol=0, atol=1e-4)
  1466. else:
  1467. assert_allclose(desired_cplx.astype(dtype), r[:, None]*A*c,
  1468. rtol=0, atol=1e-4)
  1469. def test_syequb():
  1470. desired_log2s = np.array([0, 0, 0, 0, 0, 0, -1, -1, -2, -3])
  1471. for ind, dtype in enumerate(DTYPES):
  1472. A = np.eye(10, dtype=dtype)
  1473. alpha = dtype(1. if ind < 2 else 1.j)
  1474. d = np.array([alpha * 2.**x for x in range(-5, 5)], dtype=dtype)
  1475. A += np.rot90(np.diag(d))
  1476. syequb = get_lapack_funcs('syequb', dtype=dtype)
  1477. s, scond, amax, info = syequb(A)
  1478. assert_equal(np.log2(s).astype(int), desired_log2s)
  1479. @pytest.mark.skipif(True,
  1480. reason="Failing on some OpenBLAS version, see gh-12276")
  1481. def test_heequb():
  1482. # zheequb has a bug for versions =< LAPACK 3.9.0
  1483. # See Reference-LAPACK gh-61 and gh-408
  1484. # Hence the zheequb test is customized accordingly to avoid
  1485. # work scaling.
  1486. A = np.diag([2]*5 + [1002]*5) + np.diag(np.ones(9), k=1)*1j
  1487. s, scond, amax, info = lapack.zheequb(A)
  1488. assert_equal(info, 0)
  1489. assert_allclose(np.log2(s), [0., -1.]*2 + [0.] + [-4]*5)
  1490. A = np.diag(2**np.abs(np.arange(-5, 6)) + 0j)
  1491. A[5, 5] = 1024
  1492. A[5, 0] = 16j
  1493. s, scond, amax, info = lapack.cheequb(A.astype(np.complex64), lower=1)
  1494. assert_equal(info, 0)
  1495. assert_allclose(np.log2(s), [-2, -1, -1, 0, 0, -5, 0, -1, -1, -2, -2])
  1496. def test_getc2_gesc2():
  1497. rng = np.random.RandomState(42)
  1498. n = 10
  1499. desired_real = rng.rand(n)
  1500. desired_cplx = rng.rand(n) + rng.rand(n)*1j
  1501. for ind, dtype in enumerate(DTYPES):
  1502. if ind < 2:
  1503. A = rng.rand(n, n)
  1504. A = A.astype(dtype)
  1505. b = A @ desired_real
  1506. b = b.astype(dtype)
  1507. else:
  1508. A = rng.rand(n, n) + rng.rand(n, n)*1j
  1509. A = A.astype(dtype)
  1510. b = A @ desired_cplx
  1511. b = b.astype(dtype)
  1512. getc2 = get_lapack_funcs('getc2', dtype=dtype)
  1513. gesc2 = get_lapack_funcs('gesc2', dtype=dtype)
  1514. lu, ipiv, jpiv, info = getc2(A, overwrite_a=0)
  1515. x, scale = gesc2(lu, b, ipiv, jpiv, overwrite_rhs=0)
  1516. if ind < 2:
  1517. assert_array_almost_equal(desired_real.astype(dtype),
  1518. x/scale, decimal=4)
  1519. else:
  1520. assert_array_almost_equal(desired_cplx.astype(dtype),
  1521. x/scale, decimal=4)
  1522. @pytest.mark.parametrize('size', [(6, 5), (5, 5)])
  1523. @pytest.mark.parametrize('dtype', REAL_DTYPES)
  1524. @pytest.mark.parametrize('joba', range(6)) # 'C', 'E', 'F', 'G', 'A', 'R'
  1525. @pytest.mark.parametrize('jobu', range(4)) # 'U', 'F', 'W', 'N'
  1526. @pytest.mark.parametrize('jobv', range(4)) # 'V', 'J', 'W', 'N'
  1527. @pytest.mark.parametrize('jobr', [0, 1])
  1528. @pytest.mark.parametrize('jobp', [0, 1])
  1529. def test_gejsv_general(size, dtype, joba, jobu, jobv, jobr, jobp, jobt=0):
  1530. """Test the lapack routine ?gejsv.
  1531. This function tests that a singular value decomposition can be performed
  1532. on the random M-by-N matrix A. The test performs the SVD using ?gejsv
  1533. then performs the following checks:
  1534. * ?gejsv exist successfully (info == 0)
  1535. * The returned singular values are correct
  1536. * `A` can be reconstructed from `u`, `SIGMA`, `v`
  1537. * Ensure that u.T @ u is the identity matrix
  1538. * Ensure that v.T @ v is the identity matrix
  1539. * The reported matrix rank
  1540. * The reported number of singular values
  1541. * If denormalized floats are required
  1542. Notes
  1543. -----
  1544. joba specifies several choices effecting the calculation's accuracy
  1545. Although all arguments are tested, the tests only check that the correct
  1546. solution is returned - NOT that the prescribed actions are performed
  1547. internally.
  1548. jobt is, as of v3.9.0, still experimental and removed to cut down number of
  1549. test cases. However keyword itself is tested externally.
  1550. """
  1551. rng = np.random.RandomState(42)
  1552. # Define some constants for later use:
  1553. m, n = size
  1554. atol = 100 * np.finfo(dtype).eps
  1555. A = generate_random_dtype_array(size, dtype, rng)
  1556. gejsv = get_lapack_funcs('gejsv', dtype=dtype)
  1557. # Set up checks for invalid job? combinations
  1558. # if an invalid combination occurs we set the appropriate
  1559. # exit status.
  1560. lsvec = jobu < 2 # Calculate left singular vectors
  1561. rsvec = jobv < 2 # Calculate right singular vectors
  1562. l2tran = (jobt == 1) and (m == n)
  1563. is_complex = np.iscomplexobj(A)
  1564. invalid_real_jobv = (jobv == 1) and (not lsvec) and (not is_complex)
  1565. invalid_cplx_jobu = (jobu == 2) and not (rsvec and l2tran) and is_complex
  1566. invalid_cplx_jobv = (jobv == 2) and not (lsvec and l2tran) and is_complex
  1567. # Set the exit status to the expected value.
  1568. # Here we only check for invalid combinations, not individual
  1569. # parameters.
  1570. if invalid_cplx_jobu:
  1571. exit_status = -2
  1572. elif invalid_real_jobv or invalid_cplx_jobv:
  1573. exit_status = -3
  1574. else:
  1575. exit_status = 0
  1576. if (jobu > 1) and (jobv == 1):
  1577. assert_raises(Exception, gejsv, A, joba, jobu, jobv, jobr, jobt, jobp)
  1578. else:
  1579. sva, u, v, work, iwork, info = gejsv(A,
  1580. joba=joba,
  1581. jobu=jobu,
  1582. jobv=jobv,
  1583. jobr=jobr,
  1584. jobt=jobt,
  1585. jobp=jobp)
  1586. # Check that ?gejsv exited successfully/as expected
  1587. assert_equal(info, exit_status)
  1588. # If exit_status is non-zero the combination of jobs is invalid.
  1589. # We test this above but no calculations are performed.
  1590. if not exit_status:
  1591. # Check the returned singular values
  1592. sigma = (work[0] / work[1]) * sva[:n]
  1593. assert_allclose(sigma, svd(A, compute_uv=False), atol=atol)
  1594. if jobu == 1:
  1595. # If JOBU = 'F', then u contains the M-by-M matrix of
  1596. # the left singular vectors, including an ONB of the orthogonal
  1597. # complement of the Range(A)
  1598. # However, to recalculate A we are concerned about the
  1599. # first n singular values and so can ignore the latter.
  1600. # TODO: Add a test for ONB?
  1601. u = u[:, :n]
  1602. if lsvec and rsvec:
  1603. assert_allclose(u @ np.diag(sigma) @ v.conj().T, A, atol=atol)
  1604. if lsvec:
  1605. assert_allclose(u.conj().T @ u, np.identity(n), atol=atol)
  1606. if rsvec:
  1607. assert_allclose(v.conj().T @ v, np.identity(n), atol=atol)
  1608. assert_equal(iwork[0], np.linalg.matrix_rank(A))
  1609. assert_equal(iwork[1], np.count_nonzero(sigma))
  1610. # iwork[2] is non-zero if requested accuracy is not warranted for
  1611. # the data. This should never occur for these tests.
  1612. assert_equal(iwork[2], 0)
  1613. @pytest.mark.parametrize('dtype', REAL_DTYPES)
  1614. def test_gejsv_edge_arguments(dtype):
  1615. """Test edge arguments return expected status"""
  1616. gejsv = get_lapack_funcs('gejsv', dtype=dtype)
  1617. # scalar A
  1618. sva, u, v, work, iwork, info = gejsv(1.)
  1619. assert_equal(info, 0)
  1620. assert_equal(u.shape, (1, 1))
  1621. assert_equal(v.shape, (1, 1))
  1622. assert_equal(sva, np.array([1.], dtype=dtype))
  1623. # 1d A
  1624. A = np.ones((1,), dtype=dtype)
  1625. sva, u, v, work, iwork, info = gejsv(A)
  1626. assert_equal(info, 0)
  1627. assert_equal(u.shape, (1, 1))
  1628. assert_equal(v.shape, (1, 1))
  1629. assert_equal(sva, np.array([1.], dtype=dtype))
  1630. # 2d empty A
  1631. A = np.ones((1, 0), dtype=dtype)
  1632. sva, u, v, work, iwork, info = gejsv(A)
  1633. assert_equal(info, 0)
  1634. assert_equal(u.shape, (1, 0))
  1635. assert_equal(v.shape, (1, 0))
  1636. assert_equal(sva, np.array([], dtype=dtype))
  1637. # make sure "overwrite_a" is respected - user reported in gh-13191
  1638. A = np.sin(np.arange(100).reshape(10, 10)).astype(dtype)
  1639. A = np.asfortranarray(A + A.T) # make it symmetric and column major
  1640. Ac = A.copy('A')
  1641. _ = gejsv(A)
  1642. assert_allclose(A, Ac)
  1643. @pytest.mark.parametrize(('kwargs'),
  1644. ({'joba': 9},
  1645. {'jobu': 9},
  1646. {'jobv': 9},
  1647. {'jobr': 9},
  1648. {'jobt': 9},
  1649. {'jobp': 9})
  1650. )
  1651. def test_gejsv_invalid_job_arguments(kwargs):
  1652. """Test invalid job arguments raise an Exception"""
  1653. A = np.ones((2, 2), dtype=float)
  1654. gejsv = get_lapack_funcs('gejsv', dtype=float)
  1655. assert_raises(Exception, gejsv, A, **kwargs)
  1656. @pytest.mark.parametrize("A,sva_expect,u_expect,v_expect",
  1657. [(np.array([[2.27, -1.54, 1.15, -1.94],
  1658. [0.28, -1.67, 0.94, -0.78],
  1659. [-0.48, -3.09, 0.99, -0.21],
  1660. [1.07, 1.22, 0.79, 0.63],
  1661. [-2.35, 2.93, -1.45, 2.30],
  1662. [0.62, -7.39, 1.03, -2.57]]),
  1663. np.array([9.9966, 3.6831, 1.3569, 0.5000]),
  1664. np.array([[0.2774, -0.6003, -0.1277, 0.1323],
  1665. [0.2020, -0.0301, 0.2805, 0.7034],
  1666. [0.2918, 0.3348, 0.6453, 0.1906],
  1667. [-0.0938, -0.3699, 0.6781, -0.5399],
  1668. [-0.4213, 0.5266, 0.0413, -0.0575],
  1669. [0.7816, 0.3353, -0.1645, -0.3957]]),
  1670. np.array([[0.1921, -0.8030, 0.0041, -0.5642],
  1671. [-0.8794, -0.3926, -0.0752, 0.2587],
  1672. [0.2140, -0.2980, 0.7827, 0.5027],
  1673. [-0.3795, 0.3351, 0.6178, -0.6017]]))])
  1674. def test_gejsv_NAG(A, sva_expect, u_expect, v_expect):
  1675. """
  1676. This test implements the example found in the NAG manual, f08khf.
  1677. An example was not found for the complex case.
  1678. """
  1679. # NAG manual provides accuracy up to 4 decimals
  1680. atol = 1e-4
  1681. gejsv = get_lapack_funcs('gejsv', dtype=A.dtype)
  1682. sva, u, v, work, iwork, info = gejsv(A)
  1683. assert_allclose(sva_expect, sva, atol=atol)
  1684. assert_allclose(u_expect, u, atol=atol)
  1685. assert_allclose(v_expect, v, atol=atol)
  1686. @pytest.mark.parametrize("dtype", DTYPES)
  1687. def test_gttrf_gttrs(dtype):
  1688. # The test uses ?gttrf and ?gttrs to solve a random system for each dtype,
  1689. # tests that the output of ?gttrf define LU matrices, that input
  1690. # parameters are unmodified, transposal options function correctly, that
  1691. # incompatible matrix shapes raise an error, and singular matrices return
  1692. # non zero info.
  1693. rng = np.random.RandomState(42)
  1694. n = 10
  1695. atol = 100 * np.finfo(dtype).eps
  1696. # create the matrix in accordance with the data type
  1697. du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
  1698. d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
  1699. dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
  1700. diag_cpy = [dl.copy(), d.copy(), du.copy()]
  1701. A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1)
  1702. x = rng.random(n)
  1703. b = A @ x
  1704. gttrf, gttrs = get_lapack_funcs(('gttrf', 'gttrs'), dtype=dtype)
  1705. _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du)
  1706. # test to assure that the inputs of ?gttrf are unmodified
  1707. assert_array_equal(dl, diag_cpy[0])
  1708. assert_array_equal(d, diag_cpy[1])
  1709. assert_array_equal(du, diag_cpy[2])
  1710. # generate L and U factors from ?gttrf return values
  1711. # L/U are lower/upper triangular by construction (initially and at end)
  1712. U = np.diag(_d, 0) + np.diag(_du, 1) + np.diag(du2, 2)
  1713. L = np.eye(n, dtype=dtype)
  1714. for i, m in enumerate(_dl):
  1715. # L is given in a factored form.
  1716. # See
  1717. # www.hpcavf.uclan.ac.uk/softwaredoc/sgi_scsl_html/sgi_html/ch03.html
  1718. piv = ipiv[i] - 1
  1719. # right multiply by permutation matrix
  1720. L[:, [i, piv]] = L[:, [piv, i]]
  1721. # right multiply by Li, rank-one modification of identity
  1722. L[:, i] += L[:, i+1]*m
  1723. # one last permutation
  1724. i, piv = -1, ipiv[-1] - 1
  1725. # right multiply by final permutation matrix
  1726. L[:, [i, piv]] = L[:, [piv, i]]
  1727. # check that the outputs of ?gttrf define an LU decomposition of A
  1728. assert_allclose(A, L @ U, atol=atol)
  1729. b_cpy = b.copy()
  1730. x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b)
  1731. # test that the inputs of ?gttrs are unmodified
  1732. assert_array_equal(b, b_cpy)
  1733. # test that the result of ?gttrs matches the expected input
  1734. assert_allclose(x, x_gttrs, atol=atol)
  1735. # test that ?gttrf and ?gttrs work with transposal options
  1736. if dtype in REAL_DTYPES:
  1737. trans = "T"
  1738. b_trans = A.T @ x
  1739. else:
  1740. trans = "C"
  1741. b_trans = A.conj().T @ x
  1742. x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b_trans, trans=trans)
  1743. assert_allclose(x, x_gttrs, atol=atol)
  1744. # test that ValueError is raised with incompatible matrix shapes
  1745. with assert_raises(ValueError):
  1746. gttrf(dl[:-1], d, du)
  1747. with assert_raises(ValueError):
  1748. gttrf(dl, d[:-1], du)
  1749. with assert_raises(ValueError):
  1750. gttrf(dl, d, du[:-1])
  1751. # test that matrix of size n=2 raises exception
  1752. with assert_raises(ValueError):
  1753. gttrf(dl[0], d[:1], du[0])
  1754. # test that singular (row of all zeroes) matrix fails via info
  1755. du[0] = 0
  1756. d[0] = 0
  1757. __dl, __d, __du, _du2, _ipiv, _info = gttrf(dl, d, du)
  1758. np.testing.assert_(__d[info - 1] == 0, (f"?gttrf: _d[info-1] is {__d[info - 1]},"
  1759. " not the illegal value :0."))
  1760. @pytest.mark.parametrize("du, d, dl, du_exp, d_exp, du2_exp, ipiv_exp, b, x",
  1761. [(np.array([2.1, -1.0, 1.9, 8.0]),
  1762. np.array([3.0, 2.3, -5.0, -.9, 7.1]),
  1763. np.array([3.4, 3.6, 7.0, -6.0]),
  1764. np.array([2.3, -5, -.9, 7.1]),
  1765. np.array([3.4, 3.6, 7, -6, -1.015373]),
  1766. np.array([-1, 1.9, 8]),
  1767. np.array([2, 3, 4, 5, 5]),
  1768. np.array([[2.7, 6.6],
  1769. [-0.5, 10.8],
  1770. [2.6, -3.2],
  1771. [0.6, -11.2],
  1772. [2.7, 19.1]
  1773. ]),
  1774. np.array([[-4, 5],
  1775. [7, -4],
  1776. [3, -3],
  1777. [-4, -2],
  1778. [-3, 1]])),
  1779. (
  1780. np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]),
  1781. np.array([-1.3 + 1.3j, -1.3 + 1.3j,
  1782. -1.3 + 3.3j, - .3 + 4.3j,
  1783. -3.3 + 1.3j]),
  1784. np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]),
  1785. # du exp
  1786. np.array([-1.3 + 1.3j, -1.3 + 3.3j,
  1787. -0.3 + 4.3j, -3.3 + 1.3j]),
  1788. np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j,
  1789. -1.3399 + 0.2875j]),
  1790. np.array([2 + 1j, -1 + 1j, 1 - 1j]),
  1791. np.array([2, 3, 4, 5, 5]),
  1792. np.array([[2.4 - 5j, 2.7 + 6.9j],
  1793. [3.4 + 18.2j, - 6.9 - 5.3j],
  1794. [-14.7 + 9.7j, - 6 - .6j],
  1795. [31.9 - 7.7j, -3.9 + 9.3j],
  1796. [-1 + 1.6j, -3 + 12.2j]]),
  1797. np.array([[1 + 1j, 2 - 1j],
  1798. [3 - 1j, 1 + 2j],
  1799. [4 + 5j, -1 + 1j],
  1800. [-1 - 2j, 2 + 1j],
  1801. [1 - 1j, 2 - 2j]])
  1802. )])
  1803. def test_gttrf_gttrs_NAG_f07cdf_f07cef_f07crf_f07csf(du, d, dl, du_exp, d_exp,
  1804. du2_exp, ipiv_exp, b, x):
  1805. # test to assure that wrapper is consistent with NAG Library Manual Mark 26
  1806. # example problems: f07cdf and f07cef (real)
  1807. # examples: f07crf and f07csf (complex)
  1808. # (Links may expire, so search for "NAG Library Manual Mark 26" online)
  1809. gttrf, gttrs = get_lapack_funcs(('gttrf', "gttrs"), (du[0], du[0]))
  1810. _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du)
  1811. assert_allclose(du2, du2_exp)
  1812. assert_allclose(_du, du_exp)
  1813. assert_allclose(_d, d_exp, atol=1e-4) # NAG examples provide 4 decimals.
  1814. assert_allclose(ipiv, ipiv_exp)
  1815. x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b)
  1816. assert_allclose(x_gttrs, x)
  1817. @pytest.mark.parametrize('dtype', DTYPES)
  1818. @pytest.mark.parametrize('norm', ['1', 'I', 'O'])
  1819. @pytest.mark.parametrize('n', [3, 10])
  1820. def test_gtcon(dtype, norm, n):
  1821. rng = np.random.default_rng(23498324)
  1822. d = rng.random(n) + rng.random(n)*1j
  1823. dl = rng.random(n - 1) + rng.random(n - 1)*1j
  1824. du = rng.random(n - 1) + rng.random(n - 1)*1j
  1825. A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1)
  1826. if np.issubdtype(dtype, np.floating):
  1827. A, d, dl, du = A.real, d.real, dl.real, du.real
  1828. A, d, dl, du = A.astype(dtype), d.astype(dtype), dl.astype(dtype), du.astype(dtype)
  1829. anorm = np.linalg.norm(A, ord=np.inf if norm == 'I' else 1)
  1830. gttrf, gtcon = get_lapack_funcs(('gttrf', 'gtcon'), (A,))
  1831. dl, d, du, du2, ipiv, info = gttrf(dl, d, du)
  1832. res, _ = gtcon(dl, d, du, du2, ipiv, anorm, norm=norm)
  1833. gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,))
  1834. lu, ipvt, info = getrf(A)
  1835. ref, _ = gecon(lu, anorm, norm=norm)
  1836. rtol = np.finfo(dtype).eps**0.75
  1837. assert_allclose(res, ref, rtol=rtol)
  1838. @pytest.mark.parametrize('dtype', DTYPES)
  1839. @pytest.mark.parametrize('shape', [(3, 7), (7, 3), (2**18, 2**18)])
  1840. def test_geqrfp_lwork(dtype, shape):
  1841. geqrfp_lwork = get_lapack_funcs(('geqrfp_lwork'), dtype=dtype)
  1842. m, n = shape
  1843. lwork, info = geqrfp_lwork(m=m, n=n)
  1844. assert_equal(info, 0)
  1845. @pytest.mark.parametrize("ddtype,dtype",
  1846. zip(REAL_DTYPES + REAL_DTYPES, DTYPES))
  1847. def test_pttrf_pttrs(ddtype, dtype):
  1848. rng = np.random.RandomState(42)
  1849. # set test tolerance appropriate for dtype
  1850. atol = 100*np.finfo(dtype).eps
  1851. # n is the length diagonal of A
  1852. n = 10
  1853. # create diagonals according to size and dtype
  1854. # diagonal d should always be real.
  1855. # add 4 to d so it will be dominant for all dtypes
  1856. d = generate_random_dtype_array((n,), ddtype, rng) + 4
  1857. # diagonal e may be real or complex.
  1858. e = generate_random_dtype_array((n-1,), dtype, rng)
  1859. # assemble diagonals together into matrix
  1860. A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
  1861. # store a copy of diagonals to later verify
  1862. diag_cpy = [d.copy(), e.copy()]
  1863. pttrf = get_lapack_funcs('pttrf', dtype=dtype)
  1864. _d, _e, info = pttrf(d, e)
  1865. # test to assure that the inputs of ?pttrf are unmodified
  1866. assert_array_equal(d, diag_cpy[0])
  1867. assert_array_equal(e, diag_cpy[1])
  1868. assert_equal(info, 0, err_msg=f"pttrf: info = {info}, should be 0")
  1869. # test that the factors from pttrf can be recombined to make A
  1870. L = np.diag(_e, -1) + np.diag(np.ones(n))
  1871. D = np.diag(_d)
  1872. assert_allclose(A, L@D@L.conjugate().T, atol=atol)
  1873. # generate random solution x
  1874. x = generate_random_dtype_array((n,), dtype, rng)
  1875. # determine accompanying b to get soln x
  1876. b = A@x
  1877. # determine _x from pttrs
  1878. pttrs = get_lapack_funcs('pttrs', dtype=dtype)
  1879. _x, info = pttrs(_d, _e.conj(), b)
  1880. assert_equal(info, 0, err_msg=f"pttrs: info = {info}, should be 0")
  1881. # test that _x from pttrs matches the expected x
  1882. assert_allclose(x, _x, atol=atol)
  1883. @pytest.mark.parametrize("ddtype,dtype",
  1884. zip(REAL_DTYPES + REAL_DTYPES, DTYPES))
  1885. def test_pttrf_pttrs_errors_incompatible_shape(ddtype, dtype):
  1886. n = 10
  1887. rng = np.random.RandomState(1234)
  1888. pttrf = get_lapack_funcs('pttrf', dtype=dtype)
  1889. d = generate_random_dtype_array((n,), ddtype, rng) + 2
  1890. e = generate_random_dtype_array((n-1,), dtype, rng)
  1891. # test that ValueError is raised with incompatible matrix shapes
  1892. assert_raises(ValueError, pttrf, d[:-1], e)
  1893. assert_raises(ValueError, pttrf, d, e[:-1])
  1894. @pytest.mark.parametrize("ddtype,dtype",
  1895. zip(REAL_DTYPES + REAL_DTYPES, DTYPES))
  1896. def test_pttrf_pttrs_errors_singular_nonSPD(ddtype, dtype):
  1897. n = 10
  1898. rng = np.random.RandomState(42)
  1899. pttrf = get_lapack_funcs('pttrf', dtype=dtype)
  1900. d = generate_random_dtype_array((n,), ddtype, rng) + 2
  1901. e = generate_random_dtype_array((n-1,), dtype, rng)
  1902. # test that singular (row of all zeroes) matrix fails via info
  1903. d[0] = 0
  1904. e[0] = 0
  1905. _d, _e, info = pttrf(d, e)
  1906. assert_equal(_d[info - 1], 0,
  1907. f"?pttrf: _d[info-1] is {_d[info - 1]}, not the illegal value :0.")
  1908. # test with non-spd matrix
  1909. d = generate_random_dtype_array((n,), ddtype, rng)
  1910. _d, _e, info = pttrf(d, e)
  1911. assert_(info != 0, "?pttrf should fail with non-spd matrix, but didn't")
  1912. @pytest.mark.parametrize(("d, e, d_expect, e_expect, b, x_expect"), [
  1913. (np.array([4, 10, 29, 25, 5]),
  1914. np.array([-2, -6, 15, 8]),
  1915. np.array([4, 9, 25, 16, 1]),
  1916. np.array([-.5, -.6667, .6, .5]),
  1917. np.array([[6, 10], [9, 4], [2, 9], [14, 65],
  1918. [7, 23]]),
  1919. np.array([[2.5, 2], [2, -1], [1, -3], [-1, 6],
  1920. [3, -5]])
  1921. ), (
  1922. np.array([16, 41, 46, 21]),
  1923. np.array([16 + 16j, 18 - 9j, 1 - 4j]),
  1924. np.array([16, 9, 1, 4]),
  1925. np.array([1+1j, 2-1j, 1-4j]),
  1926. np.array([[64+16j, -16-32j], [93+62j, 61-66j],
  1927. [78-80j, 71-74j], [14-27j, 35+15j]]),
  1928. np.array([[2+1j, -3-2j], [1+1j, 1+1j], [1-2j, 1-2j],
  1929. [1-1j, 2+1j]])
  1930. )])
  1931. def test_pttrf_pttrs_NAG(d, e, d_expect, e_expect, b, x_expect):
  1932. # test to assure that wrapper is consistent with NAG Manual Mark 26
  1933. # example problems: f07jdf and f07jef (real)
  1934. # examples: f07jrf and f07csf (complex)
  1935. # NAG examples provide 4 decimals.
  1936. # (Links expire, so please search for "NAG Library Manual Mark 26" online)
  1937. atol = 1e-4
  1938. pttrf = get_lapack_funcs('pttrf', dtype=e[0])
  1939. _d, _e, info = pttrf(d, e)
  1940. assert_allclose(_d, d_expect, atol=atol)
  1941. assert_allclose(_e, e_expect, atol=atol)
  1942. pttrs = get_lapack_funcs('pttrs', dtype=e[0])
  1943. _x, info = pttrs(_d, _e.conj(), b)
  1944. assert_allclose(_x, x_expect, atol=atol)
  1945. # also test option `lower`
  1946. if e.dtype in COMPLEX_DTYPES:
  1947. _x, info = pttrs(_d, _e, b, lower=1)
  1948. assert_allclose(_x, x_expect, atol=atol)
  1949. def pteqr_get_d_e_A_z(dtype, realtype, n, compute_z):
  1950. # used by ?pteqr tests to build parameters
  1951. # returns tuple of (d, e, A, z)
  1952. rng = np.random.RandomState(42)
  1953. if compute_z == 1:
  1954. # build Hermitian A from Q**T * tri * Q = A by creating Q and tri
  1955. A_eig = generate_random_dtype_array((n, n), dtype, rng)
  1956. A_eig = A_eig + np.diag(np.zeros(n) + 4*n)
  1957. A_eig = (A_eig + A_eig.conj().T) / 2
  1958. # obtain right eigenvectors (orthogonal)
  1959. vr = eigh(A_eig)[1]
  1960. # create tridiagonal matrix
  1961. d = generate_random_dtype_array((n,), realtype, rng) + 4
  1962. e = generate_random_dtype_array((n-1,), realtype, rng)
  1963. tri = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
  1964. # Build A using these factors that sytrd would: (Q**T * tri * Q = A)
  1965. A = vr @ tri @ vr.conj().T
  1966. # vr is orthogonal
  1967. z = vr
  1968. else:
  1969. # d and e are always real per lapack docs.
  1970. d = generate_random_dtype_array((n,), realtype, rng)
  1971. e = generate_random_dtype_array((n-1,), realtype, rng)
  1972. # make SPD
  1973. d = d + 4
  1974. A = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
  1975. z = np.diag(d) + np.diag(e, -1) + np.diag(e, 1)
  1976. return (d, e, A, z)
  1977. @pytest.mark.parametrize("dtype,realtype",
  1978. zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
  1979. @pytest.mark.parametrize("compute_z", range(3))
  1980. def test_pteqr(dtype, realtype, compute_z):
  1981. '''
  1982. Tests the ?pteqr lapack routine for all dtypes and compute_z parameters.
  1983. It generates random SPD matrix diagonals d and e, and then confirms
  1984. correct eigenvalues with scipy.linalg.eig. With applicable compute_z=2 it
  1985. tests that z can reform A.
  1986. '''
  1987. atol = 1000*np.finfo(dtype).eps
  1988. pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
  1989. n = 10
  1990. d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
  1991. d_pteqr, e_pteqr, z_pteqr, info = pteqr(d=d, e=e, z=z, compute_z=compute_z)
  1992. assert_equal(info, 0, f"info = {info}, should be 0.")
  1993. # compare the routine's eigenvalues with scipy.linalg.eig's.
  1994. assert_allclose(np.sort(eigh(A)[0]), np.sort(d_pteqr), atol=atol)
  1995. if compute_z:
  1996. # verify z_pteqr as orthogonal
  1997. assert_allclose(z_pteqr @ np.conj(z_pteqr).T, np.identity(n),
  1998. atol=atol)
  1999. # verify that z_pteqr recombines to A
  2000. assert_allclose(z_pteqr @ np.diag(d_pteqr) @ np.conj(z_pteqr).T,
  2001. A, atol=atol)
  2002. @pytest.mark.parametrize("dtype,realtype",
  2003. zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
  2004. @pytest.mark.parametrize("compute_z", range(3))
  2005. def test_pteqr_error_non_spd(dtype, realtype, compute_z):
  2006. pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
  2007. n = 10
  2008. d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
  2009. # test with non-spd matrix
  2010. d_pteqr, e_pteqr, z_pteqr, info = pteqr(d - 4, e, z=z, compute_z=compute_z)
  2011. assert info > 0
  2012. @pytest.mark.parametrize("dtype,realtype",
  2013. zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
  2014. @pytest.mark.parametrize("compute_z", range(3))
  2015. def test_pteqr_raise_error_wrong_shape(dtype, realtype, compute_z):
  2016. pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
  2017. n = 10
  2018. d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
  2019. # test with incorrect/incompatible array sizes
  2020. assert_raises(ValueError, pteqr, d[:-1], e, z=z, compute_z=compute_z)
  2021. assert_raises(ValueError, pteqr, d, e[:-1], z=z, compute_z=compute_z)
  2022. if compute_z:
  2023. assert_raises(ValueError, pteqr, d, e, z=z[:-1], compute_z=compute_z)
  2024. @pytest.mark.parametrize("dtype,realtype",
  2025. zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
  2026. @pytest.mark.parametrize("compute_z", range(3))
  2027. def test_pteqr_error_singular(dtype, realtype, compute_z):
  2028. pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
  2029. n = 10
  2030. d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
  2031. # test with singular matrix
  2032. d[0] = 0
  2033. e[0] = 0
  2034. d_pteqr, e_pteqr, z_pteqr, info = pteqr(d, e, z=z, compute_z=compute_z)
  2035. assert info > 0
  2036. @pytest.mark.parametrize("compute_z,d,e,d_expect,z_expect",
  2037. [(2, # "I"
  2038. np.array([4.16, 5.25, 1.09, .62]),
  2039. np.array([3.17, -.97, .55]),
  2040. np.array([8.0023, 1.9926, 1.0014, 0.1237]),
  2041. np.array([[0.6326, 0.6245, -0.4191, 0.1847],
  2042. [0.7668, -0.4270, 0.4176, -0.2352],
  2043. [-0.1082, 0.6071, 0.4594, -0.6393],
  2044. [-0.0081, 0.2432, 0.6625, 0.7084]])),
  2045. ])
  2046. def test_pteqr_NAG_f08jgf(compute_z, d, e, d_expect, z_expect):
  2047. '''
  2048. Implements real (f08jgf) example from NAG Manual Mark 26.
  2049. Tests for correct outputs.
  2050. '''
  2051. # the NAG manual has 4 decimals accuracy
  2052. atol = 1e-4
  2053. pteqr = get_lapack_funcs(('pteqr'), dtype=d.dtype)
  2054. z = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
  2055. _d, _e, _z, info = pteqr(d=d, e=e, z=z, compute_z=compute_z)
  2056. assert_allclose(_d, d_expect, atol=atol)
  2057. assert_allclose(np.abs(_z), np.abs(z_expect), atol=atol)
  2058. @pytest.mark.parametrize('dtype', DTYPES)
  2059. @pytest.mark.parametrize('matrix_size', [(3, 4), (7, 6), (6, 6)])
  2060. def test_geqrfp(dtype, matrix_size):
  2061. # Tests for all dytpes, tall, wide, and square matrices.
  2062. # Using the routine with random matrix A, Q and R are obtained and then
  2063. # tested such that R is upper triangular and non-negative on the diagonal,
  2064. # and Q is an orthogonal matrix. Verifies that A=Q@R. It also
  2065. # tests against a matrix that for which the linalg.qr method returns
  2066. # negative diagonals, and for error messaging.
  2067. # set test tolerance appropriate for dtype
  2068. rng = np.random.RandomState(42)
  2069. rtol = 250*np.finfo(dtype).eps
  2070. atol = 100*np.finfo(dtype).eps
  2071. # get appropriate ?geqrfp for dtype
  2072. geqrfp = get_lapack_funcs(('geqrfp'), dtype=dtype)
  2073. gqr = get_lapack_funcs(("orgqr"), dtype=dtype)
  2074. m, n = matrix_size
  2075. # create random matrix of dimensions m x n
  2076. A = generate_random_dtype_array((m, n), dtype=dtype, rng=rng)
  2077. # create qr matrix using geqrfp
  2078. qr_A, tau, info = geqrfp(A)
  2079. # obtain r from the upper triangular area
  2080. r = np.triu(qr_A)
  2081. # obtain q from the orgqr lapack routine
  2082. # based on linalg.qr's extraction strategy of q with orgqr
  2083. if m > n:
  2084. # this adds an extra column to the end of qr_A
  2085. # let qqr be an empty m x m matrix
  2086. qqr = np.zeros((m, m), dtype=dtype)
  2087. # set first n columns of qqr to qr_A
  2088. qqr[:, :n] = qr_A
  2089. # determine q from this qqr
  2090. # note that m is a sufficient for lwork based on LAPACK documentation
  2091. q = gqr(qqr, tau=tau, lwork=m)[0]
  2092. else:
  2093. q = gqr(qr_A[:, :m], tau=tau, lwork=m)[0]
  2094. # test that q and r still make A
  2095. assert_allclose(q@r, A, rtol=rtol)
  2096. # ensure that q is orthogonal (that q @ transposed q is the identity)
  2097. assert_allclose(np.eye(q.shape[0]), q@(q.conj().T), rtol=rtol,
  2098. atol=atol)
  2099. # ensure r is upper tri by comparing original r to r as upper triangular
  2100. assert_allclose(r, np.triu(r), rtol=rtol)
  2101. # make sure diagonals of r are positive for this random solution
  2102. assert_(np.all(np.diag(r) > np.zeros(len(np.diag(r)))))
  2103. # ensure that info is zero for this success
  2104. assert_(info == 0)
  2105. # test that this routine gives r diagonals that are positive for a
  2106. # matrix that returns negatives in the diagonal with scipy.linalg.rq
  2107. A_negative = generate_random_dtype_array((n, m), dtype=dtype, rng=rng) * -1
  2108. r_rq_neg, q_rq_neg = qr(A_negative)
  2109. rq_A_neg, tau_neg, info_neg = geqrfp(A_negative)
  2110. # assert that any of the entries on the diagonal from linalg.qr
  2111. # are negative and that all of geqrfp are positive.
  2112. assert_(np.any(np.diag(r_rq_neg) < 0) and
  2113. np.all(np.diag(r) > 0))
  2114. def test_geqrfp_errors_with_empty_array():
  2115. # check that empty array raises good error message
  2116. A_empty = np.array([])
  2117. geqrfp = get_lapack_funcs('geqrfp', dtype=A_empty.dtype)
  2118. assert_raises(Exception, geqrfp, A_empty)
  2119. @pytest.mark.parametrize("driver", ['ev', 'evd', 'evr', 'evx'])
  2120. @pytest.mark.parametrize("pfx", ['sy', 'he'])
  2121. def test_standard_eigh_lworks(pfx, driver):
  2122. n = 1200 # Some sufficiently big arbitrary number
  2123. dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES
  2124. sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0])
  2125. dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1])
  2126. try:
  2127. _compute_lwork(sc_dlw, n, lower=1)
  2128. _compute_lwork(dz_dlw, n, lower=1)
  2129. except Exception as e:
  2130. pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}")
  2131. @pytest.mark.parametrize("driver", ['gv', 'gvx'])
  2132. @pytest.mark.parametrize("pfx", ['sy', 'he'])
  2133. def test_generalized_eigh_lworks(pfx, driver):
  2134. n = 1200 # Some sufficiently big arbitrary number
  2135. dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES
  2136. sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0])
  2137. dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1])
  2138. # Shouldn't raise any exceptions
  2139. try:
  2140. _compute_lwork(sc_dlw, n, uplo="L")
  2141. _compute_lwork(dz_dlw, n, uplo="L")
  2142. except Exception as e:
  2143. pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}")
  2144. @pytest.mark.parametrize("dtype_", DTYPES)
  2145. @pytest.mark.parametrize("m", [1, 10, 100, 1000])
  2146. def test_orcsd_uncsd_lwork(dtype_, m):
  2147. rng = np.random.default_rng(1234)
  2148. p = rng.integers(0, m)
  2149. q = m - p
  2150. pfx = 'or' if dtype_ in REAL_DTYPES else 'un'
  2151. dlw = pfx + 'csd_lwork'
  2152. lw = get_lapack_funcs(dlw, dtype=dtype_)
  2153. lwval = _compute_lwork(lw, m, p, q)
  2154. lwval = lwval if pfx == 'un' else (lwval,)
  2155. assert all([x > 0 for x in lwval])
  2156. @pytest.mark.parametrize("dtype_", DTYPES)
  2157. def test_orcsd_uncsd(dtype_):
  2158. m, p, q = 250, 80, 170
  2159. pfx = 'or' if dtype_ in REAL_DTYPES else 'un'
  2160. X = ortho_group.rvs(m) if pfx == 'or' else unitary_group.rvs(m)
  2161. drv, dlw = get_lapack_funcs((pfx + 'csd', pfx + 'csd_lwork'), dtype=dtype_)
  2162. lwval = _compute_lwork(dlw, m, p, q)
  2163. lwvals = {'lwork': lwval} if pfx == 'or' else dict(zip(['lwork',
  2164. 'lrwork'], lwval))
  2165. cs11, cs12, cs21, cs22, theta, u1, u2, v1t, v2t, info =\
  2166. drv(X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:], **lwvals)
  2167. assert info == 0
  2168. U = block_diag(u1, u2)
  2169. VH = block_diag(v1t, v2t)
  2170. r = min(min(p, q), min(m-p, m-q))
  2171. n11 = min(p, q) - r
  2172. n12 = min(p, m-q) - r
  2173. n21 = min(m-p, q) - r
  2174. n22 = min(m-p, m-q) - r
  2175. S = np.zeros((m, m), dtype=dtype_)
  2176. one = dtype_(1.)
  2177. for i in range(n11):
  2178. S[i, i] = one
  2179. for i in range(n22):
  2180. S[p+i, q+i] = one
  2181. for i in range(n12):
  2182. S[i+n11+r, i+n11+r+n21+n22+r] = -one
  2183. for i in range(n21):
  2184. S[p+n22+r+i, n11+r+i] = one
  2185. for i in range(r):
  2186. S[i+n11, i+n11] = np.cos(theta[i])
  2187. S[p+n22+i, i+r+n21+n22] = np.cos(theta[i])
  2188. S[i+n11, i+n11+n21+n22+r] = -np.sin(theta[i])
  2189. S[p+n22+i, i+n11] = np.sin(theta[i])
  2190. Xc = U @ S @ VH
  2191. assert_allclose(X, Xc, rtol=0., atol=1e4*np.finfo(dtype_).eps)
  2192. @pytest.mark.parametrize("dtype", DTYPES)
  2193. @pytest.mark.parametrize("trans_bool", [False, True])
  2194. @pytest.mark.parametrize("fact", ["F", "N"])
  2195. def test_gtsvx(dtype, trans_bool, fact):
  2196. """
  2197. These tests uses ?gtsvx to solve a random Ax=b system for each dtype.
  2198. It tests that the outputs define an LU matrix, that inputs are unmodified,
  2199. transposal options, incompatible shapes, singular matrices, and
  2200. singular factorizations. It parametrizes DTYPES and the 'fact' value along
  2201. with the fact related inputs.
  2202. """
  2203. rng = np.random.RandomState(42)
  2204. # set test tolerance appropriate for dtype
  2205. atol = 100 * np.finfo(dtype).eps
  2206. # obtain routine
  2207. gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
  2208. # Generate random tridiagonal matrix A
  2209. n = 10
  2210. dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
  2211. d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
  2212. du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
  2213. A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
  2214. # generate random solution x
  2215. x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
  2216. # create b from x for equation Ax=b
  2217. trans = ("T" if dtype in REAL_DTYPES else "C") if trans_bool else "N"
  2218. b = (A.conj().T if trans_bool else A) @ x
  2219. # store a copy of the inputs to check they haven't been modified later
  2220. inputs_cpy = [dl.copy(), d.copy(), du.copy(), b.copy()]
  2221. # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
  2222. dlf_, df_, duf_, du2f_, ipiv_, info_ = \
  2223. gttrf(dl, d, du) if fact == 'F' else [None]*6
  2224. gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_,
  2225. duf=duf_, du2=du2f_, ipiv=ipiv_)
  2226. dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
  2227. assert_(info == 0, f"?gtsvx info = {info}, should be zero")
  2228. # assure that inputs are unmodified
  2229. assert_array_equal(dl, inputs_cpy[0])
  2230. assert_array_equal(d, inputs_cpy[1])
  2231. assert_array_equal(du, inputs_cpy[2])
  2232. assert_array_equal(b, inputs_cpy[3])
  2233. # test that x_soln matches the expected x
  2234. assert_allclose(x, x_soln, atol=atol)
  2235. # assert that the outputs are of correct type or shape
  2236. # rcond should be a scalar
  2237. assert_(hasattr(rcond, "__len__") is not True,
  2238. f"rcond should be scalar but is {rcond}")
  2239. # ferr should be length of # of cols in x
  2240. assert_(ferr.shape[0] == b.shape[1], (f"ferr.shape is {ferr.shape[0]} but should"
  2241. f" be {b.shape[1]}"))
  2242. # berr should be length of # of cols in x
  2243. assert_(berr.shape[0] == b.shape[1], (f"berr.shape is {berr.shape[0]} but should"
  2244. f" be {b.shape[1]}"))
  2245. @pytest.mark.parametrize("dtype", DTYPES)
  2246. @pytest.mark.parametrize("trans_bool", [0, 1])
  2247. @pytest.mark.parametrize("fact", ["F", "N"])
  2248. def test_gtsvx_error_singular(dtype, trans_bool, fact):
  2249. rng = np.random.RandomState(42)
  2250. # obtain routine
  2251. gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
  2252. # Generate random tridiagonal matrix A
  2253. n = 10
  2254. dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
  2255. d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
  2256. du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
  2257. A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
  2258. # generate random solution x
  2259. x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
  2260. # create b from x for equation Ax=b
  2261. trans = "T" if dtype in REAL_DTYPES else "C"
  2262. b = (A.conj().T if trans_bool else A) @ x
  2263. # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
  2264. dlf_, df_, duf_, du2f_, ipiv_, info_ = \
  2265. gttrf(dl, d, du) if fact == 'F' else [None]*6
  2266. gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_,
  2267. duf=duf_, du2=du2f_, ipiv=ipiv_)
  2268. dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
  2269. # test with singular matrix
  2270. # no need to test inputs with fact "F" since ?gttrf already does.
  2271. if fact == "N":
  2272. # Construct a singular example manually
  2273. d[-1] = 0
  2274. dl[-1] = 0
  2275. # solve using routine
  2276. gtsvx_out = gtsvx(dl, d, du, b)
  2277. dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
  2278. # test for the singular matrix.
  2279. assert info > 0, "info should be > 0 for singular matrix"
  2280. elif fact == 'F':
  2281. # assuming that a singular factorization is input
  2282. df_[-1] = 0
  2283. duf_[-1] = 0
  2284. du2f_[-1] = 0
  2285. gtsvx_out = gtsvx(dl, d, du, b, fact=fact, dlf=dlf_, df=df_, duf=duf_,
  2286. du2=du2f_, ipiv=ipiv_)
  2287. dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
  2288. # info should not be zero and should provide index of illegal value
  2289. assert info > 0, "info should be > 0 for singular matrix"
  2290. @pytest.mark.parametrize("dtype", DTYPES*2)
  2291. @pytest.mark.parametrize("trans_bool", [False, True])
  2292. @pytest.mark.parametrize("fact", ["F", "N"])
  2293. def test_gtsvx_error_incompatible_size(dtype, trans_bool, fact):
  2294. rng = np.random.RandomState(42)
  2295. # obtain routine
  2296. gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
  2297. # Generate random tridiagonal matrix A
  2298. n = 10
  2299. dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
  2300. d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
  2301. du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
  2302. A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
  2303. # generate random solution x
  2304. x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
  2305. # create b from x for equation Ax=b
  2306. trans = "T" if dtype in REAL_DTYPES else "C"
  2307. b = (A.conj().T if trans_bool else A) @ x
  2308. # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
  2309. dlf_, df_, duf_, du2f_, ipiv_, info_ = \
  2310. gttrf(dl, d, du) if fact == 'F' else [None]*6
  2311. if fact == "N":
  2312. assert_raises(ValueError, gtsvx, dl[:-1], d, du, b,
  2313. fact=fact, trans=trans, dlf=dlf_, df=df_,
  2314. duf=duf_, du2=du2f_, ipiv=ipiv_)
  2315. assert_raises(ValueError, gtsvx, dl, d[:-1], du, b,
  2316. fact=fact, trans=trans, dlf=dlf_, df=df_,
  2317. duf=duf_, du2=du2f_, ipiv=ipiv_)
  2318. assert_raises(ValueError, gtsvx, dl, d, du[:-1], b,
  2319. fact=fact, trans=trans, dlf=dlf_, df=df_,
  2320. duf=duf_, du2=du2f_, ipiv=ipiv_)
  2321. assert_raises(Exception, gtsvx, dl, d, du, b[:-1],
  2322. fact=fact, trans=trans, dlf=dlf_, df=df_,
  2323. duf=duf_, du2=du2f_, ipiv=ipiv_)
  2324. else:
  2325. assert_raises(ValueError, gtsvx, dl, d, du, b,
  2326. fact=fact, trans=trans, dlf=dlf_[:-1], df=df_,
  2327. duf=duf_, du2=du2f_, ipiv=ipiv_)
  2328. assert_raises(ValueError, gtsvx, dl, d, du, b,
  2329. fact=fact, trans=trans, dlf=dlf_, df=df_[:-1],
  2330. duf=duf_, du2=du2f_, ipiv=ipiv_)
  2331. assert_raises(ValueError, gtsvx, dl, d, du, b,
  2332. fact=fact, trans=trans, dlf=dlf_, df=df_,
  2333. duf=duf_[:-1], du2=du2f_, ipiv=ipiv_)
  2334. assert_raises(ValueError, gtsvx, dl, d, du, b,
  2335. fact=fact, trans=trans, dlf=dlf_, df=df_,
  2336. duf=duf_, du2=du2f_[:-1], ipiv=ipiv_)
  2337. @pytest.mark.parametrize("du,d,dl,b,x",
  2338. [(np.array([2.1, -1.0, 1.9, 8.0]),
  2339. np.array([3.0, 2.3, -5.0, -0.9, 7.1]),
  2340. np.array([3.4, 3.6, 7.0, -6.0]),
  2341. np.array([[2.7, 6.6], [-.5, 10.8], [2.6, -3.2],
  2342. [.6, -11.2], [2.7, 19.1]]),
  2343. np.array([[-4, 5], [7, -4], [3, -3], [-4, -2],
  2344. [-3, 1]])),
  2345. (np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]),
  2346. np.array([-1.3 + 1.3j, -1.3 + 1.3j, -1.3 + 3.3j,
  2347. -.3 + 4.3j, -3.3 + 1.3j]),
  2348. np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]),
  2349. np.array([[2.4 - 5j, 2.7 + 6.9j],
  2350. [3.4 + 18.2j, -6.9 - 5.3j],
  2351. [-14.7 + 9.7j, -6 - .6j],
  2352. [31.9 - 7.7j, -3.9 + 9.3j],
  2353. [-1 + 1.6j, -3 + 12.2j]]),
  2354. np.array([[1 + 1j, 2 - 1j], [3 - 1j, 1 + 2j],
  2355. [4 + 5j, -1 + 1j], [-1 - 2j, 2 + 1j],
  2356. [1 - 1j, 2 - 2j]]))])
  2357. def test_gtsvx_NAG(du, d, dl, b, x):
  2358. # Test to ensure wrapper is consistent with NAG Manual Mark 26
  2359. # example problems: real (f07cbf) and complex (f07cpf)
  2360. gtsvx = get_lapack_funcs('gtsvx', dtype=d.dtype)
  2361. gtsvx_out = gtsvx(dl, d, du, b)
  2362. dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
  2363. assert_array_almost_equal(x, x_soln)
  2364. @pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES
  2365. + REAL_DTYPES))
  2366. @pytest.mark.parametrize("fact,df_de_lambda",
  2367. [("F",
  2368. lambda d, e: get_lapack_funcs('pttrf',
  2369. dtype=e.dtype)(d, e)),
  2370. ("N", lambda d, e: (None, None, None))])
  2371. def test_ptsvx(dtype, realtype, fact, df_de_lambda):
  2372. '''
  2373. This tests the ?ptsvx lapack routine wrapper to solve a random system
  2374. Ax = b for all dtypes and input variations. Tests for: unmodified
  2375. input parameters, fact options, incompatible matrix shapes raise an error,
  2376. and singular matrices return info of illegal value.
  2377. '''
  2378. rng = np.random.RandomState(42)
  2379. # set test tolerance appropriate for dtype
  2380. atol = 100 * np.finfo(dtype).eps
  2381. ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
  2382. n = 5
  2383. # create diagonals according to size and dtype
  2384. d = generate_random_dtype_array((n,), realtype, rng) + 4
  2385. e = generate_random_dtype_array((n-1,), dtype, rng)
  2386. A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
  2387. x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
  2388. b = A @ x_soln
  2389. # use lambda to determine what df, ef are
  2390. df, ef, info = df_de_lambda(d, e)
  2391. # create copy to later test that they are unmodified
  2392. diag_cpy = [d.copy(), e.copy(), b.copy()]
  2393. # solve using routine
  2394. df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact,
  2395. df=df, ef=ef)
  2396. # d, e, and b should be unmodified
  2397. assert_array_equal(d, diag_cpy[0])
  2398. assert_array_equal(e, diag_cpy[1])
  2399. assert_array_equal(b, diag_cpy[2])
  2400. assert_(info == 0, f"info should be 0 but is {info}.")
  2401. assert_array_almost_equal(x_soln, x)
  2402. # test that the factors from ptsvx can be recombined to make A
  2403. L = np.diag(ef, -1) + np.diag(np.ones(n))
  2404. D = np.diag(df)
  2405. assert_allclose(A, L@D@(np.conj(L).T), atol=atol)
  2406. # assert that the outputs are of correct type or shape
  2407. # rcond should be a scalar
  2408. assert not hasattr(rcond, "__len__"), \
  2409. f"rcond should be scalar but is {rcond}"
  2410. # ferr should be length of # of cols in x
  2411. assert_(ferr.shape == (2,), (f"ferr.shape is {ferr.shape} but should be "
  2412. "({x_soln.shape[1]},)"))
  2413. # berr should be length of # of cols in x
  2414. assert_(berr.shape == (2,), (f"berr.shape is {berr.shape} but should be "
  2415. "({x_soln.shape[1]},)"))
  2416. @pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES
  2417. + REAL_DTYPES))
  2418. @pytest.mark.parametrize("fact,df_de_lambda",
  2419. [("F",
  2420. lambda d, e: get_lapack_funcs('pttrf',
  2421. dtype=e.dtype)(d, e)),
  2422. ("N", lambda d, e: (None, None, None))])
  2423. def test_ptsvx_error_raise_errors(dtype, realtype, fact, df_de_lambda):
  2424. rng = np.random.RandomState(42)
  2425. ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
  2426. n = 5
  2427. # create diagonals according to size and dtype
  2428. d = generate_random_dtype_array((n,), realtype, rng) + 4
  2429. e = generate_random_dtype_array((n-1,), dtype, rng)
  2430. A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
  2431. x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
  2432. b = A @ x_soln
  2433. # use lambda to determine what df, ef are
  2434. df, ef, info = df_de_lambda(d, e)
  2435. # test with malformatted array sizes
  2436. assert_raises(ValueError, ptsvx, d[:-1], e, b, fact=fact, df=df, ef=ef)
  2437. assert_raises(ValueError, ptsvx, d, e[:-1], b, fact=fact, df=df, ef=ef)
  2438. assert_raises(Exception, ptsvx, d, e, b[:-1], fact=fact, df=df, ef=ef)
  2439. @pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES
  2440. + REAL_DTYPES))
  2441. @pytest.mark.parametrize("fact,df_de_lambda",
  2442. [("F",
  2443. lambda d, e: get_lapack_funcs('pttrf',
  2444. dtype=e.dtype)(d, e)),
  2445. ("N", lambda d, e: (None, None, None))])
  2446. def test_ptsvx_non_SPD_singular(dtype, realtype, fact, df_de_lambda):
  2447. rng = np.random.RandomState(42)
  2448. ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
  2449. n = 5
  2450. # create diagonals according to size and dtype
  2451. d = generate_random_dtype_array((n,), realtype, rng) + 4
  2452. e = generate_random_dtype_array((n-1,), dtype, rng)
  2453. A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
  2454. x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
  2455. b = A @ x_soln
  2456. # use lambda to determine what df, ef are
  2457. df, ef, info = df_de_lambda(d, e)
  2458. if fact == "N":
  2459. d[3] = 0
  2460. # obtain new df, ef
  2461. df, ef, info = df_de_lambda(d, e)
  2462. # solve using routine
  2463. df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b)
  2464. # test for the singular matrix.
  2465. assert info > 0 and info <= n
  2466. # non SPD matrix
  2467. d = generate_random_dtype_array((n,), realtype, rng)
  2468. df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b)
  2469. assert info > 0 and info <= n
  2470. else:
  2471. # assuming that someone is using a singular factorization
  2472. df, ef, info = df_de_lambda(d, e)
  2473. df[0] = 0
  2474. ef[0] = 0
  2475. df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact,
  2476. df=df, ef=ef)
  2477. assert info > 0
  2478. @pytest.mark.parametrize('d,e,b,x',
  2479. [(np.array([4, 10, 29, 25, 5]),
  2480. np.array([-2, -6, 15, 8]),
  2481. np.array([[6, 10], [9, 4], [2, 9], [14, 65],
  2482. [7, 23]]),
  2483. np.array([[2.5, 2], [2, -1], [1, -3],
  2484. [-1, 6], [3, -5]])),
  2485. (np.array([16, 41, 46, 21]),
  2486. np.array([16 + 16j, 18 - 9j, 1 - 4j]),
  2487. np.array([[64 + 16j, -16 - 32j],
  2488. [93 + 62j, 61 - 66j],
  2489. [78 - 80j, 71 - 74j],
  2490. [14 - 27j, 35 + 15j]]),
  2491. np.array([[2 + 1j, -3 - 2j],
  2492. [1 + 1j, 1 + 1j],
  2493. [1 - 2j, 1 - 2j],
  2494. [1 - 1j, 2 + 1j]]))])
  2495. def test_ptsvx_NAG(d, e, b, x):
  2496. # test to assure that wrapper is consistent with NAG Manual Mark 26
  2497. # example problems: f07jbf, f07jpf
  2498. # (Links expire, so please search for "NAG Library Manual Mark 26" online)
  2499. # obtain routine with correct type based on e.dtype
  2500. ptsvx = get_lapack_funcs('ptsvx', dtype=e.dtype)
  2501. # solve using routine
  2502. df, ef, x_ptsvx, rcond, ferr, berr, info = ptsvx(d, e, b)
  2503. # determine ptsvx's solution and x are the same.
  2504. assert_array_almost_equal(x, x_ptsvx)
  2505. @pytest.mark.parametrize('lower', [False, True])
  2506. @pytest.mark.parametrize('dtype', DTYPES)
  2507. def test_pptrs_pptri_pptrf_ppsv_ppcon(dtype, lower):
  2508. rng = np.random.RandomState(1234)
  2509. atol = np.finfo(dtype).eps*100
  2510. # Manual conversion to/from packed format is feasible here.
  2511. n, nrhs = 10, 4
  2512. a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
  2513. b = generate_random_dtype_array([n, nrhs], dtype=dtype, rng=rng)
  2514. a = a.conj().T + a + np.eye(n, dtype=dtype) * dtype(5.)
  2515. if lower:
  2516. inds = ([x for y in range(n) for x in range(y, n)],
  2517. [y for y in range(n) for x in range(y, n)])
  2518. else:
  2519. inds = ([x for y in range(1, n+1) for x in range(y)],
  2520. [y-1 for y in range(1, n+1) for x in range(y)])
  2521. ap = a[inds]
  2522. ppsv, pptrf, pptrs, pptri, ppcon = get_lapack_funcs(
  2523. ('ppsv', 'pptrf', 'pptrs', 'pptri', 'ppcon'),
  2524. dtype=dtype,
  2525. ilp64="preferred")
  2526. ul, info = pptrf(n, ap, lower=lower)
  2527. assert_equal(info, 0)
  2528. aul = cholesky(a, lower=lower)[inds]
  2529. assert_allclose(ul, aul, rtol=0, atol=atol)
  2530. uli, info = pptri(n, ul, lower=lower)
  2531. assert_equal(info, 0)
  2532. auli = inv(a)[inds]
  2533. assert_allclose(uli, auli, rtol=0, atol=atol)
  2534. x, info = pptrs(n, ul, b, lower=lower)
  2535. assert_equal(info, 0)
  2536. bx = solve(a, b)
  2537. assert_allclose(x, bx, rtol=0, atol=atol)
  2538. xv, info = ppsv(n, ap, b, lower=lower)
  2539. assert_equal(info, 0)
  2540. assert_allclose(xv, bx, rtol=0, atol=atol)
  2541. anorm = np.linalg.norm(a, 1)
  2542. rcond, info = ppcon(n, ap, anorm=anorm, lower=lower)
  2543. assert_equal(info, 0)
  2544. assert_(abs(1/rcond - np.linalg.cond(a, p=1))*rcond < 1)
  2545. @pytest.mark.parametrize('dtype', DTYPES)
  2546. def test_gees_trexc(dtype):
  2547. rng = np.random.RandomState(1234)
  2548. atol = np.finfo(dtype).eps*100
  2549. n = 10
  2550. a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
  2551. gees, trexc = get_lapack_funcs(('gees', 'trexc'), dtype=dtype)
  2552. result = gees(lambda x: None, a, overwrite_a=False)
  2553. assert_equal(result[-1], 0)
  2554. t = result[0]
  2555. z = result[-3]
  2556. d2 = t[6, 6]
  2557. if dtype in COMPLEX_DTYPES:
  2558. assert_allclose(t, np.triu(t), rtol=0, atol=atol)
  2559. assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
  2560. result = trexc(t, z, 7, 1)
  2561. assert_equal(result[-1], 0)
  2562. t = result[0]
  2563. z = result[-2]
  2564. if dtype in COMPLEX_DTYPES:
  2565. assert_allclose(t, np.triu(t), rtol=0, atol=atol)
  2566. assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
  2567. assert_allclose(t[0, 0], d2, rtol=0, atol=atol)
  2568. @pytest.mark.parametrize(
  2569. "t, expect, ifst, ilst",
  2570. [(np.array([[0.80, -0.11, 0.01, 0.03],
  2571. [0.00, -0.10, 0.25, 0.35],
  2572. [0.00, -0.65, -0.10, 0.20],
  2573. [0.00, 0.00, 0.00, -0.10]]),
  2574. np.array([[-0.1000, -0.6463, 0.0874, 0.2010],
  2575. [0.2514, -0.1000, 0.0927, 0.3505],
  2576. [0.0000, 0.0000, 0.8000, -0.0117],
  2577. [0.0000, 0.0000, 0.0000, -0.1000]]),
  2578. 2, 1),
  2579. (np.array([[-6.00 - 7.00j, 0.36 - 0.36j, -0.19 + 0.48j, 0.88 - 0.25j],
  2580. [0.00 + 0.00j, -5.00 + 2.00j, -0.03 - 0.72j, -0.23 + 0.13j],
  2581. [0.00 + 0.00j, 0.00 + 0.00j, 8.00 - 1.00j, 0.94 + 0.53j],
  2582. [0.00 + 0.00j, 0.00 + 0.00j, 0.00 + 0.00j, 3.00 - 4.00j]]),
  2583. np.array([[-5.0000 + 2.0000j, -0.1574 + 0.7143j,
  2584. 0.1781 - 0.1913j, 0.3950 + 0.3861j],
  2585. [0.0000 + 0.0000j, 8.0000 - 1.0000j,
  2586. 1.0742 + 0.1447j, 0.2515 - 0.3397j],
  2587. [0.0000 + 0.0000j, 0.0000 + 0.0000j,
  2588. 3.0000 - 4.0000j, 0.2264 + 0.8962j],
  2589. [0.0000 + 0.0000j, 0.0000 + 0.0000j,
  2590. 0.0000 + 0.0000j, -6.0000 - 7.0000j]]),
  2591. 1, 4)])
  2592. def test_trexc_NAG(t, ifst, ilst, expect):
  2593. """
  2594. This test implements the example found in the NAG manual,
  2595. f08qfc, f08qtc, f08qgc, f08quc.
  2596. """
  2597. # NAG manual provides accuracy up to 4 decimals
  2598. atol = 1e-4
  2599. trexc = get_lapack_funcs('trexc', dtype=t.dtype)
  2600. result = trexc(t, t, ifst, ilst, wantq=0)
  2601. assert_equal(result[-1], 0)
  2602. t = result[0]
  2603. assert_allclose(expect, t, atol=atol)
  2604. @pytest.mark.parametrize('dtype', DTYPES)
  2605. def test_gges_tgexc(dtype):
  2606. rng = np.random.RandomState(1234)
  2607. atol = np.finfo(dtype).eps*100
  2608. n = 10
  2609. a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
  2610. b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
  2611. gges, tgexc = get_lapack_funcs(('gges', 'tgexc'), dtype=dtype)
  2612. result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False)
  2613. assert_equal(result[-1], 0)
  2614. s = result[0]
  2615. t = result[1]
  2616. q = result[-4]
  2617. z = result[-3]
  2618. d1 = s[0, 0] / t[0, 0]
  2619. d2 = s[6, 6] / t[6, 6]
  2620. if dtype in COMPLEX_DTYPES:
  2621. assert_allclose(s, np.triu(s), rtol=0, atol=atol)
  2622. assert_allclose(t, np.triu(t), rtol=0, atol=atol)
  2623. assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
  2624. assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
  2625. result = tgexc(s, t, q, z, 7, 1)
  2626. assert_equal(result[-1], 0)
  2627. s = result[0]
  2628. t = result[1]
  2629. q = result[2]
  2630. z = result[3]
  2631. if dtype in COMPLEX_DTYPES:
  2632. assert_allclose(s, np.triu(s), rtol=0, atol=atol)
  2633. assert_allclose(t, np.triu(t), rtol=0, atol=atol)
  2634. assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
  2635. assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
  2636. assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol)
  2637. assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol)
  2638. @pytest.mark.parametrize('dtype', DTYPES)
  2639. def test_gees_trsen(dtype):
  2640. rng = np.random.RandomState(1234)
  2641. atol = np.finfo(dtype).eps*100
  2642. n = 10
  2643. a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
  2644. gees, trsen, trsen_lwork = get_lapack_funcs(
  2645. ('gees', 'trsen', 'trsen_lwork'), dtype=dtype)
  2646. result = gees(lambda x: None, a, overwrite_a=False)
  2647. assert_equal(result[-1], 0)
  2648. t = result[0]
  2649. z = result[-3]
  2650. d2 = t[6, 6]
  2651. if dtype in COMPLEX_DTYPES:
  2652. assert_allclose(t, np.triu(t), rtol=0, atol=atol)
  2653. assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
  2654. select = np.zeros(n)
  2655. select[6] = 1
  2656. lwork = _compute_lwork(trsen_lwork, select, t)
  2657. if dtype in COMPLEX_DTYPES:
  2658. result = trsen(select, t, z, lwork=lwork)
  2659. else:
  2660. result = trsen(select, t, z, lwork=lwork, liwork=lwork[1])
  2661. assert_equal(result[-1], 0)
  2662. t = result[0]
  2663. z = result[1]
  2664. if dtype in COMPLEX_DTYPES:
  2665. assert_allclose(t, np.triu(t), rtol=0, atol=atol)
  2666. assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
  2667. assert_allclose(t[0, 0], d2, rtol=0, atol=atol)
  2668. @pytest.mark.parametrize(
  2669. "t, q, expect, select, expect_s, expect_sep",
  2670. [(np.array([[0.7995, -0.1144, 0.0060, 0.0336],
  2671. [0.0000, -0.0994, 0.2478, 0.3474],
  2672. [0.0000, -0.6483, -0.0994, 0.2026],
  2673. [0.0000, 0.0000, 0.0000, -0.1007]]),
  2674. np.array([[0.6551, 0.1037, 0.3450, 0.6641],
  2675. [0.5236, -0.5807, -0.6141, -0.1068],
  2676. [-0.5362, -0.3073, -0.2935, 0.7293],
  2677. [0.0956, 0.7467, -0.6463, 0.1249]]),
  2678. np.array([[0.3500, 0.4500, -0.1400, -0.1700],
  2679. [0.0900, 0.0700, -0.5399, 0.3500],
  2680. [-0.4400, -0.3300, -0.0300, 0.1700],
  2681. [0.2500, -0.3200, -0.1300, 0.1100]]),
  2682. np.array([1, 0, 0, 1]),
  2683. 1.75e+00, 3.22e+00),
  2684. (np.array([[-6.0004 - 6.9999j, 0.3637 - 0.3656j,
  2685. -0.1880 + 0.4787j, 0.8785 - 0.2539j],
  2686. [0.0000 + 0.0000j, -5.0000 + 2.0060j,
  2687. -0.0307 - 0.7217j, -0.2290 + 0.1313j],
  2688. [0.0000 + 0.0000j, 0.0000 + 0.0000j,
  2689. 7.9982 - 0.9964j, 0.9357 + 0.5359j],
  2690. [0.0000 + 0.0000j, 0.0000 + 0.0000j,
  2691. 0.0000 + 0.0000j, 3.0023 - 3.9998j]]),
  2692. np.array([[-0.8347 - 0.1364j, -0.0628 + 0.3806j,
  2693. 0.2765 - 0.0846j, 0.0633 - 0.2199j],
  2694. [0.0664 - 0.2968j, 0.2365 + 0.5240j,
  2695. -0.5877 - 0.4208j, 0.0835 + 0.2183j],
  2696. [-0.0362 - 0.3215j, 0.3143 - 0.5473j,
  2697. 0.0576 - 0.5736j, 0.0057 - 0.4058j],
  2698. [0.0086 + 0.2958j, -0.3416 - 0.0757j,
  2699. -0.1900 - 0.1600j, 0.8327 - 0.1868j]]),
  2700. np.array([[-3.9702 - 5.0406j, -4.1108 + 3.7002j,
  2701. -0.3403 + 1.0098j, 1.2899 - 0.8590j],
  2702. [0.3397 - 1.5006j, 1.5201 - 0.4301j,
  2703. 1.8797 - 5.3804j, 3.3606 + 0.6498j],
  2704. [3.3101 - 3.8506j, 2.4996 + 3.4504j,
  2705. 0.8802 - 1.0802j, 0.6401 - 1.4800j],
  2706. [-1.0999 + 0.8199j, 1.8103 - 1.5905j,
  2707. 3.2502 + 1.3297j, 1.5701 - 3.4397j]]),
  2708. np.array([1, 0, 0, 1]),
  2709. 1.02e+00, 1.82e-01)])
  2710. def test_trsen_NAG(t, q, select, expect, expect_s, expect_sep):
  2711. """
  2712. This test implements the example found in the NAG manual,
  2713. f08qgc, f08quc.
  2714. """
  2715. # NAG manual provides accuracy up to 4 and 2 decimals
  2716. atol = 1e-4
  2717. atol2 = 1e-2
  2718. trsen, trsen_lwork = get_lapack_funcs(
  2719. ('trsen', 'trsen_lwork'), dtype=t.dtype)
  2720. lwork = _compute_lwork(trsen_lwork, select, t)
  2721. if t.dtype in COMPLEX_DTYPES:
  2722. result = trsen(select, t, q, lwork=lwork)
  2723. else:
  2724. result = trsen(select, t, q, lwork=lwork, liwork=lwork[1])
  2725. assert_equal(result[-1], 0)
  2726. t = result[0]
  2727. q = result[1]
  2728. if t.dtype in COMPLEX_DTYPES:
  2729. s = result[4]
  2730. sep = result[5]
  2731. else:
  2732. s = result[5]
  2733. sep = result[6]
  2734. assert_allclose(expect, q @ t @ q.conj().T, atol=atol)
  2735. assert_allclose(expect_s, 1 / s, atol=atol2)
  2736. assert_allclose(expect_sep, 1 / sep, atol=atol2)
  2737. @pytest.mark.parametrize('dtype', DTYPES)
  2738. def test_gges_tgsen(dtype):
  2739. rng = np.random.RandomState(1234)
  2740. atol = np.finfo(dtype).eps*100
  2741. n = 10
  2742. a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
  2743. b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
  2744. gges, tgsen, tgsen_lwork = get_lapack_funcs(
  2745. ('gges', 'tgsen', 'tgsen_lwork'), dtype=dtype)
  2746. result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False)
  2747. assert_equal(result[-1], 0)
  2748. s = result[0]
  2749. t = result[1]
  2750. q = result[-4]
  2751. z = result[-3]
  2752. d1 = s[0, 0] / t[0, 0]
  2753. d2 = s[6, 6] / t[6, 6]
  2754. if dtype in COMPLEX_DTYPES:
  2755. assert_allclose(s, np.triu(s), rtol=0, atol=atol)
  2756. assert_allclose(t, np.triu(t), rtol=0, atol=atol)
  2757. assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
  2758. assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
  2759. select = np.zeros(n)
  2760. select[6] = 1
  2761. lwork = _compute_lwork(tgsen_lwork, select, s, t)
  2762. # off-by-one error in LAPACK, see gh-issue #13397
  2763. lwork = (lwork[0]+1, lwork[1])
  2764. result = tgsen(select, s, t, q, z, lwork=lwork)
  2765. assert_equal(result[-1], 0)
  2766. s = result[0]
  2767. t = result[1]
  2768. q = result[-7]
  2769. z = result[-6]
  2770. if dtype in COMPLEX_DTYPES:
  2771. assert_allclose(s, np.triu(s), rtol=0, atol=atol)
  2772. assert_allclose(t, np.triu(t), rtol=0, atol=atol)
  2773. assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
  2774. assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
  2775. assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol)
  2776. assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol)
  2777. @pytest.mark.parametrize(
  2778. "a, b, c, d, e, f, rans, lans",
  2779. [(np.array([[4.0, 1.0, 1.0, 2.0],
  2780. [0.0, 3.0, 4.0, 1.0],
  2781. [0.0, 1.0, 3.0, 1.0],
  2782. [0.0, 0.0, 0.0, 6.0]]),
  2783. np.array([[1.0, 1.0, 1.0, 1.0],
  2784. [0.0, 3.0, 4.0, 1.0],
  2785. [0.0, 1.0, 3.0, 1.0],
  2786. [0.0, 0.0, 0.0, 4.0]]),
  2787. np.array([[-4.0, 7.0, 1.0, 12.0],
  2788. [-9.0, 2.0, -2.0, -2.0],
  2789. [-4.0, 2.0, -2.0, 8.0],
  2790. [-7.0, 7.0, -6.0, 19.0]]),
  2791. np.array([[2.0, 1.0, 1.0, 3.0],
  2792. [0.0, 1.0, 2.0, 1.0],
  2793. [0.0, 0.0, 1.0, 1.0],
  2794. [0.0, 0.0, 0.0, 2.0]]),
  2795. np.array([[1.0, 1.0, 1.0, 2.0],
  2796. [0.0, 1.0, 4.0, 1.0],
  2797. [0.0, 0.0, 1.0, 1.0],
  2798. [0.0, 0.0, 0.0, 1.0]]),
  2799. np.array([[-7.0, 5.0, 0.0, 7.0],
  2800. [-5.0, 1.0, -8.0, 0.0],
  2801. [-1.0, 2.0, -3.0, 5.0],
  2802. [-3.0, 2.0, 0.0, 5.0]]),
  2803. np.array([[1.0, 1.0, 1.0, 1.0],
  2804. [-1.0, 2.0, -1.0, -1.0],
  2805. [-1.0, 1.0, 3.0, 1.0],
  2806. [-1.0, 1.0, -1.0, 4.0]]),
  2807. np.array([[4.0, -1.0, 1.0, -1.0],
  2808. [1.0, 3.0, -1.0, 1.0],
  2809. [-1.0, 1.0, 2.0, -1.0],
  2810. [1.0, -1.0, 1.0, 1.0]]))])
  2811. @pytest.mark.parametrize('dtype', REAL_DTYPES)
  2812. def test_tgsyl_NAG(a, b, c, d, e, f, rans, lans, dtype):
  2813. atol = 1e-4
  2814. tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype)
  2815. rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f)
  2816. assert_equal(info, 0)
  2817. assert_allclose(scale, 1.0, rtol=0, atol=np.finfo(dtype).eps*100,
  2818. err_msg="SCALE must be 1.0")
  2819. assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100,
  2820. err_msg="DIF must be nearly 0")
  2821. assert_allclose(rout, rans, atol=atol,
  2822. err_msg="Solution for R is incorrect")
  2823. assert_allclose(lout, lans, atol=atol,
  2824. err_msg="Solution for L is incorrect")
  2825. @pytest.mark.parametrize('dtype', REAL_DTYPES)
  2826. @pytest.mark.parametrize('trans', ('N', 'T'))
  2827. @pytest.mark.parametrize('ijob', [0, 1, 2, 3, 4])
  2828. def test_tgsyl(dtype, trans, ijob):
  2829. atol = 1e-3 if dtype == np.float32 else 1e-10
  2830. rng = np.random.default_rng(1685779866898198)
  2831. m, n = 10, 15
  2832. a, d, *_ = qz(rng.uniform(-10, 10, [m, m]).astype(dtype),
  2833. rng.uniform(-10, 10, [m, m]).astype(dtype),
  2834. output='real')
  2835. b, e, *_ = qz(rng.uniform(-10, 10, [n, n]).astype(dtype),
  2836. rng.uniform(-10, 10, [n, n]).astype(dtype),
  2837. output='real')
  2838. c = rng.uniform(-2, 2, [m, n]).astype(dtype)
  2839. f = rng.uniform(-2, 2, [m, n]).astype(dtype)
  2840. tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype)
  2841. rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f,
  2842. trans=trans, ijob=ijob)
  2843. assert info == 0, "INFO is non-zero"
  2844. assert scale >= 0.0, "SCALE must be non-negative"
  2845. if ijob == 0:
  2846. assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100,
  2847. err_msg="DIF must be 0 for ijob =0")
  2848. else:
  2849. assert dif >= 0.0, "DIF must be non-negative"
  2850. # Only DIF is calculated for ijob = 3/4
  2851. if ijob <= 2:
  2852. if trans == 'N':
  2853. lhs1 = a @ rout - lout @ b
  2854. rhs1 = scale*c
  2855. lhs2 = d @ rout - lout @ e
  2856. rhs2 = scale*f
  2857. elif trans == 'T':
  2858. lhs1 = np.transpose(a) @ rout + np.transpose(d) @ lout
  2859. rhs1 = scale*c
  2860. lhs2 = rout @ np.transpose(b) + lout @ np.transpose(e)
  2861. rhs2 = -1.0*scale*f
  2862. assert_allclose(lhs1, rhs1, atol=atol, rtol=0.,
  2863. err_msg='lhs1 and rhs1 do not match')
  2864. assert_allclose(lhs2, rhs2, atol=atol, rtol=0.,
  2865. err_msg='lhs2 and rhs2 do not match')
  2866. @pytest.mark.parametrize('mtype', ['sy', 'he']) # matrix type
  2867. @pytest.mark.parametrize('dtype', DTYPES)
  2868. @pytest.mark.parametrize('lower', (0, 1))
  2869. def test_sy_hetrs(mtype, dtype, lower):
  2870. if mtype == 'he' and dtype in REAL_DTYPES:
  2871. pytest.skip("hetrs not for real dtypes.")
  2872. rng = np.random.default_rng(1723059677121834)
  2873. n, nrhs = 20, 5
  2874. if dtype in COMPLEX_DTYPES:
  2875. A = (rng.uniform(size=(n, n)) + rng.uniform(size=(n, n))*1j).astype(dtype)
  2876. else:
  2877. A = rng.uniform(size=(n, n)).astype(dtype)
  2878. A = A + A.T if mtype == 'sy' else A + A.conj().T
  2879. b = rng.uniform(size=(n, nrhs)).astype(dtype)
  2880. names = f'{mtype}trf', f'{mtype}trf_lwork', f'{mtype}trs'
  2881. trf, trf_lwork, trs = get_lapack_funcs(names, dtype=dtype)
  2882. lwork = trf_lwork(n, lower=lower)
  2883. ldu, ipiv, info = trf(A, lwork=lwork, lower=lower)
  2884. assert info == 0
  2885. x, info = trs(a=ldu, ipiv=ipiv, b=b, lower=lower)
  2886. assert info == 0
  2887. eps = np.finfo(dtype).eps
  2888. assert_allclose(A@x, b, atol=100*n*eps)
  2889. @pytest.mark.parametrize('mtype', ['sy', 'he']) # matrix type
  2890. @pytest.mark.parametrize('dtype', DTYPES)
  2891. @pytest.mark.parametrize('lower', (0, 1))
  2892. def test_sy_he_tri(dtype, lower, mtype):
  2893. if mtype == 'he' and dtype in REAL_DTYPES:
  2894. pytest.skip("hetri not for real dtypes.")
  2895. if sysconfig.get_platform() == 'win-arm64' and dtype in COMPLEX_DTYPES:
  2896. pytest.skip("Test segfaulting on win-arm64 in CI, see gh-23133")
  2897. rng = np.random.default_rng(1723059677121834)
  2898. n = 20
  2899. A = rng.random((n, n)) + rng.random((n, n))*1j
  2900. if np.issubdtype(dtype, np.floating):
  2901. A = A.real
  2902. A = A.astype(dtype)
  2903. A = A + A.T if mtype == 'sy' else A + A.conj().T
  2904. names = f'{mtype}trf', f'{mtype}tri'
  2905. trf, tri = get_lapack_funcs(names, dtype=dtype)
  2906. ldu, ipiv, info = trf(A, lower=lower)
  2907. assert info == 0
  2908. A_inv, info = tri(a=ldu, ipiv=ipiv, lower=lower)
  2909. assert info == 0
  2910. eps = np.finfo(dtype).eps
  2911. ref = np.linalg.inv(A)
  2912. if lower:
  2913. assert_allclose(np.tril(A_inv), np.tril(ref), atol=100*n*eps)
  2914. else:
  2915. assert_allclose(np.triu(A_inv), np.triu(ref), atol=100*n*eps)
  2916. @pytest.mark.parametrize('norm', list('Mm1OoIiFfEe'))
  2917. @pytest.mark.parametrize('uplo, m, n', [('U', 5, 10), ('U', 10, 10),
  2918. ('L', 10, 5), ('L', 10, 10)])
  2919. @pytest.mark.parametrize('diag', ['N', 'U'])
  2920. @pytest.mark.parametrize('dtype', DTYPES)
  2921. def test_lantr(norm, uplo, m, n, diag, dtype):
  2922. rng = np.random.default_rng(98426598246982456)
  2923. A = rng.random(size=(m, n)).astype(dtype)
  2924. lantr, lange = get_lapack_funcs(('lantr', 'lange'), (A,))
  2925. res = lantr(norm, A, uplo=uplo, diag=diag)
  2926. # now modify the matrix according to assumptions made by `lantr`
  2927. A = np.triu(A) if uplo == 'U' else np.tril(A)
  2928. if diag == 'U':
  2929. i = np.arange(min(m, n))
  2930. A[i, i] = 1
  2931. ref = lange(norm, A)
  2932. assert_allclose(res, ref, rtol=2e-6)
  2933. @pytest.mark.parametrize('dtype', DTYPES)
  2934. @pytest.mark.parametrize('norm', ['1', 'I', 'O'])
  2935. def test_gbcon(dtype, norm):
  2936. rng = np.random.default_rng(17273783424)
  2937. # A is of shape n x n with ku/kl super/sub-diagonals
  2938. n, ku, kl = 10, 2, 2
  2939. A = rng.random((n, n)) + rng.random((n, n))*1j
  2940. # make the condition numbers more interesting
  2941. offset = rng.permuted(np.logspace(0, rng.integers(0, 10), n))
  2942. A += offset
  2943. if np.issubdtype(dtype, np.floating):
  2944. A = A.real
  2945. A = A.astype(dtype)
  2946. A[np.triu_indices(n, ku + 1)] = 0
  2947. A[np.tril_indices(n, -kl - 1)] = 0
  2948. # construct banded form
  2949. tmp = _to_banded(kl, ku, A)
  2950. # add rows required by ?gbtrf
  2951. LDAB = 2*kl + ku + 1
  2952. ab = np.zeros((LDAB, n), dtype=dtype)
  2953. ab[kl:, :] = tmp
  2954. anorm = np.linalg.norm(A, ord=np.inf if norm == 'I' else 1)
  2955. gbcon, gbtrf = get_lapack_funcs(("gbcon", "gbtrf"), (ab,))
  2956. lu_band, ipiv, _ = gbtrf(ab, kl, ku)
  2957. res = gbcon(norm=norm, kl=kl, ku=ku, ab=lu_band, ipiv=ipiv,
  2958. anorm=anorm)[0]
  2959. gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,))
  2960. lu = getrf(A)[0]
  2961. ref = gecon(lu, anorm, norm=norm)[0]
  2962. # This is an estimate of reciprocal condition number; we just need order of
  2963. # magnitude.
  2964. assert_allclose(res, ref, rtol=1)
  2965. @pytest.mark.parametrize('norm', list('Mm1OoIiFfEe'))
  2966. @pytest.mark.parametrize('dtype', DTYPES)
  2967. def test_langb(dtype, norm):
  2968. rng = np.random.default_rng(17273783424)
  2969. # A is of shape n x n with ku/kl super/sub-diagonals
  2970. n, ku, kl = 10, 2, 2
  2971. A = rng.random((n, n)) + rng.random((n, n))*1j
  2972. if np.issubdtype(dtype, np.floating):
  2973. A = A.real
  2974. A = A.astype(dtype)
  2975. A[np.triu_indices(n, ku + 1)] = 0
  2976. A[np.tril_indices(n, -kl - 1)] = 0
  2977. ab = _to_banded(kl, ku, A)
  2978. langb, lange = get_lapack_funcs(('langb', 'lange'), (A,))
  2979. ref = lange(norm, A)
  2980. res = langb(norm, kl, ku, ab)
  2981. assert_allclose(res, ref, rtol=2e-6)
  2982. @pytest.mark.parametrize('dtype', REAL_DTYPES)
  2983. @pytest.mark.parametrize('compute_v', (0, 1))
  2984. def test_stevd(dtype, compute_v):
  2985. rng = np.random.default_rng(266474747488348746)
  2986. n = 10
  2987. d = rng.random(n, dtype=dtype)
  2988. e = rng.random(n - 1, dtype=dtype)
  2989. A = np.diag(e, -1) + np.diag(d) + np.diag(e, 1)
  2990. ref = np.linalg.eigvalsh(A)
  2991. stevd = get_lapack_funcs('stevd')
  2992. U, V, info = stevd(d, e, compute_v=compute_v)
  2993. assert info == 0
  2994. assert_allclose(np.sort(U), np.sort(ref))
  2995. if compute_v:
  2996. eps = np.finfo(dtype).eps
  2997. assert_allclose(V @ np.diag(U) @ V.T, A, atol=eps**0.8)