test_function_base.py 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756
  1. import decimal
  2. import math
  3. import operator
  4. import sys
  5. import warnings
  6. from fractions import Fraction
  7. from functools import partial
  8. import hypothesis
  9. import hypothesis.strategies as st
  10. import pytest
  11. from hypothesis.extra.numpy import arrays
  12. import numpy as np
  13. import numpy.lib._function_base_impl as nfb
  14. from numpy import (
  15. angle,
  16. average,
  17. bartlett,
  18. blackman,
  19. corrcoef,
  20. cov,
  21. delete,
  22. diff,
  23. digitize,
  24. extract,
  25. flipud,
  26. gradient,
  27. hamming,
  28. hanning,
  29. i0,
  30. insert,
  31. interp,
  32. kaiser,
  33. ma,
  34. meshgrid,
  35. piecewise,
  36. place,
  37. rot90,
  38. select,
  39. setxor1d,
  40. sinc,
  41. trapezoid,
  42. trim_zeros,
  43. unique,
  44. unwrap,
  45. vectorize,
  46. )
  47. from numpy._core.numeric import normalize_axis_tuple
  48. from numpy.exceptions import AxisError
  49. from numpy.random import rand
  50. from numpy.testing import (
  51. HAS_REFCOUNT,
  52. IS_WASM,
  53. NOGIL_BUILD,
  54. assert_,
  55. assert_allclose,
  56. assert_almost_equal,
  57. assert_array_almost_equal,
  58. assert_array_equal,
  59. assert_equal,
  60. assert_raises,
  61. assert_raises_regex,
  62. )
  63. np_floats = [np.half, np.single, np.double, np.longdouble]
  64. def get_mat(n):
  65. data = np.arange(n)
  66. data = np.add.outer(data, data)
  67. return data
  68. def _make_complex(real, imag):
  69. """
  70. Like real + 1j * imag, but behaves as expected when imag contains non-finite
  71. values
  72. """
  73. ret = np.zeros(np.broadcast(real, imag).shape, np.complex128)
  74. ret.real = real
  75. ret.imag = imag
  76. return ret
  77. class TestRot90:
  78. def test_basic(self):
  79. assert_raises(ValueError, rot90, np.ones(4))
  80. assert_raises(ValueError, rot90, np.ones((2, 2, 2)), axes=(0, 1, 2))
  81. assert_raises(ValueError, rot90, np.ones((2, 2)), axes=(0, 2))
  82. assert_raises(ValueError, rot90, np.ones((2, 2)), axes=(1, 1))
  83. assert_raises(ValueError, rot90, np.ones((2, 2, 2)), axes=(-2, 1))
  84. a = [[0, 1, 2],
  85. [3, 4, 5]]
  86. b1 = [[2, 5],
  87. [1, 4],
  88. [0, 3]]
  89. b2 = [[5, 4, 3],
  90. [2, 1, 0]]
  91. b3 = [[3, 0],
  92. [4, 1],
  93. [5, 2]]
  94. b4 = [[0, 1, 2],
  95. [3, 4, 5]]
  96. for k in range(-3, 13, 4):
  97. assert_equal(rot90(a, k=k), b1)
  98. for k in range(-2, 13, 4):
  99. assert_equal(rot90(a, k=k), b2)
  100. for k in range(-1, 13, 4):
  101. assert_equal(rot90(a, k=k), b3)
  102. for k in range(0, 13, 4):
  103. assert_equal(rot90(a, k=k), b4)
  104. assert_equal(rot90(rot90(a, axes=(0, 1)), axes=(1, 0)), a)
  105. assert_equal(rot90(a, k=1, axes=(1, 0)), rot90(a, k=-1, axes=(0, 1)))
  106. def test_axes(self):
  107. a = np.ones((50, 40, 3))
  108. assert_equal(rot90(a).shape, (40, 50, 3))
  109. assert_equal(rot90(a, axes=(0, 2)), rot90(a, axes=(0, -1)))
  110. assert_equal(rot90(a, axes=(1, 2)), rot90(a, axes=(-2, -1)))
  111. def test_rotation_axes(self):
  112. a = np.arange(8).reshape((2, 2, 2))
  113. a_rot90_01 = [[[2, 3],
  114. [6, 7]],
  115. [[0, 1],
  116. [4, 5]]]
  117. a_rot90_12 = [[[1, 3],
  118. [0, 2]],
  119. [[5, 7],
  120. [4, 6]]]
  121. a_rot90_20 = [[[4, 0],
  122. [6, 2]],
  123. [[5, 1],
  124. [7, 3]]]
  125. a_rot90_10 = [[[4, 5],
  126. [0, 1]],
  127. [[6, 7],
  128. [2, 3]]]
  129. assert_equal(rot90(a, axes=(0, 1)), a_rot90_01)
  130. assert_equal(rot90(a, axes=(1, 0)), a_rot90_10)
  131. assert_equal(rot90(a, axes=(1, 2)), a_rot90_12)
  132. for k in range(1, 5):
  133. assert_equal(rot90(a, k=k, axes=(2, 0)),
  134. rot90(a_rot90_20, k=k - 1, axes=(2, 0)))
  135. class TestFlip:
  136. def test_axes(self):
  137. assert_raises(AxisError, np.flip, np.ones(4), axis=1)
  138. assert_raises(AxisError, np.flip, np.ones((4, 4)), axis=2)
  139. assert_raises(AxisError, np.flip, np.ones((4, 4)), axis=-3)
  140. assert_raises(AxisError, np.flip, np.ones((4, 4)), axis=(0, 3))
  141. def test_basic_lr(self):
  142. a = get_mat(4)
  143. b = a[:, ::-1]
  144. assert_equal(np.flip(a, 1), b)
  145. a = [[0, 1, 2],
  146. [3, 4, 5]]
  147. b = [[2, 1, 0],
  148. [5, 4, 3]]
  149. assert_equal(np.flip(a, 1), b)
  150. def test_basic_ud(self):
  151. a = get_mat(4)
  152. b = a[::-1, :]
  153. assert_equal(np.flip(a, 0), b)
  154. a = [[0, 1, 2],
  155. [3, 4, 5]]
  156. b = [[3, 4, 5],
  157. [0, 1, 2]]
  158. assert_equal(np.flip(a, 0), b)
  159. def test_3d_swap_axis0(self):
  160. a = np.array([[[0, 1],
  161. [2, 3]],
  162. [[4, 5],
  163. [6, 7]]])
  164. b = np.array([[[4, 5],
  165. [6, 7]],
  166. [[0, 1],
  167. [2, 3]]])
  168. assert_equal(np.flip(a, 0), b)
  169. def test_3d_swap_axis1(self):
  170. a = np.array([[[0, 1],
  171. [2, 3]],
  172. [[4, 5],
  173. [6, 7]]])
  174. b = np.array([[[2, 3],
  175. [0, 1]],
  176. [[6, 7],
  177. [4, 5]]])
  178. assert_equal(np.flip(a, 1), b)
  179. def test_3d_swap_axis2(self):
  180. a = np.array([[[0, 1],
  181. [2, 3]],
  182. [[4, 5],
  183. [6, 7]]])
  184. b = np.array([[[1, 0],
  185. [3, 2]],
  186. [[5, 4],
  187. [7, 6]]])
  188. assert_equal(np.flip(a, 2), b)
  189. def test_4d(self):
  190. a = np.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5)
  191. for i in range(a.ndim):
  192. assert_equal(np.flip(a, i),
  193. np.flipud(a.swapaxes(0, i)).swapaxes(i, 0))
  194. def test_default_axis(self):
  195. a = np.array([[1, 2, 3],
  196. [4, 5, 6]])
  197. b = np.array([[6, 5, 4],
  198. [3, 2, 1]])
  199. assert_equal(np.flip(a), b)
  200. def test_multiple_axes(self):
  201. a = np.array([[[0, 1],
  202. [2, 3]],
  203. [[4, 5],
  204. [6, 7]]])
  205. assert_equal(np.flip(a, axis=()), a)
  206. b = np.array([[[5, 4],
  207. [7, 6]],
  208. [[1, 0],
  209. [3, 2]]])
  210. assert_equal(np.flip(a, axis=(0, 2)), b)
  211. c = np.array([[[3, 2],
  212. [1, 0]],
  213. [[7, 6],
  214. [5, 4]]])
  215. assert_equal(np.flip(a, axis=(1, 2)), c)
  216. class TestAny:
  217. def test_basic(self):
  218. y1 = [0, 0, 1, 0]
  219. y2 = [0, 0, 0, 0]
  220. y3 = [1, 0, 1, 0]
  221. assert_(np.any(y1))
  222. assert_(np.any(y3))
  223. assert_(not np.any(y2))
  224. def test_nd(self):
  225. y1 = [[0, 0, 0], [0, 1, 0], [1, 1, 0]]
  226. assert_(np.any(y1))
  227. assert_array_equal(np.any(y1, axis=0), [1, 1, 0])
  228. assert_array_equal(np.any(y1, axis=1), [0, 1, 1])
  229. class TestAll:
  230. def test_basic(self):
  231. y1 = [0, 1, 1, 0]
  232. y2 = [0, 0, 0, 0]
  233. y3 = [1, 1, 1, 1]
  234. assert_(not np.all(y1))
  235. assert_(np.all(y3))
  236. assert_(not np.all(y2))
  237. assert_(np.all(~np.array(y2)))
  238. def test_nd(self):
  239. y1 = [[0, 0, 1], [0, 1, 1], [1, 1, 1]]
  240. assert_(not np.all(y1))
  241. assert_array_equal(np.all(y1, axis=0), [0, 0, 1])
  242. assert_array_equal(np.all(y1, axis=1), [0, 0, 1])
  243. @pytest.mark.parametrize("dtype", ["i8", "U10", "object", "datetime64[ms]"])
  244. def test_any_and_all_result_dtype(dtype):
  245. arr = np.ones(3, dtype=dtype)
  246. assert np.any(arr).dtype == np.bool
  247. assert np.all(arr).dtype == np.bool
  248. class TestCopy:
  249. def test_basic(self):
  250. a = np.array([[1, 2], [3, 4]])
  251. a_copy = np.copy(a)
  252. assert_array_equal(a, a_copy)
  253. a_copy[0, 0] = 10
  254. assert_equal(a[0, 0], 1)
  255. assert_equal(a_copy[0, 0], 10)
  256. def test_order(self):
  257. # It turns out that people rely on np.copy() preserving order by
  258. # default; changing this broke scikit-learn:
  259. # github.com/scikit-learn/scikit-learn/commit/7842748
  260. a = np.array([[1, 2], [3, 4]])
  261. assert_(a.flags.c_contiguous)
  262. assert_(not a.flags.f_contiguous)
  263. a_fort = np.array([[1, 2], [3, 4]], order="F")
  264. assert_(not a_fort.flags.c_contiguous)
  265. assert_(a_fort.flags.f_contiguous)
  266. a_copy = np.copy(a)
  267. assert_(a_copy.flags.c_contiguous)
  268. assert_(not a_copy.flags.f_contiguous)
  269. a_fort_copy = np.copy(a_fort)
  270. assert_(not a_fort_copy.flags.c_contiguous)
  271. assert_(a_fort_copy.flags.f_contiguous)
  272. def test_subok(self):
  273. mx = ma.ones(5)
  274. assert_(not ma.isMaskedArray(np.copy(mx, subok=False)))
  275. assert_(ma.isMaskedArray(np.copy(mx, subok=True)))
  276. # Default behavior
  277. assert_(not ma.isMaskedArray(np.copy(mx)))
  278. class TestAverage:
  279. def test_basic(self):
  280. y1 = np.array([1, 2, 3])
  281. assert_(average(y1, axis=0) == 2.)
  282. y2 = np.array([1., 2., 3.])
  283. assert_(average(y2, axis=0) == 2.)
  284. y3 = [0., 0., 0.]
  285. assert_(average(y3, axis=0) == 0.)
  286. y4 = np.ones((4, 4))
  287. y4[0, 1] = 0
  288. y4[1, 0] = 2
  289. assert_almost_equal(y4.mean(0), average(y4, 0))
  290. assert_almost_equal(y4.mean(1), average(y4, 1))
  291. y5 = rand(5, 5)
  292. assert_almost_equal(y5.mean(0), average(y5, 0))
  293. assert_almost_equal(y5.mean(1), average(y5, 1))
  294. @pytest.mark.parametrize(
  295. 'x, axis, expected_avg, weights, expected_wavg, expected_wsum',
  296. [([1, 2, 3], None, [2.0], [3, 4, 1], [1.75], [8.0]),
  297. ([[1, 2, 5], [1, 6, 11]], 0, [[1.0, 4.0, 8.0]],
  298. [1, 3], [[1.0, 5.0, 9.5]], [[4, 4, 4]])],
  299. )
  300. def test_basic_keepdims(self, x, axis, expected_avg,
  301. weights, expected_wavg, expected_wsum):
  302. avg = np.average(x, axis=axis, keepdims=True)
  303. assert avg.shape == np.shape(expected_avg)
  304. assert_array_equal(avg, expected_avg)
  305. wavg = np.average(x, axis=axis, weights=weights, keepdims=True)
  306. assert wavg.shape == np.shape(expected_wavg)
  307. assert_array_equal(wavg, expected_wavg)
  308. wavg, wsum = np.average(x, axis=axis, weights=weights, returned=True,
  309. keepdims=True)
  310. assert wavg.shape == np.shape(expected_wavg)
  311. assert_array_equal(wavg, expected_wavg)
  312. assert wsum.shape == np.shape(expected_wsum)
  313. assert_array_equal(wsum, expected_wsum)
  314. def test_weights(self):
  315. y = np.arange(10)
  316. w = np.arange(10)
  317. actual = average(y, weights=w)
  318. desired = (np.arange(10) ** 2).sum() * 1. / np.arange(10).sum()
  319. assert_almost_equal(actual, desired)
  320. y1 = np.array([[1, 2, 3], [4, 5, 6]])
  321. w0 = [1, 2]
  322. actual = average(y1, weights=w0, axis=0)
  323. desired = np.array([3., 4., 5.])
  324. assert_almost_equal(actual, desired)
  325. w1 = [0, 0, 1]
  326. actual = average(y1, weights=w1, axis=1)
  327. desired = np.array([3., 6.])
  328. assert_almost_equal(actual, desired)
  329. # weights and input have different shapes but no axis is specified
  330. with pytest.raises(
  331. TypeError,
  332. match="Axis must be specified when shapes of a "
  333. "and weights differ"):
  334. average(y1, weights=w1)
  335. # 2D Case
  336. w2 = [[0, 0, 1], [0, 0, 2]]
  337. desired = np.array([3., 6.])
  338. assert_array_equal(average(y1, weights=w2, axis=1), desired)
  339. assert_equal(average(y1, weights=w2), 5.)
  340. y3 = rand(5).astype(np.float32)
  341. w3 = rand(5).astype(np.float64)
  342. assert_(np.average(y3, weights=w3).dtype == np.result_type(y3, w3))
  343. # test weights with `keepdims=False` and `keepdims=True`
  344. x = np.array([2, 3, 4]).reshape(3, 1)
  345. w = np.array([4, 5, 6]).reshape(3, 1)
  346. actual = np.average(x, weights=w, axis=1, keepdims=False)
  347. desired = np.array([2., 3., 4.])
  348. assert_array_equal(actual, desired)
  349. actual = np.average(x, weights=w, axis=1, keepdims=True)
  350. desired = np.array([[2.], [3.], [4.]])
  351. assert_array_equal(actual, desired)
  352. def test_weight_and_input_dims_different(self):
  353. y = np.arange(12).reshape(2, 2, 3)
  354. w = np.array([0., 0., 1., .5, .5, 0., 0., .5, .5, 1., 0., 0.])\
  355. .reshape(2, 2, 3)
  356. subw0 = w[:, :, 0]
  357. actual = average(y, axis=(0, 1), weights=subw0)
  358. desired = np.array([7., 8., 9.])
  359. assert_almost_equal(actual, desired)
  360. subw1 = w[1, :, :]
  361. actual = average(y, axis=(1, 2), weights=subw1)
  362. desired = np.array([2.25, 8.25])
  363. assert_almost_equal(actual, desired)
  364. subw2 = w[:, 0, :]
  365. actual = average(y, axis=(0, 2), weights=subw2)
  366. desired = np.array([4.75, 7.75])
  367. assert_almost_equal(actual, desired)
  368. # here the weights have the wrong shape for the specified axes
  369. with pytest.raises(
  370. ValueError,
  371. match="Shape of weights must be consistent with "
  372. "shape of a along specified axis"):
  373. average(y, axis=(0, 1, 2), weights=subw0)
  374. with pytest.raises(
  375. ValueError,
  376. match="Shape of weights must be consistent with "
  377. "shape of a along specified axis"):
  378. average(y, axis=(0, 1), weights=subw1)
  379. # swapping the axes should be same as transposing weights
  380. actual = average(y, axis=(1, 0), weights=subw0)
  381. desired = average(y, axis=(0, 1), weights=subw0.T)
  382. assert_almost_equal(actual, desired)
  383. # if average over all axes, should have float output
  384. actual = average(y, axis=(0, 1, 2), weights=w)
  385. assert_(actual.ndim == 0)
  386. def test_returned(self):
  387. y = np.array([[1, 2, 3], [4, 5, 6]])
  388. # No weights
  389. avg, scl = average(y, returned=True)
  390. assert_equal(scl, 6.)
  391. avg, scl = average(y, 0, returned=True)
  392. assert_array_equal(scl, np.array([2., 2., 2.]))
  393. avg, scl = average(y, 1, returned=True)
  394. assert_array_equal(scl, np.array([3., 3.]))
  395. # With weights
  396. w0 = [1, 2]
  397. avg, scl = average(y, weights=w0, axis=0, returned=True)
  398. assert_array_equal(scl, np.array([3., 3., 3.]))
  399. w1 = [1, 2, 3]
  400. avg, scl = average(y, weights=w1, axis=1, returned=True)
  401. assert_array_equal(scl, np.array([6., 6.]))
  402. w2 = [[0, 0, 1], [1, 2, 3]]
  403. avg, scl = average(y, weights=w2, axis=1, returned=True)
  404. assert_array_equal(scl, np.array([1., 6.]))
  405. def test_subclasses(self):
  406. class subclass(np.ndarray):
  407. pass
  408. a = np.array([[1, 2], [3, 4]]).view(subclass)
  409. w = np.array([[1, 2], [3, 4]]).view(subclass)
  410. assert_equal(type(np.average(a)), subclass)
  411. assert_equal(type(np.average(a, weights=w)), subclass)
  412. # Ensure a possibly returned sum of weights is correct too.
  413. ra, rw = np.average(a, weights=w, returned=True)
  414. assert_equal(type(ra), subclass)
  415. assert_equal(type(rw), subclass)
  416. # Even if it needs to be broadcast.
  417. ra, rw = np.average(a, weights=w[0], axis=1, returned=True)
  418. assert_equal(type(ra), subclass)
  419. assert_equal(type(rw), subclass)
  420. def test_upcasting(self):
  421. typs = [('i4', 'i4', 'f8'), ('i4', 'f4', 'f8'), ('f4', 'i4', 'f8'),
  422. ('f4', 'f4', 'f4'), ('f4', 'f8', 'f8')]
  423. for at, wt, rt in typs:
  424. a = np.array([[1, 2], [3, 4]], dtype=at)
  425. w = np.array([[1, 2], [3, 4]], dtype=wt)
  426. assert_equal(np.average(a, weights=w).dtype, np.dtype(rt))
  427. def test_object_dtype(self):
  428. a = np.array([decimal.Decimal(x) for x in range(10)])
  429. w = np.array([decimal.Decimal(1) for _ in range(10)])
  430. w /= w.sum()
  431. assert_almost_equal(a.mean(0), average(a, weights=w))
  432. def test_object_no_weights(self):
  433. a = np.array([decimal.Decimal(x) for x in range(10)])
  434. m = average(a)
  435. assert m == decimal.Decimal('4.5')
  436. def test_average_class_without_dtype(self):
  437. # see gh-21988
  438. a = np.array([Fraction(1, 5), Fraction(3, 5)])
  439. assert_equal(np.average(a), Fraction(2, 5))
  440. class TestSelect:
  441. choices = [np.array([1, 2, 3]),
  442. np.array([4, 5, 6]),
  443. np.array([7, 8, 9])]
  444. conditions = [np.array([False, False, False]),
  445. np.array([False, True, False]),
  446. np.array([False, False, True])]
  447. def _select(self, cond, values, default=0):
  448. output = []
  449. for m in range(len(cond)):
  450. output += [V[m] for V, C in zip(values, cond) if C[m]] or [default]
  451. return output
  452. def test_basic(self):
  453. choices = self.choices
  454. conditions = self.conditions
  455. assert_array_equal(select(conditions, choices, default=15),
  456. self._select(conditions, choices, default=15))
  457. assert_equal(len(choices), 3)
  458. assert_equal(len(conditions), 3)
  459. def test_broadcasting(self):
  460. conditions = [np.array(True), np.array([False, True, False])]
  461. choices = [1, np.arange(12).reshape(4, 3)]
  462. assert_array_equal(select(conditions, choices), np.ones((4, 3)))
  463. # default can broadcast too:
  464. assert_equal(select([True], [0], default=[0]).shape, (1,))
  465. def test_return_dtype(self):
  466. assert_equal(select(self.conditions, self.choices, 1j).dtype,
  467. np.complex128)
  468. # But the conditions need to be stronger then the scalar default
  469. # if it is scalar.
  470. choices = [choice.astype(np.int8) for choice in self.choices]
  471. assert_equal(select(self.conditions, choices).dtype, np.int8)
  472. d = np.array([1, 2, 3, np.nan, 5, 7])
  473. m = np.isnan(d)
  474. assert_equal(select([m], [d]), [0, 0, 0, np.nan, 0, 0])
  475. def test_non_bool_deprecation(self):
  476. choices = self.choices
  477. conditions = self.conditions[:]
  478. conditions[0] = conditions[0].astype(np.int_)
  479. assert_raises(TypeError, select, conditions, choices)
  480. conditions[0] = conditions[0].astype(np.uint8)
  481. assert_raises(TypeError, select, conditions, choices)
  482. assert_raises(TypeError, select, conditions, choices)
  483. def test_many_arguments(self):
  484. # This used to be limited by NPY_MAXARGS == 32
  485. conditions = [np.array([False])] * 100
  486. choices = [np.array([1])] * 100
  487. select(conditions, choices)
  488. class TestInsert:
  489. def test_basic(self):
  490. a = [1, 2, 3]
  491. assert_equal(insert(a, 0, 1), [1, 1, 2, 3])
  492. assert_equal(insert(a, 3, 1), [1, 2, 3, 1])
  493. assert_equal(insert(a, [1, 1, 1], [1, 2, 3]), [1, 1, 2, 3, 2, 3])
  494. assert_equal(insert(a, 1, [1, 2, 3]), [1, 1, 2, 3, 2, 3])
  495. assert_equal(insert(a, [1, -1, 3], 9), [1, 9, 2, 9, 3, 9])
  496. assert_equal(insert(a, slice(-1, None, -1), 9), [9, 1, 9, 2, 9, 3])
  497. assert_equal(insert(a, [-1, 1, 3], [7, 8, 9]), [1, 8, 2, 7, 3, 9])
  498. b = np.array([0, 1], dtype=np.float64)
  499. assert_equal(insert(b, 0, b[0]), [0., 0., 1.])
  500. assert_equal(insert(b, [], []), b)
  501. assert_equal(insert(a, np.array([True] * 4), 9), [9, 1, 9, 2, 9, 3, 9])
  502. assert_equal(insert(a, np.array([True, False, True, False]), 9),
  503. [9, 1, 2, 9, 3])
  504. def test_multidim(self):
  505. a = [[1, 1, 1]]
  506. r = [[2, 2, 2],
  507. [1, 1, 1]]
  508. assert_equal(insert(a, 0, [1]), [1, 1, 1, 1])
  509. assert_equal(insert(a, 0, [2, 2, 2], axis=0), r)
  510. assert_equal(insert(a, 0, 2, axis=0), r)
  511. assert_equal(insert(a, 2, 2, axis=1), [[1, 1, 2, 1]])
  512. a = np.array([[1, 1], [2, 2], [3, 3]])
  513. b = np.arange(1, 4).repeat(3).reshape(3, 3)
  514. c = np.concatenate(
  515. (a[:, 0:1], np.arange(1, 4).repeat(3).reshape(3, 3).T,
  516. a[:, 1:2]), axis=1)
  517. assert_equal(insert(a, [1], [[1], [2], [3]], axis=1), b)
  518. assert_equal(insert(a, [1], [1, 2, 3], axis=1), c)
  519. # scalars behave differently, in this case exactly opposite:
  520. assert_equal(insert(a, 1, [1, 2, 3], axis=1), b)
  521. assert_equal(insert(a, 1, [[1], [2], [3]], axis=1), c)
  522. a = np.arange(4).reshape(2, 2)
  523. assert_equal(insert(a[:, :1], 1, a[:, 1], axis=1), a)
  524. assert_equal(insert(a[:1, :], 1, a[1, :], axis=0), a)
  525. # negative axis value
  526. a = np.arange(24).reshape((2, 3, 4))
  527. assert_equal(insert(a, 1, a[:, :, 3], axis=-1),
  528. insert(a, 1, a[:, :, 3], axis=2))
  529. assert_equal(insert(a, 1, a[:, 2, :], axis=-2),
  530. insert(a, 1, a[:, 2, :], axis=1))
  531. # invalid axis value
  532. assert_raises(AxisError, insert, a, 1, a[:, 2, :], axis=3)
  533. assert_raises(AxisError, insert, a, 1, a[:, 2, :], axis=-4)
  534. # negative axis value
  535. a = np.arange(24).reshape((2, 3, 4))
  536. assert_equal(insert(a, 1, a[:, :, 3], axis=-1),
  537. insert(a, 1, a[:, :, 3], axis=2))
  538. assert_equal(insert(a, 1, a[:, 2, :], axis=-2),
  539. insert(a, 1, a[:, 2, :], axis=1))
  540. def test_0d(self):
  541. a = np.array(1)
  542. with pytest.raises(AxisError):
  543. insert(a, [], 2, axis=0)
  544. with pytest.raises(TypeError):
  545. insert(a, [], 2, axis="nonsense")
  546. def test_subclass(self):
  547. class SubClass(np.ndarray):
  548. pass
  549. a = np.arange(10).view(SubClass)
  550. assert_(isinstance(np.insert(a, 0, [0]), SubClass))
  551. assert_(isinstance(np.insert(a, [], []), SubClass))
  552. assert_(isinstance(np.insert(a, [0, 1], [1, 2]), SubClass))
  553. assert_(isinstance(np.insert(a, slice(1, 2), [1, 2]), SubClass))
  554. assert_(isinstance(np.insert(a, slice(1, -2, -1), []), SubClass))
  555. # This is an error in the future:
  556. a = np.array(1).view(SubClass)
  557. assert_(isinstance(np.insert(a, 0, [0]), SubClass))
  558. def test_index_array_copied(self):
  559. x = np.array([1, 1, 1])
  560. np.insert([0, 1, 2], x, [3, 4, 5])
  561. assert_equal(x, np.array([1, 1, 1]))
  562. def test_structured_array(self):
  563. a = np.array([(1, 'a'), (2, 'b'), (3, 'c')],
  564. dtype=[('foo', 'i'), ('bar', 'S1')])
  565. val = (4, 'd')
  566. b = np.insert(a, 0, val)
  567. assert_array_equal(b[0], np.array(val, dtype=b.dtype))
  568. val = [(4, 'd')] * 2
  569. b = np.insert(a, [0, 2], val)
  570. assert_array_equal(b[[0, 3]], np.array(val, dtype=b.dtype))
  571. def test_index_floats(self):
  572. with pytest.raises(IndexError):
  573. np.insert([0, 1, 2], np.array([1.0, 2.0]), [10, 20])
  574. with pytest.raises(IndexError):
  575. np.insert([0, 1, 2], np.array([], dtype=float), [])
  576. @pytest.mark.parametrize('idx', [4, -4])
  577. def test_index_out_of_bounds(self, idx):
  578. with pytest.raises(IndexError, match='out of bounds'):
  579. np.insert([0, 1, 2], [idx], [3, 4])
  580. class TestAmax:
  581. def test_basic(self):
  582. a = [3, 4, 5, 10, -3, -5, 6.0]
  583. assert_equal(np.amax(a), 10.0)
  584. b = [[3, 6.0, 9.0],
  585. [4, 10.0, 5.0],
  586. [8, 3.0, 2.0]]
  587. assert_equal(np.amax(b, axis=0), [8.0, 10.0, 9.0])
  588. assert_equal(np.amax(b, axis=1), [9.0, 10.0, 8.0])
  589. class TestAmin:
  590. def test_basic(self):
  591. a = [3, 4, 5, 10, -3, -5, 6.0]
  592. assert_equal(np.amin(a), -5.0)
  593. b = [[3, 6.0, 9.0],
  594. [4, 10.0, 5.0],
  595. [8, 3.0, 2.0]]
  596. assert_equal(np.amin(b, axis=0), [3.0, 3.0, 2.0])
  597. assert_equal(np.amin(b, axis=1), [3.0, 4.0, 2.0])
  598. class TestPtp:
  599. def test_basic(self):
  600. a = np.array([3, 4, 5, 10, -3, -5, 6.0])
  601. assert_equal(np.ptp(a, axis=0), 15.0)
  602. b = np.array([[3, 6.0, 9.0],
  603. [4, 10.0, 5.0],
  604. [8, 3.0, 2.0]])
  605. assert_equal(np.ptp(b, axis=0), [5.0, 7.0, 7.0])
  606. assert_equal(np.ptp(b, axis=-1), [6.0, 6.0, 6.0])
  607. assert_equal(np.ptp(b, axis=0, keepdims=True), [[5.0, 7.0, 7.0]])
  608. assert_equal(np.ptp(b, axis=(0, 1), keepdims=True), [[8.0]])
  609. class TestCumsum:
  610. @pytest.mark.parametrize("cumsum", [np.cumsum, np.cumulative_sum])
  611. def test_basic(self, cumsum):
  612. ba = [1, 2, 10, 11, 6, 5, 4]
  613. ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
  614. for ctype in [np.int8, np.uint8, np.int16, np.uint16, np.int32,
  615. np.uint32, np.float32, np.float64, np.complex64,
  616. np.complex128]:
  617. a = np.array(ba, ctype)
  618. a2 = np.array(ba2, ctype)
  619. tgt = np.array([1, 3, 13, 24, 30, 35, 39], ctype)
  620. assert_array_equal(cumsum(a, axis=0), tgt)
  621. tgt = np.array(
  622. [[1, 2, 3, 4], [6, 8, 10, 13], [16, 11, 14, 18]], ctype)
  623. assert_array_equal(cumsum(a2, axis=0), tgt)
  624. tgt = np.array(
  625. [[1, 3, 6, 10], [5, 11, 18, 27], [10, 13, 17, 22]], ctype)
  626. assert_array_equal(cumsum(a2, axis=1), tgt)
  627. class TestProd:
  628. def test_basic(self):
  629. ba = [1, 2, 10, 11, 6, 5, 4]
  630. ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
  631. for ctype in [np.int16, np.uint16, np.int32, np.uint32,
  632. np.float32, np.float64, np.complex64, np.complex128]:
  633. a = np.array(ba, ctype)
  634. a2 = np.array(ba2, ctype)
  635. if ctype in ['1', 'b']:
  636. assert_raises(ArithmeticError, np.prod, a)
  637. assert_raises(ArithmeticError, np.prod, a2, 1)
  638. else:
  639. assert_equal(a.prod(axis=0), 26400)
  640. assert_array_equal(a2.prod(axis=0),
  641. np.array([50, 36, 84, 180], ctype))
  642. assert_array_equal(a2.prod(axis=-1),
  643. np.array([24, 1890, 600], ctype))
  644. class TestCumprod:
  645. @pytest.mark.parametrize("cumprod", [np.cumprod, np.cumulative_prod])
  646. def test_basic(self, cumprod):
  647. ba = [1, 2, 10, 11, 6, 5, 4]
  648. ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
  649. for ctype in [np.int16, np.uint16, np.int32, np.uint32,
  650. np.float32, np.float64, np.complex64, np.complex128]:
  651. a = np.array(ba, ctype)
  652. a2 = np.array(ba2, ctype)
  653. if ctype in ['1', 'b']:
  654. assert_raises(ArithmeticError, cumprod, a)
  655. assert_raises(ArithmeticError, cumprod, a2, 1)
  656. assert_raises(ArithmeticError, cumprod, a)
  657. else:
  658. assert_array_equal(cumprod(a, axis=-1),
  659. np.array([1, 2, 20, 220,
  660. 1320, 6600, 26400], ctype))
  661. assert_array_equal(cumprod(a2, axis=0),
  662. np.array([[1, 2, 3, 4],
  663. [5, 12, 21, 36],
  664. [50, 36, 84, 180]], ctype))
  665. assert_array_equal(cumprod(a2, axis=-1),
  666. np.array([[1, 2, 6, 24],
  667. [5, 30, 210, 1890],
  668. [10, 30, 120, 600]], ctype))
  669. def test_cumulative_include_initial():
  670. arr = np.arange(8).reshape((2, 2, 2))
  671. expected = np.array([
  672. [[0, 0], [0, 1], [2, 4]], [[0, 0], [4, 5], [10, 12]]
  673. ])
  674. assert_array_equal(
  675. np.cumulative_sum(arr, axis=1, include_initial=True), expected
  676. )
  677. expected = np.array([
  678. [[1, 0, 0], [1, 2, 6]], [[1, 4, 20], [1, 6, 42]]
  679. ])
  680. assert_array_equal(
  681. np.cumulative_prod(arr, axis=2, include_initial=True), expected
  682. )
  683. out = np.zeros((3, 2), dtype=np.float64)
  684. expected = np.array([[0, 0], [1, 2], [4, 6]], dtype=np.float64)
  685. arr = np.arange(1, 5).reshape((2, 2))
  686. np.cumulative_sum(arr, axis=0, out=out, include_initial=True)
  687. assert_array_equal(out, expected)
  688. expected = np.array([1, 2, 4])
  689. assert_array_equal(
  690. np.cumulative_prod(np.array([2, 2]), include_initial=True), expected
  691. )
  692. class TestDiff:
  693. def test_basic(self):
  694. x = [1, 4, 6, 7, 12]
  695. out = np.array([3, 2, 1, 5])
  696. out2 = np.array([-1, -1, 4])
  697. out3 = np.array([0, 5])
  698. assert_array_equal(diff(x), out)
  699. assert_array_equal(diff(x, n=2), out2)
  700. assert_array_equal(diff(x, n=3), out3)
  701. x = [1.1, 2.2, 3.0, -0.2, -0.1]
  702. out = np.array([1.1, 0.8, -3.2, 0.1])
  703. assert_almost_equal(diff(x), out)
  704. x = [True, True, False, False]
  705. out = np.array([False, True, False])
  706. out2 = np.array([True, True])
  707. assert_array_equal(diff(x), out)
  708. assert_array_equal(diff(x, n=2), out2)
  709. def test_axis(self):
  710. x = np.zeros((10, 20, 30))
  711. x[:, 1::2, :] = 1
  712. exp = np.ones((10, 19, 30))
  713. exp[:, 1::2, :] = -1
  714. assert_array_equal(diff(x), np.zeros((10, 20, 29)))
  715. assert_array_equal(diff(x, axis=-1), np.zeros((10, 20, 29)))
  716. assert_array_equal(diff(x, axis=0), np.zeros((9, 20, 30)))
  717. assert_array_equal(diff(x, axis=1), exp)
  718. assert_array_equal(diff(x, axis=-2), exp)
  719. assert_raises(AxisError, diff, x, axis=3)
  720. assert_raises(AxisError, diff, x, axis=-4)
  721. x = np.array(1.11111111111, np.float64)
  722. assert_raises(ValueError, diff, x)
  723. def test_nd(self):
  724. x = 20 * rand(10, 20, 30)
  725. out1 = x[:, :, 1:] - x[:, :, :-1]
  726. out2 = out1[:, :, 1:] - out1[:, :, :-1]
  727. out3 = x[1:, :, :] - x[:-1, :, :]
  728. out4 = out3[1:, :, :] - out3[:-1, :, :]
  729. assert_array_equal(diff(x), out1)
  730. assert_array_equal(diff(x, n=2), out2)
  731. assert_array_equal(diff(x, axis=0), out3)
  732. assert_array_equal(diff(x, n=2, axis=0), out4)
  733. def test_n(self):
  734. x = list(range(3))
  735. assert_raises(ValueError, diff, x, n=-1)
  736. output = [diff(x, n=n) for n in range(1, 5)]
  737. expected = [[1, 1], [0], [], []]
  738. assert_(diff(x, n=0) is x)
  739. for n, (expected_n, output_n) in enumerate(zip(expected, output), start=1):
  740. assert_(type(output_n) is np.ndarray)
  741. assert_array_equal(output_n, expected_n)
  742. assert_equal(output_n.dtype, np.int_)
  743. assert_equal(len(output_n), max(0, len(x) - n))
  744. def test_times(self):
  745. x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
  746. expected = [
  747. np.array([1, 1], dtype='timedelta64[D]'),
  748. np.array([0], dtype='timedelta64[D]'),
  749. ]
  750. expected.extend([np.array([], dtype='timedelta64[D]')] * 3)
  751. for n, exp in enumerate(expected, start=1):
  752. out = diff(x, n=n)
  753. assert_array_equal(out, exp)
  754. assert_equal(out.dtype, exp.dtype)
  755. def test_subclass(self):
  756. x = ma.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]],
  757. mask=[[False, False], [True, False],
  758. [False, True], [True, True], [False, False]])
  759. out = diff(x)
  760. assert_array_equal(out.data, [[1], [1], [1], [1], [1]])
  761. assert_array_equal(out.mask, [[False], [True],
  762. [True], [True], [False]])
  763. assert_(type(out) is type(x))
  764. out3 = diff(x, n=3)
  765. assert_array_equal(out3.data, [[], [], [], [], []])
  766. assert_array_equal(out3.mask, [[], [], [], [], []])
  767. assert_(type(out3) is type(x))
  768. def test_prepend(self):
  769. x = np.arange(5) + 1
  770. assert_array_equal(diff(x, prepend=0), np.ones(5))
  771. assert_array_equal(diff(x, prepend=[0]), np.ones(5))
  772. assert_array_equal(np.cumsum(np.diff(x, prepend=0)), x)
  773. assert_array_equal(diff(x, prepend=[-1, 0]), np.ones(6))
  774. x = np.arange(4).reshape(2, 2)
  775. result = np.diff(x, axis=1, prepend=0)
  776. expected = [[0, 1], [2, 1]]
  777. assert_array_equal(result, expected)
  778. result = np.diff(x, axis=1, prepend=[[0], [0]])
  779. assert_array_equal(result, expected)
  780. result = np.diff(x, axis=0, prepend=0)
  781. expected = [[0, 1], [2, 2]]
  782. assert_array_equal(result, expected)
  783. result = np.diff(x, axis=0, prepend=[[0, 0]])
  784. assert_array_equal(result, expected)
  785. assert_raises(ValueError, np.diff, x, prepend=np.zeros((3, 3)))
  786. assert_raises(AxisError, diff, x, prepend=0, axis=3)
  787. def test_append(self):
  788. x = np.arange(5)
  789. result = diff(x, append=0)
  790. expected = [1, 1, 1, 1, -4]
  791. assert_array_equal(result, expected)
  792. result = diff(x, append=[0])
  793. assert_array_equal(result, expected)
  794. result = diff(x, append=[0, 2])
  795. expected = expected + [2]
  796. assert_array_equal(result, expected)
  797. x = np.arange(4).reshape(2, 2)
  798. result = np.diff(x, axis=1, append=0)
  799. expected = [[1, -1], [1, -3]]
  800. assert_array_equal(result, expected)
  801. result = np.diff(x, axis=1, append=[[0], [0]])
  802. assert_array_equal(result, expected)
  803. result = np.diff(x, axis=0, append=0)
  804. expected = [[2, 2], [-2, -3]]
  805. assert_array_equal(result, expected)
  806. result = np.diff(x, axis=0, append=[[0, 0]])
  807. assert_array_equal(result, expected)
  808. assert_raises(ValueError, np.diff, x, append=np.zeros((3, 3)))
  809. assert_raises(AxisError, diff, x, append=0, axis=3)
  810. class TestDelete:
  811. def _create_arrays(self):
  812. a = np.arange(5)
  813. nd_a = np.arange(5).repeat(2).reshape(1, 5, 2)
  814. return a, nd_a
  815. def _check_inverse_of_slicing(self, indices):
  816. a, nd_a = self._create_arrays()
  817. a_del = delete(a, indices)
  818. nd_a_del = delete(nd_a, indices, axis=1)
  819. msg = f'Delete failed for obj: {indices!r}'
  820. assert_array_equal(setxor1d(a_del, a[indices, ]), a,
  821. err_msg=msg)
  822. xor = setxor1d(nd_a_del[0, :, 0], nd_a[0, indices, 0])
  823. assert_array_equal(xor, nd_a[0, :, 0], err_msg=msg)
  824. def test_slices(self):
  825. lims = [-6, -2, 0, 1, 2, 4, 5]
  826. steps = [-3, -1, 1, 3]
  827. for start in lims:
  828. for stop in lims:
  829. for step in steps:
  830. s = slice(start, stop, step)
  831. self._check_inverse_of_slicing(s)
  832. def test_fancy(self):
  833. a, _ = self._create_arrays()
  834. self._check_inverse_of_slicing(np.array([[0, 1], [2, 1]]))
  835. with pytest.raises(IndexError):
  836. delete(a, [100])
  837. with pytest.raises(IndexError):
  838. delete(a, [-100])
  839. self._check_inverse_of_slicing([0, -1, 2, 2])
  840. self._check_inverse_of_slicing([True, False, False, True, False])
  841. # not legal, indexing with these would change the dimension
  842. with pytest.raises(ValueError):
  843. delete(a, True)
  844. with pytest.raises(ValueError):
  845. delete(a, False)
  846. # not enough items
  847. with pytest.raises(ValueError):
  848. delete(a, [False] * 4)
  849. def test_single(self):
  850. self._check_inverse_of_slicing(0)
  851. self._check_inverse_of_slicing(-4)
  852. def test_0d(self):
  853. a = np.array(1)
  854. with pytest.raises(AxisError):
  855. delete(a, [], axis=0)
  856. with pytest.raises(TypeError):
  857. delete(a, [], axis="nonsense")
  858. def test_subclass(self):
  859. class SubClass(np.ndarray):
  860. pass
  861. a_orig, _ = self._create_arrays()
  862. a = a_orig.view(SubClass)
  863. assert_(isinstance(delete(a, 0), SubClass))
  864. assert_(isinstance(delete(a, []), SubClass))
  865. assert_(isinstance(delete(a, [0, 1]), SubClass))
  866. assert_(isinstance(delete(a, slice(1, 2)), SubClass))
  867. assert_(isinstance(delete(a, slice(1, -2)), SubClass))
  868. def test_array_order_preserve(self):
  869. # See gh-7113
  870. k = np.arange(10).reshape(2, 5, order='F')
  871. m = delete(k, slice(60, None), axis=1)
  872. # 'k' is Fortran ordered, and 'm' should have the
  873. # same ordering as 'k' and NOT become C ordered
  874. assert_equal(m.flags.c_contiguous, k.flags.c_contiguous)
  875. assert_equal(m.flags.f_contiguous, k.flags.f_contiguous)
  876. def test_index_floats(self):
  877. with pytest.raises(IndexError):
  878. np.delete([0, 1, 2], np.array([1.0, 2.0]))
  879. with pytest.raises(IndexError):
  880. np.delete([0, 1, 2], np.array([], dtype=float))
  881. @pytest.mark.parametrize("indexer", [np.array([1]), [1]])
  882. def test_single_item_array(self, indexer):
  883. a, nd_a = self._create_arrays()
  884. a_del_int = delete(a, 1)
  885. a_del = delete(a, indexer)
  886. assert_equal(a_del_int, a_del)
  887. nd_a_del_int = delete(nd_a, 1, axis=1)
  888. nd_a_del = delete(nd_a, np.array([1]), axis=1)
  889. assert_equal(nd_a_del_int, nd_a_del)
  890. def test_single_item_array_non_int(self):
  891. # Special handling for integer arrays must not affect non-integer ones.
  892. # If `False` was cast to `0` it would delete the element:
  893. res = delete(np.ones(1), np.array([False]))
  894. assert_array_equal(res, np.ones(1))
  895. # Test the more complicated (with axis) case from gh-21840
  896. x = np.ones((3, 1))
  897. false_mask = np.array([False], dtype=bool)
  898. true_mask = np.array([True], dtype=bool)
  899. res = delete(x, false_mask, axis=-1)
  900. assert_array_equal(res, x)
  901. res = delete(x, true_mask, axis=-1)
  902. assert_array_equal(res, x[:, :0])
  903. # Object or e.g. timedeltas should *not* be allowed
  904. with pytest.raises(IndexError):
  905. delete(np.ones(2), np.array([0], dtype=object))
  906. with pytest.raises(IndexError):
  907. # timedeltas are sometimes "integral, but clearly not allowed:
  908. delete(np.ones(2), np.array([0], dtype="m8[ns]"))
  909. class TestGradient:
  910. def test_basic(self):
  911. v = [[1, 1], [3, 4]]
  912. x = np.array(v)
  913. dx = [np.array([[2., 3.], [2., 3.]]),
  914. np.array([[0., 0.], [1., 1.]])]
  915. assert_array_equal(gradient(x), dx)
  916. assert_array_equal(gradient(v), dx)
  917. def test_args(self):
  918. dx = np.cumsum(np.ones(5))
  919. dx_uneven = [1., 2., 5., 9., 11.]
  920. f_2d = np.arange(25).reshape(5, 5)
  921. # distances must be scalars or have size equal to gradient[axis]
  922. gradient(np.arange(5), 3.)
  923. gradient(np.arange(5), np.array(3.))
  924. gradient(np.arange(5), dx)
  925. # dy is set equal to dx because scalar
  926. gradient(f_2d, 1.5)
  927. gradient(f_2d, np.array(1.5))
  928. gradient(f_2d, dx_uneven, dx_uneven)
  929. # mix between even and uneven spaces and
  930. # mix between scalar and vector
  931. gradient(f_2d, dx, 2)
  932. # 2D but axis specified
  933. gradient(f_2d, dx, axis=1)
  934. # 2d coordinate arguments are not yet allowed
  935. assert_raises_regex(ValueError, '.*scalars or 1d',
  936. gradient, f_2d, np.stack([dx] * 2, axis=-1), 1)
  937. def test_badargs(self):
  938. f_2d = np.arange(25).reshape(5, 5)
  939. x = np.cumsum(np.ones(5))
  940. # wrong sizes
  941. assert_raises(ValueError, gradient, f_2d, x, np.ones(2))
  942. assert_raises(ValueError, gradient, f_2d, 1, np.ones(2))
  943. assert_raises(ValueError, gradient, f_2d, np.ones(2), np.ones(2))
  944. # wrong number of arguments
  945. assert_raises(TypeError, gradient, f_2d, x)
  946. assert_raises(TypeError, gradient, f_2d, x, axis=(0, 1))
  947. assert_raises(TypeError, gradient, f_2d, x, x, x)
  948. assert_raises(TypeError, gradient, f_2d, 1, 1, 1)
  949. assert_raises(TypeError, gradient, f_2d, x, x, axis=1)
  950. assert_raises(TypeError, gradient, f_2d, 1, 1, axis=1)
  951. def test_datetime64(self):
  952. # Make sure gradient() can handle special types like datetime64
  953. x = np.array(
  954. ['1910-08-16', '1910-08-11', '1910-08-10', '1910-08-12',
  955. '1910-10-12', '1910-12-12', '1912-12-12'],
  956. dtype='datetime64[D]')
  957. dx = np.array(
  958. [-5, -3, 0, 31, 61, 396, 731],
  959. dtype='timedelta64[D]')
  960. assert_array_equal(gradient(x), dx)
  961. assert_(dx.dtype == np.dtype('timedelta64[D]'))
  962. def test_masked(self):
  963. # Make sure that gradient supports subclasses like masked arrays
  964. x = np.ma.array([[1, 1], [3, 4]],
  965. mask=[[False, False], [False, False]])
  966. out = gradient(x)[0]
  967. assert_equal(type(out), type(x))
  968. # And make sure that the output and input don't have aliased mask
  969. # arrays
  970. assert_(x._mask is not out._mask)
  971. # Also check that edge_order=2 doesn't alter the original mask
  972. x2 = np.ma.arange(5)
  973. x2[2] = np.ma.masked
  974. np.gradient(x2, edge_order=2)
  975. assert_array_equal(x2.mask, [False, False, True, False, False])
  976. def test_second_order_accurate(self):
  977. # Testing that the relative numerical error is less that 3% for
  978. # this example problem. This corresponds to second order
  979. # accurate finite differences for all interior and boundary
  980. # points.
  981. x = np.linspace(0, 1, 10)
  982. dx = x[1] - x[0]
  983. y = 2 * x ** 3 + 4 * x ** 2 + 2 * x
  984. analytical = 6 * x ** 2 + 8 * x + 2
  985. num_error = np.abs((np.gradient(y, dx, edge_order=2) / analytical) - 1)
  986. assert_(np.all(num_error < 0.03) == True)
  987. # test with unevenly spaced
  988. rng = np.random.default_rng(0)
  989. x = np.sort(rng.random(10))
  990. y = 2 * x ** 3 + 4 * x ** 2 + 2 * x
  991. analytical = 6 * x ** 2 + 8 * x + 2
  992. num_error = np.abs((np.gradient(y, x, edge_order=2) / analytical) - 1)
  993. assert_(np.all(num_error < 0.03) == True)
  994. def test_spacing(self):
  995. f = np.array([0, 2., 3., 4., 5., 5.])
  996. f = np.tile(f, (6, 1)) + f.reshape(-1, 1)
  997. x_uneven = np.array([0., 0.5, 1., 3., 5., 7.])
  998. x_even = np.arange(6.)
  999. fdx_even_ord1 = np.tile([2., 1.5, 1., 1., 0.5, 0.], (6, 1))
  1000. fdx_even_ord2 = np.tile([2.5, 1.5, 1., 1., 0.5, -0.5], (6, 1))
  1001. fdx_uneven_ord1 = np.tile([4., 3., 1.7, 0.5, 0.25, 0.], (6, 1))
  1002. fdx_uneven_ord2 = np.tile([5., 3., 1.7, 0.5, 0.25, -0.25], (6, 1))
  1003. # evenly spaced
  1004. for edge_order, exp_res in [(1, fdx_even_ord1), (2, fdx_even_ord2)]:
  1005. res1 = gradient(f, 1., axis=(0, 1), edge_order=edge_order)
  1006. res2 = gradient(f, x_even, x_even,
  1007. axis=(0, 1), edge_order=edge_order)
  1008. res3 = gradient(f, x_even, x_even,
  1009. axis=None, edge_order=edge_order)
  1010. assert_array_equal(res1, res2)
  1011. assert_array_equal(res2, res3)
  1012. assert_almost_equal(res1[0], exp_res.T)
  1013. assert_almost_equal(res1[1], exp_res)
  1014. res1 = gradient(f, 1., axis=0, edge_order=edge_order)
  1015. res2 = gradient(f, x_even, axis=0, edge_order=edge_order)
  1016. assert_(res1.shape == res2.shape)
  1017. assert_almost_equal(res2, exp_res.T)
  1018. res1 = gradient(f, 1., axis=1, edge_order=edge_order)
  1019. res2 = gradient(f, x_even, axis=1, edge_order=edge_order)
  1020. assert_(res1.shape == res2.shape)
  1021. assert_array_equal(res2, exp_res)
  1022. # unevenly spaced
  1023. for edge_order, exp_res in [(1, fdx_uneven_ord1), (2, fdx_uneven_ord2)]:
  1024. res1 = gradient(f, x_uneven, x_uneven,
  1025. axis=(0, 1), edge_order=edge_order)
  1026. res2 = gradient(f, x_uneven, x_uneven,
  1027. axis=None, edge_order=edge_order)
  1028. assert_array_equal(res1, res2)
  1029. assert_almost_equal(res1[0], exp_res.T)
  1030. assert_almost_equal(res1[1], exp_res)
  1031. res1 = gradient(f, x_uneven, axis=0, edge_order=edge_order)
  1032. assert_almost_equal(res1, exp_res.T)
  1033. res1 = gradient(f, x_uneven, axis=1, edge_order=edge_order)
  1034. assert_almost_equal(res1, exp_res)
  1035. # mixed
  1036. res1 = gradient(f, x_even, x_uneven, axis=(0, 1), edge_order=1)
  1037. res2 = gradient(f, x_uneven, x_even, axis=(1, 0), edge_order=1)
  1038. assert_array_equal(res1[0], res2[1])
  1039. assert_array_equal(res1[1], res2[0])
  1040. assert_almost_equal(res1[0], fdx_even_ord1.T)
  1041. assert_almost_equal(res1[1], fdx_uneven_ord1)
  1042. res1 = gradient(f, x_even, x_uneven, axis=(0, 1), edge_order=2)
  1043. res2 = gradient(f, x_uneven, x_even, axis=(1, 0), edge_order=2)
  1044. assert_array_equal(res1[0], res2[1])
  1045. assert_array_equal(res1[1], res2[0])
  1046. assert_almost_equal(res1[0], fdx_even_ord2.T)
  1047. assert_almost_equal(res1[1], fdx_uneven_ord2)
  1048. def test_specific_axes(self):
  1049. # Testing that gradient can work on a given axis only
  1050. v = [[1, 1], [3, 4]]
  1051. x = np.array(v)
  1052. dx = [np.array([[2., 3.], [2., 3.]]),
  1053. np.array([[0., 0.], [1., 1.]])]
  1054. assert_array_equal(gradient(x, axis=0), dx[0])
  1055. assert_array_equal(gradient(x, axis=1), dx[1])
  1056. assert_array_equal(gradient(x, axis=-1), dx[1])
  1057. assert_array_equal(gradient(x, axis=(1, 0)), [dx[1], dx[0]])
  1058. # test axis=None which means all axes
  1059. assert_almost_equal(gradient(x, axis=None), [dx[0], dx[1]])
  1060. # and is the same as no axis keyword given
  1061. assert_almost_equal(gradient(x, axis=None), gradient(x))
  1062. # test vararg order
  1063. assert_array_equal(gradient(x, 2, 3, axis=(1, 0)),
  1064. [dx[1] / 2.0, dx[0] / 3.0])
  1065. # test maximal number of varargs
  1066. assert_raises(TypeError, gradient, x, 1, 2, axis=1)
  1067. assert_raises(AxisError, gradient, x, axis=3)
  1068. assert_raises(AxisError, gradient, x, axis=-3)
  1069. # assert_raises(TypeError, gradient, x, axis=[1,])
  1070. def test_timedelta64(self):
  1071. # Make sure gradient() can handle special types like timedelta64
  1072. x = np.array(
  1073. [-5, -3, 10, 12, 61, 321, 300],
  1074. dtype='timedelta64[D]')
  1075. dx = np.array(
  1076. [2, 7, 7, 25, 154, 119, -21],
  1077. dtype='timedelta64[D]')
  1078. assert_array_equal(gradient(x), dx)
  1079. assert_(dx.dtype == np.dtype('timedelta64[D]'))
  1080. def test_inexact_dtypes(self):
  1081. for dt in [np.float16, np.float32, np.float64]:
  1082. # dtypes should not be promoted in a different way to what diff does
  1083. x = np.array([1, 2, 3], dtype=dt)
  1084. assert_equal(gradient(x).dtype, np.diff(x).dtype)
  1085. def test_values(self):
  1086. # needs at least 2 points for edge_order ==1
  1087. gradient(np.arange(2), edge_order=1)
  1088. # needs at least 3 points for edge_order ==1
  1089. gradient(np.arange(3), edge_order=2)
  1090. assert_raises(ValueError, gradient, np.arange(0), edge_order=1)
  1091. assert_raises(ValueError, gradient, np.arange(0), edge_order=2)
  1092. assert_raises(ValueError, gradient, np.arange(1), edge_order=1)
  1093. assert_raises(ValueError, gradient, np.arange(1), edge_order=2)
  1094. assert_raises(ValueError, gradient, np.arange(2), edge_order=2)
  1095. @pytest.mark.parametrize('f_dtype', [np.uint8, np.uint16,
  1096. np.uint32, np.uint64])
  1097. def test_f_decreasing_unsigned_int(self, f_dtype):
  1098. f = np.array([5, 4, 3, 2, 1], dtype=f_dtype)
  1099. g = gradient(f)
  1100. assert_array_equal(g, [-1] * len(f))
  1101. @pytest.mark.parametrize('f_dtype', [np.int8, np.int16,
  1102. np.int32, np.int64])
  1103. def test_f_signed_int_big_jump(self, f_dtype):
  1104. maxint = np.iinfo(f_dtype).max
  1105. x = np.array([1, 3])
  1106. f = np.array([-1, maxint], dtype=f_dtype)
  1107. dfdx = gradient(f, x)
  1108. assert_array_equal(dfdx, [(maxint + 1) // 2] * 2)
  1109. @pytest.mark.parametrize('x_dtype', [np.uint8, np.uint16,
  1110. np.uint32, np.uint64])
  1111. def test_x_decreasing_unsigned(self, x_dtype):
  1112. x = np.array([3, 2, 1], dtype=x_dtype)
  1113. f = np.array([0, 2, 4])
  1114. dfdx = gradient(f, x)
  1115. assert_array_equal(dfdx, [-2] * len(x))
  1116. @pytest.mark.parametrize('x_dtype', [np.int8, np.int16,
  1117. np.int32, np.int64])
  1118. def test_x_signed_int_big_jump(self, x_dtype):
  1119. minint = np.iinfo(x_dtype).min
  1120. maxint = np.iinfo(x_dtype).max
  1121. x = np.array([-1, maxint], dtype=x_dtype)
  1122. f = np.array([minint // 2, 0])
  1123. dfdx = gradient(f, x)
  1124. assert_array_equal(dfdx, [0.5, 0.5])
  1125. def test_return_type(self):
  1126. res = np.gradient(([1, 2], [2, 3]))
  1127. assert type(res) is tuple
  1128. class TestAngle:
  1129. def test_basic(self):
  1130. x = [1 + 3j, np.sqrt(2) / 2.0 + 1j * np.sqrt(2) / 2,
  1131. 1, 1j, -1, -1j, 1 - 3j, -1 + 3j]
  1132. y = angle(x)
  1133. yo = [
  1134. np.arctan(3.0 / 1.0),
  1135. np.arctan(1.0), 0, np.pi / 2, np.pi, -np.pi / 2.0,
  1136. -np.arctan(3.0 / 1.0), np.pi - np.arctan(3.0 / 1.0)]
  1137. z = angle(x, deg=True)
  1138. zo = np.array(yo) * 180 / np.pi
  1139. assert_array_almost_equal(y, yo, 11)
  1140. assert_array_almost_equal(z, zo, 11)
  1141. def test_subclass(self):
  1142. x = np.ma.array([1 + 3j, 1, np.sqrt(2) / 2 * (1 + 1j)])
  1143. x[1] = np.ma.masked
  1144. expected = np.ma.array([np.arctan(3.0 / 1.0), 0, np.arctan(1.0)])
  1145. expected[1] = np.ma.masked
  1146. actual = angle(x)
  1147. assert_equal(type(actual), type(expected))
  1148. assert_equal(actual.mask, expected.mask)
  1149. assert_equal(actual, expected)
  1150. class TestTrimZeros:
  1151. a = np.array([0, 0, 1, 0, 2, 3, 4, 0])
  1152. b = a.astype(float)
  1153. c = a.astype(complex)
  1154. d = a.astype(object)
  1155. def construct_input_output(self, rng, shape, axis, trim):
  1156. """Construct an input/output test pair for trim_zeros"""
  1157. # Standardize axis to a tuple.
  1158. if axis is None:
  1159. axis = tuple(range(len(shape)))
  1160. elif isinstance(axis, int):
  1161. axis = (len(shape) + axis if axis < 0 else axis,)
  1162. else:
  1163. axis = tuple(len(shape) + ax if ax < 0 else ax for ax in axis)
  1164. # Populate a random interior slice with nonzero entries.
  1165. data = np.zeros(shape)
  1166. i_start = rng.integers(low=0, high=np.array(shape) - 1)
  1167. i_end = rng.integers(low=i_start + 1, high=shape)
  1168. inner_shape = tuple(i_end - i_start)
  1169. inner_data = 1 + rng.random(inner_shape)
  1170. data[tuple(slice(i, j) for i, j in zip(i_start, i_end))] = inner_data
  1171. # Construct the expected output of N-dimensional trim_zeros
  1172. # with the given axis and trim arguments.
  1173. if 'f' not in trim:
  1174. i_start = np.array([None for _ in shape])
  1175. if 'b' not in trim:
  1176. i_end = np.array([None for _ in shape])
  1177. idx = tuple(slice(i, j) if ax in axis else slice(None)
  1178. for ax, (i, j) in enumerate(zip(i_start, i_end)))
  1179. expected = data[idx]
  1180. return data, expected
  1181. def values(self):
  1182. attr_names = ('a', 'b', 'c', 'd')
  1183. return (getattr(self, name) for name in attr_names)
  1184. def test_basic(self):
  1185. slc = np.s_[2:-1]
  1186. for arr in self.values():
  1187. res = trim_zeros(arr)
  1188. assert_array_equal(res, arr[slc])
  1189. def test_leading_skip(self):
  1190. slc = np.s_[:-1]
  1191. for arr in self.values():
  1192. res = trim_zeros(arr, trim='b')
  1193. assert_array_equal(res, arr[slc])
  1194. def test_trailing_skip(self):
  1195. slc = np.s_[2:]
  1196. for arr in self.values():
  1197. res = trim_zeros(arr, trim='F')
  1198. assert_array_equal(res, arr[slc])
  1199. def test_all_zero(self):
  1200. for _arr in self.values():
  1201. arr = np.zeros_like(_arr, dtype=_arr.dtype)
  1202. res1 = trim_zeros(arr, trim='B')
  1203. assert len(res1) == 0
  1204. res2 = trim_zeros(arr, trim='f')
  1205. assert len(res2) == 0
  1206. def test_size_zero(self):
  1207. arr = np.zeros(0)
  1208. res = trim_zeros(arr)
  1209. assert_array_equal(arr, res)
  1210. @pytest.mark.parametrize(
  1211. 'arr',
  1212. [np.array([0, 2**62, 0]),
  1213. np.array([0, 2**63, 0]),
  1214. np.array([0, 2**64, 0])]
  1215. )
  1216. def test_overflow(self, arr):
  1217. slc = np.s_[1:2]
  1218. res = trim_zeros(arr)
  1219. assert_array_equal(res, arr[slc])
  1220. def test_no_trim(self):
  1221. arr = np.array([None, 1, None])
  1222. res = trim_zeros(arr)
  1223. assert_array_equal(arr, res)
  1224. def test_list_to_list(self):
  1225. res = trim_zeros(self.a.tolist())
  1226. assert isinstance(res, list)
  1227. @pytest.mark.parametrize("ndim", (0, 1, 2, 3, 10))
  1228. def test_nd_basic(self, ndim):
  1229. a = np.ones((2,) * ndim)
  1230. b = np.pad(a, (2, 1), mode="constant", constant_values=0)
  1231. res = trim_zeros(b, axis=None)
  1232. assert_array_equal(a, res)
  1233. @pytest.mark.parametrize("ndim", (0, 1, 2, 3))
  1234. def test_allzero(self, ndim):
  1235. a = np.zeros((3,) * ndim)
  1236. res = trim_zeros(a, axis=None)
  1237. assert_array_equal(res, np.zeros((0,) * ndim))
  1238. def test_trim_arg(self):
  1239. a = np.array([0, 1, 2, 0])
  1240. res = trim_zeros(a, trim='f')
  1241. assert_array_equal(res, [1, 2, 0])
  1242. res = trim_zeros(a, trim='b')
  1243. assert_array_equal(res, [0, 1, 2])
  1244. @pytest.mark.parametrize("trim", ("front", ""))
  1245. def test_unexpected_trim_value(self, trim):
  1246. arr = self.a
  1247. with pytest.raises(ValueError, match=r"unexpected character\(s\) in `trim`"):
  1248. trim_zeros(arr, trim=trim)
  1249. @pytest.mark.parametrize("shape, axis", [
  1250. [(5,), None],
  1251. [(5,), ()],
  1252. [(5,), 0],
  1253. [(5, 6), None],
  1254. [(5, 6), ()],
  1255. [(5, 6), 0],
  1256. [(5, 6), (-1,)],
  1257. [(5, 6, 7), None],
  1258. [(5, 6, 7), ()],
  1259. [(5, 6, 7), 1],
  1260. [(5, 6, 7), (0, 2)],
  1261. [(5, 6, 7, 8), None],
  1262. [(5, 6, 7, 8), ()],
  1263. [(5, 6, 7, 8), -2],
  1264. [(5, 6, 7, 8), (0, 1, 3)],
  1265. ])
  1266. @pytest.mark.parametrize("trim", ['fb', 'f', 'b'])
  1267. def test_multiple_axes(self, shape, axis, trim):
  1268. rng = np.random.default_rng(4321)
  1269. data, expected = self.construct_input_output(rng, shape, axis, trim)
  1270. assert_array_equal(trim_zeros(data, axis=axis, trim=trim), expected)
  1271. class TestExtins:
  1272. def test_basic(self):
  1273. a = np.array([1, 3, 2, 1, 2, 3, 3])
  1274. b = extract(a > 1, a)
  1275. assert_array_equal(b, [3, 2, 2, 3, 3])
  1276. def test_place(self):
  1277. # Make sure that non-np.ndarray objects
  1278. # raise an error instead of doing nothing
  1279. assert_raises(TypeError, place, [1, 2, 3], [True, False], [0, 1])
  1280. a = np.array([1, 4, 3, 2, 5, 8, 7])
  1281. place(a, [0, 1, 0, 1, 0, 1, 0], [2, 4, 6])
  1282. assert_array_equal(a, [1, 2, 3, 4, 5, 6, 7])
  1283. place(a, np.zeros(7), [])
  1284. assert_array_equal(a, np.arange(1, 8))
  1285. place(a, [1, 0, 1, 0, 1, 0, 1], [8, 9])
  1286. assert_array_equal(a, [8, 2, 9, 4, 8, 6, 9])
  1287. assert_raises_regex(ValueError, "Cannot insert from an empty array",
  1288. lambda: place(a, [0, 0, 0, 0, 0, 1, 0], []))
  1289. # See Issue #6974
  1290. a = np.array(['12', '34'])
  1291. place(a, [0, 1], '9')
  1292. assert_array_equal(a, ['12', '9'])
  1293. def test_both(self):
  1294. a = rand(10)
  1295. mask = a > 0.5
  1296. ac = a.copy()
  1297. c = extract(mask, a)
  1298. place(a, mask, 0)
  1299. place(a, mask, c)
  1300. assert_array_equal(a, ac)
  1301. # _foo1 and _foo2 are used in some tests in TestVectorize.
  1302. def _foo1(x, y=1.0):
  1303. return y * math.floor(x)
  1304. def _foo2(x, y=1.0, z=0.0):
  1305. return y * math.floor(x) + z
  1306. class TestVectorize:
  1307. def test_simple(self):
  1308. def addsubtract(a, b):
  1309. if a > b:
  1310. return a - b
  1311. else:
  1312. return a + b
  1313. f = vectorize(addsubtract)
  1314. r = f([0, 3, 6, 9], [1, 3, 5, 7])
  1315. assert_array_equal(r, [1, 6, 1, 2])
  1316. def test_scalar(self):
  1317. def addsubtract(a, b):
  1318. if a > b:
  1319. return a - b
  1320. else:
  1321. return a + b
  1322. f = vectorize(addsubtract)
  1323. r = f([0, 3, 6, 9], 5)
  1324. assert_array_equal(r, [5, 8, 1, 4])
  1325. def test_large(self):
  1326. x = np.linspace(-3, 2, 10000)
  1327. f = vectorize(lambda x: x)
  1328. y = f(x)
  1329. assert_array_equal(y, x)
  1330. def test_ufunc(self):
  1331. f = vectorize(math.cos)
  1332. args = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi, 2 * np.pi])
  1333. r1 = f(args)
  1334. r2 = np.cos(args)
  1335. assert_array_almost_equal(r1, r2)
  1336. def test_keywords(self):
  1337. def foo(a, b=1):
  1338. return a + b
  1339. f = vectorize(foo)
  1340. args = np.array([1, 2, 3])
  1341. r1 = f(args)
  1342. r2 = np.array([2, 3, 4])
  1343. assert_array_equal(r1, r2)
  1344. r1 = f(args, 2)
  1345. r2 = np.array([3, 4, 5])
  1346. assert_array_equal(r1, r2)
  1347. def test_keywords_with_otypes_order1(self):
  1348. # gh-1620: The second call of f would crash with
  1349. # `ValueError: invalid number of arguments`.
  1350. f = vectorize(_foo1, otypes=[float])
  1351. # We're testing the caching of ufuncs by vectorize, so the order
  1352. # of these function calls is an important part of the test.
  1353. r1 = f(np.arange(3.0), 1.0)
  1354. r2 = f(np.arange(3.0))
  1355. assert_array_equal(r1, r2)
  1356. def test_keywords_with_otypes_order2(self):
  1357. # gh-1620: The second call of f would crash with
  1358. # `ValueError: non-broadcastable output operand with shape ()
  1359. # doesn't match the broadcast shape (3,)`.
  1360. f = vectorize(_foo1, otypes=[float])
  1361. # We're testing the caching of ufuncs by vectorize, so the order
  1362. # of these function calls is an important part of the test.
  1363. r1 = f(np.arange(3.0))
  1364. r2 = f(np.arange(3.0), 1.0)
  1365. assert_array_equal(r1, r2)
  1366. def test_keywords_with_otypes_order3(self):
  1367. # gh-1620: The third call of f would crash with
  1368. # `ValueError: invalid number of arguments`.
  1369. f = vectorize(_foo1, otypes=[float])
  1370. # We're testing the caching of ufuncs by vectorize, so the order
  1371. # of these function calls is an important part of the test.
  1372. r1 = f(np.arange(3.0))
  1373. r2 = f(np.arange(3.0), y=1.0)
  1374. r3 = f(np.arange(3.0))
  1375. assert_array_equal(r1, r2)
  1376. assert_array_equal(r1, r3)
  1377. def test_keywords_with_otypes_several_kwd_args1(self):
  1378. # gh-1620 Make sure different uses of keyword arguments
  1379. # don't break the vectorized function.
  1380. f = vectorize(_foo2, otypes=[float])
  1381. # We're testing the caching of ufuncs by vectorize, so the order
  1382. # of these function calls is an important part of the test.
  1383. r1 = f(10.4, z=100)
  1384. r2 = f(10.4, y=-1)
  1385. r3 = f(10.4)
  1386. assert_equal(r1, _foo2(10.4, z=100))
  1387. assert_equal(r2, _foo2(10.4, y=-1))
  1388. assert_equal(r3, _foo2(10.4))
  1389. def test_keywords_with_otypes_several_kwd_args2(self):
  1390. # gh-1620 Make sure different uses of keyword arguments
  1391. # don't break the vectorized function.
  1392. f = vectorize(_foo2, otypes=[float])
  1393. # We're testing the caching of ufuncs by vectorize, so the order
  1394. # of these function calls is an important part of the test.
  1395. r1 = f(z=100, x=10.4, y=-1)
  1396. r2 = f(1, 2, 3)
  1397. assert_equal(r1, _foo2(z=100, x=10.4, y=-1))
  1398. assert_equal(r2, _foo2(1, 2, 3))
  1399. def test_keywords_no_func_code(self):
  1400. # This needs to test a function that has keywords but
  1401. # no func_code attribute, since otherwise vectorize will
  1402. # inspect the func_code.
  1403. import random
  1404. try:
  1405. vectorize(random.randrange) # Should succeed
  1406. except Exception:
  1407. raise AssertionError
  1408. def test_keywords2_ticket_2100(self):
  1409. # Test kwarg support: enhancement ticket 2100
  1410. def foo(a, b=1):
  1411. return a + b
  1412. f = vectorize(foo)
  1413. args = np.array([1, 2, 3])
  1414. r1 = f(a=args)
  1415. r2 = np.array([2, 3, 4])
  1416. assert_array_equal(r1, r2)
  1417. r1 = f(b=1, a=args)
  1418. assert_array_equal(r1, r2)
  1419. r1 = f(args, b=2)
  1420. r2 = np.array([3, 4, 5])
  1421. assert_array_equal(r1, r2)
  1422. def test_keywords3_ticket_2100(self):
  1423. # Test excluded with mixed positional and kwargs: ticket 2100
  1424. def mypolyval(x, p):
  1425. _p = list(p)
  1426. res = _p.pop(0)
  1427. while _p:
  1428. res = res * x + _p.pop(0)
  1429. return res
  1430. vpolyval = np.vectorize(mypolyval, excluded=['p', 1])
  1431. ans = [3, 6]
  1432. assert_array_equal(ans, vpolyval(x=[0, 1], p=[1, 2, 3]))
  1433. assert_array_equal(ans, vpolyval([0, 1], p=[1, 2, 3]))
  1434. assert_array_equal(ans, vpolyval([0, 1], [1, 2, 3]))
  1435. def test_keywords4_ticket_2100(self):
  1436. # Test vectorizing function with no positional args.
  1437. @vectorize
  1438. def f(**kw):
  1439. res = 1.0
  1440. for _k in kw:
  1441. res *= kw[_k]
  1442. return res
  1443. assert_array_equal(f(a=[1, 2], b=[3, 4]), [3, 8])
  1444. def test_keywords5_ticket_2100(self):
  1445. # Test vectorizing function with no kwargs args.
  1446. @vectorize
  1447. def f(*v):
  1448. return np.prod(v)
  1449. assert_array_equal(f([1, 2], [3, 4]), [3, 8])
  1450. def test_coverage1_ticket_2100(self):
  1451. def foo():
  1452. return 1
  1453. f = vectorize(foo)
  1454. assert_array_equal(f(), 1)
  1455. def test_assigning_docstring(self):
  1456. def foo(x):
  1457. """Original documentation"""
  1458. return x
  1459. f = vectorize(foo)
  1460. assert_equal(f.__doc__, foo.__doc__)
  1461. doc = "Provided documentation"
  1462. f = vectorize(foo, doc=doc)
  1463. assert_equal(f.__doc__, doc)
  1464. def test_UnboundMethod_ticket_1156(self):
  1465. # Regression test for issue 1156
  1466. class Foo:
  1467. b = 2
  1468. def bar(self, a):
  1469. return a ** self.b
  1470. assert_array_equal(vectorize(Foo().bar)(np.arange(9)),
  1471. np.arange(9) ** 2)
  1472. assert_array_equal(vectorize(Foo.bar)(Foo(), np.arange(9)),
  1473. np.arange(9) ** 2)
  1474. def test_execution_order_ticket_1487(self):
  1475. # Regression test for dependence on execution order: issue 1487
  1476. f1 = vectorize(lambda x: x)
  1477. res1a = f1(np.arange(3))
  1478. res1b = f1(np.arange(0.1, 3))
  1479. f2 = vectorize(lambda x: x)
  1480. res2b = f2(np.arange(0.1, 3))
  1481. res2a = f2(np.arange(3))
  1482. assert_equal(res1a, res2a)
  1483. assert_equal(res1b, res2b)
  1484. def test_string_ticket_1892(self):
  1485. # Test vectorization over strings: issue 1892.
  1486. f = np.vectorize(lambda x: x)
  1487. s = '0123456789' * 10
  1488. assert_equal(s, f(s))
  1489. def test_dtype_promotion_gh_29189(self):
  1490. # dtype should not be silently promoted (int32 -> int64)
  1491. dtypes = [np.int16, np.int32, np.int64, np.float16, np.float32, np.float64]
  1492. for dtype in dtypes:
  1493. x = np.asarray([1, 2, 3], dtype=dtype)
  1494. y = np.vectorize(lambda x: x + x)(x)
  1495. assert x.dtype == y.dtype
  1496. def test_cache(self):
  1497. # Ensure that vectorized func called exactly once per argument.
  1498. _calls = [0]
  1499. @vectorize
  1500. def f(x):
  1501. _calls[0] += 1
  1502. return x ** 2
  1503. f.cache = True
  1504. x = np.arange(5)
  1505. assert_array_equal(f(x), x * x)
  1506. assert_equal(_calls[0], len(x))
  1507. def test_otypes(self):
  1508. f = np.vectorize(lambda x: x)
  1509. f.otypes = 'i'
  1510. x = np.arange(5)
  1511. assert_array_equal(f(x), x)
  1512. def test_otypes_object_28624(self):
  1513. # with object otype, the vectorized function should return y
  1514. # wrapped into an object array
  1515. y = np.arange(3)
  1516. f = vectorize(lambda x: y, otypes=[object])
  1517. assert f(None).item() is y
  1518. assert f([None]).item() is y
  1519. y = [1, 2, 3]
  1520. f = vectorize(lambda x: y, otypes=[object])
  1521. assert f(None).item() is y
  1522. assert f([None]).item() is y
  1523. def test_parse_gufunc_signature(self):
  1524. assert_equal(nfb._parse_gufunc_signature('(x)->()'), ([('x',)], [()]))
  1525. assert_equal(nfb._parse_gufunc_signature('(x,y)->()'),
  1526. ([('x', 'y')], [()]))
  1527. assert_equal(nfb._parse_gufunc_signature('(x),(y)->()'),
  1528. ([('x',), ('y',)], [()]))
  1529. assert_equal(nfb._parse_gufunc_signature('(x)->(y)'),
  1530. ([('x',)], [('y',)]))
  1531. assert_equal(nfb._parse_gufunc_signature('(x)->(y),()'),
  1532. ([('x',)], [('y',), ()]))
  1533. assert_equal(nfb._parse_gufunc_signature('(),(a,b,c),(d)->(d,e)'),
  1534. ([(), ('a', 'b', 'c'), ('d',)], [('d', 'e')]))
  1535. # Tests to check if whitespaces are ignored
  1536. assert_equal(nfb._parse_gufunc_signature('(x )->()'), ([('x',)], [()]))
  1537. assert_equal(nfb._parse_gufunc_signature('( x , y )->( )'),
  1538. ([('x', 'y')], [()]))
  1539. assert_equal(nfb._parse_gufunc_signature('(x),( y) ->()'),
  1540. ([('x',), ('y',)], [()]))
  1541. assert_equal(nfb._parse_gufunc_signature('( x)-> (y ) '),
  1542. ([('x',)], [('y',)]))
  1543. assert_equal(nfb._parse_gufunc_signature(' (x)->( y),( )'),
  1544. ([('x',)], [('y',), ()]))
  1545. assert_equal(nfb._parse_gufunc_signature(
  1546. '( ), ( a, b,c ) ,( d) -> (d , e)'),
  1547. ([(), ('a', 'b', 'c'), ('d',)], [('d', 'e')]))
  1548. with assert_raises(ValueError):
  1549. nfb._parse_gufunc_signature('(x)(y)->()')
  1550. with assert_raises(ValueError):
  1551. nfb._parse_gufunc_signature('(x),(y)->')
  1552. with assert_raises(ValueError):
  1553. nfb._parse_gufunc_signature('((x))->(x)')
  1554. def test_signature_simple(self):
  1555. def addsubtract(a, b):
  1556. if a > b:
  1557. return a - b
  1558. else:
  1559. return a + b
  1560. f = vectorize(addsubtract, signature='(),()->()')
  1561. r = f([0, 3, 6, 9], [1, 3, 5, 7])
  1562. assert_array_equal(r, [1, 6, 1, 2])
  1563. def test_signature_mean_last(self):
  1564. def mean(a):
  1565. return a.mean()
  1566. f = vectorize(mean, signature='(n)->()')
  1567. r = f([[1, 3], [2, 4]])
  1568. assert_array_equal(r, [2, 3])
  1569. def test_signature_center(self):
  1570. def center(a):
  1571. return a - a.mean()
  1572. f = vectorize(center, signature='(n)->(n)')
  1573. r = f([[1, 3], [2, 4]])
  1574. assert_array_equal(r, [[-1, 1], [-1, 1]])
  1575. def test_signature_two_outputs(self):
  1576. f = vectorize(lambda x: (x, x), signature='()->(),()')
  1577. r = f([1, 2, 3])
  1578. assert_(isinstance(r, tuple) and len(r) == 2)
  1579. assert_array_equal(r[0], [1, 2, 3])
  1580. assert_array_equal(r[1], [1, 2, 3])
  1581. def test_signature_outer(self):
  1582. f = vectorize(np.outer, signature='(a),(b)->(a,b)')
  1583. r = f([1, 2], [1, 2, 3])
  1584. assert_array_equal(r, [[1, 2, 3], [2, 4, 6]])
  1585. r = f([[[1, 2]]], [1, 2, 3])
  1586. assert_array_equal(r, [[[[1, 2, 3], [2, 4, 6]]]])
  1587. r = f([[1, 0], [2, 0]], [1, 2, 3])
  1588. assert_array_equal(r, [[[1, 2, 3], [0, 0, 0]],
  1589. [[2, 4, 6], [0, 0, 0]]])
  1590. r = f([1, 2], [[1, 2, 3], [0, 0, 0]])
  1591. assert_array_equal(r, [[[1, 2, 3], [2, 4, 6]],
  1592. [[0, 0, 0], [0, 0, 0]]])
  1593. def test_signature_computed_size(self):
  1594. f = vectorize(lambda x: x[:-1], signature='(n)->(m)')
  1595. r = f([1, 2, 3])
  1596. assert_array_equal(r, [1, 2])
  1597. r = f([[1, 2, 3], [2, 3, 4]])
  1598. assert_array_equal(r, [[1, 2], [2, 3]])
  1599. def test_signature_excluded(self):
  1600. def foo(a, b=1):
  1601. return a + b
  1602. f = vectorize(foo, signature='()->()', excluded={'b'})
  1603. assert_array_equal(f([1, 2, 3]), [2, 3, 4])
  1604. assert_array_equal(f([1, 2, 3], b=0), [1, 2, 3])
  1605. def test_signature_otypes(self):
  1606. f = vectorize(lambda x: x, signature='(n)->(n)', otypes=['float64'])
  1607. r = f([1, 2, 3])
  1608. assert_equal(r.dtype, np.dtype('float64'))
  1609. assert_array_equal(r, [1, 2, 3])
  1610. def test_signature_invalid_inputs(self):
  1611. f = vectorize(operator.add, signature='(n),(n)->(n)')
  1612. with assert_raises_regex(TypeError, 'wrong number of positional'):
  1613. f([1, 2])
  1614. with assert_raises_regex(
  1615. ValueError, 'does not have enough dimensions'):
  1616. f(1, 2)
  1617. with assert_raises_regex(
  1618. ValueError, 'inconsistent size for core dimension'):
  1619. f([1, 2], [1, 2, 3])
  1620. f = vectorize(operator.add, signature='()->()')
  1621. with assert_raises_regex(TypeError, 'wrong number of positional'):
  1622. f(1, 2)
  1623. def test_signature_invalid_outputs(self):
  1624. f = vectorize(lambda x: x[:-1], signature='(n)->(n)')
  1625. with assert_raises_regex(
  1626. ValueError, 'inconsistent size for core dimension'):
  1627. f([1, 2, 3])
  1628. f = vectorize(lambda x: x, signature='()->(),()')
  1629. with assert_raises_regex(ValueError, 'wrong number of outputs'):
  1630. f(1)
  1631. f = vectorize(lambda x: (x, x), signature='()->()')
  1632. with assert_raises_regex(ValueError, 'wrong number of outputs'):
  1633. f([1, 2])
  1634. def test_size_zero_output(self):
  1635. # see issue 5868
  1636. f = np.vectorize(lambda x: x)
  1637. x = np.zeros([0, 5], dtype=int)
  1638. with assert_raises_regex(ValueError, 'otypes'):
  1639. f(x)
  1640. f.otypes = 'i'
  1641. assert_array_equal(f(x), x)
  1642. f = np.vectorize(lambda x: x, signature='()->()')
  1643. with assert_raises_regex(ValueError, 'otypes'):
  1644. f(x)
  1645. f = np.vectorize(lambda x: x, signature='()->()', otypes='i')
  1646. assert_array_equal(f(x), x)
  1647. f = np.vectorize(lambda x: x, signature='(n)->(n)', otypes='i')
  1648. assert_array_equal(f(x), x)
  1649. f = np.vectorize(lambda x: x, signature='(n)->(n)')
  1650. assert_array_equal(f(x.T), x.T)
  1651. f = np.vectorize(lambda x: [x], signature='()->(n)', otypes='i')
  1652. with assert_raises_regex(ValueError, 'new output dimensions'):
  1653. f(x)
  1654. def test_subclasses(self):
  1655. class subclass(np.ndarray):
  1656. pass
  1657. m = np.array([[1., 0., 0.],
  1658. [0., 0., 1.],
  1659. [0., 1., 0.]]).view(subclass)
  1660. v = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]).view(subclass)
  1661. # generalized (gufunc)
  1662. matvec = np.vectorize(np.matmul, signature='(m,m),(m)->(m)')
  1663. r = matvec(m, v)
  1664. assert_equal(type(r), subclass)
  1665. assert_equal(r, [[1., 3., 2.], [4., 6., 5.], [7., 9., 8.]])
  1666. # element-wise (ufunc)
  1667. mult = np.vectorize(lambda x, y: x * y)
  1668. r = mult(m, v)
  1669. assert_equal(type(r), subclass)
  1670. assert_equal(r, m * v)
  1671. def test_name(self):
  1672. # gh-23021
  1673. @np.vectorize
  1674. def f2(a, b):
  1675. return a + b
  1676. assert f2.__name__ == 'f2'
  1677. def test_decorator(self):
  1678. @vectorize
  1679. def addsubtract(a, b):
  1680. if a > b:
  1681. return a - b
  1682. else:
  1683. return a + b
  1684. r = addsubtract([0, 3, 6, 9], [1, 3, 5, 7])
  1685. assert_array_equal(r, [1, 6, 1, 2])
  1686. def test_docstring(self):
  1687. @vectorize
  1688. def f(x):
  1689. """Docstring"""
  1690. return x
  1691. if sys.flags.optimize < 2:
  1692. assert f.__doc__ == "Docstring"
  1693. def test_partial(self):
  1694. def foo(x, y):
  1695. return x + y
  1696. bar = partial(foo, 3)
  1697. vbar = np.vectorize(bar)
  1698. assert vbar(1) == 4
  1699. def test_signature_otypes_decorator(self):
  1700. @vectorize(signature='(n)->(n)', otypes=['float64'])
  1701. def f(x):
  1702. return x
  1703. r = f([1, 2, 3])
  1704. assert_equal(r.dtype, np.dtype('float64'))
  1705. assert_array_equal(r, [1, 2, 3])
  1706. assert f.__name__ == 'f'
  1707. def test_bad_input(self):
  1708. with assert_raises(TypeError):
  1709. A = np.vectorize(pyfunc=3)
  1710. def test_no_keywords(self):
  1711. with assert_raises(TypeError):
  1712. @np.vectorize("string")
  1713. def foo():
  1714. return "bar"
  1715. def test_positional_regression_9477(self):
  1716. # This supplies the first keyword argument as a positional,
  1717. # to ensure that they are still properly forwarded after the
  1718. # enhancement for #9477
  1719. f = vectorize((lambda x: x), ['float64'])
  1720. r = f([2])
  1721. assert_equal(r.dtype, np.dtype('float64'))
  1722. def test_datetime_conversion(self):
  1723. otype = "datetime64[ns]"
  1724. arr = np.array(['2024-01-01', '2024-01-02', '2024-01-03'],
  1725. dtype='datetime64[ns]')
  1726. assert_array_equal(np.vectorize(lambda x: x, signature="(i)->(j)",
  1727. otypes=[otype])(arr), arr)
  1728. class TestLeaks:
  1729. class A:
  1730. iters = 20
  1731. def bound(self, *args):
  1732. return 0
  1733. @staticmethod
  1734. def unbound(*args):
  1735. return 0
  1736. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  1737. @pytest.mark.skipif(NOGIL_BUILD,
  1738. reason=("Functions are immortalized if a thread is "
  1739. "launched, making this test flaky"))
  1740. @pytest.mark.parametrize('name, incr', [
  1741. ('bound', A.iters),
  1742. ('unbound', 0),
  1743. ])
  1744. @pytest.mark.thread_unsafe(
  1745. reason="test result depends on the reference count of a global object"
  1746. )
  1747. def test_frompyfunc_leaks(self, name, incr):
  1748. # exposed in gh-11867 as np.vectorized, but the problem stems from
  1749. # frompyfunc.
  1750. # class.attribute = np.frompyfunc(<method>) creates a
  1751. # reference cycle if <method> is a bound class method.
  1752. # It requires a gc collection cycle to break the cycle.
  1753. import gc
  1754. A_func = getattr(self.A, name)
  1755. gc.disable()
  1756. try:
  1757. refcount = sys.getrefcount(A_func)
  1758. for i in range(self.A.iters):
  1759. a = self.A()
  1760. a.f = np.frompyfunc(getattr(a, name), 1, 1)
  1761. out = a.f(np.arange(10))
  1762. a = None
  1763. # A.func is part of a reference cycle if incr is non-zero
  1764. assert_equal(sys.getrefcount(A_func), refcount + incr)
  1765. for i in range(5):
  1766. gc.collect()
  1767. assert_equal(sys.getrefcount(A_func), refcount)
  1768. finally:
  1769. gc.enable()
  1770. class TestDigitize:
  1771. def test_forward(self):
  1772. x = np.arange(-6, 5)
  1773. bins = np.arange(-5, 5)
  1774. assert_array_equal(digitize(x, bins), np.arange(11))
  1775. def test_reverse(self):
  1776. x = np.arange(5, -6, -1)
  1777. bins = np.arange(5, -5, -1)
  1778. assert_array_equal(digitize(x, bins), np.arange(11))
  1779. def test_random(self):
  1780. x = rand(10)
  1781. bin = np.linspace(x.min(), x.max(), 10)
  1782. assert_(np.all(digitize(x, bin) != 0))
  1783. def test_right_basic(self):
  1784. x = [1, 5, 4, 10, 8, 11, 0]
  1785. bins = [1, 5, 10]
  1786. default_answer = [1, 2, 1, 3, 2, 3, 0]
  1787. assert_array_equal(digitize(x, bins), default_answer)
  1788. right_answer = [0, 1, 1, 2, 2, 3, 0]
  1789. assert_array_equal(digitize(x, bins, True), right_answer)
  1790. def test_right_open(self):
  1791. x = np.arange(-6, 5)
  1792. bins = np.arange(-6, 4)
  1793. assert_array_equal(digitize(x, bins, True), np.arange(11))
  1794. def test_right_open_reverse(self):
  1795. x = np.arange(5, -6, -1)
  1796. bins = np.arange(4, -6, -1)
  1797. assert_array_equal(digitize(x, bins, True), np.arange(11))
  1798. def test_right_open_random(self):
  1799. x = rand(10)
  1800. bins = np.linspace(x.min(), x.max(), 10)
  1801. assert_(np.all(digitize(x, bins, True) != 10))
  1802. def test_monotonic(self):
  1803. x = [-1, 0, 1, 2]
  1804. bins = [0, 0, 1]
  1805. assert_array_equal(digitize(x, bins, False), [0, 2, 3, 3])
  1806. assert_array_equal(digitize(x, bins, True), [0, 0, 2, 3])
  1807. bins = [1, 1, 0]
  1808. assert_array_equal(digitize(x, bins, False), [3, 2, 0, 0])
  1809. assert_array_equal(digitize(x, bins, True), [3, 3, 2, 0])
  1810. bins = [1, 1, 1, 1]
  1811. assert_array_equal(digitize(x, bins, False), [0, 0, 4, 4])
  1812. assert_array_equal(digitize(x, bins, True), [0, 0, 0, 4])
  1813. bins = [0, 0, 1, 0]
  1814. assert_raises(ValueError, digitize, x, bins)
  1815. bins = [1, 1, 0, 1]
  1816. assert_raises(ValueError, digitize, x, bins)
  1817. def test_casting_error(self):
  1818. x = [1, 2, 3 + 1.j]
  1819. bins = [1, 2, 3]
  1820. assert_raises(TypeError, digitize, x, bins)
  1821. x, bins = bins, x
  1822. assert_raises(TypeError, digitize, x, bins)
  1823. def test_return_type(self):
  1824. # Functions returning indices should always return base ndarrays
  1825. class A(np.ndarray):
  1826. pass
  1827. a = np.arange(5).view(A)
  1828. b = np.arange(1, 3).view(A)
  1829. assert_(not isinstance(digitize(b, a, False), A))
  1830. assert_(not isinstance(digitize(b, a, True), A))
  1831. def test_large_integers_increasing(self):
  1832. # gh-11022
  1833. x = 2**54 # loses precision in a float
  1834. assert_equal(np.digitize(x, [x - 1, x + 1]), 1)
  1835. @pytest.mark.xfail(
  1836. reason="gh-11022: np._core.multiarray._monoticity loses precision")
  1837. def test_large_integers_decreasing(self):
  1838. # gh-11022
  1839. x = 2**54 # loses precision in a float
  1840. assert_equal(np.digitize(x, [x + 1, x - 1]), 1)
  1841. class TestUnwrap:
  1842. def test_simple(self):
  1843. # check that unwrap removes jumps greater that 2*pi
  1844. assert_array_equal(unwrap([1, 1 + 2 * np.pi]), [1, 1])
  1845. # check that unwrap maintains continuity
  1846. assert_(np.all(diff(unwrap(rand(10) * 100)) < np.pi))
  1847. def test_period(self):
  1848. # check that unwrap removes jumps greater that 255
  1849. assert_array_equal(unwrap([1, 1 + 256], period=255), [1, 2])
  1850. # check that unwrap maintains continuity
  1851. assert_(np.all(diff(unwrap(rand(10) * 1000, period=255)) < 255))
  1852. # check simple case
  1853. simple_seq = np.array([0, 75, 150, 225, 300])
  1854. wrap_seq = np.mod(simple_seq, 255)
  1855. assert_array_equal(unwrap(wrap_seq, period=255), simple_seq)
  1856. # check custom discont value
  1857. uneven_seq = np.array([0, 75, 150, 225, 300, 430])
  1858. wrap_uneven = np.mod(uneven_seq, 250)
  1859. no_discont = unwrap(wrap_uneven, period=250)
  1860. assert_array_equal(no_discont, [0, 75, 150, 225, 300, 180])
  1861. sm_discont = unwrap(wrap_uneven, period=250, discont=140)
  1862. assert_array_equal(sm_discont, [0, 75, 150, 225, 300, 430])
  1863. assert sm_discont.dtype == wrap_uneven.dtype
  1864. @pytest.mark.parametrize(
  1865. "dtype", "O" + np.typecodes["AllInteger"] + np.typecodes["Float"]
  1866. )
  1867. @pytest.mark.parametrize("M", [0, 1, 10])
  1868. class TestFilterwindows:
  1869. def test_hanning(self, dtype: str, M: int) -> None:
  1870. scalar = np.array(M, dtype=dtype)[()]
  1871. w = hanning(scalar)
  1872. if dtype == "O":
  1873. ref_dtype = np.float64
  1874. else:
  1875. ref_dtype = np.result_type(scalar.dtype, np.float64)
  1876. assert w.dtype == ref_dtype
  1877. # check symmetry
  1878. assert_equal(w, flipud(w))
  1879. # check known value
  1880. if scalar < 1:
  1881. assert_array_equal(w, np.array([]))
  1882. elif scalar == 1:
  1883. assert_array_equal(w, np.ones(1))
  1884. else:
  1885. assert_almost_equal(np.sum(w, axis=0), 4.500, 4)
  1886. def test_hamming(self, dtype: str, M: int) -> None:
  1887. scalar = np.array(M, dtype=dtype)[()]
  1888. w = hamming(scalar)
  1889. if dtype == "O":
  1890. ref_dtype = np.float64
  1891. else:
  1892. ref_dtype = np.result_type(scalar.dtype, np.float64)
  1893. assert w.dtype == ref_dtype
  1894. # check symmetry
  1895. assert_equal(w, flipud(w))
  1896. # check known value
  1897. if scalar < 1:
  1898. assert_array_equal(w, np.array([]))
  1899. elif scalar == 1:
  1900. assert_array_equal(w, np.ones(1))
  1901. else:
  1902. assert_almost_equal(np.sum(w, axis=0), 4.9400, 4)
  1903. def test_bartlett(self, dtype: str, M: int) -> None:
  1904. scalar = np.array(M, dtype=dtype)[()]
  1905. w = bartlett(scalar)
  1906. if dtype == "O":
  1907. ref_dtype = np.float64
  1908. else:
  1909. ref_dtype = np.result_type(scalar.dtype, np.float64)
  1910. assert w.dtype == ref_dtype
  1911. # check symmetry
  1912. assert_equal(w, flipud(w))
  1913. # check known value
  1914. if scalar < 1:
  1915. assert_array_equal(w, np.array([]))
  1916. elif scalar == 1:
  1917. assert_array_equal(w, np.ones(1))
  1918. else:
  1919. assert_almost_equal(np.sum(w, axis=0), 4.4444, 4)
  1920. def test_blackman(self, dtype: str, M: int) -> None:
  1921. scalar = np.array(M, dtype=dtype)[()]
  1922. w = blackman(scalar)
  1923. if dtype == "O":
  1924. ref_dtype = np.float64
  1925. else:
  1926. ref_dtype = np.result_type(scalar.dtype, np.float64)
  1927. assert w.dtype == ref_dtype
  1928. # check symmetry
  1929. assert_equal(w, flipud(w))
  1930. # check known value
  1931. if scalar < 1:
  1932. assert_array_equal(w, np.array([]))
  1933. elif scalar == 1:
  1934. assert_array_equal(w, np.ones(1))
  1935. else:
  1936. assert_almost_equal(np.sum(w, axis=0), 3.7800, 4)
  1937. def test_kaiser(self, dtype: str, M: int) -> None:
  1938. scalar = np.array(M, dtype=dtype)[()]
  1939. w = kaiser(scalar, 0)
  1940. if dtype == "O":
  1941. ref_dtype = np.float64
  1942. else:
  1943. ref_dtype = np.result_type(scalar.dtype, np.float64)
  1944. assert w.dtype == ref_dtype
  1945. # check symmetry
  1946. assert_equal(w, flipud(w))
  1947. # check known value
  1948. if scalar < 1:
  1949. assert_array_equal(w, np.array([]))
  1950. elif scalar == 1:
  1951. assert_array_equal(w, np.ones(1))
  1952. else:
  1953. assert_almost_equal(np.sum(w, axis=0), 10, 15)
  1954. class TestTrapezoid:
  1955. def test_simple(self):
  1956. x = np.arange(-10, 10, .1)
  1957. r = trapezoid(np.exp(-.5 * x ** 2) / np.sqrt(2 * np.pi), dx=0.1)
  1958. # check integral of normal equals 1
  1959. assert_almost_equal(r, 1, 7)
  1960. def test_ndim(self):
  1961. x = np.linspace(0, 1, 3)
  1962. y = np.linspace(0, 2, 8)
  1963. z = np.linspace(0, 3, 13)
  1964. wx = np.ones_like(x) * (x[1] - x[0])
  1965. wx[0] /= 2
  1966. wx[-1] /= 2
  1967. wy = np.ones_like(y) * (y[1] - y[0])
  1968. wy[0] /= 2
  1969. wy[-1] /= 2
  1970. wz = np.ones_like(z) * (z[1] - z[0])
  1971. wz[0] /= 2
  1972. wz[-1] /= 2
  1973. q = x[:, None, None] + y[None, :, None] + z[None, None, :]
  1974. qx = (q * wx[:, None, None]).sum(axis=0)
  1975. qy = (q * wy[None, :, None]).sum(axis=1)
  1976. qz = (q * wz[None, None, :]).sum(axis=2)
  1977. # n-d `x`
  1978. r = trapezoid(q, x=x[:, None, None], axis=0)
  1979. assert_almost_equal(r, qx)
  1980. r = trapezoid(q, x=y[None, :, None], axis=1)
  1981. assert_almost_equal(r, qy)
  1982. r = trapezoid(q, x=z[None, None, :], axis=2)
  1983. assert_almost_equal(r, qz)
  1984. # 1-d `x`
  1985. r = trapezoid(q, x=x, axis=0)
  1986. assert_almost_equal(r, qx)
  1987. r = trapezoid(q, x=y, axis=1)
  1988. assert_almost_equal(r, qy)
  1989. r = trapezoid(q, x=z, axis=2)
  1990. assert_almost_equal(r, qz)
  1991. def test_masked(self):
  1992. # Testing that masked arrays behave as if the function is 0 where
  1993. # masked
  1994. x = np.arange(5)
  1995. y = x * x
  1996. mask = x == 2
  1997. ym = np.ma.array(y, mask=mask)
  1998. r = 13.0 # sum(0.5 * (0 + 1) * 1.0 + 0.5 * (9 + 16))
  1999. assert_almost_equal(trapezoid(ym, x), r)
  2000. xm = np.ma.array(x, mask=mask)
  2001. assert_almost_equal(trapezoid(ym, xm), r)
  2002. xm = np.ma.array(x, mask=mask)
  2003. assert_almost_equal(trapezoid(y, xm), r)
  2004. class TestSinc:
  2005. def test_simple(self):
  2006. assert_(sinc(0) == 1)
  2007. w = sinc(np.linspace(-1, 1, 100))
  2008. # check symmetry
  2009. assert_array_almost_equal(w, flipud(w), 7)
  2010. def test_array_like(self):
  2011. x = [0, 0.5]
  2012. y1 = sinc(np.array(x))
  2013. y2 = sinc(list(x))
  2014. y3 = sinc(tuple(x))
  2015. assert_array_equal(y1, y2)
  2016. assert_array_equal(y1, y3)
  2017. def test_bool_dtype(self):
  2018. x = (np.arange(4, dtype=np.uint8) % 2 == 1)
  2019. actual = sinc(x)
  2020. expected = sinc(x.astype(np.float64))
  2021. assert_allclose(actual, expected)
  2022. assert actual.dtype == np.float64
  2023. @pytest.mark.parametrize('dtype', [np.uint8, np.int16, np.uint64])
  2024. def test_int_dtypes(self, dtype):
  2025. x = np.arange(4, dtype=dtype)
  2026. actual = sinc(x)
  2027. expected = sinc(x.astype(np.float64))
  2028. assert_allclose(actual, expected)
  2029. assert actual.dtype == np.float64
  2030. @pytest.mark.parametrize(
  2031. 'dtype',
  2032. [np.float16, np.float32, np.longdouble, np.complex64, np.complex128]
  2033. )
  2034. def test_float_dtypes(self, dtype):
  2035. x = np.arange(4, dtype=dtype)
  2036. assert sinc(x).dtype == x.dtype
  2037. def test_float16_underflow(self):
  2038. x = np.float16(0)
  2039. # before gh-27784, fill value for 0 in input would underflow float16,
  2040. # resulting in nan
  2041. assert_array_equal(sinc(x), np.asarray(1.0))
  2042. class TestUnique:
  2043. def test_simple(self):
  2044. x = np.array([4, 3, 2, 1, 1, 2, 3, 4, 0])
  2045. assert_(np.all(unique(x) == [0, 1, 2, 3, 4]))
  2046. assert_(unique(np.array([1, 1, 1, 1, 1])) == np.array([1]))
  2047. x = ['widget', 'ham', 'foo', 'bar', 'foo', 'ham']
  2048. assert_(np.all(unique(x) == ['bar', 'foo', 'ham', 'widget']))
  2049. x = np.array([5 + 6j, 1 + 1j, 1 + 10j, 10, 5 + 6j])
  2050. assert_(np.all(unique(x) == [1 + 1j, 1 + 10j, 5 + 6j, 10]))
  2051. class TestCheckFinite:
  2052. def test_simple(self):
  2053. a = [1, 2, 3]
  2054. b = [1, 2, np.inf]
  2055. c = [1, 2, np.nan]
  2056. np.asarray_chkfinite(a)
  2057. assert_raises(ValueError, np.asarray_chkfinite, b)
  2058. assert_raises(ValueError, np.asarray_chkfinite, c)
  2059. def test_dtype_order(self):
  2060. # Regression test for missing dtype and order arguments
  2061. a = [1, 2, 3]
  2062. a = np.asarray_chkfinite(a, order='F', dtype=np.float64)
  2063. assert_(a.dtype == np.float64)
  2064. class TestCorrCoef:
  2065. A = np.array(
  2066. [[0.15391142, 0.18045767, 0.14197213],
  2067. [0.70461506, 0.96474128, 0.27906989],
  2068. [0.9297531, 0.32296769, 0.19267156]])
  2069. B = np.array(
  2070. [[0.10377691, 0.5417086, 0.49807457],
  2071. [0.82872117, 0.77801674, 0.39226705],
  2072. [0.9314666, 0.66800209, 0.03538394]])
  2073. res1 = np.array(
  2074. [[1., 0.9379533, -0.04931983],
  2075. [0.9379533, 1., 0.30007991],
  2076. [-0.04931983, 0.30007991, 1.]])
  2077. res2 = np.array(
  2078. [[1., 0.9379533, -0.04931983, 0.30151751, 0.66318558, 0.51532523],
  2079. [0.9379533, 1., 0.30007991, -0.04781421, 0.88157256, 0.78052386],
  2080. [-0.04931983, 0.30007991, 1., -0.96717111, 0.71483595, 0.83053601],
  2081. [0.30151751, -0.04781421, -0.96717111, 1., -0.51366032, -0.66173113],
  2082. [0.66318558, 0.88157256, 0.71483595, -0.51366032, 1., 0.98317823],
  2083. [0.51532523, 0.78052386, 0.83053601, -0.66173113, 0.98317823, 1.]])
  2084. def test_non_array(self):
  2085. assert_almost_equal(np.corrcoef([0, 1, 0], [1, 0, 1]),
  2086. [[1., -1.], [-1., 1.]])
  2087. def test_simple(self):
  2088. tgt1 = corrcoef(self.A)
  2089. assert_almost_equal(tgt1, self.res1)
  2090. assert_(np.all(np.abs(tgt1) <= 1.0))
  2091. tgt2 = corrcoef(self.A, self.B)
  2092. assert_almost_equal(tgt2, self.res2)
  2093. assert_(np.all(np.abs(tgt2) <= 1.0))
  2094. def test_complex(self):
  2095. x = np.array([[1, 2, 3], [1j, 2j, 3j]])
  2096. res = corrcoef(x)
  2097. tgt = np.array([[1., -1.j], [1.j, 1.]])
  2098. assert_allclose(res, tgt)
  2099. assert_(np.all(np.abs(res) <= 1.0))
  2100. def test_xy(self):
  2101. x = np.array([[1, 2, 3]])
  2102. y = np.array([[1j, 2j, 3j]])
  2103. assert_allclose(np.corrcoef(x, y), np.array([[1., -1.j], [1.j, 1.]]))
  2104. def test_empty(self):
  2105. with warnings.catch_warnings(record=True):
  2106. warnings.simplefilter('always', RuntimeWarning)
  2107. assert_array_equal(corrcoef(np.array([])), np.nan)
  2108. assert_array_equal(corrcoef(np.array([]).reshape(0, 2)),
  2109. np.array([]).reshape(0, 0))
  2110. assert_array_equal(corrcoef(np.array([]).reshape(2, 0)),
  2111. np.array([[np.nan, np.nan], [np.nan, np.nan]]))
  2112. def test_extreme(self):
  2113. x = [[1e-100, 1e100], [1e100, 1e-100]]
  2114. with np.errstate(all='raise'):
  2115. c = corrcoef(x)
  2116. assert_array_almost_equal(c, np.array([[1., -1.], [-1., 1.]]))
  2117. assert_(np.all(np.abs(c) <= 1.0))
  2118. @pytest.mark.parametrize("test_type", np_floats)
  2119. def test_corrcoef_dtype(self, test_type):
  2120. cast_A = self.A.astype(test_type)
  2121. res = corrcoef(cast_A, dtype=test_type)
  2122. assert test_type == res.dtype
  2123. class TestCov:
  2124. x1 = np.array([[0, 2], [1, 1], [2, 0]]).T
  2125. res1 = np.array([[1., -1.], [-1., 1.]])
  2126. x2 = np.array([0.0, 1.0, 2.0], ndmin=2)
  2127. frequencies = np.array([1, 4, 1])
  2128. x2_repeats = np.array([[0.0], [1.0], [1.0], [1.0], [1.0], [2.0]]).T
  2129. res2 = np.array([[0.4, -0.4], [-0.4, 0.4]])
  2130. unit_frequencies = np.ones(3, dtype=np.int_)
  2131. weights = np.array([1.0, 4.0, 1.0])
  2132. res3 = np.array([[2. / 3., -2. / 3.], [-2. / 3., 2. / 3.]])
  2133. unit_weights = np.ones(3)
  2134. x3 = np.array([0.3942, 0.5969, 0.7730, 0.9918, 0.7964])
  2135. def test_basic(self):
  2136. assert_allclose(cov(self.x1), self.res1)
  2137. def test_complex(self):
  2138. x = np.array([[1, 2, 3], [1j, 2j, 3j]])
  2139. res = np.array([[1., -1.j], [1.j, 1.]])
  2140. assert_allclose(cov(x), res)
  2141. assert_allclose(cov(x, aweights=np.ones(3)), res)
  2142. def test_xy(self):
  2143. x = np.array([[1, 2, 3]])
  2144. y = np.array([[1j, 2j, 3j]])
  2145. assert_allclose(cov(x, y), np.array([[1., -1.j], [1.j, 1.]]))
  2146. def test_empty(self):
  2147. with warnings.catch_warnings(record=True):
  2148. warnings.simplefilter('always', RuntimeWarning)
  2149. assert_array_equal(cov(np.array([])), np.nan)
  2150. assert_array_equal(cov(np.array([]).reshape(0, 2)),
  2151. np.array([]).reshape(0, 0))
  2152. assert_array_equal(cov(np.array([]).reshape(2, 0)),
  2153. np.array([[np.nan, np.nan], [np.nan, np.nan]]))
  2154. def test_wrong_ddof(self):
  2155. with warnings.catch_warnings(record=True):
  2156. warnings.simplefilter('always', RuntimeWarning)
  2157. assert_array_equal(cov(self.x1, ddof=5),
  2158. np.array([[np.inf, -np.inf],
  2159. [-np.inf, np.inf]]))
  2160. def test_1D_rowvar(self):
  2161. assert_allclose(cov(self.x3), cov(self.x3, rowvar=False))
  2162. y = np.array([0.0780, 0.3107, 0.2111, 0.0334, 0.8501])
  2163. assert_allclose(cov(self.x3, y), cov(self.x3, y, rowvar=False))
  2164. def test_1D_variance(self):
  2165. assert_allclose(cov(self.x3, ddof=1), np.var(self.x3, ddof=1))
  2166. def test_fweights(self):
  2167. assert_allclose(cov(self.x2, fweights=self.frequencies),
  2168. cov(self.x2_repeats))
  2169. assert_allclose(cov(self.x1, fweights=self.frequencies),
  2170. self.res2)
  2171. assert_allclose(cov(self.x1, fweights=self.unit_frequencies),
  2172. self.res1)
  2173. nonint = self.frequencies + 0.5
  2174. assert_raises(TypeError, cov, self.x1, fweights=nonint)
  2175. f = np.ones((2, 3), dtype=np.int_)
  2176. assert_raises(RuntimeError, cov, self.x1, fweights=f)
  2177. f = np.ones(2, dtype=np.int_)
  2178. assert_raises(RuntimeError, cov, self.x1, fweights=f)
  2179. f = -1 * np.ones(3, dtype=np.int_)
  2180. assert_raises(ValueError, cov, self.x1, fweights=f)
  2181. def test_aweights(self):
  2182. assert_allclose(cov(self.x1, aweights=self.weights), self.res3)
  2183. assert_allclose(cov(self.x1, aweights=3.0 * self.weights),
  2184. cov(self.x1, aweights=self.weights))
  2185. assert_allclose(cov(self.x1, aweights=self.unit_weights), self.res1)
  2186. w = np.ones((2, 3))
  2187. assert_raises(RuntimeError, cov, self.x1, aweights=w)
  2188. w = np.ones(2)
  2189. assert_raises(RuntimeError, cov, self.x1, aweights=w)
  2190. w = -1.0 * np.ones(3)
  2191. assert_raises(ValueError, cov, self.x1, aweights=w)
  2192. def test_unit_fweights_and_aweights(self):
  2193. assert_allclose(cov(self.x2, fweights=self.frequencies,
  2194. aweights=self.unit_weights),
  2195. cov(self.x2_repeats))
  2196. assert_allclose(cov(self.x1, fweights=self.frequencies,
  2197. aweights=self.unit_weights),
  2198. self.res2)
  2199. assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
  2200. aweights=self.unit_weights),
  2201. self.res1)
  2202. assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
  2203. aweights=self.weights),
  2204. self.res3)
  2205. assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
  2206. aweights=3.0 * self.weights),
  2207. cov(self.x1, aweights=self.weights))
  2208. assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
  2209. aweights=self.unit_weights),
  2210. self.res1)
  2211. @pytest.mark.parametrize("test_type", np_floats)
  2212. def test_cov_dtype(self, test_type):
  2213. cast_x1 = self.x1.astype(test_type)
  2214. res = cov(cast_x1, dtype=test_type)
  2215. assert test_type == res.dtype
  2216. def test_gh_27658(self):
  2217. x = np.ones((3, 1))
  2218. expected = np.cov(x, ddof=0, rowvar=True)
  2219. actual = np.cov(x.T, ddof=0, rowvar=False)
  2220. assert_allclose(actual, expected, strict=True)
  2221. class Test_I0:
  2222. def test_simple(self):
  2223. assert_almost_equal(
  2224. i0(0.5),
  2225. np.array(1.0634833707413234))
  2226. # need at least one test above 8, as the implementation is piecewise
  2227. A = np.array([0.49842636, 0.6969809, 0.22011976, 0.0155549, 10.0])
  2228. expected = np.array([1.06307822, 1.12518299, 1.01214991,
  2229. 1.00006049, 2815.71662847])
  2230. assert_almost_equal(i0(A), expected)
  2231. assert_almost_equal(i0(-A), expected)
  2232. B = np.array([[0.827002, 0.99959078],
  2233. [0.89694769, 0.39298162],
  2234. [0.37954418, 0.05206293],
  2235. [0.36465447, 0.72446427],
  2236. [0.48164949, 0.50324519]])
  2237. assert_almost_equal(
  2238. i0(B),
  2239. np.array([[1.17843223, 1.26583466],
  2240. [1.21147086, 1.03898290],
  2241. [1.03633899, 1.00067775],
  2242. [1.03352052, 1.13557954],
  2243. [1.05884290, 1.06432317]]))
  2244. # Regression test for gh-11205
  2245. i0_0 = np.i0([0.])
  2246. assert_equal(i0_0.shape, (1,))
  2247. assert_array_equal(np.i0([0.]), np.array([1.]))
  2248. def test_non_array(self):
  2249. a = np.arange(4)
  2250. class array_like:
  2251. __array_interface__ = a.__array_interface__
  2252. def __array_wrap__(self, arr, context, return_scalar):
  2253. return self
  2254. # E.g. pandas series survive ufunc calls through array-wrap:
  2255. assert isinstance(np.abs(array_like()), array_like)
  2256. exp = np.i0(a)
  2257. res = np.i0(array_like())
  2258. assert_array_equal(exp, res)
  2259. def test_complex(self):
  2260. a = np.array([0, 1 + 2j])
  2261. with pytest.raises(TypeError, match="i0 not supported for complex values"):
  2262. res = i0(a)
  2263. class TestKaiser:
  2264. def test_simple(self):
  2265. assert_(np.isfinite(kaiser(1, 1.0)))
  2266. assert_almost_equal(kaiser(0, 1.0),
  2267. np.array([]))
  2268. assert_almost_equal(kaiser(2, 1.0),
  2269. np.array([0.78984831, 0.78984831]))
  2270. assert_almost_equal(kaiser(5, 1.0),
  2271. np.array([0.78984831, 0.94503323, 1.,
  2272. 0.94503323, 0.78984831]))
  2273. assert_almost_equal(kaiser(5, 1.56789),
  2274. np.array([0.58285404, 0.88409679, 1.,
  2275. 0.88409679, 0.58285404]))
  2276. def test_int_beta(self):
  2277. kaiser(3, 4)
  2278. class TestMeshgrid:
  2279. def test_simple(self):
  2280. [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7])
  2281. assert_array_equal(X, np.array([[1, 2, 3],
  2282. [1, 2, 3],
  2283. [1, 2, 3],
  2284. [1, 2, 3]]))
  2285. assert_array_equal(Y, np.array([[4, 4, 4],
  2286. [5, 5, 5],
  2287. [6, 6, 6],
  2288. [7, 7, 7]]))
  2289. def test_single_input(self):
  2290. [X] = meshgrid([1, 2, 3, 4])
  2291. assert_array_equal(X, np.array([1, 2, 3, 4]))
  2292. def test_no_input(self):
  2293. args = []
  2294. assert_array_equal([], meshgrid(*args))
  2295. assert_array_equal([], meshgrid(*args, copy=False))
  2296. def test_indexing(self):
  2297. x = [1, 2, 3]
  2298. y = [4, 5, 6, 7]
  2299. [X, Y] = meshgrid(x, y, indexing='ij')
  2300. assert_array_equal(X, np.array([[1, 1, 1, 1],
  2301. [2, 2, 2, 2],
  2302. [3, 3, 3, 3]]))
  2303. assert_array_equal(Y, np.array([[4, 5, 6, 7],
  2304. [4, 5, 6, 7],
  2305. [4, 5, 6, 7]]))
  2306. # Test expected shapes:
  2307. z = [8, 9]
  2308. assert_(meshgrid(x, y)[0].shape == (4, 3))
  2309. assert_(meshgrid(x, y, indexing='ij')[0].shape == (3, 4))
  2310. assert_(meshgrid(x, y, z)[0].shape == (4, 3, 2))
  2311. assert_(meshgrid(x, y, z, indexing='ij')[0].shape == (3, 4, 2))
  2312. assert_raises(ValueError, meshgrid, x, y, indexing='notvalid')
  2313. def test_sparse(self):
  2314. [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7], sparse=True)
  2315. assert_array_equal(X, np.array([[1, 2, 3]]))
  2316. assert_array_equal(Y, np.array([[4], [5], [6], [7]]))
  2317. def test_invalid_arguments(self):
  2318. # Test that meshgrid complains about invalid arguments
  2319. # Regression test for issue #4755:
  2320. # https://github.com/numpy/numpy/issues/4755
  2321. assert_raises(TypeError, meshgrid,
  2322. [1, 2, 3], [4, 5, 6, 7], indices='ij')
  2323. def test_return_type(self):
  2324. # Test for appropriate dtype in returned arrays.
  2325. # Regression test for issue #5297
  2326. # https://github.com/numpy/numpy/issues/5297
  2327. x = np.arange(0, 10, dtype=np.float32)
  2328. y = np.arange(10, 20, dtype=np.float64)
  2329. X, Y = np.meshgrid(x, y)
  2330. assert_(X.dtype == x.dtype)
  2331. assert_(Y.dtype == y.dtype)
  2332. # copy
  2333. X, Y = np.meshgrid(x, y, copy=True)
  2334. assert_(X.dtype == x.dtype)
  2335. assert_(Y.dtype == y.dtype)
  2336. # sparse
  2337. X, Y = np.meshgrid(x, y, sparse=True)
  2338. assert_(X.dtype == x.dtype)
  2339. assert_(Y.dtype == y.dtype)
  2340. def test_writeback(self):
  2341. # Issue 8561
  2342. X = np.array([1.1, 2.2])
  2343. Y = np.array([3.3, 4.4])
  2344. x, y = np.meshgrid(X, Y, sparse=False, copy=True)
  2345. x[0, :] = 0
  2346. assert_equal(x[0, :], 0)
  2347. assert_equal(x[1, :], X)
  2348. def test_nd_shape(self):
  2349. a, b, c, d, e = np.meshgrid(*([0] * i for i in range(1, 6)))
  2350. expected_shape = (2, 1, 3, 4, 5)
  2351. assert_equal(a.shape, expected_shape)
  2352. assert_equal(b.shape, expected_shape)
  2353. assert_equal(c.shape, expected_shape)
  2354. assert_equal(d.shape, expected_shape)
  2355. assert_equal(e.shape, expected_shape)
  2356. def test_nd_values(self):
  2357. a, b, c = np.meshgrid([0], [1, 2], [3, 4, 5])
  2358. assert_equal(a, [[[0, 0, 0]], [[0, 0, 0]]])
  2359. assert_equal(b, [[[1, 1, 1]], [[2, 2, 2]]])
  2360. assert_equal(c, [[[3, 4, 5]], [[3, 4, 5]]])
  2361. def test_nd_indexing(self):
  2362. a, b, c = np.meshgrid([0], [1, 2], [3, 4, 5], indexing='ij')
  2363. assert_equal(a, [[[0, 0, 0], [0, 0, 0]]])
  2364. assert_equal(b, [[[1, 1, 1], [2, 2, 2]]])
  2365. assert_equal(c, [[[3, 4, 5], [3, 4, 5]]])
  2366. class TestPiecewise:
  2367. def test_simple(self):
  2368. # Condition is single bool list
  2369. x = piecewise([0, 0], [True, False], [1])
  2370. assert_array_equal(x, [1, 0])
  2371. # List of conditions: single bool list
  2372. x = piecewise([0, 0], [[True, False]], [1])
  2373. assert_array_equal(x, [1, 0])
  2374. # Conditions is single bool array
  2375. x = piecewise([0, 0], np.array([True, False]), [1])
  2376. assert_array_equal(x, [1, 0])
  2377. # Condition is single int array
  2378. x = piecewise([0, 0], np.array([1, 0]), [1])
  2379. assert_array_equal(x, [1, 0])
  2380. # List of conditions: int array
  2381. x = piecewise([0, 0], [np.array([1, 0])], [1])
  2382. assert_array_equal(x, [1, 0])
  2383. x = piecewise([0, 0], [[False, True]], [lambda x:-1])
  2384. assert_array_equal(x, [0, -1])
  2385. assert_raises_regex(ValueError, '1 or 2 functions are expected',
  2386. piecewise, [0, 0], [[False, True]], [])
  2387. assert_raises_regex(ValueError, '1 or 2 functions are expected',
  2388. piecewise, [0, 0], [[False, True]], [1, 2, 3])
  2389. def test_two_conditions(self):
  2390. x = piecewise([1, 2], [[True, False], [False, True]], [3, 4])
  2391. assert_array_equal(x, [3, 4])
  2392. def test_scalar_domains_three_conditions(self):
  2393. x = piecewise(3, [True, False, False], [4, 2, 0])
  2394. assert_equal(x, 4)
  2395. def test_default(self):
  2396. # No value specified for x[1], should be 0
  2397. x = piecewise([1, 2], [True, False], [2])
  2398. assert_array_equal(x, [2, 0])
  2399. # Should set x[1] to 3
  2400. x = piecewise([1, 2], [True, False], [2, 3])
  2401. assert_array_equal(x, [2, 3])
  2402. def test_0d(self):
  2403. x = np.array(3)
  2404. y = piecewise(x, x > 3, [4, 0])
  2405. assert_(y.ndim == 0)
  2406. assert_(y == 0)
  2407. x = 5
  2408. y = piecewise(x, [True, False], [1, 0])
  2409. assert_(y.ndim == 0)
  2410. assert_(y == 1)
  2411. # With 3 ranges (It was failing, before)
  2412. y = piecewise(x, [False, False, True], [1, 2, 3])
  2413. assert_array_equal(y, 3)
  2414. def test_0d_comparison(self):
  2415. x = 3
  2416. y = piecewise(x, [x <= 3, x > 3], [4, 0]) # Should succeed.
  2417. assert_equal(y, 4)
  2418. # With 3 ranges (It was failing, before)
  2419. x = 4
  2420. y = piecewise(x, [x <= 3, (x > 3) * (x <= 5), x > 5], [1, 2, 3])
  2421. assert_array_equal(y, 2)
  2422. assert_raises_regex(ValueError, '2 or 3 functions are expected',
  2423. piecewise, x, [x <= 3, x > 3], [1])
  2424. assert_raises_regex(ValueError, '2 or 3 functions are expected',
  2425. piecewise, x, [x <= 3, x > 3], [1, 1, 1, 1])
  2426. def test_0d_0d_condition(self):
  2427. x = np.array(3)
  2428. c = np.array(x > 3)
  2429. y = piecewise(x, [c], [1, 2])
  2430. assert_equal(y, 2)
  2431. def test_multidimensional_extrafunc(self):
  2432. x = np.array([[-2.5, -1.5, -0.5],
  2433. [0.5, 1.5, 2.5]])
  2434. y = piecewise(x, [x < 0, x >= 2], [-1, 1, 3])
  2435. assert_array_equal(y, np.array([[-1., -1., -1.],
  2436. [3., 3., 1.]]))
  2437. def test_subclasses(self):
  2438. class subclass(np.ndarray):
  2439. pass
  2440. x = np.arange(5.).view(subclass)
  2441. r = piecewise(x, [x < 2., x >= 4], [-1., 1., 0.])
  2442. assert_equal(type(r), subclass)
  2443. assert_equal(r, [-1., -1., 0., 0., 1.])
  2444. class TestBincount:
  2445. def test_simple(self):
  2446. y = np.bincount(np.arange(4))
  2447. assert_array_equal(y, np.ones(4))
  2448. def test_simple2(self):
  2449. y = np.bincount(np.array([1, 5, 2, 4, 1]))
  2450. assert_array_equal(y, np.array([0, 2, 1, 0, 1, 1]))
  2451. def test_simple_weight(self):
  2452. x = np.arange(4)
  2453. w = np.array([0.2, 0.3, 0.5, 0.1])
  2454. y = np.bincount(x, w)
  2455. assert_array_equal(y, w)
  2456. def test_simple_weight2(self):
  2457. x = np.array([1, 2, 4, 5, 2])
  2458. w = np.array([0.2, 0.3, 0.5, 0.1, 0.2])
  2459. y = np.bincount(x, w)
  2460. assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1]))
  2461. def test_with_minlength(self):
  2462. x = np.array([0, 1, 0, 1, 1])
  2463. y = np.bincount(x, minlength=3)
  2464. assert_array_equal(y, np.array([2, 3, 0]))
  2465. x = []
  2466. y = np.bincount(x, minlength=0)
  2467. assert_array_equal(y, np.array([]))
  2468. def test_with_minlength_smaller_than_maxvalue(self):
  2469. x = np.array([0, 1, 1, 2, 2, 3, 3])
  2470. y = np.bincount(x, minlength=2)
  2471. assert_array_equal(y, np.array([1, 2, 2, 2]))
  2472. y = np.bincount(x, minlength=0)
  2473. assert_array_equal(y, np.array([1, 2, 2, 2]))
  2474. def test_with_minlength_and_weights(self):
  2475. x = np.array([1, 2, 4, 5, 2])
  2476. w = np.array([0.2, 0.3, 0.5, 0.1, 0.2])
  2477. y = np.bincount(x, w, 8)
  2478. assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1, 0, 0]))
  2479. def test_empty(self):
  2480. x = np.array([], dtype=int)
  2481. y = np.bincount(x)
  2482. assert_array_equal(x, y)
  2483. def test_empty_with_minlength(self):
  2484. x = np.array([], dtype=int)
  2485. y = np.bincount(x, minlength=5)
  2486. assert_array_equal(y, np.zeros(5, dtype=int))
  2487. @pytest.mark.parametrize('minlength', [0, 3])
  2488. def test_empty_list(self, minlength):
  2489. assert_array_equal(np.bincount([], minlength=minlength),
  2490. np.zeros(minlength, dtype=int))
  2491. def test_with_incorrect_minlength(self):
  2492. x = np.array([], dtype=int)
  2493. assert_raises_regex(TypeError,
  2494. "'str' object cannot be interpreted",
  2495. lambda: np.bincount(x, minlength="foobar"))
  2496. assert_raises_regex(ValueError,
  2497. "must not be negative",
  2498. lambda: np.bincount(x, minlength=-1))
  2499. x = np.arange(5)
  2500. assert_raises_regex(TypeError,
  2501. "'str' object cannot be interpreted",
  2502. lambda: np.bincount(x, minlength="foobar"))
  2503. assert_raises_regex(ValueError,
  2504. "must not be negative",
  2505. lambda: np.bincount(x, minlength=-1))
  2506. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  2507. def test_dtype_reference_leaks(self):
  2508. # gh-6805
  2509. intp_refcount = sys.getrefcount(np.dtype(np.intp))
  2510. double_refcount = sys.getrefcount(np.dtype(np.double))
  2511. for j in range(10):
  2512. np.bincount([1, 2, 3])
  2513. assert_equal(sys.getrefcount(np.dtype(np.intp)), intp_refcount)
  2514. assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)
  2515. for j in range(10):
  2516. np.bincount([1, 2, 3], [4, 5, 6])
  2517. assert_equal(sys.getrefcount(np.dtype(np.intp)), intp_refcount)
  2518. assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)
  2519. @pytest.mark.parametrize("vals", [[[2, 2]], 2])
  2520. def test_error_not_1d(self, vals):
  2521. # Test that values has to be 1-D (both as array and nested list)
  2522. vals_arr = np.asarray(vals)
  2523. with assert_raises(ValueError):
  2524. np.bincount(vals_arr)
  2525. with assert_raises(ValueError):
  2526. np.bincount(vals)
  2527. @pytest.mark.parametrize("dt", np.typecodes["AllInteger"])
  2528. def test_gh_28354(self, dt):
  2529. a = np.array([0, 1, 1, 3, 2, 1, 7], dtype=dt)
  2530. actual = np.bincount(a)
  2531. expected = [1, 3, 1, 1, 0, 0, 0, 1]
  2532. assert_array_equal(actual, expected)
  2533. def test_contiguous_handling(self):
  2534. # check for absence of hard crash
  2535. np.bincount(np.arange(10000)[::2])
  2536. def test_gh_28354_array_like(self):
  2537. class A:
  2538. def __array__(self):
  2539. return np.array([0, 1, 1, 3, 2, 1, 7], dtype=np.uint64)
  2540. a = A()
  2541. actual = np.bincount(a)
  2542. expected = [1, 3, 1, 1, 0, 0, 0, 1]
  2543. assert_array_equal(actual, expected)
  2544. class TestInterp:
  2545. def test_exceptions(self):
  2546. assert_raises(ValueError, interp, 0, [], [])
  2547. assert_raises(ValueError, interp, 0, [0], [1, 2])
  2548. assert_raises(ValueError, interp, 0, [0, 1], [1, 2], period=0)
  2549. assert_raises(ValueError, interp, 0, [], [], period=360)
  2550. assert_raises(ValueError, interp, 0, [0], [1, 2], period=360)
  2551. def test_basic(self):
  2552. x = np.linspace(0, 1, 5)
  2553. y = np.linspace(0, 1, 5)
  2554. x0 = np.linspace(0, 1, 50)
  2555. assert_almost_equal(np.interp(x0, x, y), x0)
  2556. def test_right_left_behavior(self):
  2557. # Needs range of sizes to test different code paths.
  2558. # size ==1 is special cased, 1 < size < 5 is linear search, and
  2559. # size >= 5 goes through local search and possibly binary search.
  2560. for size in range(1, 10):
  2561. xp = np.arange(size, dtype=np.double)
  2562. yp = np.ones(size, dtype=np.double)
  2563. incpts = np.array([-1, 0, size - 1, size], dtype=np.double)
  2564. decpts = incpts[::-1]
  2565. incres = interp(incpts, xp, yp)
  2566. decres = interp(decpts, xp, yp)
  2567. inctgt = np.array([1, 1, 1, 1], dtype=float)
  2568. dectgt = inctgt[::-1]
  2569. assert_equal(incres, inctgt)
  2570. assert_equal(decres, dectgt)
  2571. incres = interp(incpts, xp, yp, left=0)
  2572. decres = interp(decpts, xp, yp, left=0)
  2573. inctgt = np.array([0, 1, 1, 1], dtype=float)
  2574. dectgt = inctgt[::-1]
  2575. assert_equal(incres, inctgt)
  2576. assert_equal(decres, dectgt)
  2577. incres = interp(incpts, xp, yp, right=2)
  2578. decres = interp(decpts, xp, yp, right=2)
  2579. inctgt = np.array([1, 1, 1, 2], dtype=float)
  2580. dectgt = inctgt[::-1]
  2581. assert_equal(incres, inctgt)
  2582. assert_equal(decres, dectgt)
  2583. incres = interp(incpts, xp, yp, left=0, right=2)
  2584. decres = interp(decpts, xp, yp, left=0, right=2)
  2585. inctgt = np.array([0, 1, 1, 2], dtype=float)
  2586. dectgt = inctgt[::-1]
  2587. assert_equal(incres, inctgt)
  2588. assert_equal(decres, dectgt)
  2589. def test_scalar_interpolation_point(self):
  2590. x = np.linspace(0, 1, 5)
  2591. y = np.linspace(0, 1, 5)
  2592. x0 = 0
  2593. assert_almost_equal(np.interp(x0, x, y), x0)
  2594. x0 = .3
  2595. assert_almost_equal(np.interp(x0, x, y), x0)
  2596. x0 = np.float32(.3)
  2597. assert_almost_equal(np.interp(x0, x, y), x0)
  2598. x0 = np.float64(.3)
  2599. assert_almost_equal(np.interp(x0, x, y), x0)
  2600. x0 = np.nan
  2601. assert_almost_equal(np.interp(x0, x, y), x0)
  2602. def test_non_finite_behavior_exact_x(self):
  2603. x = [1, 2, 2.5, 3, 4]
  2604. xp = [1, 2, 3, 4]
  2605. fp = [1, 2, np.inf, 4]
  2606. assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.inf, np.inf, 4])
  2607. fp = [1, 2, np.nan, 4]
  2608. assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.nan, np.nan, 4])
  2609. @pytest.fixture(params=[
  2610. np.float64,
  2611. lambda x: _make_complex(x, 0),
  2612. lambda x: _make_complex(0, x),
  2613. lambda x: _make_complex(x, np.multiply(x, -2))
  2614. ], ids=[
  2615. 'real',
  2616. 'complex-real',
  2617. 'complex-imag',
  2618. 'complex-both'
  2619. ])
  2620. def sc(self, request):
  2621. """ scale function used by the below tests """
  2622. return request.param
  2623. def test_non_finite_any_nan(self, sc):
  2624. """ test that nans are propagated """
  2625. assert_equal(np.interp(0.5, [np.nan, 1], sc([ 0, 10])), sc(np.nan))
  2626. assert_equal(np.interp(0.5, [ 0, np.nan], sc([ 0, 10])), sc(np.nan))
  2627. assert_equal(np.interp(0.5, [ 0, 1], sc([np.nan, 10])), sc(np.nan))
  2628. assert_equal(np.interp(0.5, [ 0, 1], sc([ 0, np.nan])), sc(np.nan))
  2629. def test_non_finite_inf(self, sc):
  2630. """ Test that interp between opposite infs gives nan """
  2631. inf = np.inf
  2632. nan = np.nan
  2633. assert_equal(np.interp(0.5, [-inf, +inf], sc([ 0, 10])), sc(nan))
  2634. assert_equal(np.interp(0.5, [ 0, 1], sc([-inf, +inf])), sc(nan))
  2635. assert_equal(np.interp(0.5, [ 0, 1], sc([+inf, -inf])), sc(nan))
  2636. # unless the y values are equal
  2637. assert_equal(np.interp(0.5, [-np.inf, +np.inf], sc([ 10, 10])), sc(10))
  2638. def test_non_finite_half_inf_xf(self, sc):
  2639. """ Test that interp where both axes have a bound at inf gives nan """
  2640. inf = np.inf
  2641. nan = np.nan
  2642. assert_equal(np.interp(0.5, [-inf, 1], sc([-inf, 10])), sc(nan))
  2643. assert_equal(np.interp(0.5, [-inf, 1], sc([+inf, 10])), sc(nan))
  2644. assert_equal(np.interp(0.5, [-inf, 1], sc([ 0, -inf])), sc(nan))
  2645. assert_equal(np.interp(0.5, [-inf, 1], sc([ 0, +inf])), sc(nan))
  2646. assert_equal(np.interp(0.5, [ 0, +inf], sc([-inf, 10])), sc(nan))
  2647. assert_equal(np.interp(0.5, [ 0, +inf], sc([+inf, 10])), sc(nan))
  2648. assert_equal(np.interp(0.5, [ 0, +inf], sc([ 0, -inf])), sc(nan))
  2649. assert_equal(np.interp(0.5, [ 0, +inf], sc([ 0, +inf])), sc(nan))
  2650. def test_non_finite_half_inf_x(self, sc):
  2651. """ Test interp where the x axis has a bound at inf """
  2652. assert_equal(np.interp(0.5, [-np.inf, -np.inf], sc([0, 10])), sc(10))
  2653. assert_equal(np.interp(0.5, [-np.inf, 1 ], sc([0, 10])), sc(10)) # noqa: E202
  2654. assert_equal(np.interp(0.5, [ 0, +np.inf], sc([0, 10])), sc(0))
  2655. assert_equal(np.interp(0.5, [+np.inf, +np.inf], sc([0, 10])), sc(0))
  2656. def test_non_finite_half_inf_f(self, sc):
  2657. """ Test interp where the f axis has a bound at inf """
  2658. assert_equal(np.interp(0.5, [0, 1], sc([ 0, -np.inf])), sc(-np.inf))
  2659. assert_equal(np.interp(0.5, [0, 1], sc([ 0, +np.inf])), sc(+np.inf))
  2660. assert_equal(np.interp(0.5, [0, 1], sc([-np.inf, 10])), sc(-np.inf))
  2661. assert_equal(np.interp(0.5, [0, 1], sc([+np.inf, 10])), sc(+np.inf))
  2662. assert_equal(np.interp(0.5, [0, 1], sc([-np.inf, -np.inf])), sc(-np.inf))
  2663. assert_equal(np.interp(0.5, [0, 1], sc([+np.inf, +np.inf])), sc(+np.inf))
  2664. def test_complex_interp(self):
  2665. # test complex interpolation
  2666. x = np.linspace(0, 1, 5)
  2667. y = np.linspace(0, 1, 5) + (1 + np.linspace(0, 1, 5)) * 1.0j
  2668. x0 = 0.3
  2669. y0 = x0 + (1 + x0) * 1.0j
  2670. assert_almost_equal(np.interp(x0, x, y), y0)
  2671. # test complex left and right
  2672. x0 = -1
  2673. left = 2 + 3.0j
  2674. assert_almost_equal(np.interp(x0, x, y, left=left), left)
  2675. x0 = 2.0
  2676. right = 2 + 3.0j
  2677. assert_almost_equal(np.interp(x0, x, y, right=right), right)
  2678. # test complex non finite
  2679. x = [1, 2, 2.5, 3, 4]
  2680. xp = [1, 2, 3, 4]
  2681. fp = [1, 2 + 1j, np.inf, 4]
  2682. y = [1, 2 + 1j, np.inf + 0.5j, np.inf, 4]
  2683. assert_almost_equal(np.interp(x, xp, fp), y)
  2684. # test complex periodic
  2685. x = [-180, -170, -185, 185, -10, -5, 0, 365]
  2686. xp = [190, -190, 350, -350]
  2687. fp = [5 + 1.0j, 10 + 2j, 3 + 3j, 4 + 4j]
  2688. y = [7.5 + 1.5j, 5. + 1.0j, 8.75 + 1.75j, 6.25 + 1.25j, 3. + 3j, 3.25 + 3.25j,
  2689. 3.5 + 3.5j, 3.75 + 3.75j]
  2690. assert_almost_equal(np.interp(x, xp, fp, period=360), y)
  2691. def test_zero_dimensional_interpolation_point(self):
  2692. x = np.linspace(0, 1, 5)
  2693. y = np.linspace(0, 1, 5)
  2694. x0 = np.array(.3)
  2695. assert_almost_equal(np.interp(x0, x, y), x0)
  2696. xp = np.array([0, 2, 4])
  2697. fp = np.array([1, -1, 1])
  2698. actual = np.interp(np.array(1), xp, fp)
  2699. assert_equal(actual, 0)
  2700. assert_(isinstance(actual, np.float64))
  2701. actual = np.interp(np.array(4.5), xp, fp, period=4)
  2702. assert_equal(actual, 0.5)
  2703. assert_(isinstance(actual, np.float64))
  2704. def test_if_len_x_is_small(self):
  2705. xp = np.arange(0, 10, 0.0001)
  2706. fp = np.sin(xp)
  2707. assert_almost_equal(np.interp(np.pi, xp, fp), 0.0)
  2708. def test_period(self):
  2709. x = [-180, -170, -185, 185, -10, -5, 0, 365]
  2710. xp = [190, -190, 350, -350]
  2711. fp = [5, 10, 3, 4]
  2712. y = [7.5, 5., 8.75, 6.25, 3., 3.25, 3.5, 3.75]
  2713. assert_almost_equal(np.interp(x, xp, fp, period=360), y)
  2714. x = np.array(x, order='F').reshape(2, -1)
  2715. y = np.array(y, order='C').reshape(2, -1)
  2716. assert_almost_equal(np.interp(x, xp, fp, period=360), y)
  2717. quantile_methods = [
  2718. 'inverted_cdf', 'averaged_inverted_cdf', 'closest_observation',
  2719. 'interpolated_inverted_cdf', 'hazen', 'weibull', 'linear',
  2720. 'median_unbiased', 'normal_unbiased', 'nearest', 'lower', 'higher',
  2721. 'midpoint']
  2722. # Note: Technically, averaged_inverted_cdf and midpoint are not interpolated.
  2723. # but NumPy doesn't currently make a difference (at least w.r.t. to promotion).
  2724. interpolating_quantile_methods = [
  2725. 'averaged_inverted_cdf', 'interpolated_inverted_cdf', 'hazen', 'weibull',
  2726. 'linear', 'median_unbiased', 'normal_unbiased', 'midpoint']
  2727. methods_supporting_weights = ["inverted_cdf"]
  2728. class TestPercentile:
  2729. def test_basic(self):
  2730. x = np.arange(8) * 0.5
  2731. assert_equal(np.percentile(x, 0), 0.)
  2732. assert_equal(np.percentile(x, 100), 3.5)
  2733. assert_equal(np.percentile(x, 50), 1.75)
  2734. x[1] = np.nan
  2735. assert_equal(np.percentile(x, 0), np.nan)
  2736. assert_equal(np.percentile(x, 0, method='nearest'), np.nan)
  2737. assert_equal(np.percentile(x, 0, method='inverted_cdf'), np.nan)
  2738. assert_equal(
  2739. np.percentile(x, 0, method='inverted_cdf',
  2740. weights=np.ones_like(x)),
  2741. np.nan,
  2742. )
  2743. def test_fraction(self):
  2744. x = [Fraction(i, 2) for i in range(8)]
  2745. p = np.percentile(x, Fraction(0))
  2746. assert_equal(p, Fraction(0))
  2747. assert_equal(type(p), Fraction)
  2748. p = np.percentile(x, Fraction(100))
  2749. assert_equal(p, Fraction(7, 2))
  2750. assert_equal(type(p), Fraction)
  2751. p = np.percentile(x, Fraction(50))
  2752. assert_equal(p, Fraction(7, 4))
  2753. assert_equal(type(p), Fraction)
  2754. p = np.percentile(x, [Fraction(50)])
  2755. assert_equal(p, np.array([Fraction(7, 4)]))
  2756. assert_equal(type(p), np.ndarray)
  2757. def test_api(self):
  2758. d = np.ones(5)
  2759. np.percentile(d, 5, None, None, False)
  2760. np.percentile(d, 5, None, None, False, 'linear')
  2761. o = np.ones((1,))
  2762. np.percentile(d, 5, None, o, False, 'linear')
  2763. def test_complex(self):
  2764. arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='G')
  2765. assert_raises(TypeError, np.percentile, arr_c, 0.5)
  2766. arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='D')
  2767. assert_raises(TypeError, np.percentile, arr_c, 0.5)
  2768. arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='F')
  2769. assert_raises(TypeError, np.percentile, arr_c, 0.5)
  2770. def test_2D(self):
  2771. x = np.array([[1, 1, 1],
  2772. [1, 1, 1],
  2773. [4, 4, 3],
  2774. [1, 1, 1],
  2775. [1, 1, 1]])
  2776. assert_array_equal(np.percentile(x, 50, axis=0), [1, 1, 1])
  2777. @pytest.mark.parametrize("dtype", np.typecodes["Float"])
  2778. def test_linear_nan_1D(self, dtype):
  2779. # METHOD 1 of H&F
  2780. arr = np.asarray([15.0, np.nan, 35.0, 40.0, 50.0], dtype=dtype)
  2781. res = np.percentile(
  2782. arr,
  2783. 40.0,
  2784. method="linear")
  2785. np.testing.assert_equal(res, np.nan)
  2786. np.testing.assert_equal(res.dtype, arr.dtype)
  2787. H_F_TYPE_CODES = [(int_type, np.float64)
  2788. for int_type in np.typecodes["AllInteger"]
  2789. ] + [(np.float16, np.float16),
  2790. (np.float32, np.float32),
  2791. (np.float64, np.float64),
  2792. (np.longdouble, np.longdouble),
  2793. (np.dtype("O"), np.float64)]
  2794. @pytest.mark.parametrize(["function", "quantile"],
  2795. [(np.quantile, 0.4),
  2796. (np.percentile, 40.0)])
  2797. @pytest.mark.parametrize(["input_dtype", "expected_dtype"], H_F_TYPE_CODES)
  2798. @pytest.mark.parametrize(["method", "weighted", "expected"],
  2799. [("inverted_cdf", False, 20),
  2800. ("inverted_cdf", True, 20),
  2801. ("averaged_inverted_cdf", False, 27.5),
  2802. ("closest_observation", False, 20),
  2803. ("interpolated_inverted_cdf", False, 20),
  2804. ("hazen", False, 27.5),
  2805. ("weibull", False, 26),
  2806. ("linear", False, 29),
  2807. ("median_unbiased", False, 27),
  2808. ("normal_unbiased", False, 27.125),
  2809. ])
  2810. def test_linear_interpolation(self,
  2811. function,
  2812. quantile,
  2813. method,
  2814. weighted,
  2815. expected,
  2816. input_dtype,
  2817. expected_dtype):
  2818. expected_dtype = np.dtype(expected_dtype)
  2819. arr = np.asarray([15.0, 20.0, 35.0, 40.0, 50.0], dtype=input_dtype)
  2820. weights = np.ones_like(arr) if weighted else None
  2821. if input_dtype is np.longdouble:
  2822. if function is np.quantile:
  2823. # 0.4 is not exactly representable and it matters
  2824. # for "averaged_inverted_cdf", so we need to cheat.
  2825. quantile = input_dtype("0.4")
  2826. # We want to use nulp, but that does not work for longdouble
  2827. test_function = np.testing.assert_almost_equal
  2828. else:
  2829. test_function = np.testing.assert_array_almost_equal_nulp
  2830. actual = function(arr, quantile, method=method, weights=weights)
  2831. test_function(actual, expected_dtype.type(expected))
  2832. if method in ["inverted_cdf", "closest_observation"]:
  2833. if input_dtype == "O":
  2834. np.testing.assert_equal(np.asarray(actual).dtype, np.float64)
  2835. else:
  2836. np.testing.assert_equal(np.asarray(actual).dtype,
  2837. np.dtype(input_dtype))
  2838. else:
  2839. np.testing.assert_equal(np.asarray(actual).dtype,
  2840. np.dtype(expected_dtype))
  2841. TYPE_CODES = np.typecodes["AllInteger"] + np.typecodes["Float"] + "O"
  2842. @pytest.mark.parametrize("dtype", TYPE_CODES)
  2843. def test_lower_higher(self, dtype):
  2844. assert_equal(np.percentile(np.arange(10, dtype=dtype), 50,
  2845. method='lower'), 4)
  2846. assert_equal(np.percentile(np.arange(10, dtype=dtype), 50,
  2847. method='higher'), 5)
  2848. @pytest.mark.parametrize("dtype", TYPE_CODES)
  2849. def test_midpoint(self, dtype):
  2850. assert_equal(np.percentile(np.arange(10, dtype=dtype), 51,
  2851. method='midpoint'), 4.5)
  2852. assert_equal(np.percentile(np.arange(9, dtype=dtype) + 1, 50,
  2853. method='midpoint'), 5)
  2854. assert_equal(np.percentile(np.arange(11, dtype=dtype), 51,
  2855. method='midpoint'), 5.5)
  2856. assert_equal(np.percentile(np.arange(11, dtype=dtype), 50,
  2857. method='midpoint'), 5)
  2858. @pytest.mark.parametrize("dtype", TYPE_CODES)
  2859. def test_nearest(self, dtype):
  2860. assert_equal(np.percentile(np.arange(10, dtype=dtype), 51,
  2861. method='nearest'), 5)
  2862. assert_equal(np.percentile(np.arange(10, dtype=dtype), 49,
  2863. method='nearest'), 4)
  2864. def test_linear_interpolation_extrapolation(self):
  2865. arr = np.random.rand(5)
  2866. actual = np.percentile(arr, 100)
  2867. np.testing.assert_equal(actual, arr.max())
  2868. actual = np.percentile(arr, 0)
  2869. np.testing.assert_equal(actual, arr.min())
  2870. def test_sequence(self):
  2871. x = np.arange(8) * 0.5
  2872. assert_equal(np.percentile(x, [0, 100, 50]), [0, 3.5, 1.75])
  2873. def test_axis(self):
  2874. x = np.arange(12).reshape(3, 4)
  2875. assert_equal(np.percentile(x, (25, 50, 100)), [2.75, 5.5, 11.0])
  2876. r0 = [[2, 3, 4, 5], [4, 5, 6, 7], [8, 9, 10, 11]]
  2877. assert_equal(np.percentile(x, (25, 50, 100), axis=0), r0)
  2878. r1 = [[0.75, 1.5, 3], [4.75, 5.5, 7], [8.75, 9.5, 11]]
  2879. assert_equal(np.percentile(x, (25, 50, 100), axis=1), np.array(r1).T)
  2880. # ensure qth axis is always first as with np.array(old_percentile(..))
  2881. x = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6)
  2882. assert_equal(np.percentile(x, (25, 50)).shape, (2,))
  2883. assert_equal(np.percentile(x, (25, 50, 75)).shape, (3,))
  2884. assert_equal(np.percentile(x, (25, 50), axis=0).shape, (2, 4, 5, 6))
  2885. assert_equal(np.percentile(x, (25, 50), axis=1).shape, (2, 3, 5, 6))
  2886. assert_equal(np.percentile(x, (25, 50), axis=2).shape, (2, 3, 4, 6))
  2887. assert_equal(np.percentile(x, (25, 50), axis=3).shape, (2, 3, 4, 5))
  2888. assert_equal(
  2889. np.percentile(x, (25, 50, 75), axis=1).shape, (3, 3, 5, 6))
  2890. assert_equal(np.percentile(x, (25, 50),
  2891. method="higher").shape, (2,))
  2892. assert_equal(np.percentile(x, (25, 50, 75),
  2893. method="higher").shape, (3,))
  2894. assert_equal(np.percentile(x, (25, 50), axis=0,
  2895. method="higher").shape, (2, 4, 5, 6))
  2896. assert_equal(np.percentile(x, (25, 50), axis=1,
  2897. method="higher").shape, (2, 3, 5, 6))
  2898. assert_equal(np.percentile(x, (25, 50), axis=2,
  2899. method="higher").shape, (2, 3, 4, 6))
  2900. assert_equal(np.percentile(x, (25, 50), axis=3,
  2901. method="higher").shape, (2, 3, 4, 5))
  2902. assert_equal(np.percentile(x, (25, 50, 75), axis=1,
  2903. method="higher").shape, (3, 3, 5, 6))
  2904. def test_scalar_q(self):
  2905. # test for no empty dimensions for compatibility with old percentile
  2906. x = np.arange(12).reshape(3, 4)
  2907. assert_equal(np.percentile(x, 50), 5.5)
  2908. assert_(np.isscalar(np.percentile(x, 50)))
  2909. r0 = np.array([4., 5., 6., 7.])
  2910. assert_equal(np.percentile(x, 50, axis=0), r0)
  2911. assert_equal(np.percentile(x, 50, axis=0).shape, r0.shape)
  2912. r1 = np.array([1.5, 5.5, 9.5])
  2913. assert_almost_equal(np.percentile(x, 50, axis=1), r1)
  2914. assert_equal(np.percentile(x, 50, axis=1).shape, r1.shape)
  2915. out = np.empty(1)
  2916. assert_equal(np.percentile(x, 50, out=out), 5.5)
  2917. assert_equal(out, 5.5)
  2918. out = np.empty(4)
  2919. assert_equal(np.percentile(x, 50, axis=0, out=out), r0)
  2920. assert_equal(out, r0)
  2921. out = np.empty(3)
  2922. assert_equal(np.percentile(x, 50, axis=1, out=out), r1)
  2923. assert_equal(out, r1)
  2924. # test for no empty dimensions for compatibility with old percentile
  2925. x = np.arange(12).reshape(3, 4)
  2926. assert_equal(np.percentile(x, 50, method='lower'), 5.)
  2927. assert_(np.isscalar(np.percentile(x, 50)))
  2928. r0 = np.array([4., 5., 6., 7.])
  2929. c0 = np.percentile(x, 50, method='lower', axis=0)
  2930. assert_equal(c0, r0)
  2931. assert_equal(c0.shape, r0.shape)
  2932. r1 = np.array([1., 5., 9.])
  2933. c1 = np.percentile(x, 50, method='lower', axis=1)
  2934. assert_almost_equal(c1, r1)
  2935. assert_equal(c1.shape, r1.shape)
  2936. out = np.empty((), dtype=x.dtype)
  2937. c = np.percentile(x, 50, method='lower', out=out)
  2938. assert_equal(c, 5)
  2939. assert_equal(out, 5)
  2940. out = np.empty(4, dtype=x.dtype)
  2941. c = np.percentile(x, 50, method='lower', axis=0, out=out)
  2942. assert_equal(c, r0)
  2943. assert_equal(out, r0)
  2944. out = np.empty(3, dtype=x.dtype)
  2945. c = np.percentile(x, 50, method='lower', axis=1, out=out)
  2946. assert_equal(c, r1)
  2947. assert_equal(out, r1)
  2948. def test_exception(self):
  2949. assert_raises(ValueError, np.percentile, [1, 2], 56,
  2950. method='foobar')
  2951. assert_raises(ValueError, np.percentile, [1], 101)
  2952. assert_raises(ValueError, np.percentile, [1], -1)
  2953. assert_raises(ValueError, np.percentile, [1], list(range(50)) + [101])
  2954. assert_raises(ValueError, np.percentile, [1], list(range(50)) + [-0.1])
  2955. def test_percentile_list(self):
  2956. assert_equal(np.percentile([1, 2, 3], 0), 1)
  2957. @pytest.mark.parametrize(
  2958. "percentile, with_weights",
  2959. [
  2960. (np.percentile, False),
  2961. (partial(np.percentile, method="inverted_cdf"), True),
  2962. ]
  2963. )
  2964. def test_percentile_out(self, percentile, with_weights):
  2965. out_dtype = int if with_weights else float
  2966. x = np.array([1, 2, 3])
  2967. y = np.zeros((3,), dtype=out_dtype)
  2968. p = (1, 2, 3)
  2969. weights = np.ones_like(x) if with_weights else None
  2970. r = percentile(x, p, out=y, weights=weights)
  2971. assert r is y
  2972. assert_equal(percentile(x, p, weights=weights), y)
  2973. x = np.array([[1, 2, 3],
  2974. [4, 5, 6]])
  2975. y = np.zeros((3, 3), dtype=out_dtype)
  2976. weights = np.ones_like(x) if with_weights else None
  2977. r = percentile(x, p, axis=0, out=y, weights=weights)
  2978. assert r is y
  2979. assert_equal(percentile(x, p, weights=weights, axis=0), y)
  2980. y = np.zeros((3, 2), dtype=out_dtype)
  2981. percentile(x, p, axis=1, out=y, weights=weights)
  2982. assert_equal(percentile(x, p, weights=weights, axis=1), y)
  2983. x = np.arange(12).reshape(3, 4)
  2984. # q.dim > 1, float
  2985. if with_weights:
  2986. r0 = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])
  2987. else:
  2988. r0 = np.array([[2., 3., 4., 5.], [4., 5., 6., 7.]])
  2989. out = np.empty((2, 4), dtype=out_dtype)
  2990. weights = np.ones_like(x) if with_weights else None
  2991. assert_equal(
  2992. percentile(x, (25, 50), axis=0, out=out, weights=weights), r0
  2993. )
  2994. assert_equal(out, r0)
  2995. r1 = np.array([[0.75, 4.75, 8.75], [1.5, 5.5, 9.5]])
  2996. out = np.empty((2, 3))
  2997. assert_equal(np.percentile(x, (25, 50), axis=1, out=out), r1)
  2998. assert_equal(out, r1)
  2999. # q.dim > 1, int
  3000. r0 = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])
  3001. out = np.empty((2, 4), dtype=x.dtype)
  3002. c = np.percentile(x, (25, 50), method='lower', axis=0, out=out)
  3003. assert_equal(c, r0)
  3004. assert_equal(out, r0)
  3005. r1 = np.array([[0, 4, 8], [1, 5, 9]])
  3006. out = np.empty((2, 3), dtype=x.dtype)
  3007. c = np.percentile(x, (25, 50), method='lower', axis=1, out=out)
  3008. assert_equal(c, r1)
  3009. assert_equal(out, r1)
  3010. def test_percentile_empty_dim(self):
  3011. # empty dims are preserved
  3012. d = np.arange(11 * 2).reshape(11, 1, 2, 1)
  3013. assert_array_equal(np.percentile(d, 50, axis=0).shape, (1, 2, 1))
  3014. assert_array_equal(np.percentile(d, 50, axis=1).shape, (11, 2, 1))
  3015. assert_array_equal(np.percentile(d, 50, axis=2).shape, (11, 1, 1))
  3016. assert_array_equal(np.percentile(d, 50, axis=3).shape, (11, 1, 2))
  3017. assert_array_equal(np.percentile(d, 50, axis=-1).shape, (11, 1, 2))
  3018. assert_array_equal(np.percentile(d, 50, axis=-2).shape, (11, 1, 1))
  3019. assert_array_equal(np.percentile(d, 50, axis=-3).shape, (11, 2, 1))
  3020. assert_array_equal(np.percentile(d, 50, axis=-4).shape, (1, 2, 1))
  3021. assert_array_equal(np.percentile(d, 50, axis=2,
  3022. method='midpoint').shape,
  3023. (11, 1, 1))
  3024. assert_array_equal(np.percentile(d, 50, axis=-2,
  3025. method='midpoint').shape,
  3026. (11, 1, 1))
  3027. assert_array_equal(np.array(np.percentile(d, [10, 50], axis=0)).shape,
  3028. (2, 1, 2, 1))
  3029. assert_array_equal(np.array(np.percentile(d, [10, 50], axis=1)).shape,
  3030. (2, 11, 2, 1))
  3031. assert_array_equal(np.array(np.percentile(d, [10, 50], axis=2)).shape,
  3032. (2, 11, 1, 1))
  3033. assert_array_equal(np.array(np.percentile(d, [10, 50], axis=3)).shape,
  3034. (2, 11, 1, 2))
  3035. def test_percentile_no_overwrite(self):
  3036. a = np.array([2, 3, 4, 1])
  3037. np.percentile(a, [50], overwrite_input=False)
  3038. assert_equal(a, np.array([2, 3, 4, 1]))
  3039. a = np.array([2, 3, 4, 1])
  3040. np.percentile(a, [50])
  3041. assert_equal(a, np.array([2, 3, 4, 1]))
  3042. def test_no_p_overwrite(self):
  3043. p = np.linspace(0., 100., num=5)
  3044. np.percentile(np.arange(100.), p, method="midpoint")
  3045. assert_array_equal(p, np.linspace(0., 100., num=5))
  3046. p = np.linspace(0., 100., num=5).tolist()
  3047. np.percentile(np.arange(100.), p, method="midpoint")
  3048. assert_array_equal(p, np.linspace(0., 100., num=5).tolist())
  3049. def test_percentile_overwrite(self):
  3050. a = np.array([2, 3, 4, 1])
  3051. b = np.percentile(a, [50], overwrite_input=True)
  3052. assert_equal(b, np.array([2.5]))
  3053. b = np.percentile([2, 3, 4, 1], [50], overwrite_input=True)
  3054. assert_equal(b, np.array([2.5]))
  3055. def test_extended_axis(self):
  3056. o = np.random.normal(size=(71, 23))
  3057. x = np.dstack([o] * 10)
  3058. assert_equal(np.percentile(x, 30, axis=(0, 1)), np.percentile(o, 30))
  3059. x = np.moveaxis(x, -1, 0)
  3060. assert_equal(np.percentile(x, 30, axis=(-2, -1)), np.percentile(o, 30))
  3061. x = x.swapaxes(0, 1).copy()
  3062. assert_equal(np.percentile(x, 30, axis=(0, -1)), np.percentile(o, 30))
  3063. x = x.swapaxes(0, 1).copy()
  3064. assert_equal(np.percentile(x, [25, 60], axis=(0, 1, 2)),
  3065. np.percentile(x, [25, 60], axis=None))
  3066. assert_equal(np.percentile(x, [25, 60], axis=(0,)),
  3067. np.percentile(x, [25, 60], axis=0))
  3068. d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
  3069. np.random.shuffle(d.ravel())
  3070. assert_equal(np.percentile(d, 25, axis=(0, 1, 2))[0],
  3071. np.percentile(d[:, :, :, 0].flatten(), 25))
  3072. assert_equal(np.percentile(d, [10, 90], axis=(0, 1, 3))[:, 1],
  3073. np.percentile(d[:, :, 1, :].flatten(), [10, 90]))
  3074. assert_equal(np.percentile(d, 25, axis=(3, 1, -4))[2],
  3075. np.percentile(d[:, :, 2, :].flatten(), 25))
  3076. assert_equal(np.percentile(d, 25, axis=(3, 1, 2))[2],
  3077. np.percentile(d[2, :, :, :].flatten(), 25))
  3078. assert_equal(np.percentile(d, 25, axis=(3, 2))[2, 1],
  3079. np.percentile(d[2, 1, :, :].flatten(), 25))
  3080. assert_equal(np.percentile(d, 25, axis=(1, -2))[2, 1],
  3081. np.percentile(d[2, :, :, 1].flatten(), 25))
  3082. assert_equal(np.percentile(d, 25, axis=(1, 3))[2, 2],
  3083. np.percentile(d[2, :, 2, :].flatten(), 25))
  3084. def test_extended_axis_invalid(self):
  3085. d = np.ones((3, 5, 7, 11))
  3086. assert_raises(AxisError, np.percentile, d, axis=-5, q=25)
  3087. assert_raises(AxisError, np.percentile, d, axis=(0, -5), q=25)
  3088. assert_raises(AxisError, np.percentile, d, axis=4, q=25)
  3089. assert_raises(AxisError, np.percentile, d, axis=(0, 4), q=25)
  3090. # each of these refers to the same axis twice
  3091. assert_raises(ValueError, np.percentile, d, axis=(1, 1), q=25)
  3092. assert_raises(ValueError, np.percentile, d, axis=(-1, -1), q=25)
  3093. assert_raises(ValueError, np.percentile, d, axis=(3, -1), q=25)
  3094. def test_keepdims(self):
  3095. d = np.ones((3, 5, 7, 11))
  3096. assert_equal(np.percentile(d, 7, axis=None, keepdims=True).shape,
  3097. (1, 1, 1, 1))
  3098. assert_equal(np.percentile(d, 7, axis=(0, 1), keepdims=True).shape,
  3099. (1, 1, 7, 11))
  3100. assert_equal(np.percentile(d, 7, axis=(0, 3), keepdims=True).shape,
  3101. (1, 5, 7, 1))
  3102. assert_equal(np.percentile(d, 7, axis=(1,), keepdims=True).shape,
  3103. (3, 1, 7, 11))
  3104. assert_equal(np.percentile(d, 7, (0, 1, 2, 3), keepdims=True).shape,
  3105. (1, 1, 1, 1))
  3106. assert_equal(np.percentile(d, 7, axis=(0, 1, 3), keepdims=True).shape,
  3107. (1, 1, 7, 1))
  3108. assert_equal(np.percentile(d, [1, 7], axis=(0, 1, 3),
  3109. keepdims=True).shape, (2, 1, 1, 7, 1))
  3110. assert_equal(np.percentile(d, [1, 7], axis=(0, 3),
  3111. keepdims=True).shape, (2, 1, 5, 7, 1))
  3112. @pytest.mark.parametrize('q', [7, [1, 7]])
  3113. @pytest.mark.parametrize(
  3114. argnames='axis',
  3115. argvalues=[
  3116. None,
  3117. 1,
  3118. (1,),
  3119. (0, 1),
  3120. (-3, -1),
  3121. ]
  3122. )
  3123. def test_keepdims_out(self, q, axis):
  3124. d = np.ones((3, 5, 7, 11))
  3125. if axis is None:
  3126. shape_out = (1,) * d.ndim
  3127. else:
  3128. axis_norm = normalize_axis_tuple(axis, d.ndim)
  3129. shape_out = tuple(
  3130. 1 if i in axis_norm else d.shape[i] for i in range(d.ndim))
  3131. shape_out = np.shape(q) + shape_out
  3132. out = np.empty(shape_out)
  3133. result = np.percentile(d, q, axis=axis, keepdims=True, out=out)
  3134. assert result is out
  3135. assert_equal(result.shape, shape_out)
  3136. def test_out(self):
  3137. o = np.zeros((4,))
  3138. d = np.ones((3, 4))
  3139. assert_equal(np.percentile(d, 0, 0, out=o), o)
  3140. assert_equal(np.percentile(d, 0, 0, method='nearest', out=o), o)
  3141. o = np.zeros((3,))
  3142. assert_equal(np.percentile(d, 1, 1, out=o), o)
  3143. assert_equal(np.percentile(d, 1, 1, method='nearest', out=o), o)
  3144. o = np.zeros(())
  3145. assert_equal(np.percentile(d, 2, out=o), o)
  3146. assert_equal(np.percentile(d, 2, method='nearest', out=o), o)
  3147. @pytest.mark.parametrize("method, weighted", [
  3148. ("linear", False),
  3149. ("nearest", False),
  3150. ("inverted_cdf", False),
  3151. ("inverted_cdf", True),
  3152. ])
  3153. def test_out_nan(self, method, weighted):
  3154. if weighted:
  3155. kwargs = {"weights": np.ones((3, 4)), "method": method}
  3156. else:
  3157. kwargs = {"method": method}
  3158. with warnings.catch_warnings(record=True):
  3159. warnings.filterwarnings('always', '', RuntimeWarning)
  3160. o = np.zeros((4,))
  3161. d = np.ones((3, 4))
  3162. d[2, 1] = np.nan
  3163. assert_equal(np.percentile(d, 0, 0, out=o, **kwargs), o)
  3164. o = np.zeros((3,))
  3165. assert_equal(np.percentile(d, 1, 1, out=o, **kwargs), o)
  3166. o = np.zeros(())
  3167. assert_equal(np.percentile(d, 1, out=o, **kwargs), o)
  3168. def test_nan_behavior(self):
  3169. a = np.arange(24, dtype=float)
  3170. a[2] = np.nan
  3171. assert_equal(np.percentile(a, 0.3), np.nan)
  3172. assert_equal(np.percentile(a, 0.3, axis=0), np.nan)
  3173. assert_equal(np.percentile(a, [0.3, 0.6], axis=0),
  3174. np.array([np.nan] * 2))
  3175. a = np.arange(24, dtype=float).reshape(2, 3, 4)
  3176. a[1, 2, 3] = np.nan
  3177. a[1, 1, 2] = np.nan
  3178. # no axis
  3179. assert_equal(np.percentile(a, 0.3), np.nan)
  3180. assert_equal(np.percentile(a, 0.3).ndim, 0)
  3181. # axis0 zerod
  3182. b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 0)
  3183. b[2, 3] = np.nan
  3184. b[1, 2] = np.nan
  3185. assert_equal(np.percentile(a, 0.3, 0), b)
  3186. # axis0 not zerod
  3187. b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
  3188. [0.3, 0.6], 0)
  3189. b[:, 2, 3] = np.nan
  3190. b[:, 1, 2] = np.nan
  3191. assert_equal(np.percentile(a, [0.3, 0.6], 0), b)
  3192. # axis1 zerod
  3193. b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 1)
  3194. b[1, 3] = np.nan
  3195. b[1, 2] = np.nan
  3196. assert_equal(np.percentile(a, 0.3, 1), b)
  3197. # axis1 not zerod
  3198. b = np.percentile(
  3199. np.arange(24, dtype=float).reshape(2, 3, 4), [0.3, 0.6], 1)
  3200. b[:, 1, 3] = np.nan
  3201. b[:, 1, 2] = np.nan
  3202. assert_equal(np.percentile(a, [0.3, 0.6], 1), b)
  3203. # axis02 zerod
  3204. b = np.percentile(
  3205. np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, (0, 2))
  3206. b[1] = np.nan
  3207. b[2] = np.nan
  3208. assert_equal(np.percentile(a, 0.3, (0, 2)), b)
  3209. # axis02 not zerod
  3210. b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
  3211. [0.3, 0.6], (0, 2))
  3212. b[:, 1] = np.nan
  3213. b[:, 2] = np.nan
  3214. assert_equal(np.percentile(a, [0.3, 0.6], (0, 2)), b)
  3215. # axis02 not zerod with method='nearest'
  3216. b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
  3217. [0.3, 0.6], (0, 2), method='nearest')
  3218. b[:, 1] = np.nan
  3219. b[:, 2] = np.nan
  3220. assert_equal(np.percentile(
  3221. a, [0.3, 0.6], (0, 2), method='nearest'), b)
  3222. def test_nan_q(self):
  3223. # GH18830
  3224. with pytest.raises(ValueError, match="Percentiles must be in"):
  3225. np.percentile([1, 2, 3, 4.0], np.nan)
  3226. with pytest.raises(ValueError, match="Percentiles must be in"):
  3227. np.percentile([1, 2, 3, 4.0], [np.nan])
  3228. q = np.linspace(1.0, 99.0, 16)
  3229. q[0] = np.nan
  3230. with pytest.raises(ValueError, match="Percentiles must be in"):
  3231. np.percentile([1, 2, 3, 4.0], q)
  3232. @pytest.mark.parametrize("dtype", ["m8[D]", "M8[s]"])
  3233. @pytest.mark.parametrize("pos", [0, 23, 10])
  3234. def test_nat_basic(self, dtype, pos):
  3235. # TODO: Note that times have dubious rounding as of fixing NaTs!
  3236. # NaT and NaN should behave the same, do basic tests for NaT:
  3237. a = np.arange(0, 24, dtype=dtype)
  3238. a[pos] = "NaT"
  3239. res = np.percentile(a, 30)
  3240. assert res.dtype == dtype
  3241. assert np.isnat(res)
  3242. res = np.percentile(a, [30, 60])
  3243. assert res.dtype == dtype
  3244. assert np.isnat(res).all()
  3245. a = np.arange(0, 24 * 3, dtype=dtype).reshape(-1, 3)
  3246. a[pos, 1] = "NaT"
  3247. res = np.percentile(a, 30, axis=0)
  3248. assert_array_equal(np.isnat(res), [False, True, False])
  3249. @pytest.mark.parametrize("qtype", [np.float16, np.float32])
  3250. @pytest.mark.parametrize("method", quantile_methods)
  3251. def test_percentile_gh_29003(self, qtype, method):
  3252. # test that with float16 or float32 input we do not get overflow
  3253. zero = qtype(0)
  3254. one = qtype(1)
  3255. a = np.zeros(65521, qtype)
  3256. a[:20_000] = one
  3257. z = np.percentile(a, 50, method=method)
  3258. assert z == zero
  3259. assert z.dtype == a.dtype
  3260. z = np.percentile(a, 99, method=method)
  3261. assert z == one
  3262. assert z.dtype == a.dtype
  3263. def test_percentile_gh_29003_Fraction(self):
  3264. zero = Fraction(0)
  3265. one = Fraction(1)
  3266. a = np.array([zero] * 65521)
  3267. a[:20_000] = one
  3268. z = np.percentile(a, 50)
  3269. assert z == zero
  3270. z = np.percentile(a, Fraction(50))
  3271. assert z == zero
  3272. assert np.array(z).dtype == a.dtype
  3273. z = np.percentile(a, 99)
  3274. assert z == one
  3275. # test that with only Fraction input the return type is a Fraction
  3276. z = np.percentile(a, Fraction(99))
  3277. assert z == one
  3278. assert np.array(z).dtype == a.dtype
  3279. @pytest.mark.parametrize("method", interpolating_quantile_methods)
  3280. @pytest.mark.parametrize("q", [50, 10.0])
  3281. def test_q_weak_promotion(self, method, q):
  3282. a = np.array([1, 2, 3, 4, 5], dtype=np.float32)
  3283. value = np.percentile(a, q, method=method)
  3284. assert value.dtype == np.float32
  3285. @pytest.mark.parametrize("method", interpolating_quantile_methods)
  3286. def test_q_strong_promotion(self, method):
  3287. # For interpolating methods, the dtype should be float64, for
  3288. # discrete ones the original int8. (technically, mid-point has no
  3289. # reason to take into account `q`, but does so anyway.)
  3290. a = np.array([1, 2, 3, 4, 5], dtype=np.float32)
  3291. value = np.percentile(a, np.float64(50), method=method)
  3292. assert value.dtype == np.float64
  3293. # Check that we don't do accidental promotion either:
  3294. value = np.percentile(a, np.float32(50), method=method)
  3295. assert value.dtype == np.float32
  3296. class TestQuantile:
  3297. # most of this is already tested by TestPercentile
  3298. def V(self, x, y, alpha):
  3299. # Identification function used in several tests.
  3300. return (x >= y) - alpha
  3301. def test_max_ulp(self):
  3302. x = [0.0, 0.2, 0.4]
  3303. a = np.quantile(x, 0.45)
  3304. # The default linear method would result in 0 + 0.2 * (0.45/2) = 0.18.
  3305. # 0.18 is not exactly representable and the formula leads to a 1 ULP
  3306. # different result. Ensure it is this exact within 1 ULP, see gh-20331.
  3307. np.testing.assert_array_max_ulp(a, 0.18, maxulp=1)
  3308. def test_basic(self):
  3309. x = np.arange(8) * 0.5
  3310. assert_equal(np.quantile(x, 0), 0.)
  3311. assert_equal(np.quantile(x, 1), 3.5)
  3312. assert_equal(np.quantile(x, 0.5), 1.75)
  3313. def test_correct_quantile_value(self):
  3314. a = np.array([True])
  3315. tf_quant = np.quantile(True, False)
  3316. assert_equal(tf_quant, a[0])
  3317. assert_equal(type(tf_quant), a.dtype)
  3318. a = np.array([False, True, True])
  3319. quant_res = np.quantile(a, a)
  3320. assert_array_equal(quant_res, a)
  3321. assert_equal(quant_res.dtype, a.dtype)
  3322. def test_fraction(self):
  3323. # fractional input, integral quantile
  3324. x = [Fraction(i, 2) for i in range(8)]
  3325. q = np.quantile(x, 0)
  3326. assert_equal(q, 0)
  3327. assert_equal(type(q), Fraction)
  3328. q = np.quantile(x, 1)
  3329. assert_equal(q, Fraction(7, 2))
  3330. assert_equal(type(q), Fraction)
  3331. q = np.quantile(x, .5)
  3332. assert_equal(q, 1.75)
  3333. assert isinstance(q, float)
  3334. q = np.quantile(x, Fraction(1, 2))
  3335. assert_equal(q, Fraction(7, 4))
  3336. assert_equal(type(q), Fraction)
  3337. q = np.quantile(x, [Fraction(1, 2)])
  3338. assert_equal(q, np.array([Fraction(7, 4)]))
  3339. assert_equal(type(q), np.ndarray)
  3340. q = np.quantile(x, [[Fraction(1, 2)]])
  3341. assert_equal(q, np.array([[Fraction(7, 4)]]))
  3342. assert_equal(type(q), np.ndarray)
  3343. # repeat with integral input but fractional quantile
  3344. x = np.arange(8)
  3345. assert_equal(np.quantile(x, Fraction(1, 2)), Fraction(7, 2))
  3346. def test_complex(self):
  3347. # gh-22652
  3348. arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='G')
  3349. assert_raises(TypeError, np.quantile, arr_c, 0.5)
  3350. arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='D')
  3351. assert_raises(TypeError, np.quantile, arr_c, 0.5)
  3352. arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='F')
  3353. assert_raises(TypeError, np.quantile, arr_c, 0.5)
  3354. def test_no_p_overwrite(self):
  3355. # this is worth retesting, because quantile does not make a copy
  3356. p0 = np.array([0, 0.75, 0.25, 0.5, 1.0])
  3357. p = p0.copy()
  3358. np.quantile(np.arange(100.), p, method="midpoint")
  3359. assert_array_equal(p, p0)
  3360. p0 = p0.tolist()
  3361. p = p.tolist()
  3362. np.quantile(np.arange(100.), p, method="midpoint")
  3363. assert_array_equal(p, p0)
  3364. @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
  3365. def test_quantile_preserve_int_type(self, dtype):
  3366. res = np.quantile(np.array([1, 2], dtype=dtype), [0.5],
  3367. method="nearest")
  3368. assert res.dtype == dtype
  3369. @pytest.mark.parametrize("method", quantile_methods)
  3370. def test_q_zero_one(self, method):
  3371. # gh-24710
  3372. arr = [10, 11, 12]
  3373. quantile = np.quantile(arr, q=[0, 1], method=method)
  3374. assert_equal(quantile, np.array([10, 12]))
  3375. @pytest.mark.parametrize("method", quantile_methods)
  3376. def test_quantile_monotonic(self, method):
  3377. # GH 14685
  3378. # test that the return value of quantile is monotonic if p0 is ordered
  3379. # Also tests that the boundary values are not mishandled.
  3380. p0 = np.linspace(0, 1, 101)
  3381. quantile = np.quantile(np.array([0, 1, 1, 2, 2, 3, 3, 4, 5, 5, 1, 1, 9, 9, 9,
  3382. 8, 8, 7]) * 0.1, p0, method=method)
  3383. assert_equal(np.sort(quantile), quantile)
  3384. # Also test one where the number of data points is clearly divisible:
  3385. quantile = np.quantile([0., 1., 2., 3.], p0, method=method)
  3386. assert_equal(np.sort(quantile), quantile)
  3387. @hypothesis.given(
  3388. arr=arrays(dtype=np.float64,
  3389. shape=st.integers(min_value=3, max_value=1000),
  3390. elements=st.floats(allow_infinity=False, allow_nan=False,
  3391. min_value=-1e300, max_value=1e300)))
  3392. def test_quantile_monotonic_hypo(self, arr):
  3393. p0 = np.arange(0, 1, 0.01)
  3394. quantile = np.quantile(arr, p0)
  3395. assert_equal(np.sort(quantile), quantile)
  3396. def test_quantile_scalar_nan(self):
  3397. a = np.array([[10., 7., 4.], [3., 2., 1.]])
  3398. a[0][1] = np.nan
  3399. actual = np.quantile(a, 0.5)
  3400. assert np.isscalar(actual)
  3401. assert_equal(np.quantile(a, 0.5), np.nan)
  3402. @pytest.mark.parametrize("weights", [False, True])
  3403. @pytest.mark.parametrize("method", quantile_methods)
  3404. @pytest.mark.parametrize("alpha", [0.2, 0.5, 0.9])
  3405. def test_quantile_identification_equation(self, weights, method, alpha):
  3406. # Test that the identification equation holds for the empirical
  3407. # CDF:
  3408. # E[V(x, Y)] = 0 <=> x is quantile
  3409. # with Y the random variable for which we have observed values and
  3410. # V(x, y) the canonical identification function for the quantile (at
  3411. # level alpha), see
  3412. # https://doi.org/10.48550/arXiv.0912.0902
  3413. if weights and method not in methods_supporting_weights:
  3414. pytest.skip("Weights not supported by method.")
  3415. rng = np.random.default_rng(4321)
  3416. # We choose n and alpha such that we cover 3 cases:
  3417. # - n * alpha is an integer
  3418. # - n * alpha is a float that gets rounded down
  3419. # - n * alpha is a float that gest rounded up
  3420. n = 102 # n * alpha = 20.4, 51. , 91.8
  3421. y = rng.random(n)
  3422. w = rng.integers(low=0, high=10, size=n) if weights else None
  3423. x = np.quantile(y, alpha, method=method, weights=w)
  3424. if method in ("higher",):
  3425. # These methods do not fulfill the identification equation.
  3426. assert np.abs(np.mean(self.V(x, y, alpha))) > 0.1 / n
  3427. elif int(n * alpha) == n * alpha and not weights:
  3428. # We can expect exact results, up to machine precision.
  3429. assert_allclose(
  3430. np.average(self.V(x, y, alpha), weights=w), 0, atol=1e-14,
  3431. )
  3432. else:
  3433. # V = (x >= y) - alpha cannot sum to zero exactly but within
  3434. # "sample precision".
  3435. assert_allclose(np.average(self.V(x, y, alpha), weights=w), 0,
  3436. atol=1 / n / np.amin([alpha, 1 - alpha]))
  3437. @pytest.mark.parametrize("weights", [False, True])
  3438. @pytest.mark.parametrize("method", quantile_methods)
  3439. @pytest.mark.parametrize("alpha", [0.2, 0.5, 0.9])
  3440. def test_quantile_add_and_multiply_constant(self, weights, method, alpha):
  3441. # Test that
  3442. # 1. quantile(c + x) = c + quantile(x)
  3443. # 2. quantile(c * x) = c * quantile(x)
  3444. # 3. quantile(-x) = -quantile(x, 1 - alpha)
  3445. # On empirical quantiles, this equation does not hold exactly.
  3446. # Koenker (2005) "Quantile Regression" Chapter 2.2.3 calls these
  3447. # properties equivariance.
  3448. if weights and method not in methods_supporting_weights:
  3449. pytest.skip("Weights not supported by method.")
  3450. rng = np.random.default_rng(4321)
  3451. # We choose n and alpha such that we have cases for
  3452. # - n * alpha is an integer
  3453. # - n * alpha is a float that gets rounded down
  3454. # - n * alpha is a float that gest rounded up
  3455. n = 102 # n * alpha = 20.4, 51. , 91.8
  3456. y = rng.random(n)
  3457. w = rng.integers(low=0, high=10, size=n) if weights else None
  3458. q = np.quantile(y, alpha, method=method, weights=w)
  3459. c = 13.5
  3460. # 1
  3461. assert_allclose(np.quantile(c + y, alpha, method=method, weights=w),
  3462. c + q)
  3463. # 2
  3464. assert_allclose(np.quantile(c * y, alpha, method=method, weights=w),
  3465. c * q)
  3466. # 3
  3467. if weights:
  3468. # From here on, we would need more methods to support weights.
  3469. return
  3470. q = -np.quantile(-y, 1 - alpha, method=method)
  3471. if method == "inverted_cdf":
  3472. if (
  3473. n * alpha == int(n * alpha)
  3474. or np.round(n * alpha) == int(n * alpha) + 1
  3475. ):
  3476. assert_allclose(q, np.quantile(y, alpha, method="higher"))
  3477. else:
  3478. assert_allclose(q, np.quantile(y, alpha, method="lower"))
  3479. elif method == "closest_observation":
  3480. if n * alpha == int(n * alpha):
  3481. assert_allclose(q, np.quantile(y, alpha, method="higher"))
  3482. elif np.round(n * alpha) == int(n * alpha) + 1:
  3483. assert_allclose(
  3484. q, np.quantile(y, alpha + 1 / n, method="higher"))
  3485. else:
  3486. assert_allclose(q, np.quantile(y, alpha, method="lower"))
  3487. elif method == "interpolated_inverted_cdf":
  3488. assert_allclose(q, np.quantile(y, alpha + 1 / n, method=method))
  3489. elif method == "nearest":
  3490. if n * alpha == int(n * alpha):
  3491. assert_allclose(q, np.quantile(y, alpha + 1 / n, method=method))
  3492. else:
  3493. assert_allclose(q, np.quantile(y, alpha, method=method))
  3494. elif method == "lower":
  3495. assert_allclose(q, np.quantile(y, alpha, method="higher"))
  3496. elif method == "higher":
  3497. assert_allclose(q, np.quantile(y, alpha, method="lower"))
  3498. else:
  3499. # "averaged_inverted_cdf", "hazen", "weibull", "linear",
  3500. # "median_unbiased", "normal_unbiased", "midpoint"
  3501. assert_allclose(q, np.quantile(y, alpha, method=method))
  3502. @pytest.mark.parametrize("method", methods_supporting_weights)
  3503. @pytest.mark.parametrize("alpha", [0.2, 0.5, 0.9])
  3504. def test_quantile_constant_weights(self, method, alpha):
  3505. rng = np.random.default_rng(4321)
  3506. # We choose n and alpha such that we have cases for
  3507. # - n * alpha is an integer
  3508. # - n * alpha is a float that gets rounded down
  3509. # - n * alpha is a float that gest rounded up
  3510. n = 102 # n * alpha = 20.4, 51. , 91.8
  3511. y = rng.random(n)
  3512. q = np.quantile(y, alpha, method=method)
  3513. w = np.ones_like(y)
  3514. qw = np.quantile(y, alpha, method=method, weights=w)
  3515. assert_allclose(qw, q)
  3516. w = 8.125 * np.ones_like(y)
  3517. qw = np.quantile(y, alpha, method=method, weights=w)
  3518. assert_allclose(qw, q)
  3519. @pytest.mark.parametrize("method", methods_supporting_weights)
  3520. @pytest.mark.parametrize("alpha", [0, 0.2, 0.5, 0.9, 1])
  3521. def test_quantile_with_integer_weights(self, method, alpha):
  3522. # Integer weights can be interpreted as repeated observations.
  3523. rng = np.random.default_rng(4321)
  3524. # We choose n and alpha such that we have cases for
  3525. # - n * alpha is an integer
  3526. # - n * alpha is a float that gets rounded down
  3527. # - n * alpha is a float that gest rounded up
  3528. n = 102 # n * alpha = 20.4, 51. , 91.8
  3529. y = rng.random(n)
  3530. w = rng.integers(low=0, high=10, size=n, dtype=np.int32)
  3531. qw = np.quantile(y, alpha, method=method, weights=w)
  3532. q = np.quantile(np.repeat(y, w), alpha, method=method)
  3533. assert_allclose(qw, q)
  3534. @pytest.mark.parametrize("method", methods_supporting_weights)
  3535. def test_quantile_with_weights_and_axis(self, method):
  3536. rng = np.random.default_rng(4321)
  3537. # 1d weight and single alpha
  3538. y = rng.random((2, 10, 3))
  3539. w = np.abs(rng.random(10))
  3540. alpha = 0.5
  3541. q = np.quantile(y, alpha, weights=w, method=method, axis=1)
  3542. q_res = np.zeros(shape=(2, 3))
  3543. for i in range(2):
  3544. for j in range(3):
  3545. q_res[i, j] = np.quantile(
  3546. y[i, :, j], alpha, method=method, weights=w
  3547. )
  3548. assert_allclose(q, q_res)
  3549. # 1d weight and 1d alpha
  3550. alpha = [0, 0.2, 0.4, 0.6, 0.8, 1] # shape (6,)
  3551. q = np.quantile(y, alpha, weights=w, method=method, axis=1)
  3552. q_res = np.zeros(shape=(6, 2, 3))
  3553. for i in range(2):
  3554. for j in range(3):
  3555. q_res[:, i, j] = np.quantile(
  3556. y[i, :, j], alpha, method=method, weights=w
  3557. )
  3558. assert_allclose(q, q_res)
  3559. # 1d weight and 2d alpha
  3560. alpha = [[0, 0.2], [0.4, 0.6], [0.8, 1]] # shape (3, 2)
  3561. q = np.quantile(y, alpha, weights=w, method=method, axis=1)
  3562. q_res = q_res.reshape((3, 2, 2, 3))
  3563. assert_allclose(q, q_res)
  3564. # shape of weights equals shape of y
  3565. w = np.abs(rng.random((2, 10, 3)))
  3566. alpha = 0.5
  3567. q = np.quantile(y, alpha, weights=w, method=method, axis=1)
  3568. q_res = np.zeros(shape=(2, 3))
  3569. for i in range(2):
  3570. for j in range(3):
  3571. q_res[i, j] = np.quantile(
  3572. y[i, :, j], alpha, method=method, weights=w[i, :, j]
  3573. )
  3574. assert_allclose(q, q_res)
  3575. # axis is a tuple of all axes
  3576. q = np.quantile(y, alpha, weights=w, method=method, axis=(0, 1, 2))
  3577. q_res = np.quantile(y, alpha, weights=w, method=method, axis=None)
  3578. assert_allclose(q, q_res)
  3579. q = np.quantile(y, alpha, weights=w, method=method, axis=(1, 2))
  3580. q_res = np.zeros(shape=(2,))
  3581. for i in range(2):
  3582. q_res[i] = np.quantile(y[i], alpha, weights=w[i], method=method)
  3583. assert_allclose(q, q_res)
  3584. @pytest.mark.parametrize("method", methods_supporting_weights)
  3585. def test_quantile_weights_min_max(self, method):
  3586. # Test weighted quantile at 0 and 1 with leading and trailing zero
  3587. # weights.
  3588. w = [0, 0, 1, 2, 3, 0]
  3589. y = np.arange(6)
  3590. y_min = np.quantile(y, 0, weights=w, method="inverted_cdf")
  3591. y_max = np.quantile(y, 1, weights=w, method="inverted_cdf")
  3592. assert y_min == y[2] # == 2
  3593. assert y_max == y[4] # == 4
  3594. def test_quantile_weights_raises_negative_weights(self):
  3595. y = [1, 2]
  3596. w = [-0.5, 1]
  3597. with pytest.raises(ValueError, match="Weights must be non-negative"):
  3598. np.quantile(y, 0.5, weights=w, method="inverted_cdf")
  3599. @pytest.mark.parametrize(
  3600. "method",
  3601. sorted(set(quantile_methods) - set(methods_supporting_weights)),
  3602. )
  3603. def test_quantile_weights_raises_unsupported_methods(self, method):
  3604. y = [1, 2]
  3605. w = [0.5, 1]
  3606. msg = "Only method 'inverted_cdf' supports weights"
  3607. with pytest.raises(ValueError, match=msg):
  3608. np.quantile(y, 0.5, weights=w, method=method)
  3609. def test_weibull_fraction(self):
  3610. arr = [Fraction(0, 1), Fraction(1, 10)]
  3611. quantile = np.quantile(arr, [0, ], method='weibull')
  3612. assert_equal(quantile, np.array(Fraction(0, 1)))
  3613. quantile = np.quantile(arr, [Fraction(1, 2)], method='weibull')
  3614. assert_equal(quantile, np.array(Fraction(1, 20)))
  3615. def test_closest_observation(self):
  3616. # Round ties to nearest even order statistic (see #26656)
  3617. m = 'closest_observation'
  3618. q = 0.5
  3619. arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  3620. assert_equal(2, np.quantile(arr[0:3], q, method=m))
  3621. assert_equal(2, np.quantile(arr[0:4], q, method=m))
  3622. assert_equal(2, np.quantile(arr[0:5], q, method=m))
  3623. assert_equal(3, np.quantile(arr[0:6], q, method=m))
  3624. assert_equal(4, np.quantile(arr[0:7], q, method=m))
  3625. assert_equal(4, np.quantile(arr[0:8], q, method=m))
  3626. assert_equal(4, np.quantile(arr[0:9], q, method=m))
  3627. assert_equal(5, np.quantile(arr, q, method=m))
  3628. @pytest.mark.parametrize("weights",
  3629. [[1, np.inf, 1, 1], [1, np.inf, 1, np.inf], [0, 0, 0, 0],
  3630. [np.finfo("float64").max] * 4])
  3631. @pytest.mark.parametrize("dty", ["f8", "O"])
  3632. def test_inf_zeroes_err(self, weights, dty):
  3633. m = "inverted_cdf"
  3634. q = 0.5
  3635. arr = np.array([[1, 2, 3, 4]] * 2)
  3636. # Make one entry have bad weights and another good ones.
  3637. wgts = np.array([weights, [0.5] * 4], dtype=dty)
  3638. with pytest.raises(ValueError,
  3639. match=r"Weights included NaN, inf or were all zero"):
  3640. # We (currently) don't bother to check ahead so 0/0 or
  3641. # overflow to `inf` while summing weights, or `inf / inf`
  3642. # will all warn before the error is raised.
  3643. with np.errstate(all="ignore"):
  3644. a = np.quantile(arr, q, weights=wgts, method=m, axis=1)
  3645. @pytest.mark.parametrize("weights",
  3646. [[1, np.nan, 1, 1], [1, np.nan, np.nan, 1]])
  3647. @pytest.mark.parametrize(["err", "dty"],
  3648. [(ValueError, "f8"), ((RuntimeWarning, ValueError), "O")])
  3649. def test_nan_err(self, err, dty, weights):
  3650. m = "inverted_cdf"
  3651. q = 0.5
  3652. arr = np.array([[1, 2, 3, 4]] * 2)
  3653. # Make one entry have bad weights and another good ones.
  3654. wgts = np.array([weights, [0.5] * 4], dtype=dty)
  3655. with pytest.raises(err):
  3656. a = np.quantile(arr, q, weights=wgts, method=m)
  3657. def test_quantile_gh_29003_Fraction(self):
  3658. r = np.quantile([1, 2], q=Fraction(1))
  3659. assert r == Fraction(2)
  3660. assert isinstance(r, Fraction)
  3661. r = np.quantile([1, 2], q=Fraction(.5))
  3662. assert r == Fraction(3, 2)
  3663. assert isinstance(r, Fraction)
  3664. def test_float16_gh_29003(self):
  3665. a = np.arange(50_001, dtype=np.float16)
  3666. q = .999
  3667. value = np.quantile(a, q)
  3668. assert value == q * 50_000
  3669. assert value.dtype == np.float16
  3670. @pytest.mark.parametrize("method", interpolating_quantile_methods)
  3671. @pytest.mark.parametrize("q", [0.5, 1])
  3672. def test_q_weak_promotion(self, method, q):
  3673. a = np.array([1, 2, 3, 4, 5], dtype=np.float32)
  3674. value = np.quantile(a, q, method=method)
  3675. assert value.dtype == np.float32
  3676. @pytest.mark.parametrize("method", interpolating_quantile_methods)
  3677. def test_q_strong_promotion(self, method):
  3678. # For interpolating methods, the dtype should be float64, for
  3679. # discrete ones the original int8. (technically, mid-point has no
  3680. # reason to take into account `q`, but does so anyway.)
  3681. a = np.array([1, 2, 3, 4, 5], dtype=np.float32)
  3682. value = np.quantile(a, np.float64(0.5), method=method)
  3683. assert value.dtype == np.float64
  3684. # Check that we don't do accidental promotion either:
  3685. value = np.quantile(a, np.float32(0.5), method=method)
  3686. assert value.dtype == np.float32
  3687. class TestLerp:
  3688. @hypothesis.given(t0=st.floats(allow_nan=False, allow_infinity=False,
  3689. min_value=0, max_value=1),
  3690. t1=st.floats(allow_nan=False, allow_infinity=False,
  3691. min_value=0, max_value=1),
  3692. a=st.floats(allow_nan=False, allow_infinity=False,
  3693. min_value=-1e300, max_value=1e300),
  3694. b=st.floats(allow_nan=False, allow_infinity=False,
  3695. min_value=-1e300, max_value=1e300))
  3696. def test_linear_interpolation_formula_monotonic(self, t0, t1, a, b):
  3697. l0 = nfb._lerp(a, b, t0)
  3698. l1 = nfb._lerp(a, b, t1)
  3699. if t0 == t1 or a == b:
  3700. assert l0 == l1 # uninteresting
  3701. elif (t0 < t1) == (a < b):
  3702. assert l0 <= l1
  3703. else:
  3704. assert l0 >= l1
  3705. @hypothesis.given(t=st.floats(allow_nan=False, allow_infinity=False,
  3706. min_value=0, max_value=1),
  3707. a=st.floats(allow_nan=False, allow_infinity=False,
  3708. min_value=-1e300, max_value=1e300),
  3709. b=st.floats(allow_nan=False, allow_infinity=False,
  3710. min_value=-1e300, max_value=1e300))
  3711. def test_linear_interpolation_formula_bounded(self, t, a, b):
  3712. if a <= b:
  3713. assert a <= nfb._lerp(a, b, t) <= b
  3714. else:
  3715. assert b <= nfb._lerp(a, b, t) <= a
  3716. @hypothesis.given(t=st.floats(allow_nan=False, allow_infinity=False,
  3717. min_value=0, max_value=1),
  3718. a=st.floats(allow_nan=False, allow_infinity=False,
  3719. min_value=-1e300, max_value=1e300),
  3720. b=st.floats(allow_nan=False, allow_infinity=False,
  3721. min_value=-1e300, max_value=1e300))
  3722. def test_linear_interpolation_formula_symmetric(self, t, a, b):
  3723. # double subtraction is needed to remove the extra precision of t < 0.5
  3724. left = nfb._lerp(a, b, 1 - (1 - t))
  3725. right = nfb._lerp(b, a, 1 - t)
  3726. assert_allclose(left, right)
  3727. def test_linear_interpolation_formula_0d_inputs(self):
  3728. a = np.array(2)
  3729. b = np.array(5)
  3730. t = np.array(0.2)
  3731. assert nfb._lerp(a, b, t) == 2.6
  3732. class TestMedian:
  3733. def test_basic(self):
  3734. a0 = np.array(1)
  3735. a1 = np.arange(2)
  3736. a2 = np.arange(6).reshape(2, 3)
  3737. assert_equal(np.median(a0), 1)
  3738. assert_allclose(np.median(a1), 0.5)
  3739. assert_allclose(np.median(a2), 2.5)
  3740. assert_allclose(np.median(a2, axis=0), [1.5, 2.5, 3.5])
  3741. assert_equal(np.median(a2, axis=1), [1, 4])
  3742. assert_allclose(np.median(a2, axis=None), 2.5)
  3743. a = np.array([0.0444502, 0.0463301, 0.141249, 0.0606775])
  3744. assert_almost_equal((a[1] + a[3]) / 2., np.median(a))
  3745. a = np.array([0.0463301, 0.0444502, 0.141249])
  3746. assert_equal(a[0], np.median(a))
  3747. a = np.array([0.0444502, 0.141249, 0.0463301])
  3748. assert_equal(a[-1], np.median(a))
  3749. # check array scalar result
  3750. assert_equal(np.median(a).ndim, 0)
  3751. a[1] = np.nan
  3752. assert_equal(np.median(a).ndim, 0)
  3753. def test_axis_keyword(self):
  3754. a3 = np.array([[2, 3],
  3755. [0, 1],
  3756. [6, 7],
  3757. [4, 5]])
  3758. for a in [a3, np.random.randint(0, 100, size=(2, 3, 4))]:
  3759. orig = a.copy()
  3760. np.median(a, axis=None)
  3761. for ax in range(a.ndim):
  3762. np.median(a, axis=ax)
  3763. assert_array_equal(a, orig)
  3764. assert_allclose(np.median(a3, axis=0), [3, 4])
  3765. assert_allclose(np.median(a3.T, axis=1), [3, 4])
  3766. assert_allclose(np.median(a3), 3.5)
  3767. assert_allclose(np.median(a3, axis=None), 3.5)
  3768. assert_allclose(np.median(a3.T), 3.5)
  3769. def test_overwrite_keyword(self):
  3770. a3 = np.array([[2, 3],
  3771. [0, 1],
  3772. [6, 7],
  3773. [4, 5]])
  3774. a0 = np.array(1)
  3775. a1 = np.arange(2)
  3776. a2 = np.arange(6).reshape(2, 3)
  3777. assert_allclose(np.median(a0.copy(), overwrite_input=True), 1)
  3778. assert_allclose(np.median(a1.copy(), overwrite_input=True), 0.5)
  3779. assert_allclose(np.median(a2.copy(), overwrite_input=True), 2.5)
  3780. assert_allclose(
  3781. np.median(a2.copy(), overwrite_input=True, axis=0), [1.5, 2.5, 3.5])
  3782. assert_allclose(
  3783. np.median(a2.copy(), overwrite_input=True, axis=1), [1, 4])
  3784. assert_allclose(
  3785. np.median(a2.copy(), overwrite_input=True, axis=None), 2.5)
  3786. assert_allclose(
  3787. np.median(a3.copy(), overwrite_input=True, axis=0), [3, 4])
  3788. assert_allclose(
  3789. np.median(a3.T.copy(), overwrite_input=True, axis=1), [3, 4])
  3790. a4 = np.arange(3 * 4 * 5, dtype=np.float32).reshape((3, 4, 5))
  3791. np.random.shuffle(a4.ravel())
  3792. assert_allclose(np.median(a4, axis=None),
  3793. np.median(a4.copy(), axis=None, overwrite_input=True))
  3794. assert_allclose(np.median(a4, axis=0),
  3795. np.median(a4.copy(), axis=0, overwrite_input=True))
  3796. assert_allclose(np.median(a4, axis=1),
  3797. np.median(a4.copy(), axis=1, overwrite_input=True))
  3798. assert_allclose(np.median(a4, axis=2),
  3799. np.median(a4.copy(), axis=2, overwrite_input=True))
  3800. def test_array_like(self):
  3801. x = [1, 2, 3]
  3802. assert_almost_equal(np.median(x), 2)
  3803. x2 = [x]
  3804. assert_almost_equal(np.median(x2), 2)
  3805. assert_allclose(np.median(x2, axis=0), x)
  3806. def test_subclass(self):
  3807. # gh-3846
  3808. class MySubClass(np.ndarray):
  3809. def __new__(cls, input_array, info=None):
  3810. obj = np.asarray(input_array).view(cls)
  3811. obj.info = info
  3812. return obj
  3813. def mean(self, axis=None, dtype=None, out=None):
  3814. return -7
  3815. a = MySubClass([1, 2, 3])
  3816. assert_equal(np.median(a), -7)
  3817. @pytest.mark.parametrize('arr',
  3818. ([1., 2., 3.], [1., np.nan, 3.], np.nan, 0.))
  3819. def test_subclass2(self, arr):
  3820. """Check that we return subclasses, even if a NaN scalar."""
  3821. class MySubclass(np.ndarray):
  3822. pass
  3823. m = np.median(np.array(arr).view(MySubclass))
  3824. assert isinstance(m, MySubclass)
  3825. def test_out(self):
  3826. o = np.zeros((4,))
  3827. d = np.ones((3, 4))
  3828. assert_equal(np.median(d, 0, out=o), o)
  3829. o = np.zeros((3,))
  3830. assert_equal(np.median(d, 1, out=o), o)
  3831. o = np.zeros(())
  3832. assert_equal(np.median(d, out=o), o)
  3833. def test_out_nan(self):
  3834. with warnings.catch_warnings(record=True):
  3835. warnings.filterwarnings('always', '', RuntimeWarning)
  3836. o = np.zeros((4,))
  3837. d = np.ones((3, 4))
  3838. d[2, 1] = np.nan
  3839. assert_equal(np.median(d, 0, out=o), o)
  3840. o = np.zeros((3,))
  3841. assert_equal(np.median(d, 1, out=o), o)
  3842. o = np.zeros(())
  3843. assert_equal(np.median(d, out=o), o)
  3844. def test_nan_behavior(self):
  3845. a = np.arange(24, dtype=float)
  3846. a[2] = np.nan
  3847. assert_equal(np.median(a), np.nan)
  3848. assert_equal(np.median(a, axis=0), np.nan)
  3849. a = np.arange(24, dtype=float).reshape(2, 3, 4)
  3850. a[1, 2, 3] = np.nan
  3851. a[1, 1, 2] = np.nan
  3852. # no axis
  3853. assert_equal(np.median(a), np.nan)
  3854. assert_equal(np.median(a).ndim, 0)
  3855. # axis0
  3856. b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), 0)
  3857. b[2, 3] = np.nan
  3858. b[1, 2] = np.nan
  3859. assert_equal(np.median(a, 0), b)
  3860. # axis1
  3861. b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), 1)
  3862. b[1, 3] = np.nan
  3863. b[1, 2] = np.nan
  3864. assert_equal(np.median(a, 1), b)
  3865. # axis02
  3866. b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), (0, 2))
  3867. b[1] = np.nan
  3868. b[2] = np.nan
  3869. assert_equal(np.median(a, (0, 2)), b)
  3870. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work correctly")
  3871. def test_empty(self):
  3872. # mean(empty array) emits two warnings: empty slice and divide by 0
  3873. a = np.array([], dtype=float)
  3874. with warnings.catch_warnings(record=True) as w:
  3875. warnings.filterwarnings('always', '', RuntimeWarning)
  3876. assert_equal(np.median(a), np.nan)
  3877. assert_(w[0].category is RuntimeWarning)
  3878. assert_equal(len(w), 2)
  3879. # multiple dimensions
  3880. a = np.array([], dtype=float, ndmin=3)
  3881. # no axis
  3882. with warnings.catch_warnings(record=True) as w:
  3883. warnings.filterwarnings('always', '', RuntimeWarning)
  3884. assert_equal(np.median(a), np.nan)
  3885. assert_(w[0].category is RuntimeWarning)
  3886. # axis 0 and 1
  3887. b = np.array([], dtype=float, ndmin=2)
  3888. assert_equal(np.median(a, axis=0), b)
  3889. assert_equal(np.median(a, axis=1), b)
  3890. # axis 2
  3891. b = np.array(np.nan, dtype=float, ndmin=2)
  3892. with warnings.catch_warnings(record=True) as w:
  3893. warnings.filterwarnings('always', '', RuntimeWarning)
  3894. assert_equal(np.median(a, axis=2), b)
  3895. assert_(w[0].category is RuntimeWarning)
  3896. def test_object(self):
  3897. o = np.arange(7.)
  3898. assert_(type(np.median(o.astype(object))), float)
  3899. o[2] = np.nan
  3900. assert_(type(np.median(o.astype(object))), float)
  3901. def test_extended_axis(self):
  3902. o = np.random.normal(size=(71, 23))
  3903. x = np.dstack([o] * 10)
  3904. assert_equal(np.median(x, axis=(0, 1)), np.median(o))
  3905. x = np.moveaxis(x, -1, 0)
  3906. assert_equal(np.median(x, axis=(-2, -1)), np.median(o))
  3907. x = x.swapaxes(0, 1).copy()
  3908. assert_equal(np.median(x, axis=(0, -1)), np.median(o))
  3909. assert_equal(np.median(x, axis=(0, 1, 2)), np.median(x, axis=None))
  3910. assert_equal(np.median(x, axis=(0, )), np.median(x, axis=0))
  3911. assert_equal(np.median(x, axis=(-1, )), np.median(x, axis=-1))
  3912. d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
  3913. np.random.shuffle(d.ravel())
  3914. assert_equal(np.median(d, axis=(0, 1, 2))[0],
  3915. np.median(d[:, :, :, 0].flatten()))
  3916. assert_equal(np.median(d, axis=(0, 1, 3))[1],
  3917. np.median(d[:, :, 1, :].flatten()))
  3918. assert_equal(np.median(d, axis=(3, 1, -4))[2],
  3919. np.median(d[:, :, 2, :].flatten()))
  3920. assert_equal(np.median(d, axis=(3, 1, 2))[2],
  3921. np.median(d[2, :, :, :].flatten()))
  3922. assert_equal(np.median(d, axis=(3, 2))[2, 1],
  3923. np.median(d[2, 1, :, :].flatten()))
  3924. assert_equal(np.median(d, axis=(1, -2))[2, 1],
  3925. np.median(d[2, :, :, 1].flatten()))
  3926. assert_equal(np.median(d, axis=(1, 3))[2, 2],
  3927. np.median(d[2, :, 2, :].flatten()))
  3928. def test_extended_axis_invalid(self):
  3929. d = np.ones((3, 5, 7, 11))
  3930. assert_raises(AxisError, np.median, d, axis=-5)
  3931. assert_raises(AxisError, np.median, d, axis=(0, -5))
  3932. assert_raises(AxisError, np.median, d, axis=4)
  3933. assert_raises(AxisError, np.median, d, axis=(0, 4))
  3934. assert_raises(ValueError, np.median, d, axis=(1, 1))
  3935. def test_keepdims(self):
  3936. d = np.ones((3, 5, 7, 11))
  3937. assert_equal(np.median(d, axis=None, keepdims=True).shape,
  3938. (1, 1, 1, 1))
  3939. assert_equal(np.median(d, axis=(0, 1), keepdims=True).shape,
  3940. (1, 1, 7, 11))
  3941. assert_equal(np.median(d, axis=(0, 3), keepdims=True).shape,
  3942. (1, 5, 7, 1))
  3943. assert_equal(np.median(d, axis=(1,), keepdims=True).shape,
  3944. (3, 1, 7, 11))
  3945. assert_equal(np.median(d, axis=(0, 1, 2, 3), keepdims=True).shape,
  3946. (1, 1, 1, 1))
  3947. assert_equal(np.median(d, axis=(0, 1, 3), keepdims=True).shape,
  3948. (1, 1, 7, 1))
  3949. @pytest.mark.parametrize(
  3950. argnames='axis',
  3951. argvalues=[
  3952. None,
  3953. 1,
  3954. (1, ),
  3955. (0, 1),
  3956. (-3, -1),
  3957. ]
  3958. )
  3959. def test_keepdims_out(self, axis):
  3960. d = np.ones((3, 5, 7, 11))
  3961. if axis is None:
  3962. shape_out = (1,) * d.ndim
  3963. else:
  3964. axis_norm = normalize_axis_tuple(axis, d.ndim)
  3965. shape_out = tuple(
  3966. 1 if i in axis_norm else d.shape[i] for i in range(d.ndim))
  3967. out = np.empty(shape_out)
  3968. result = np.median(d, axis=axis, keepdims=True, out=out)
  3969. assert result is out
  3970. assert_equal(result.shape, shape_out)
  3971. @pytest.mark.parametrize("dtype", ["m8[s]"])
  3972. @pytest.mark.parametrize("pos", [0, 23, 10])
  3973. def test_nat_behavior(self, dtype, pos):
  3974. # TODO: Median does not support Datetime, due to `mean`.
  3975. # NaT and NaN should behave the same, do basic tests for NaT.
  3976. a = np.arange(0, 24, dtype=dtype)
  3977. a[pos] = "NaT"
  3978. res = np.median(a)
  3979. assert res.dtype == dtype
  3980. assert np.isnat(res)
  3981. res = np.percentile(a, [30, 60])
  3982. assert res.dtype == dtype
  3983. assert np.isnat(res).all()
  3984. a = np.arange(0, 24 * 3, dtype=dtype).reshape(-1, 3)
  3985. a[pos, 1] = "NaT"
  3986. res = np.median(a, axis=0)
  3987. assert_array_equal(np.isnat(res), [False, True, False])
  3988. class TestSortComplex:
  3989. @pytest.mark.parametrize("type_in, type_out", [
  3990. ('l', 'D'),
  3991. ('h', 'F'),
  3992. ('H', 'F'),
  3993. ('b', 'F'),
  3994. ('B', 'F'),
  3995. ('g', 'G'),
  3996. ])
  3997. def test_sort_real(self, type_in, type_out):
  3998. # sort_complex() type casting for real input types
  3999. a = np.array([5, 3, 6, 2, 1], dtype=type_in)
  4000. actual = np.sort_complex(a)
  4001. expected = np.sort(a).astype(type_out)
  4002. assert_equal(actual, expected)
  4003. assert_equal(actual.dtype, expected.dtype)
  4004. def test_sort_complex(self):
  4005. # sort_complex() handling of complex input
  4006. a = np.array([2 + 3j, 1 - 2j, 1 - 3j, 2 + 1j], dtype='D')
  4007. expected = np.array([1 - 3j, 1 - 2j, 2 + 1j, 2 + 3j], dtype='D')
  4008. actual = np.sort_complex(a)
  4009. assert_equal(actual, expected)
  4010. assert_equal(actual.dtype, expected.dtype)