test_core.py 206 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566
  1. # pylint: disable-msg=W0400,W0511,W0611,W0612,W0614,R0201,E1102
  2. """Tests suite for MaskedArray & subclassing.
  3. :author: Pierre Gerard-Marchant
  4. :contact: pierregm_at_uga_dot_edu
  5. """
  6. __author__ = "Pierre GF Gerard-Marchant"
  7. import sys
  8. import warnings
  9. import operator
  10. import itertools
  11. import textwrap
  12. import pytest
  13. from functools import reduce
  14. import numpy as np
  15. import numpy.ma.core
  16. import numpy.core.fromnumeric as fromnumeric
  17. import numpy.core.umath as umath
  18. from numpy.testing import (
  19. assert_raises, assert_warns, suppress_warnings, IS_WASM
  20. )
  21. from numpy.testing._private.utils import requires_memory
  22. from numpy import ndarray
  23. from numpy.compat import asbytes
  24. from numpy.ma.testutils import (
  25. assert_, assert_array_equal, assert_equal, assert_almost_equal,
  26. assert_equal_records, fail_if_equal, assert_not_equal,
  27. assert_mask_equal
  28. )
  29. from numpy.ma.core import (
  30. MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all,
  31. allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2,
  32. arcsin, arctan, argsort, array, asarray, choose, concatenate,
  33. conjugate, cos, cosh, count, default_fill_value, diag, divide, doc_note,
  34. empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid,
  35. flatten_structured_array, fromflex, getmask, getmaskarray, greater,
  36. greater_equal, identity, inner, isMaskedArray, less, less_equal, log,
  37. log10, make_mask, make_mask_descr, mask_or, masked, masked_array,
  38. masked_equal, masked_greater, masked_greater_equal, masked_inside,
  39. masked_less, masked_less_equal, masked_not_equal, masked_outside,
  40. masked_print_option, masked_values, masked_where, max, maximum,
  41. maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply,
  42. mvoid, nomask, not_equal, ones, ones_like, outer, power, product, put,
  43. putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort,
  44. sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros, zeros_like,
  45. )
  46. from numpy.compat import pickle
  47. pi = np.pi
  48. suppress_copy_mask_on_assignment = suppress_warnings()
  49. suppress_copy_mask_on_assignment.filter(
  50. numpy.ma.core.MaskedArrayFutureWarning,
  51. "setting an item on a masked array which has a shared mask will not copy")
  52. # For parametrized numeric testing
  53. num_dts = [np.dtype(dt_) for dt_ in '?bhilqBHILQefdgFD']
  54. num_ids = [dt_.char for dt_ in num_dts]
  55. class TestMaskedArray:
  56. # Base test class for MaskedArrays.
  57. def setup_method(self):
  58. # Base data definition.
  59. x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
  60. y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
  61. a10 = 10.
  62. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
  63. m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
  64. xm = masked_array(x, mask=m1)
  65. ym = masked_array(y, mask=m2)
  66. z = np.array([-.5, 0., .5, .8])
  67. zm = masked_array(z, mask=[0, 1, 0, 0])
  68. xf = np.where(m1, 1e+20, x)
  69. xm.set_fill_value(1e+20)
  70. self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
  71. def test_basicattributes(self):
  72. # Tests some basic array attributes.
  73. a = array([1, 3, 2])
  74. b = array([1, 3, 2], mask=[1, 0, 1])
  75. assert_equal(a.ndim, 1)
  76. assert_equal(b.ndim, 1)
  77. assert_equal(a.size, 3)
  78. assert_equal(b.size, 3)
  79. assert_equal(a.shape, (3,))
  80. assert_equal(b.shape, (3,))
  81. def test_basic0d(self):
  82. # Checks masking a scalar
  83. x = masked_array(0)
  84. assert_equal(str(x), '0')
  85. x = masked_array(0, mask=True)
  86. assert_equal(str(x), str(masked_print_option))
  87. x = masked_array(0, mask=False)
  88. assert_equal(str(x), '0')
  89. x = array(0, mask=1)
  90. assert_(x.filled().dtype is x._data.dtype)
  91. def test_basic1d(self):
  92. # Test of basic array creation and properties in 1 dimension.
  93. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  94. assert_(not isMaskedArray(x))
  95. assert_(isMaskedArray(xm))
  96. assert_((xm - ym).filled(0).any())
  97. fail_if_equal(xm.mask.astype(int), ym.mask.astype(int))
  98. s = x.shape
  99. assert_equal(np.shape(xm), s)
  100. assert_equal(xm.shape, s)
  101. assert_equal(xm.dtype, x.dtype)
  102. assert_equal(zm.dtype, z.dtype)
  103. assert_equal(xm.size, reduce(lambda x, y:x * y, s))
  104. assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1))
  105. assert_array_equal(xm, xf)
  106. assert_array_equal(filled(xm, 1.e20), xf)
  107. assert_array_equal(x, xm)
  108. def test_basic2d(self):
  109. # Test of basic array creation and properties in 2 dimensions.
  110. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  111. for s in [(4, 3), (6, 2)]:
  112. x.shape = s
  113. y.shape = s
  114. xm.shape = s
  115. ym.shape = s
  116. xf.shape = s
  117. assert_(not isMaskedArray(x))
  118. assert_(isMaskedArray(xm))
  119. assert_equal(shape(xm), s)
  120. assert_equal(xm.shape, s)
  121. assert_equal(xm.size, reduce(lambda x, y:x * y, s))
  122. assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1))
  123. assert_equal(xm, xf)
  124. assert_equal(filled(xm, 1.e20), xf)
  125. assert_equal(x, xm)
  126. def test_concatenate_basic(self):
  127. # Tests concatenations.
  128. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  129. # basic concatenation
  130. assert_equal(np.concatenate((x, y)), concatenate((xm, ym)))
  131. assert_equal(np.concatenate((x, y)), concatenate((x, y)))
  132. assert_equal(np.concatenate((x, y)), concatenate((xm, y)))
  133. assert_equal(np.concatenate((x, y, x)), concatenate((x, ym, x)))
  134. def test_concatenate_alongaxis(self):
  135. # Tests concatenations.
  136. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  137. # Concatenation along an axis
  138. s = (3, 4)
  139. x.shape = y.shape = xm.shape = ym.shape = s
  140. assert_equal(xm.mask, np.reshape(m1, s))
  141. assert_equal(ym.mask, np.reshape(m2, s))
  142. xmym = concatenate((xm, ym), 1)
  143. assert_equal(np.concatenate((x, y), 1), xmym)
  144. assert_equal(np.concatenate((xm.mask, ym.mask), 1), xmym._mask)
  145. x = zeros(2)
  146. y = array(ones(2), mask=[False, True])
  147. z = concatenate((x, y))
  148. assert_array_equal(z, [0, 0, 1, 1])
  149. assert_array_equal(z.mask, [False, False, False, True])
  150. z = concatenate((y, x))
  151. assert_array_equal(z, [1, 1, 0, 0])
  152. assert_array_equal(z.mask, [False, True, False, False])
  153. def test_concatenate_flexible(self):
  154. # Tests the concatenation on flexible arrays.
  155. data = masked_array(list(zip(np.random.rand(10),
  156. np.arange(10))),
  157. dtype=[('a', float), ('b', int)])
  158. test = concatenate([data[:5], data[5:]])
  159. assert_equal_records(test, data)
  160. def test_creation_ndmin(self):
  161. # Check the use of ndmin
  162. x = array([1, 2, 3], mask=[1, 0, 0], ndmin=2)
  163. assert_equal(x.shape, (1, 3))
  164. assert_equal(x._data, [[1, 2, 3]])
  165. assert_equal(x._mask, [[1, 0, 0]])
  166. def test_creation_ndmin_from_maskedarray(self):
  167. # Make sure we're not losing the original mask w/ ndmin
  168. x = array([1, 2, 3])
  169. x[-1] = masked
  170. xx = array(x, ndmin=2, dtype=float)
  171. assert_equal(x.shape, x._mask.shape)
  172. assert_equal(xx.shape, xx._mask.shape)
  173. def test_creation_maskcreation(self):
  174. # Tests how masks are initialized at the creation of Maskedarrays.
  175. data = arange(24, dtype=float)
  176. data[[3, 6, 15]] = masked
  177. dma_1 = MaskedArray(data)
  178. assert_equal(dma_1.mask, data.mask)
  179. dma_2 = MaskedArray(dma_1)
  180. assert_equal(dma_2.mask, dma_1.mask)
  181. dma_3 = MaskedArray(dma_1, mask=[1, 0, 0, 0] * 6)
  182. fail_if_equal(dma_3.mask, dma_1.mask)
  183. x = array([1, 2, 3], mask=True)
  184. assert_equal(x._mask, [True, True, True])
  185. x = array([1, 2, 3], mask=False)
  186. assert_equal(x._mask, [False, False, False])
  187. y = array([1, 2, 3], mask=x._mask, copy=False)
  188. assert_(np.may_share_memory(x.mask, y.mask))
  189. y = array([1, 2, 3], mask=x._mask, copy=True)
  190. assert_(not np.may_share_memory(x.mask, y.mask))
  191. def test_masked_singleton_array_creation_warns(self):
  192. # The first works, but should not (ideally), there may be no way
  193. # to solve this, however, as long as `np.ma.masked` is an ndarray.
  194. np.array(np.ma.masked)
  195. with pytest.warns(UserWarning):
  196. # Tries to create a float array, using `float(np.ma.masked)`.
  197. # We may want to define this is invalid behaviour in the future!
  198. # (requiring np.ma.masked to be a known NumPy scalar probably
  199. # with a DType.)
  200. np.array([3., np.ma.masked])
  201. def test_creation_with_list_of_maskedarrays(self):
  202. # Tests creating a masked array from a list of masked arrays.
  203. x = array(np.arange(5), mask=[1, 0, 0, 0, 0])
  204. data = array((x, x[::-1]))
  205. assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])
  206. assert_equal(data._mask, [[1, 0, 0, 0, 0], [0, 0, 0, 0, 1]])
  207. x.mask = nomask
  208. data = array((x, x[::-1]))
  209. assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])
  210. assert_(data.mask is nomask)
  211. def test_creation_with_list_of_maskedarrays_no_bool_cast(self):
  212. # Tests the regression in gh-18551
  213. masked_str = np.ma.masked_array(['a', 'b'], mask=[True, False])
  214. normal_int = np.arange(2)
  215. res = np.ma.asarray([masked_str, normal_int], dtype="U21")
  216. assert_array_equal(res.mask, [[True, False], [False, False]])
  217. # The above only failed due a long chain of oddity, try also with
  218. # an object array that cannot be converted to bool always:
  219. class NotBool():
  220. def __bool__(self):
  221. raise ValueError("not a bool!")
  222. masked_obj = np.ma.masked_array([NotBool(), 'b'], mask=[True, False])
  223. # Check that the NotBool actually fails like we would expect:
  224. with pytest.raises(ValueError, match="not a bool!"):
  225. np.asarray([masked_obj], dtype=bool)
  226. res = np.ma.asarray([masked_obj, normal_int])
  227. assert_array_equal(res.mask, [[True, False], [False, False]])
  228. def test_creation_from_ndarray_with_padding(self):
  229. x = np.array([('A', 0)], dtype={'names':['f0','f1'],
  230. 'formats':['S4','i8'],
  231. 'offsets':[0,8]})
  232. array(x) # used to fail due to 'V' padding field in x.dtype.descr
  233. def test_unknown_keyword_parameter(self):
  234. with pytest.raises(TypeError, match="unexpected keyword argument"):
  235. MaskedArray([1, 2, 3], maks=[0, 1, 0]) # `mask` is misspelled.
  236. def test_asarray(self):
  237. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  238. xm.fill_value = -9999
  239. xm._hardmask = True
  240. xmm = asarray(xm)
  241. assert_equal(xmm._data, xm._data)
  242. assert_equal(xmm._mask, xm._mask)
  243. assert_equal(xmm.fill_value, xm.fill_value)
  244. assert_equal(xmm._hardmask, xm._hardmask)
  245. def test_asarray_default_order(self):
  246. # See Issue #6646
  247. m = np.eye(3).T
  248. assert_(not m.flags.c_contiguous)
  249. new_m = asarray(m)
  250. assert_(new_m.flags.c_contiguous)
  251. def test_asarray_enforce_order(self):
  252. # See Issue #6646
  253. m = np.eye(3).T
  254. assert_(not m.flags.c_contiguous)
  255. new_m = asarray(m, order='C')
  256. assert_(new_m.flags.c_contiguous)
  257. def test_fix_invalid(self):
  258. # Checks fix_invalid.
  259. with np.errstate(invalid='ignore'):
  260. data = masked_array([np.nan, 0., 1.], mask=[0, 0, 1])
  261. data_fixed = fix_invalid(data)
  262. assert_equal(data_fixed._data, [data.fill_value, 0., 1.])
  263. assert_equal(data_fixed._mask, [1., 0., 1.])
  264. def test_maskedelement(self):
  265. # Test of masked element
  266. x = arange(6)
  267. x[1] = masked
  268. assert_(str(masked) == '--')
  269. assert_(x[1] is masked)
  270. assert_equal(filled(x[1], 0), 0)
  271. def test_set_element_as_object(self):
  272. # Tests setting elements with object
  273. a = empty(1, dtype=object)
  274. x = (1, 2, 3, 4, 5)
  275. a[0] = x
  276. assert_equal(a[0], x)
  277. assert_(a[0] is x)
  278. import datetime
  279. dt = datetime.datetime.now()
  280. a[0] = dt
  281. assert_(a[0] is dt)
  282. def test_indexing(self):
  283. # Tests conversions and indexing
  284. x1 = np.array([1, 2, 4, 3])
  285. x2 = array(x1, mask=[1, 0, 0, 0])
  286. x3 = array(x1, mask=[0, 1, 0, 1])
  287. x4 = array(x1)
  288. # test conversion to strings
  289. str(x2) # raises?
  290. repr(x2) # raises?
  291. assert_equal(np.sort(x1), sort(x2, endwith=False))
  292. # tests of indexing
  293. assert_(type(x2[1]) is type(x1[1]))
  294. assert_(x1[1] == x2[1])
  295. assert_(x2[0] is masked)
  296. assert_equal(x1[2], x2[2])
  297. assert_equal(x1[2:5], x2[2:5])
  298. assert_equal(x1[:], x2[:])
  299. assert_equal(x1[1:], x3[1:])
  300. x1[2] = 9
  301. x2[2] = 9
  302. assert_equal(x1, x2)
  303. x1[1:3] = 99
  304. x2[1:3] = 99
  305. assert_equal(x1, x2)
  306. x2[1] = masked
  307. assert_equal(x1, x2)
  308. x2[1:3] = masked
  309. assert_equal(x1, x2)
  310. x2[:] = x1
  311. x2[1] = masked
  312. assert_(allequal(getmask(x2), array([0, 1, 0, 0])))
  313. x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
  314. assert_(allequal(getmask(x3), array([0, 1, 1, 0])))
  315. x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
  316. assert_(allequal(getmask(x4), array([0, 1, 1, 0])))
  317. assert_(allequal(x4, array([1, 2, 3, 4])))
  318. x1 = np.arange(5) * 1.0
  319. x2 = masked_values(x1, 3.0)
  320. assert_equal(x1, x2)
  321. assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask))
  322. assert_equal(3.0, x2.fill_value)
  323. x1 = array([1, 'hello', 2, 3], object)
  324. x2 = np.array([1, 'hello', 2, 3], object)
  325. s1 = x1[1]
  326. s2 = x2[1]
  327. assert_equal(type(s2), str)
  328. assert_equal(type(s1), str)
  329. assert_equal(s1, s2)
  330. assert_(x1[1:1].shape == (0,))
  331. def test_setitem_no_warning(self):
  332. # Setitem shouldn't warn, because the assignment might be masked
  333. # and warning for a masked assignment is weird (see gh-23000)
  334. # (When the value is masked, otherwise a warning would be acceptable
  335. # but is not given currently.)
  336. x = np.ma.arange(60).reshape((6, 10))
  337. index = (slice(1, 5, 2), [7, 5])
  338. value = np.ma.masked_all((2, 2))
  339. value._data[...] = np.inf # not a valid integer...
  340. x[index] = value
  341. # The masked scalar is special cased, but test anyway (it's NaN):
  342. x[...] = np.ma.masked
  343. # Finally, a large value that cannot be cast to the float32 `x`
  344. x = np.ma.arange(3., dtype=np.float32)
  345. value = np.ma.array([2e234, 1, 1], mask=[True, False, False])
  346. x[...] = value
  347. x[[0, 1, 2]] = value
  348. @suppress_copy_mask_on_assignment
  349. def test_copy(self):
  350. # Tests of some subtle points of copying and sizing.
  351. n = [0, 0, 1, 0, 0]
  352. m = make_mask(n)
  353. m2 = make_mask(m)
  354. assert_(m is m2)
  355. m3 = make_mask(m, copy=True)
  356. assert_(m is not m3)
  357. x1 = np.arange(5)
  358. y1 = array(x1, mask=m)
  359. assert_equal(y1._data.__array_interface__, x1.__array_interface__)
  360. assert_(allequal(x1, y1.data))
  361. assert_equal(y1._mask.__array_interface__, m.__array_interface__)
  362. y1a = array(y1)
  363. # Default for masked array is not to copy; see gh-10318.
  364. assert_(y1a._data.__array_interface__ ==
  365. y1._data.__array_interface__)
  366. assert_(y1a._mask.__array_interface__ ==
  367. y1._mask.__array_interface__)
  368. y2 = array(x1, mask=m3)
  369. assert_(y2._data.__array_interface__ == x1.__array_interface__)
  370. assert_(y2._mask.__array_interface__ == m3.__array_interface__)
  371. assert_(y2[2] is masked)
  372. y2[2] = 9
  373. assert_(y2[2] is not masked)
  374. assert_(y2._mask.__array_interface__ == m3.__array_interface__)
  375. assert_(allequal(y2.mask, 0))
  376. y2a = array(x1, mask=m, copy=1)
  377. assert_(y2a._data.__array_interface__ != x1.__array_interface__)
  378. #assert_( y2a._mask is not m)
  379. assert_(y2a._mask.__array_interface__ != m.__array_interface__)
  380. assert_(y2a[2] is masked)
  381. y2a[2] = 9
  382. assert_(y2a[2] is not masked)
  383. #assert_( y2a._mask is not m)
  384. assert_(y2a._mask.__array_interface__ != m.__array_interface__)
  385. assert_(allequal(y2a.mask, 0))
  386. y3 = array(x1 * 1.0, mask=m)
  387. assert_(filled(y3).dtype is (x1 * 1.0).dtype)
  388. x4 = arange(4)
  389. x4[2] = masked
  390. y4 = resize(x4, (8,))
  391. assert_equal(concatenate([x4, x4]), y4)
  392. assert_equal(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0])
  393. y5 = repeat(x4, (2, 2, 2, 2), axis=0)
  394. assert_equal(y5, [0, 0, 1, 1, 2, 2, 3, 3])
  395. y6 = repeat(x4, 2, axis=0)
  396. assert_equal(y5, y6)
  397. y7 = x4.repeat((2, 2, 2, 2), axis=0)
  398. assert_equal(y5, y7)
  399. y8 = x4.repeat(2, 0)
  400. assert_equal(y5, y8)
  401. y9 = x4.copy()
  402. assert_equal(y9._data, x4._data)
  403. assert_equal(y9._mask, x4._mask)
  404. x = masked_array([1, 2, 3], mask=[0, 1, 0])
  405. # Copy is False by default
  406. y = masked_array(x)
  407. assert_equal(y._data.ctypes.data, x._data.ctypes.data)
  408. assert_equal(y._mask.ctypes.data, x._mask.ctypes.data)
  409. y = masked_array(x, copy=True)
  410. assert_not_equal(y._data.ctypes.data, x._data.ctypes.data)
  411. assert_not_equal(y._mask.ctypes.data, x._mask.ctypes.data)
  412. def test_copy_0d(self):
  413. # gh-9430
  414. x = np.ma.array(43, mask=True)
  415. xc = x.copy()
  416. assert_equal(xc.mask, True)
  417. def test_copy_on_python_builtins(self):
  418. # Tests copy works on python builtins (issue#8019)
  419. assert_(isMaskedArray(np.ma.copy([1,2,3])))
  420. assert_(isMaskedArray(np.ma.copy((1,2,3))))
  421. def test_copy_immutable(self):
  422. # Tests that the copy method is immutable, GitHub issue #5247
  423. a = np.ma.array([1, 2, 3])
  424. b = np.ma.array([4, 5, 6])
  425. a_copy_method = a.copy
  426. b.copy
  427. assert_equal(a_copy_method(), [1, 2, 3])
  428. def test_deepcopy(self):
  429. from copy import deepcopy
  430. a = array([0, 1, 2], mask=[False, True, False])
  431. copied = deepcopy(a)
  432. assert_equal(copied.mask, a.mask)
  433. assert_not_equal(id(a._mask), id(copied._mask))
  434. copied[1] = 1
  435. assert_equal(copied.mask, [0, 0, 0])
  436. assert_equal(a.mask, [0, 1, 0])
  437. copied = deepcopy(a)
  438. assert_equal(copied.mask, a.mask)
  439. copied.mask[1] = False
  440. assert_equal(copied.mask, [0, 0, 0])
  441. assert_equal(a.mask, [0, 1, 0])
  442. def test_format(self):
  443. a = array([0, 1, 2], mask=[False, True, False])
  444. assert_equal(format(a), "[0 -- 2]")
  445. assert_equal(format(masked), "--")
  446. assert_equal(format(masked, ""), "--")
  447. # Postponed from PR #15410, perhaps address in the future.
  448. # assert_equal(format(masked, " >5"), " --")
  449. # assert_equal(format(masked, " <5"), "-- ")
  450. # Expect a FutureWarning for using format_spec with MaskedElement
  451. with assert_warns(FutureWarning):
  452. with_format_string = format(masked, " >5")
  453. assert_equal(with_format_string, "--")
  454. def test_str_repr(self):
  455. a = array([0, 1, 2], mask=[False, True, False])
  456. assert_equal(str(a), '[0 -- 2]')
  457. assert_equal(
  458. repr(a),
  459. textwrap.dedent('''\
  460. masked_array(data=[0, --, 2],
  461. mask=[False, True, False],
  462. fill_value=999999)''')
  463. )
  464. # arrays with a continuation
  465. a = np.ma.arange(2000)
  466. a[1:50] = np.ma.masked
  467. assert_equal(
  468. repr(a),
  469. textwrap.dedent('''\
  470. masked_array(data=[0, --, --, ..., 1997, 1998, 1999],
  471. mask=[False, True, True, ..., False, False, False],
  472. fill_value=999999)''')
  473. )
  474. # line-wrapped 1d arrays are correctly aligned
  475. a = np.ma.arange(20)
  476. assert_equal(
  477. repr(a),
  478. textwrap.dedent('''\
  479. masked_array(data=[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
  480. 14, 15, 16, 17, 18, 19],
  481. mask=False,
  482. fill_value=999999)''')
  483. )
  484. # 2d arrays cause wrapping
  485. a = array([[1, 2, 3], [4, 5, 6]], dtype=np.int8)
  486. a[1,1] = np.ma.masked
  487. assert_equal(
  488. repr(a),
  489. textwrap.dedent('''\
  490. masked_array(
  491. data=[[1, 2, 3],
  492. [4, --, 6]],
  493. mask=[[False, False, False],
  494. [False, True, False]],
  495. fill_value=999999,
  496. dtype=int8)''')
  497. )
  498. # but not it they're a row vector
  499. assert_equal(
  500. repr(a[:1]),
  501. textwrap.dedent('''\
  502. masked_array(data=[[1, 2, 3]],
  503. mask=[[False, False, False]],
  504. fill_value=999999,
  505. dtype=int8)''')
  506. )
  507. # dtype=int is implied, so not shown
  508. assert_equal(
  509. repr(a.astype(int)),
  510. textwrap.dedent('''\
  511. masked_array(
  512. data=[[1, 2, 3],
  513. [4, --, 6]],
  514. mask=[[False, False, False],
  515. [False, True, False]],
  516. fill_value=999999)''')
  517. )
  518. def test_str_repr_legacy(self):
  519. oldopts = np.get_printoptions()
  520. np.set_printoptions(legacy='1.13')
  521. try:
  522. a = array([0, 1, 2], mask=[False, True, False])
  523. assert_equal(str(a), '[0 -- 2]')
  524. assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
  525. ' mask = [False True False],\n'
  526. ' fill_value = 999999)\n')
  527. a = np.ma.arange(2000)
  528. a[1:50] = np.ma.masked
  529. assert_equal(
  530. repr(a),
  531. 'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
  532. ' mask = [False True True ..., False False False],\n'
  533. ' fill_value = 999999)\n'
  534. )
  535. finally:
  536. np.set_printoptions(**oldopts)
  537. def test_0d_unicode(self):
  538. u = 'caf\xe9'
  539. utype = type(u)
  540. arr_nomask = np.ma.array(u)
  541. arr_masked = np.ma.array(u, mask=True)
  542. assert_equal(utype(arr_nomask), u)
  543. assert_equal(utype(arr_masked), '--')
  544. def test_pickling(self):
  545. # Tests pickling
  546. for dtype in (int, float, str, object):
  547. a = arange(10).astype(dtype)
  548. a.fill_value = 999
  549. masks = ([0, 0, 0, 1, 0, 1, 0, 1, 0, 1], # partially masked
  550. True, # Fully masked
  551. False) # Fully unmasked
  552. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  553. for mask in masks:
  554. a.mask = mask
  555. a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))
  556. assert_equal(a_pickled._mask, a._mask)
  557. assert_equal(a_pickled._data, a._data)
  558. if dtype in (object, int):
  559. assert_equal(a_pickled.fill_value, 999)
  560. else:
  561. assert_equal(a_pickled.fill_value, dtype(999))
  562. assert_array_equal(a_pickled.mask, mask)
  563. def test_pickling_subbaseclass(self):
  564. # Test pickling w/ a subclass of ndarray
  565. x = np.array([(1.0, 2), (3.0, 4)],
  566. dtype=[('x', float), ('y', int)]).view(np.recarray)
  567. a = masked_array(x, mask=[(True, False), (False, True)])
  568. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  569. a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))
  570. assert_equal(a_pickled._mask, a._mask)
  571. assert_equal(a_pickled, a)
  572. assert_(isinstance(a_pickled._data, np.recarray))
  573. def test_pickling_maskedconstant(self):
  574. # Test pickling MaskedConstant
  575. mc = np.ma.masked
  576. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  577. mc_pickled = pickle.loads(pickle.dumps(mc, protocol=proto))
  578. assert_equal(mc_pickled._baseclass, mc._baseclass)
  579. assert_equal(mc_pickled._mask, mc._mask)
  580. assert_equal(mc_pickled._data, mc._data)
  581. def test_pickling_wstructured(self):
  582. # Tests pickling w/ structured array
  583. a = array([(1, 1.), (2, 2.)], mask=[(0, 0), (0, 1)],
  584. dtype=[('a', int), ('b', float)])
  585. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  586. a_pickled = pickle.loads(pickle.dumps(a, protocol=proto))
  587. assert_equal(a_pickled._mask, a._mask)
  588. assert_equal(a_pickled, a)
  589. def test_pickling_keepalignment(self):
  590. # Tests pickling w/ F_CONTIGUOUS arrays
  591. a = arange(10)
  592. a.shape = (-1, 2)
  593. b = a.T
  594. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  595. test = pickle.loads(pickle.dumps(b, protocol=proto))
  596. assert_equal(test, b)
  597. def test_single_element_subscript(self):
  598. # Tests single element subscripts of Maskedarrays.
  599. a = array([1, 3, 2])
  600. b = array([1, 3, 2], mask=[1, 0, 1])
  601. assert_equal(a[0].shape, ())
  602. assert_equal(b[0].shape, ())
  603. assert_equal(b[1].shape, ())
  604. def test_topython(self):
  605. # Tests some communication issues with Python.
  606. assert_equal(1, int(array(1)))
  607. assert_equal(1.0, float(array(1)))
  608. assert_equal(1, int(array([[[1]]])))
  609. assert_equal(1.0, float(array([[1]])))
  610. assert_raises(TypeError, float, array([1, 1]))
  611. with suppress_warnings() as sup:
  612. sup.filter(UserWarning, 'Warning: converting a masked element')
  613. assert_(np.isnan(float(array([1], mask=[1]))))
  614. a = array([1, 2, 3], mask=[1, 0, 0])
  615. assert_raises(TypeError, lambda: float(a))
  616. assert_equal(float(a[-1]), 3.)
  617. assert_(np.isnan(float(a[0])))
  618. assert_raises(TypeError, int, a)
  619. assert_equal(int(a[-1]), 3)
  620. assert_raises(MAError, lambda:int(a[0]))
  621. def test_oddfeatures_1(self):
  622. # Test of other odd features
  623. x = arange(20)
  624. x = x.reshape(4, 5)
  625. x.flat[5] = 12
  626. assert_(x[1, 0] == 12)
  627. z = x + 10j * x
  628. assert_equal(z.real, x)
  629. assert_equal(z.imag, 10 * x)
  630. assert_equal((z * conjugate(z)).real, 101 * x * x)
  631. z.imag[...] = 0.0
  632. x = arange(10)
  633. x[3] = masked
  634. assert_(str(x[3]) == str(masked))
  635. c = x >= 8
  636. assert_(count(where(c, masked, masked)) == 0)
  637. assert_(shape(where(c, masked, masked)) == c.shape)
  638. z = masked_where(c, x)
  639. assert_(z.dtype is x.dtype)
  640. assert_(z[3] is masked)
  641. assert_(z[4] is not masked)
  642. assert_(z[7] is not masked)
  643. assert_(z[8] is masked)
  644. assert_(z[9] is masked)
  645. assert_equal(x, z)
  646. def test_oddfeatures_2(self):
  647. # Tests some more features.
  648. x = array([1., 2., 3., 4., 5.])
  649. c = array([1, 1, 1, 0, 0])
  650. x[2] = masked
  651. z = where(c, x, -x)
  652. assert_equal(z, [1., 2., 0., -4., -5])
  653. c[0] = masked
  654. z = where(c, x, -x)
  655. assert_equal(z, [1., 2., 0., -4., -5])
  656. assert_(z[0] is masked)
  657. assert_(z[1] is not masked)
  658. assert_(z[2] is masked)
  659. @suppress_copy_mask_on_assignment
  660. def test_oddfeatures_3(self):
  661. # Tests some generic features
  662. atest = array([10], mask=True)
  663. btest = array([20])
  664. idx = atest.mask
  665. atest[idx] = btest[idx]
  666. assert_equal(atest, [20])
  667. def test_filled_with_object_dtype(self):
  668. a = np.ma.masked_all(1, dtype='O')
  669. assert_equal(a.filled('x')[0], 'x')
  670. def test_filled_with_flexible_dtype(self):
  671. # Test filled w/ flexible dtype
  672. flexi = array([(1, 1, 1)],
  673. dtype=[('i', int), ('s', '|S8'), ('f', float)])
  674. flexi[0] = masked
  675. assert_equal(flexi.filled(),
  676. np.array([(default_fill_value(0),
  677. default_fill_value('0'),
  678. default_fill_value(0.),)], dtype=flexi.dtype))
  679. flexi[0] = masked
  680. assert_equal(flexi.filled(1),
  681. np.array([(1, '1', 1.)], dtype=flexi.dtype))
  682. def test_filled_with_mvoid(self):
  683. # Test filled w/ mvoid
  684. ndtype = [('a', int), ('b', float)]
  685. a = mvoid((1, 2.), mask=[(0, 1)], dtype=ndtype)
  686. # Filled using default
  687. test = a.filled()
  688. assert_equal(tuple(test), (1, default_fill_value(1.)))
  689. # Explicit fill_value
  690. test = a.filled((-1, -1))
  691. assert_equal(tuple(test), (1, -1))
  692. # Using predefined filling values
  693. a.fill_value = (-999, -999)
  694. assert_equal(tuple(a.filled()), (1, -999))
  695. def test_filled_with_nested_dtype(self):
  696. # Test filled w/ nested dtype
  697. ndtype = [('A', int), ('B', [('BA', int), ('BB', int)])]
  698. a = array([(1, (1, 1)), (2, (2, 2))],
  699. mask=[(0, (1, 0)), (0, (0, 1))], dtype=ndtype)
  700. test = a.filled(0)
  701. control = np.array([(1, (0, 1)), (2, (2, 0))], dtype=ndtype)
  702. assert_equal(test, control)
  703. test = a['B'].filled(0)
  704. control = np.array([(0, 1), (2, 0)], dtype=a['B'].dtype)
  705. assert_equal(test, control)
  706. # test if mask gets set correctly (see #6760)
  707. Z = numpy.ma.zeros(2, numpy.dtype([("A", "(2,2)i1,(2,2)i1", (2,2))]))
  708. assert_equal(Z.data.dtype, numpy.dtype([('A', [('f0', 'i1', (2, 2)),
  709. ('f1', 'i1', (2, 2))], (2, 2))]))
  710. assert_equal(Z.mask.dtype, numpy.dtype([('A', [('f0', '?', (2, 2)),
  711. ('f1', '?', (2, 2))], (2, 2))]))
  712. def test_filled_with_f_order(self):
  713. # Test filled w/ F-contiguous array
  714. a = array(np.array([(0, 1, 2), (4, 5, 6)], order='F'),
  715. mask=np.array([(0, 0, 1), (1, 0, 0)], order='F'),
  716. order='F') # this is currently ignored
  717. assert_(a.flags['F_CONTIGUOUS'])
  718. assert_(a.filled(0).flags['F_CONTIGUOUS'])
  719. def test_optinfo_propagation(self):
  720. # Checks that _optinfo dictionary isn't back-propagated
  721. x = array([1, 2, 3, ], dtype=float)
  722. x._optinfo['info'] = '???'
  723. y = x.copy()
  724. assert_equal(y._optinfo['info'], '???')
  725. y._optinfo['info'] = '!!!'
  726. assert_equal(x._optinfo['info'], '???')
  727. def test_optinfo_forward_propagation(self):
  728. a = array([1,2,2,4])
  729. a._optinfo["key"] = "value"
  730. assert_equal(a._optinfo["key"], (a == 2)._optinfo["key"])
  731. assert_equal(a._optinfo["key"], (a != 2)._optinfo["key"])
  732. assert_equal(a._optinfo["key"], (a > 2)._optinfo["key"])
  733. assert_equal(a._optinfo["key"], (a >= 2)._optinfo["key"])
  734. assert_equal(a._optinfo["key"], (a <= 2)._optinfo["key"])
  735. assert_equal(a._optinfo["key"], (a + 2)._optinfo["key"])
  736. assert_equal(a._optinfo["key"], (a - 2)._optinfo["key"])
  737. assert_equal(a._optinfo["key"], (a * 2)._optinfo["key"])
  738. assert_equal(a._optinfo["key"], (a / 2)._optinfo["key"])
  739. assert_equal(a._optinfo["key"], a[:2]._optinfo["key"])
  740. assert_equal(a._optinfo["key"], a[[0,0,2]]._optinfo["key"])
  741. assert_equal(a._optinfo["key"], np.exp(a)._optinfo["key"])
  742. assert_equal(a._optinfo["key"], np.abs(a)._optinfo["key"])
  743. assert_equal(a._optinfo["key"], array(a, copy=True)._optinfo["key"])
  744. assert_equal(a._optinfo["key"], np.zeros_like(a)._optinfo["key"])
  745. def test_fancy_printoptions(self):
  746. # Test printing a masked array w/ fancy dtype.
  747. fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
  748. test = array([(1, (2, 3.0)), (4, (5, 6.0))],
  749. mask=[(1, (0, 1)), (0, (1, 0))],
  750. dtype=fancydtype)
  751. control = "[(--, (2, --)) (4, (--, 6.0))]"
  752. assert_equal(str(test), control)
  753. # Test 0-d array with multi-dimensional dtype
  754. t_2d0 = masked_array(data = (0, [[0.0, 0.0, 0.0],
  755. [0.0, 0.0, 0.0]],
  756. 0.0),
  757. mask = (False, [[True, False, True],
  758. [False, False, True]],
  759. False),
  760. dtype = "int, (2,3)float, float")
  761. control = "(0, [[--, 0.0, --], [0.0, 0.0, --]], 0.0)"
  762. assert_equal(str(t_2d0), control)
  763. def test_flatten_structured_array(self):
  764. # Test flatten_structured_array on arrays
  765. # On ndarray
  766. ndtype = [('a', int), ('b', float)]
  767. a = np.array([(1, 1), (2, 2)], dtype=ndtype)
  768. test = flatten_structured_array(a)
  769. control = np.array([[1., 1.], [2., 2.]], dtype=float)
  770. assert_equal(test, control)
  771. assert_equal(test.dtype, control.dtype)
  772. # On masked_array
  773. a = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)
  774. test = flatten_structured_array(a)
  775. control = array([[1., 1.], [2., 2.]],
  776. mask=[[0, 1], [1, 0]], dtype=float)
  777. assert_equal(test, control)
  778. assert_equal(test.dtype, control.dtype)
  779. assert_equal(test.mask, control.mask)
  780. # On masked array with nested structure
  781. ndtype = [('a', int), ('b', [('ba', int), ('bb', float)])]
  782. a = array([(1, (1, 1.1)), (2, (2, 2.2))],
  783. mask=[(0, (1, 0)), (1, (0, 1))], dtype=ndtype)
  784. test = flatten_structured_array(a)
  785. control = array([[1., 1., 1.1], [2., 2., 2.2]],
  786. mask=[[0, 1, 0], [1, 0, 1]], dtype=float)
  787. assert_equal(test, control)
  788. assert_equal(test.dtype, control.dtype)
  789. assert_equal(test.mask, control.mask)
  790. # Keeping the initial shape
  791. ndtype = [('a', int), ('b', float)]
  792. a = np.array([[(1, 1), ], [(2, 2), ]], dtype=ndtype)
  793. test = flatten_structured_array(a)
  794. control = np.array([[[1., 1.], ], [[2., 2.], ]], dtype=float)
  795. assert_equal(test, control)
  796. assert_equal(test.dtype, control.dtype)
  797. def test_void0d(self):
  798. # Test creating a mvoid object
  799. ndtype = [('a', int), ('b', int)]
  800. a = np.array([(1, 2,)], dtype=ndtype)[0]
  801. f = mvoid(a)
  802. assert_(isinstance(f, mvoid))
  803. a = masked_array([(1, 2)], mask=[(1, 0)], dtype=ndtype)[0]
  804. assert_(isinstance(a, mvoid))
  805. a = masked_array([(1, 2), (1, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)
  806. f = mvoid(a._data[0], a._mask[0])
  807. assert_(isinstance(f, mvoid))
  808. def test_mvoid_getitem(self):
  809. # Test mvoid.__getitem__
  810. ndtype = [('a', int), ('b', int)]
  811. a = masked_array([(1, 2,), (3, 4)], mask=[(0, 0), (1, 0)],
  812. dtype=ndtype)
  813. # w/o mask
  814. f = a[0]
  815. assert_(isinstance(f, mvoid))
  816. assert_equal((f[0], f['a']), (1, 1))
  817. assert_equal(f['b'], 2)
  818. # w/ mask
  819. f = a[1]
  820. assert_(isinstance(f, mvoid))
  821. assert_(f[0] is masked)
  822. assert_(f['a'] is masked)
  823. assert_equal(f[1], 4)
  824. # exotic dtype
  825. A = masked_array(data=[([0,1],)],
  826. mask=[([True, False],)],
  827. dtype=[("A", ">i2", (2,))])
  828. assert_equal(A[0]["A"], A["A"][0])
  829. assert_equal(A[0]["A"], masked_array(data=[0, 1],
  830. mask=[True, False], dtype=">i2"))
  831. def test_mvoid_iter(self):
  832. # Test iteration on __getitem__
  833. ndtype = [('a', int), ('b', int)]
  834. a = masked_array([(1, 2,), (3, 4)], mask=[(0, 0), (1, 0)],
  835. dtype=ndtype)
  836. # w/o mask
  837. assert_equal(list(a[0]), [1, 2])
  838. # w/ mask
  839. assert_equal(list(a[1]), [masked, 4])
  840. def test_mvoid_print(self):
  841. # Test printing a mvoid
  842. mx = array([(1, 1), (2, 2)], dtype=[('a', int), ('b', int)])
  843. assert_equal(str(mx[0]), "(1, 1)")
  844. mx['b'][0] = masked
  845. ini_display = masked_print_option._display
  846. masked_print_option.set_display("-X-")
  847. try:
  848. assert_equal(str(mx[0]), "(1, -X-)")
  849. assert_equal(repr(mx[0]), "(1, -X-)")
  850. finally:
  851. masked_print_option.set_display(ini_display)
  852. # also check if there are object datatypes (see gh-7493)
  853. mx = array([(1,), (2,)], dtype=[('a', 'O')])
  854. assert_equal(str(mx[0]), "(1,)")
  855. def test_mvoid_multidim_print(self):
  856. # regression test for gh-6019
  857. t_ma = masked_array(data = [([1, 2, 3],)],
  858. mask = [([False, True, False],)],
  859. fill_value = ([999999, 999999, 999999],),
  860. dtype = [('a', '<i4', (3,))])
  861. assert_(str(t_ma[0]) == "([1, --, 3],)")
  862. assert_(repr(t_ma[0]) == "([1, --, 3],)")
  863. # additional tests with structured arrays
  864. t_2d = masked_array(data = [([[1, 2], [3,4]],)],
  865. mask = [([[False, True], [True, False]],)],
  866. dtype = [('a', '<i4', (2,2))])
  867. assert_(str(t_2d[0]) == "([[1, --], [--, 4]],)")
  868. assert_(repr(t_2d[0]) == "([[1, --], [--, 4]],)")
  869. t_0d = masked_array(data = [(1,2)],
  870. mask = [(True,False)],
  871. dtype = [('a', '<i4'), ('b', '<i4')])
  872. assert_(str(t_0d[0]) == "(--, 2)")
  873. assert_(repr(t_0d[0]) == "(--, 2)")
  874. t_2d = masked_array(data = [([[1, 2], [3,4]], 1)],
  875. mask = [([[False, True], [True, False]], False)],
  876. dtype = [('a', '<i4', (2,2)), ('b', float)])
  877. assert_(str(t_2d[0]) == "([[1, --], [--, 4]], 1.0)")
  878. assert_(repr(t_2d[0]) == "([[1, --], [--, 4]], 1.0)")
  879. t_ne = masked_array(data=[(1, (1, 1))],
  880. mask=[(True, (True, False))],
  881. dtype = [('a', '<i4'), ('b', 'i4,i4')])
  882. assert_(str(t_ne[0]) == "(--, (--, 1))")
  883. assert_(repr(t_ne[0]) == "(--, (--, 1))")
  884. def test_object_with_array(self):
  885. mx1 = masked_array([1.], mask=[True])
  886. mx2 = masked_array([1., 2.])
  887. mx = masked_array([mx1, mx2], mask=[False, True], dtype=object)
  888. assert_(mx[0] is mx1)
  889. assert_(mx[1] is not mx2)
  890. assert_(np.all(mx[1].data == mx2.data))
  891. assert_(np.all(mx[1].mask))
  892. # check that we return a view.
  893. mx[1].data[0] = 0.
  894. assert_(mx2[0] == 0.)
  895. class TestMaskedArrayArithmetic:
  896. # Base test class for MaskedArrays.
  897. def setup_method(self):
  898. # Base data definition.
  899. x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
  900. y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
  901. a10 = 10.
  902. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
  903. m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
  904. xm = masked_array(x, mask=m1)
  905. ym = masked_array(y, mask=m2)
  906. z = np.array([-.5, 0., .5, .8])
  907. zm = masked_array(z, mask=[0, 1, 0, 0])
  908. xf = np.where(m1, 1e+20, x)
  909. xm.set_fill_value(1e+20)
  910. self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
  911. self.err_status = np.geterr()
  912. np.seterr(divide='ignore', invalid='ignore')
  913. def teardown_method(self):
  914. np.seterr(**self.err_status)
  915. def test_basic_arithmetic(self):
  916. # Test of basic arithmetic.
  917. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  918. a2d = array([[1, 2], [0, 4]])
  919. a2dm = masked_array(a2d, [[0, 0], [1, 0]])
  920. assert_equal(a2d * a2d, a2d * a2dm)
  921. assert_equal(a2d + a2d, a2d + a2dm)
  922. assert_equal(a2d - a2d, a2d - a2dm)
  923. for s in [(12,), (4, 3), (2, 6)]:
  924. x = x.reshape(s)
  925. y = y.reshape(s)
  926. xm = xm.reshape(s)
  927. ym = ym.reshape(s)
  928. xf = xf.reshape(s)
  929. assert_equal(-x, -xm)
  930. assert_equal(x + y, xm + ym)
  931. assert_equal(x - y, xm - ym)
  932. assert_equal(x * y, xm * ym)
  933. assert_equal(x / y, xm / ym)
  934. assert_equal(a10 + y, a10 + ym)
  935. assert_equal(a10 - y, a10 - ym)
  936. assert_equal(a10 * y, a10 * ym)
  937. assert_equal(a10 / y, a10 / ym)
  938. assert_equal(x + a10, xm + a10)
  939. assert_equal(x - a10, xm - a10)
  940. assert_equal(x * a10, xm * a10)
  941. assert_equal(x / a10, xm / a10)
  942. assert_equal(x ** 2, xm ** 2)
  943. assert_equal(abs(x) ** 2.5, abs(xm) ** 2.5)
  944. assert_equal(x ** y, xm ** ym)
  945. assert_equal(np.add(x, y), add(xm, ym))
  946. assert_equal(np.subtract(x, y), subtract(xm, ym))
  947. assert_equal(np.multiply(x, y), multiply(xm, ym))
  948. assert_equal(np.divide(x, y), divide(xm, ym))
  949. def test_divide_on_different_shapes(self):
  950. x = arange(6, dtype=float)
  951. x.shape = (2, 3)
  952. y = arange(3, dtype=float)
  953. z = x / y
  954. assert_equal(z, [[-1., 1., 1.], [-1., 4., 2.5]])
  955. assert_equal(z.mask, [[1, 0, 0], [1, 0, 0]])
  956. z = x / y[None,:]
  957. assert_equal(z, [[-1., 1., 1.], [-1., 4., 2.5]])
  958. assert_equal(z.mask, [[1, 0, 0], [1, 0, 0]])
  959. y = arange(2, dtype=float)
  960. z = x / y[:, None]
  961. assert_equal(z, [[-1., -1., -1.], [3., 4., 5.]])
  962. assert_equal(z.mask, [[1, 1, 1], [0, 0, 0]])
  963. def test_mixed_arithmetic(self):
  964. # Tests mixed arithmetic.
  965. na = np.array([1])
  966. ma = array([1])
  967. assert_(isinstance(na + ma, MaskedArray))
  968. assert_(isinstance(ma + na, MaskedArray))
  969. def test_limits_arithmetic(self):
  970. tiny = np.finfo(float).tiny
  971. a = array([tiny, 1. / tiny, 0.])
  972. assert_equal(getmaskarray(a / 2), [0, 0, 0])
  973. assert_equal(getmaskarray(2 / a), [1, 0, 1])
  974. def test_masked_singleton_arithmetic(self):
  975. # Tests some scalar arithmetic on MaskedArrays.
  976. # Masked singleton should remain masked no matter what
  977. xm = array(0, mask=1)
  978. assert_((1 / array(0)).mask)
  979. assert_((1 + xm).mask)
  980. assert_((-xm).mask)
  981. assert_(maximum(xm, xm).mask)
  982. assert_(minimum(xm, xm).mask)
  983. def test_masked_singleton_equality(self):
  984. # Tests (in)equality on masked singleton
  985. a = array([1, 2, 3], mask=[1, 1, 0])
  986. assert_((a[0] == 0) is masked)
  987. assert_((a[0] != 0) is masked)
  988. assert_equal((a[-1] == 0), False)
  989. assert_equal((a[-1] != 0), True)
  990. def test_arithmetic_with_masked_singleton(self):
  991. # Checks that there's no collapsing to masked
  992. x = masked_array([1, 2])
  993. y = x * masked
  994. assert_equal(y.shape, x.shape)
  995. assert_equal(y._mask, [True, True])
  996. y = x[0] * masked
  997. assert_(y is masked)
  998. y = x + masked
  999. assert_equal(y.shape, x.shape)
  1000. assert_equal(y._mask, [True, True])
  1001. def test_arithmetic_with_masked_singleton_on_1d_singleton(self):
  1002. # Check that we're not losing the shape of a singleton
  1003. x = masked_array([1, ])
  1004. y = x + masked
  1005. assert_equal(y.shape, x.shape)
  1006. assert_equal(y.mask, [True, ])
  1007. def test_scalar_arithmetic(self):
  1008. x = array(0, mask=0)
  1009. assert_equal(x.filled().ctypes.data, x.ctypes.data)
  1010. # Make sure we don't lose the shape in some circumstances
  1011. xm = array((0, 0)) / 0.
  1012. assert_equal(xm.shape, (2,))
  1013. assert_equal(xm.mask, [1, 1])
  1014. def test_basic_ufuncs(self):
  1015. # Test various functions such as sin, cos.
  1016. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  1017. assert_equal(np.cos(x), cos(xm))
  1018. assert_equal(np.cosh(x), cosh(xm))
  1019. assert_equal(np.sin(x), sin(xm))
  1020. assert_equal(np.sinh(x), sinh(xm))
  1021. assert_equal(np.tan(x), tan(xm))
  1022. assert_equal(np.tanh(x), tanh(xm))
  1023. assert_equal(np.sqrt(abs(x)), sqrt(xm))
  1024. assert_equal(np.log(abs(x)), log(xm))
  1025. assert_equal(np.log10(abs(x)), log10(xm))
  1026. assert_equal(np.exp(x), exp(xm))
  1027. assert_equal(np.arcsin(z), arcsin(zm))
  1028. assert_equal(np.arccos(z), arccos(zm))
  1029. assert_equal(np.arctan(z), arctan(zm))
  1030. assert_equal(np.arctan2(x, y), arctan2(xm, ym))
  1031. assert_equal(np.absolute(x), absolute(xm))
  1032. assert_equal(np.angle(x + 1j*y), angle(xm + 1j*ym))
  1033. assert_equal(np.angle(x + 1j*y, deg=True), angle(xm + 1j*ym, deg=True))
  1034. assert_equal(np.equal(x, y), equal(xm, ym))
  1035. assert_equal(np.not_equal(x, y), not_equal(xm, ym))
  1036. assert_equal(np.less(x, y), less(xm, ym))
  1037. assert_equal(np.greater(x, y), greater(xm, ym))
  1038. assert_equal(np.less_equal(x, y), less_equal(xm, ym))
  1039. assert_equal(np.greater_equal(x, y), greater_equal(xm, ym))
  1040. assert_equal(np.conjugate(x), conjugate(xm))
  1041. def test_count_func(self):
  1042. # Tests count
  1043. assert_equal(1, count(1))
  1044. assert_equal(0, array(1, mask=[1]))
  1045. ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
  1046. res = count(ott)
  1047. assert_(res.dtype.type is np.intp)
  1048. assert_equal(3, res)
  1049. ott = ott.reshape((2, 2))
  1050. res = count(ott)
  1051. assert_(res.dtype.type is np.intp)
  1052. assert_equal(3, res)
  1053. res = count(ott, 0)
  1054. assert_(isinstance(res, ndarray))
  1055. assert_equal([1, 2], res)
  1056. assert_(getmask(res) is nomask)
  1057. ott = array([0., 1., 2., 3.])
  1058. res = count(ott, 0)
  1059. assert_(isinstance(res, ndarray))
  1060. assert_(res.dtype.type is np.intp)
  1061. assert_raises(np.AxisError, ott.count, axis=1)
  1062. def test_count_on_python_builtins(self):
  1063. # Tests count works on python builtins (issue#8019)
  1064. assert_equal(3, count([1,2,3]))
  1065. assert_equal(2, count((1,2)))
  1066. def test_minmax_func(self):
  1067. # Tests minimum and maximum.
  1068. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  1069. # max doesn't work if shaped
  1070. xr = np.ravel(x)
  1071. xmr = ravel(xm)
  1072. # following are true because of careful selection of data
  1073. assert_equal(max(xr), maximum.reduce(xmr))
  1074. assert_equal(min(xr), minimum.reduce(xmr))
  1075. assert_equal(minimum([1, 2, 3], [4, 0, 9]), [1, 0, 3])
  1076. assert_equal(maximum([1, 2, 3], [4, 0, 9]), [4, 2, 9])
  1077. x = arange(5)
  1078. y = arange(5) - 2
  1079. x[3] = masked
  1080. y[0] = masked
  1081. assert_equal(minimum(x, y), where(less(x, y), x, y))
  1082. assert_equal(maximum(x, y), where(greater(x, y), x, y))
  1083. assert_(minimum.reduce(x) == 0)
  1084. assert_(maximum.reduce(x) == 4)
  1085. x = arange(4).reshape(2, 2)
  1086. x[-1, -1] = masked
  1087. assert_equal(maximum.reduce(x, axis=None), 2)
  1088. def test_minimummaximum_func(self):
  1089. a = np.ones((2, 2))
  1090. aminimum = minimum(a, a)
  1091. assert_(isinstance(aminimum, MaskedArray))
  1092. assert_equal(aminimum, np.minimum(a, a))
  1093. aminimum = minimum.outer(a, a)
  1094. assert_(isinstance(aminimum, MaskedArray))
  1095. assert_equal(aminimum, np.minimum.outer(a, a))
  1096. amaximum = maximum(a, a)
  1097. assert_(isinstance(amaximum, MaskedArray))
  1098. assert_equal(amaximum, np.maximum(a, a))
  1099. amaximum = maximum.outer(a, a)
  1100. assert_(isinstance(amaximum, MaskedArray))
  1101. assert_equal(amaximum, np.maximum.outer(a, a))
  1102. def test_minmax_reduce(self):
  1103. # Test np.min/maximum.reduce on array w/ full False mask
  1104. a = array([1, 2, 3], mask=[False, False, False])
  1105. b = np.maximum.reduce(a)
  1106. assert_equal(b, 3)
  1107. def test_minmax_funcs_with_output(self):
  1108. # Tests the min/max functions with explicit outputs
  1109. mask = np.random.rand(12).round()
  1110. xm = array(np.random.uniform(0, 10, 12), mask=mask)
  1111. xm.shape = (3, 4)
  1112. for funcname in ('min', 'max'):
  1113. # Initialize
  1114. npfunc = getattr(np, funcname)
  1115. mafunc = getattr(numpy.ma.core, funcname)
  1116. # Use the np version
  1117. nout = np.empty((4,), dtype=int)
  1118. try:
  1119. result = npfunc(xm, axis=0, out=nout)
  1120. except MaskError:
  1121. pass
  1122. nout = np.empty((4,), dtype=float)
  1123. result = npfunc(xm, axis=0, out=nout)
  1124. assert_(result is nout)
  1125. # Use the ma version
  1126. nout.fill(-999)
  1127. result = mafunc(xm, axis=0, out=nout)
  1128. assert_(result is nout)
  1129. def test_minmax_methods(self):
  1130. # Additional tests on max/min
  1131. (_, _, _, _, _, xm, _, _, _, _) = self.d
  1132. xm.shape = (xm.size,)
  1133. assert_equal(xm.max(), 10)
  1134. assert_(xm[0].max() is masked)
  1135. assert_(xm[0].max(0) is masked)
  1136. assert_(xm[0].max(-1) is masked)
  1137. assert_equal(xm.min(), -10.)
  1138. assert_(xm[0].min() is masked)
  1139. assert_(xm[0].min(0) is masked)
  1140. assert_(xm[0].min(-1) is masked)
  1141. assert_equal(xm.ptp(), 20.)
  1142. assert_(xm[0].ptp() is masked)
  1143. assert_(xm[0].ptp(0) is masked)
  1144. assert_(xm[0].ptp(-1) is masked)
  1145. x = array([1, 2, 3], mask=True)
  1146. assert_(x.min() is masked)
  1147. assert_(x.max() is masked)
  1148. assert_(x.ptp() is masked)
  1149. def test_minmax_dtypes(self):
  1150. # Additional tests on max/min for non-standard float and complex dtypes
  1151. x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
  1152. a10 = 10.
  1153. an10 = -10.0
  1154. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
  1155. xm = masked_array(x, mask=m1)
  1156. xm.set_fill_value(1e+20)
  1157. float_dtypes = [np.half, np.single, np.double,
  1158. np.longdouble, np.cfloat, np.cdouble, np.clongdouble]
  1159. for float_dtype in float_dtypes:
  1160. assert_equal(masked_array(x, mask=m1, dtype=float_dtype).max(),
  1161. float_dtype(a10))
  1162. assert_equal(masked_array(x, mask=m1, dtype=float_dtype).min(),
  1163. float_dtype(an10))
  1164. assert_equal(xm.min(), an10)
  1165. assert_equal(xm.max(), a10)
  1166. # Non-complex type only test
  1167. for float_dtype in float_dtypes[:4]:
  1168. assert_equal(masked_array(x, mask=m1, dtype=float_dtype).max(),
  1169. float_dtype(a10))
  1170. assert_equal(masked_array(x, mask=m1, dtype=float_dtype).min(),
  1171. float_dtype(an10))
  1172. # Complex types only test
  1173. for float_dtype in float_dtypes[-3:]:
  1174. ym = masked_array([1e20+1j, 1e20-2j, 1e20-1j], mask=[0, 1, 0],
  1175. dtype=float_dtype)
  1176. assert_equal(ym.min(), float_dtype(1e20-1j))
  1177. assert_equal(ym.max(), float_dtype(1e20+1j))
  1178. zm = masked_array([np.inf+2j, np.inf+3j, -np.inf-1j], mask=[0, 1, 0],
  1179. dtype=float_dtype)
  1180. assert_equal(zm.min(), float_dtype(-np.inf-1j))
  1181. assert_equal(zm.max(), float_dtype(np.inf+2j))
  1182. cmax = np.inf - 1j * np.finfo(np.float64).max
  1183. assert masked_array([-cmax, 0], mask=[0, 1]).max() == -cmax
  1184. assert masked_array([cmax, 0], mask=[0, 1]).min() == cmax
  1185. def test_addsumprod(self):
  1186. # Tests add, sum, product.
  1187. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  1188. assert_equal(np.add.reduce(x), add.reduce(x))
  1189. assert_equal(np.add.accumulate(x), add.accumulate(x))
  1190. assert_equal(4, sum(array(4), axis=0))
  1191. assert_equal(4, sum(array(4), axis=0))
  1192. assert_equal(np.sum(x, axis=0), sum(x, axis=0))
  1193. assert_equal(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0))
  1194. assert_equal(np.sum(x, 0), sum(x, 0))
  1195. assert_equal(np.product(x, axis=0), product(x, axis=0))
  1196. assert_equal(np.product(x, 0), product(x, 0))
  1197. assert_equal(np.product(filled(xm, 1), axis=0), product(xm, axis=0))
  1198. s = (3, 4)
  1199. x.shape = y.shape = xm.shape = ym.shape = s
  1200. if len(s) > 1:
  1201. assert_equal(np.concatenate((x, y), 1), concatenate((xm, ym), 1))
  1202. assert_equal(np.add.reduce(x, 1), add.reduce(x, 1))
  1203. assert_equal(np.sum(x, 1), sum(x, 1))
  1204. assert_equal(np.product(x, 1), product(x, 1))
  1205. def test_binops_d2D(self):
  1206. # Test binary operations on 2D data
  1207. a = array([[1.], [2.], [3.]], mask=[[False], [True], [True]])
  1208. b = array([[2., 3.], [4., 5.], [6., 7.]])
  1209. test = a * b
  1210. control = array([[2., 3.], [2., 2.], [3., 3.]],
  1211. mask=[[0, 0], [1, 1], [1, 1]])
  1212. assert_equal(test, control)
  1213. assert_equal(test.data, control.data)
  1214. assert_equal(test.mask, control.mask)
  1215. test = b * a
  1216. control = array([[2., 3.], [4., 5.], [6., 7.]],
  1217. mask=[[0, 0], [1, 1], [1, 1]])
  1218. assert_equal(test, control)
  1219. assert_equal(test.data, control.data)
  1220. assert_equal(test.mask, control.mask)
  1221. a = array([[1.], [2.], [3.]])
  1222. b = array([[2., 3.], [4., 5.], [6., 7.]],
  1223. mask=[[0, 0], [0, 0], [0, 1]])
  1224. test = a * b
  1225. control = array([[2, 3], [8, 10], [18, 3]],
  1226. mask=[[0, 0], [0, 0], [0, 1]])
  1227. assert_equal(test, control)
  1228. assert_equal(test.data, control.data)
  1229. assert_equal(test.mask, control.mask)
  1230. test = b * a
  1231. control = array([[2, 3], [8, 10], [18, 7]],
  1232. mask=[[0, 0], [0, 0], [0, 1]])
  1233. assert_equal(test, control)
  1234. assert_equal(test.data, control.data)
  1235. assert_equal(test.mask, control.mask)
  1236. def test_domained_binops_d2D(self):
  1237. # Test domained binary operations on 2D data
  1238. a = array([[1.], [2.], [3.]], mask=[[False], [True], [True]])
  1239. b = array([[2., 3.], [4., 5.], [6., 7.]])
  1240. test = a / b
  1241. control = array([[1. / 2., 1. / 3.], [2., 2.], [3., 3.]],
  1242. mask=[[0, 0], [1, 1], [1, 1]])
  1243. assert_equal(test, control)
  1244. assert_equal(test.data, control.data)
  1245. assert_equal(test.mask, control.mask)
  1246. test = b / a
  1247. control = array([[2. / 1., 3. / 1.], [4., 5.], [6., 7.]],
  1248. mask=[[0, 0], [1, 1], [1, 1]])
  1249. assert_equal(test, control)
  1250. assert_equal(test.data, control.data)
  1251. assert_equal(test.mask, control.mask)
  1252. a = array([[1.], [2.], [3.]])
  1253. b = array([[2., 3.], [4., 5.], [6., 7.]],
  1254. mask=[[0, 0], [0, 0], [0, 1]])
  1255. test = a / b
  1256. control = array([[1. / 2, 1. / 3], [2. / 4, 2. / 5], [3. / 6, 3]],
  1257. mask=[[0, 0], [0, 0], [0, 1]])
  1258. assert_equal(test, control)
  1259. assert_equal(test.data, control.data)
  1260. assert_equal(test.mask, control.mask)
  1261. test = b / a
  1262. control = array([[2 / 1., 3 / 1.], [4 / 2., 5 / 2.], [6 / 3., 7]],
  1263. mask=[[0, 0], [0, 0], [0, 1]])
  1264. assert_equal(test, control)
  1265. assert_equal(test.data, control.data)
  1266. assert_equal(test.mask, control.mask)
  1267. def test_noshrinking(self):
  1268. # Check that we don't shrink a mask when not wanted
  1269. # Binary operations
  1270. a = masked_array([1., 2., 3.], mask=[False, False, False],
  1271. shrink=False)
  1272. b = a + 1
  1273. assert_equal(b.mask, [0, 0, 0])
  1274. # In place binary operation
  1275. a += 1
  1276. assert_equal(a.mask, [0, 0, 0])
  1277. # Domained binary operation
  1278. b = a / 1.
  1279. assert_equal(b.mask, [0, 0, 0])
  1280. # In place binary operation
  1281. a /= 1.
  1282. assert_equal(a.mask, [0, 0, 0])
  1283. def test_ufunc_nomask(self):
  1284. # check the case ufuncs should set the mask to false
  1285. m = np.ma.array([1])
  1286. # check we don't get array([False], dtype=bool)
  1287. assert_equal(np.true_divide(m, 5).mask.shape, ())
  1288. def test_noshink_on_creation(self):
  1289. # Check that the mask is not shrunk on array creation when not wanted
  1290. a = np.ma.masked_values([1., 2.5, 3.1], 1.5, shrink=False)
  1291. assert_equal(a.mask, [0, 0, 0])
  1292. def test_mod(self):
  1293. # Tests mod
  1294. (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
  1295. assert_equal(mod(x, y), mod(xm, ym))
  1296. test = mod(ym, xm)
  1297. assert_equal(test, np.mod(ym, xm))
  1298. assert_equal(test.mask, mask_or(xm.mask, ym.mask))
  1299. test = mod(xm, ym)
  1300. assert_equal(test, np.mod(xm, ym))
  1301. assert_equal(test.mask, mask_or(mask_or(xm.mask, ym.mask), (ym == 0)))
  1302. def test_TakeTransposeInnerOuter(self):
  1303. # Test of take, transpose, inner, outer products
  1304. x = arange(24)
  1305. y = np.arange(24)
  1306. x[5:6] = masked
  1307. x = x.reshape(2, 3, 4)
  1308. y = y.reshape(2, 3, 4)
  1309. assert_equal(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1)))
  1310. assert_equal(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1))
  1311. assert_equal(np.inner(filled(x, 0), filled(y, 0)),
  1312. inner(x, y))
  1313. assert_equal(np.outer(filled(x, 0), filled(y, 0)),
  1314. outer(x, y))
  1315. y = array(['abc', 1, 'def', 2, 3], object)
  1316. y[2] = masked
  1317. t = take(y, [0, 3, 4])
  1318. assert_(t[0] == 'abc')
  1319. assert_(t[1] == 2)
  1320. assert_(t[2] == 3)
  1321. def test_imag_real(self):
  1322. # Check complex
  1323. xx = array([1 + 10j, 20 + 2j], mask=[1, 0])
  1324. assert_equal(xx.imag, [10, 2])
  1325. assert_equal(xx.imag.filled(), [1e+20, 2])
  1326. assert_equal(xx.imag.dtype, xx._data.imag.dtype)
  1327. assert_equal(xx.real, [1, 20])
  1328. assert_equal(xx.real.filled(), [1e+20, 20])
  1329. assert_equal(xx.real.dtype, xx._data.real.dtype)
  1330. def test_methods_with_output(self):
  1331. xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4)
  1332. xm[:, 0] = xm[0] = xm[-1, -1] = masked
  1333. funclist = ('sum', 'prod', 'var', 'std', 'max', 'min', 'ptp', 'mean',)
  1334. for funcname in funclist:
  1335. npfunc = getattr(np, funcname)
  1336. xmmeth = getattr(xm, funcname)
  1337. # A ndarray as explicit input
  1338. output = np.empty(4, dtype=float)
  1339. output.fill(-9999)
  1340. result = npfunc(xm, axis=0, out=output)
  1341. # ... the result should be the given output
  1342. assert_(result is output)
  1343. assert_equal(result, xmmeth(axis=0, out=output))
  1344. output = empty(4, dtype=int)
  1345. result = xmmeth(axis=0, out=output)
  1346. assert_(result is output)
  1347. assert_(output[0] is masked)
  1348. def test_eq_on_structured(self):
  1349. # Test the equality of structured arrays
  1350. ndtype = [('A', int), ('B', int)]
  1351. a = array([(1, 1), (2, 2)], mask=[(0, 1), (0, 0)], dtype=ndtype)
  1352. test = (a == a)
  1353. assert_equal(test.data, [True, True])
  1354. assert_equal(test.mask, [False, False])
  1355. assert_(test.fill_value == True)
  1356. test = (a == a[0])
  1357. assert_equal(test.data, [True, False])
  1358. assert_equal(test.mask, [False, False])
  1359. assert_(test.fill_value == True)
  1360. b = array([(1, 1), (2, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)
  1361. test = (a == b)
  1362. assert_equal(test.data, [False, True])
  1363. assert_equal(test.mask, [True, False])
  1364. assert_(test.fill_value == True)
  1365. test = (a[0] == b)
  1366. assert_equal(test.data, [False, False])
  1367. assert_equal(test.mask, [True, False])
  1368. assert_(test.fill_value == True)
  1369. b = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)
  1370. test = (a == b)
  1371. assert_equal(test.data, [True, True])
  1372. assert_equal(test.mask, [False, False])
  1373. assert_(test.fill_value == True)
  1374. # complicated dtype, 2-dimensional array.
  1375. ndtype = [('A', int), ('B', [('BA', int), ('BB', int)])]
  1376. a = array([[(1, (1, 1)), (2, (2, 2))],
  1377. [(3, (3, 3)), (4, (4, 4))]],
  1378. mask=[[(0, (1, 0)), (0, (0, 1))],
  1379. [(1, (0, 0)), (1, (1, 1))]], dtype=ndtype)
  1380. test = (a[0, 0] == a)
  1381. assert_equal(test.data, [[True, False], [False, False]])
  1382. assert_equal(test.mask, [[False, False], [False, True]])
  1383. assert_(test.fill_value == True)
  1384. def test_ne_on_structured(self):
  1385. # Test the equality of structured arrays
  1386. ndtype = [('A', int), ('B', int)]
  1387. a = array([(1, 1), (2, 2)], mask=[(0, 1), (0, 0)], dtype=ndtype)
  1388. test = (a != a)
  1389. assert_equal(test.data, [False, False])
  1390. assert_equal(test.mask, [False, False])
  1391. assert_(test.fill_value == True)
  1392. test = (a != a[0])
  1393. assert_equal(test.data, [False, True])
  1394. assert_equal(test.mask, [False, False])
  1395. assert_(test.fill_value == True)
  1396. b = array([(1, 1), (2, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)
  1397. test = (a != b)
  1398. assert_equal(test.data, [True, False])
  1399. assert_equal(test.mask, [True, False])
  1400. assert_(test.fill_value == True)
  1401. test = (a[0] != b)
  1402. assert_equal(test.data, [True, True])
  1403. assert_equal(test.mask, [True, False])
  1404. assert_(test.fill_value == True)
  1405. b = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)
  1406. test = (a != b)
  1407. assert_equal(test.data, [False, False])
  1408. assert_equal(test.mask, [False, False])
  1409. assert_(test.fill_value == True)
  1410. # complicated dtype, 2-dimensional array.
  1411. ndtype = [('A', int), ('B', [('BA', int), ('BB', int)])]
  1412. a = array([[(1, (1, 1)), (2, (2, 2))],
  1413. [(3, (3, 3)), (4, (4, 4))]],
  1414. mask=[[(0, (1, 0)), (0, (0, 1))],
  1415. [(1, (0, 0)), (1, (1, 1))]], dtype=ndtype)
  1416. test = (a[0, 0] != a)
  1417. assert_equal(test.data, [[False, True], [True, True]])
  1418. assert_equal(test.mask, [[False, False], [False, True]])
  1419. assert_(test.fill_value == True)
  1420. def test_eq_ne_structured_extra(self):
  1421. # ensure simple examples are symmetric and make sense.
  1422. # from https://github.com/numpy/numpy/pull/8590#discussion_r101126465
  1423. dt = np.dtype('i4,i4')
  1424. for m1 in (mvoid((1, 2), mask=(0, 0), dtype=dt),
  1425. mvoid((1, 2), mask=(0, 1), dtype=dt),
  1426. mvoid((1, 2), mask=(1, 0), dtype=dt),
  1427. mvoid((1, 2), mask=(1, 1), dtype=dt)):
  1428. ma1 = m1.view(MaskedArray)
  1429. r1 = ma1.view('2i4')
  1430. for m2 in (np.array((1, 1), dtype=dt),
  1431. mvoid((1, 1), dtype=dt),
  1432. mvoid((1, 0), mask=(0, 1), dtype=dt),
  1433. mvoid((3, 2), mask=(0, 1), dtype=dt)):
  1434. ma2 = m2.view(MaskedArray)
  1435. r2 = ma2.view('2i4')
  1436. eq_expected = (r1 == r2).all()
  1437. assert_equal(m1 == m2, eq_expected)
  1438. assert_equal(m2 == m1, eq_expected)
  1439. assert_equal(ma1 == m2, eq_expected)
  1440. assert_equal(m1 == ma2, eq_expected)
  1441. assert_equal(ma1 == ma2, eq_expected)
  1442. # Also check it is the same if we do it element by element.
  1443. el_by_el = [m1[name] == m2[name] for name in dt.names]
  1444. assert_equal(array(el_by_el, dtype=bool).all(), eq_expected)
  1445. ne_expected = (r1 != r2).any()
  1446. assert_equal(m1 != m2, ne_expected)
  1447. assert_equal(m2 != m1, ne_expected)
  1448. assert_equal(ma1 != m2, ne_expected)
  1449. assert_equal(m1 != ma2, ne_expected)
  1450. assert_equal(ma1 != ma2, ne_expected)
  1451. el_by_el = [m1[name] != m2[name] for name in dt.names]
  1452. assert_equal(array(el_by_el, dtype=bool).any(), ne_expected)
  1453. @pytest.mark.parametrize('dt', ['S', 'U'])
  1454. @pytest.mark.parametrize('fill', [None, 'A'])
  1455. def test_eq_for_strings(self, dt, fill):
  1456. # Test the equality of structured arrays
  1457. a = array(['a', 'b'], dtype=dt, mask=[0, 1], fill_value=fill)
  1458. test = (a == a)
  1459. assert_equal(test.data, [True, True])
  1460. assert_equal(test.mask, [False, True])
  1461. assert_(test.fill_value == True)
  1462. test = (a == a[0])
  1463. assert_equal(test.data, [True, False])
  1464. assert_equal(test.mask, [False, True])
  1465. assert_(test.fill_value == True)
  1466. b = array(['a', 'b'], dtype=dt, mask=[1, 0], fill_value=fill)
  1467. test = (a == b)
  1468. assert_equal(test.data, [False, False])
  1469. assert_equal(test.mask, [True, True])
  1470. assert_(test.fill_value == True)
  1471. test = (a[0] == b)
  1472. assert_equal(test.data, [False, False])
  1473. assert_equal(test.mask, [True, False])
  1474. assert_(test.fill_value == True)
  1475. test = (b == a[0])
  1476. assert_equal(test.data, [False, False])
  1477. assert_equal(test.mask, [True, False])
  1478. assert_(test.fill_value == True)
  1479. @pytest.mark.parametrize('dt', ['S', 'U'])
  1480. @pytest.mark.parametrize('fill', [None, 'A'])
  1481. def test_ne_for_strings(self, dt, fill):
  1482. # Test the equality of structured arrays
  1483. a = array(['a', 'b'], dtype=dt, mask=[0, 1], fill_value=fill)
  1484. test = (a != a)
  1485. assert_equal(test.data, [False, False])
  1486. assert_equal(test.mask, [False, True])
  1487. assert_(test.fill_value == True)
  1488. test = (a != a[0])
  1489. assert_equal(test.data, [False, True])
  1490. assert_equal(test.mask, [False, True])
  1491. assert_(test.fill_value == True)
  1492. b = array(['a', 'b'], dtype=dt, mask=[1, 0], fill_value=fill)
  1493. test = (a != b)
  1494. assert_equal(test.data, [True, True])
  1495. assert_equal(test.mask, [True, True])
  1496. assert_(test.fill_value == True)
  1497. test = (a[0] != b)
  1498. assert_equal(test.data, [True, True])
  1499. assert_equal(test.mask, [True, False])
  1500. assert_(test.fill_value == True)
  1501. test = (b != a[0])
  1502. assert_equal(test.data, [True, True])
  1503. assert_equal(test.mask, [True, False])
  1504. assert_(test.fill_value == True)
  1505. @pytest.mark.parametrize('dt1', num_dts, ids=num_ids)
  1506. @pytest.mark.parametrize('dt2', num_dts, ids=num_ids)
  1507. @pytest.mark.parametrize('fill', [None, 1])
  1508. def test_eq_for_numeric(self, dt1, dt2, fill):
  1509. # Test the equality of structured arrays
  1510. a = array([0, 1], dtype=dt1, mask=[0, 1], fill_value=fill)
  1511. test = (a == a)
  1512. assert_equal(test.data, [True, True])
  1513. assert_equal(test.mask, [False, True])
  1514. assert_(test.fill_value == True)
  1515. test = (a == a[0])
  1516. assert_equal(test.data, [True, False])
  1517. assert_equal(test.mask, [False, True])
  1518. assert_(test.fill_value == True)
  1519. b = array([0, 1], dtype=dt2, mask=[1, 0], fill_value=fill)
  1520. test = (a == b)
  1521. assert_equal(test.data, [False, False])
  1522. assert_equal(test.mask, [True, True])
  1523. assert_(test.fill_value == True)
  1524. test = (a[0] == b)
  1525. assert_equal(test.data, [False, False])
  1526. assert_equal(test.mask, [True, False])
  1527. assert_(test.fill_value == True)
  1528. test = (b == a[0])
  1529. assert_equal(test.data, [False, False])
  1530. assert_equal(test.mask, [True, False])
  1531. assert_(test.fill_value == True)
  1532. @pytest.mark.parametrize('dt1', num_dts, ids=num_ids)
  1533. @pytest.mark.parametrize('dt2', num_dts, ids=num_ids)
  1534. @pytest.mark.parametrize('fill', [None, 1])
  1535. def test_ne_for_numeric(self, dt1, dt2, fill):
  1536. # Test the equality of structured arrays
  1537. a = array([0, 1], dtype=dt1, mask=[0, 1], fill_value=fill)
  1538. test = (a != a)
  1539. assert_equal(test.data, [False, False])
  1540. assert_equal(test.mask, [False, True])
  1541. assert_(test.fill_value == True)
  1542. test = (a != a[0])
  1543. assert_equal(test.data, [False, True])
  1544. assert_equal(test.mask, [False, True])
  1545. assert_(test.fill_value == True)
  1546. b = array([0, 1], dtype=dt2, mask=[1, 0], fill_value=fill)
  1547. test = (a != b)
  1548. assert_equal(test.data, [True, True])
  1549. assert_equal(test.mask, [True, True])
  1550. assert_(test.fill_value == True)
  1551. test = (a[0] != b)
  1552. assert_equal(test.data, [True, True])
  1553. assert_equal(test.mask, [True, False])
  1554. assert_(test.fill_value == True)
  1555. test = (b != a[0])
  1556. assert_equal(test.data, [True, True])
  1557. assert_equal(test.mask, [True, False])
  1558. assert_(test.fill_value == True)
  1559. @pytest.mark.parametrize('dt1', num_dts, ids=num_ids)
  1560. @pytest.mark.parametrize('dt2', num_dts, ids=num_ids)
  1561. @pytest.mark.parametrize('fill', [None, 1])
  1562. @pytest.mark.parametrize('op',
  1563. [operator.le, operator.lt, operator.ge, operator.gt])
  1564. def test_comparisons_for_numeric(self, op, dt1, dt2, fill):
  1565. # Test the equality of structured arrays
  1566. a = array([0, 1], dtype=dt1, mask=[0, 1], fill_value=fill)
  1567. test = op(a, a)
  1568. assert_equal(test.data, op(a._data, a._data))
  1569. assert_equal(test.mask, [False, True])
  1570. assert_(test.fill_value == True)
  1571. test = op(a, a[0])
  1572. assert_equal(test.data, op(a._data, a._data[0]))
  1573. assert_equal(test.mask, [False, True])
  1574. assert_(test.fill_value == True)
  1575. b = array([0, 1], dtype=dt2, mask=[1, 0], fill_value=fill)
  1576. test = op(a, b)
  1577. assert_equal(test.data, op(a._data, b._data))
  1578. assert_equal(test.mask, [True, True])
  1579. assert_(test.fill_value == True)
  1580. test = op(a[0], b)
  1581. assert_equal(test.data, op(a._data[0], b._data))
  1582. assert_equal(test.mask, [True, False])
  1583. assert_(test.fill_value == True)
  1584. test = op(b, a[0])
  1585. assert_equal(test.data, op(b._data, a._data[0]))
  1586. assert_equal(test.mask, [True, False])
  1587. assert_(test.fill_value == True)
  1588. @pytest.mark.parametrize('op',
  1589. [operator.le, operator.lt, operator.ge, operator.gt])
  1590. @pytest.mark.parametrize('fill', [None, "N/A"])
  1591. def test_comparisons_strings(self, op, fill):
  1592. # See gh-21770, mask propagation is broken for strings (and some other
  1593. # cases) so we explicitly test strings here.
  1594. # In principle only == and != may need special handling...
  1595. ma1 = masked_array(["a", "b", "cde"], mask=[0, 1, 0], fill_value=fill)
  1596. ma2 = masked_array(["cde", "b", "a"], mask=[0, 1, 0], fill_value=fill)
  1597. assert_equal(op(ma1, ma2)._data, op(ma1._data, ma2._data))
  1598. def test_eq_with_None(self):
  1599. # Really, comparisons with None should not be done, but check them
  1600. # anyway. Note that pep8 will flag these tests.
  1601. # Deprecation is in place for arrays, and when it happens this
  1602. # test will fail (and have to be changed accordingly).
  1603. # With partial mask
  1604. with suppress_warnings() as sup:
  1605. sup.filter(FutureWarning, "Comparison to `None`")
  1606. a = array([None, 1], mask=[0, 1])
  1607. assert_equal(a == None, array([True, False], mask=[0, 1]))
  1608. assert_equal(a.data == None, [True, False])
  1609. assert_equal(a != None, array([False, True], mask=[0, 1]))
  1610. # With nomask
  1611. a = array([None, 1], mask=False)
  1612. assert_equal(a == None, [True, False])
  1613. assert_equal(a != None, [False, True])
  1614. # With complete mask
  1615. a = array([None, 2], mask=True)
  1616. assert_equal(a == None, array([False, True], mask=True))
  1617. assert_equal(a != None, array([True, False], mask=True))
  1618. # Fully masked, even comparison to None should return "masked"
  1619. a = masked
  1620. assert_equal(a == None, masked)
  1621. def test_eq_with_scalar(self):
  1622. a = array(1)
  1623. assert_equal(a == 1, True)
  1624. assert_equal(a == 0, False)
  1625. assert_equal(a != 1, False)
  1626. assert_equal(a != 0, True)
  1627. b = array(1, mask=True)
  1628. assert_equal(b == 0, masked)
  1629. assert_equal(b == 1, masked)
  1630. assert_equal(b != 0, masked)
  1631. assert_equal(b != 1, masked)
  1632. def test_eq_different_dimensions(self):
  1633. m1 = array([1, 1], mask=[0, 1])
  1634. # test comparison with both masked and regular arrays.
  1635. for m2 in (array([[0, 1], [1, 2]]),
  1636. np.array([[0, 1], [1, 2]])):
  1637. test = (m1 == m2)
  1638. assert_equal(test.data, [[False, False],
  1639. [True, False]])
  1640. assert_equal(test.mask, [[False, True],
  1641. [False, True]])
  1642. def test_numpyarithmetic(self):
  1643. # Check that the mask is not back-propagated when using numpy functions
  1644. a = masked_array([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1])
  1645. control = masked_array([np.nan, np.nan, 0, np.log(2), -1],
  1646. mask=[1, 1, 0, 0, 1])
  1647. test = log(a)
  1648. assert_equal(test, control)
  1649. assert_equal(test.mask, control.mask)
  1650. assert_equal(a.mask, [0, 0, 0, 0, 1])
  1651. test = np.log(a)
  1652. assert_equal(test, control)
  1653. assert_equal(test.mask, control.mask)
  1654. assert_equal(a.mask, [0, 0, 0, 0, 1])
  1655. class TestMaskedArrayAttributes:
  1656. def test_keepmask(self):
  1657. # Tests the keep mask flag
  1658. x = masked_array([1, 2, 3], mask=[1, 0, 0])
  1659. mx = masked_array(x)
  1660. assert_equal(mx.mask, x.mask)
  1661. mx = masked_array(x, mask=[0, 1, 0], keep_mask=False)
  1662. assert_equal(mx.mask, [0, 1, 0])
  1663. mx = masked_array(x, mask=[0, 1, 0], keep_mask=True)
  1664. assert_equal(mx.mask, [1, 1, 0])
  1665. # We default to true
  1666. mx = masked_array(x, mask=[0, 1, 0])
  1667. assert_equal(mx.mask, [1, 1, 0])
  1668. def test_hardmask(self):
  1669. # Test hard_mask
  1670. d = arange(5)
  1671. n = [0, 0, 0, 1, 1]
  1672. m = make_mask(n)
  1673. xh = array(d, mask=m, hard_mask=True)
  1674. # We need to copy, to avoid updating d in xh !
  1675. xs = array(d, mask=m, hard_mask=False, copy=True)
  1676. xh[[1, 4]] = [10, 40]
  1677. xs[[1, 4]] = [10, 40]
  1678. assert_equal(xh._data, [0, 10, 2, 3, 4])
  1679. assert_equal(xs._data, [0, 10, 2, 3, 40])
  1680. assert_equal(xs.mask, [0, 0, 0, 1, 0])
  1681. assert_(xh._hardmask)
  1682. assert_(not xs._hardmask)
  1683. xh[1:4] = [10, 20, 30]
  1684. xs[1:4] = [10, 20, 30]
  1685. assert_equal(xh._data, [0, 10, 20, 3, 4])
  1686. assert_equal(xs._data, [0, 10, 20, 30, 40])
  1687. assert_equal(xs.mask, nomask)
  1688. xh[0] = masked
  1689. xs[0] = masked
  1690. assert_equal(xh.mask, [1, 0, 0, 1, 1])
  1691. assert_equal(xs.mask, [1, 0, 0, 0, 0])
  1692. xh[:] = 1
  1693. xs[:] = 1
  1694. assert_equal(xh._data, [0, 1, 1, 3, 4])
  1695. assert_equal(xs._data, [1, 1, 1, 1, 1])
  1696. assert_equal(xh.mask, [1, 0, 0, 1, 1])
  1697. assert_equal(xs.mask, nomask)
  1698. # Switch to soft mask
  1699. xh.soften_mask()
  1700. xh[:] = arange(5)
  1701. assert_equal(xh._data, [0, 1, 2, 3, 4])
  1702. assert_equal(xh.mask, nomask)
  1703. # Switch back to hard mask
  1704. xh.harden_mask()
  1705. xh[xh < 3] = masked
  1706. assert_equal(xh._data, [0, 1, 2, 3, 4])
  1707. assert_equal(xh._mask, [1, 1, 1, 0, 0])
  1708. xh[filled(xh > 1, False)] = 5
  1709. assert_equal(xh._data, [0, 1, 2, 5, 5])
  1710. assert_equal(xh._mask, [1, 1, 1, 0, 0])
  1711. xh = array([[1, 2], [3, 4]], mask=[[1, 0], [0, 0]], hard_mask=True)
  1712. xh[0] = 0
  1713. assert_equal(xh._data, [[1, 0], [3, 4]])
  1714. assert_equal(xh._mask, [[1, 0], [0, 0]])
  1715. xh[-1, -1] = 5
  1716. assert_equal(xh._data, [[1, 0], [3, 5]])
  1717. assert_equal(xh._mask, [[1, 0], [0, 0]])
  1718. xh[filled(xh < 5, False)] = 2
  1719. assert_equal(xh._data, [[1, 2], [2, 5]])
  1720. assert_equal(xh._mask, [[1, 0], [0, 0]])
  1721. def test_hardmask_again(self):
  1722. # Another test of hardmask
  1723. d = arange(5)
  1724. n = [0, 0, 0, 1, 1]
  1725. m = make_mask(n)
  1726. xh = array(d, mask=m, hard_mask=True)
  1727. xh[4:5] = 999
  1728. xh[0:1] = 999
  1729. assert_equal(xh._data, [999, 1, 2, 3, 4])
  1730. def test_hardmask_oncemore_yay(self):
  1731. # OK, yet another test of hardmask
  1732. # Make sure that harden_mask/soften_mask//unshare_mask returns self
  1733. a = array([1, 2, 3], mask=[1, 0, 0])
  1734. b = a.harden_mask()
  1735. assert_equal(a, b)
  1736. b[0] = 0
  1737. assert_equal(a, b)
  1738. assert_equal(b, array([1, 2, 3], mask=[1, 0, 0]))
  1739. a = b.soften_mask()
  1740. a[0] = 0
  1741. assert_equal(a, b)
  1742. assert_equal(b, array([0, 2, 3], mask=[0, 0, 0]))
  1743. def test_smallmask(self):
  1744. # Checks the behaviour of _smallmask
  1745. a = arange(10)
  1746. a[1] = masked
  1747. a[1] = 1
  1748. assert_equal(a._mask, nomask)
  1749. a = arange(10)
  1750. a._smallmask = False
  1751. a[1] = masked
  1752. a[1] = 1
  1753. assert_equal(a._mask, zeros(10))
  1754. def test_shrink_mask(self):
  1755. # Tests .shrink_mask()
  1756. a = array([1, 2, 3], mask=[0, 0, 0])
  1757. b = a.shrink_mask()
  1758. assert_equal(a, b)
  1759. assert_equal(a.mask, nomask)
  1760. # Mask cannot be shrunk on structured types, so is a no-op
  1761. a = np.ma.array([(1, 2.0)], [('a', int), ('b', float)])
  1762. b = a.copy()
  1763. a.shrink_mask()
  1764. assert_equal(a.mask, b.mask)
  1765. def test_flat(self):
  1766. # Test that flat can return all types of items [#4585, #4615]
  1767. # test 2-D record array
  1768. # ... on structured array w/ masked records
  1769. x = array([[(1, 1.1, 'one'), (2, 2.2, 'two'), (3, 3.3, 'thr')],
  1770. [(4, 4.4, 'fou'), (5, 5.5, 'fiv'), (6, 6.6, 'six')]],
  1771. dtype=[('a', int), ('b', float), ('c', '|S8')])
  1772. x['a'][0, 1] = masked
  1773. x['b'][1, 0] = masked
  1774. x['c'][0, 2] = masked
  1775. x[-1, -1] = masked
  1776. xflat = x.flat
  1777. assert_equal(xflat[0], x[0, 0])
  1778. assert_equal(xflat[1], x[0, 1])
  1779. assert_equal(xflat[2], x[0, 2])
  1780. assert_equal(xflat[:3], x[0])
  1781. assert_equal(xflat[3], x[1, 0])
  1782. assert_equal(xflat[4], x[1, 1])
  1783. assert_equal(xflat[5], x[1, 2])
  1784. assert_equal(xflat[3:], x[1])
  1785. assert_equal(xflat[-1], x[-1, -1])
  1786. i = 0
  1787. j = 0
  1788. for xf in xflat:
  1789. assert_equal(xf, x[j, i])
  1790. i += 1
  1791. if i >= x.shape[-1]:
  1792. i = 0
  1793. j += 1
  1794. def test_assign_dtype(self):
  1795. # check that the mask's dtype is updated when dtype is changed
  1796. a = np.zeros(4, dtype='f4,i4')
  1797. m = np.ma.array(a)
  1798. m.dtype = np.dtype('f4')
  1799. repr(m) # raises?
  1800. assert_equal(m.dtype, np.dtype('f4'))
  1801. # check that dtype changes that change shape of mask too much
  1802. # are not allowed
  1803. def assign():
  1804. m = np.ma.array(a)
  1805. m.dtype = np.dtype('f8')
  1806. assert_raises(ValueError, assign)
  1807. b = a.view(dtype='f4', type=np.ma.MaskedArray) # raises?
  1808. assert_equal(b.dtype, np.dtype('f4'))
  1809. # check that nomask is preserved
  1810. a = np.zeros(4, dtype='f4')
  1811. m = np.ma.array(a)
  1812. m.dtype = np.dtype('f4,i4')
  1813. assert_equal(m.dtype, np.dtype('f4,i4'))
  1814. assert_equal(m._mask, np.ma.nomask)
  1815. class TestFillingValues:
  1816. def test_check_on_scalar(self):
  1817. # Test _check_fill_value set to valid and invalid values
  1818. _check_fill_value = np.ma.core._check_fill_value
  1819. fval = _check_fill_value(0, int)
  1820. assert_equal(fval, 0)
  1821. fval = _check_fill_value(None, int)
  1822. assert_equal(fval, default_fill_value(0))
  1823. fval = _check_fill_value(0, "|S3")
  1824. assert_equal(fval, b"0")
  1825. fval = _check_fill_value(None, "|S3")
  1826. assert_equal(fval, default_fill_value(b"camelot!"))
  1827. assert_raises(TypeError, _check_fill_value, 1e+20, int)
  1828. assert_raises(TypeError, _check_fill_value, 'stuff', int)
  1829. def test_check_on_fields(self):
  1830. # Tests _check_fill_value with records
  1831. _check_fill_value = np.ma.core._check_fill_value
  1832. ndtype = [('a', int), ('b', float), ('c', "|S3")]
  1833. # A check on a list should return a single record
  1834. fval = _check_fill_value([-999, -12345678.9, "???"], ndtype)
  1835. assert_(isinstance(fval, ndarray))
  1836. assert_equal(fval.item(), [-999, -12345678.9, b"???"])
  1837. # A check on None should output the defaults
  1838. fval = _check_fill_value(None, ndtype)
  1839. assert_(isinstance(fval, ndarray))
  1840. assert_equal(fval.item(), [default_fill_value(0),
  1841. default_fill_value(0.),
  1842. asbytes(default_fill_value("0"))])
  1843. #.....Using a structured type as fill_value should work
  1844. fill_val = np.array((-999, -12345678.9, "???"), dtype=ndtype)
  1845. fval = _check_fill_value(fill_val, ndtype)
  1846. assert_(isinstance(fval, ndarray))
  1847. assert_equal(fval.item(), [-999, -12345678.9, b"???"])
  1848. #.....Using a flexible type w/ a different type shouldn't matter
  1849. # BEHAVIOR in 1.5 and earlier, and 1.13 and later: match structured
  1850. # types by position
  1851. fill_val = np.array((-999, -12345678.9, "???"),
  1852. dtype=[("A", int), ("B", float), ("C", "|S3")])
  1853. fval = _check_fill_value(fill_val, ndtype)
  1854. assert_(isinstance(fval, ndarray))
  1855. assert_equal(fval.item(), [-999, -12345678.9, b"???"])
  1856. #.....Using an object-array shouldn't matter either
  1857. fill_val = np.ndarray(shape=(1,), dtype=object)
  1858. fill_val[0] = (-999, -12345678.9, b"???")
  1859. fval = _check_fill_value(fill_val, object)
  1860. assert_(isinstance(fval, ndarray))
  1861. assert_equal(fval.item(), [-999, -12345678.9, b"???"])
  1862. # NOTE: This test was never run properly as "fill_value" rather than
  1863. # "fill_val" was assigned. Written properly, it fails.
  1864. #fill_val = np.array((-999, -12345678.9, "???"))
  1865. #fval = _check_fill_value(fill_val, ndtype)
  1866. #assert_(isinstance(fval, ndarray))
  1867. #assert_equal(fval.item(), [-999, -12345678.9, b"???"])
  1868. #.....One-field-only flexible type should work as well
  1869. ndtype = [("a", int)]
  1870. fval = _check_fill_value(-999999999, ndtype)
  1871. assert_(isinstance(fval, ndarray))
  1872. assert_equal(fval.item(), (-999999999,))
  1873. def test_fillvalue_conversion(self):
  1874. # Tests the behavior of fill_value during conversion
  1875. # We had a tailored comment to make sure special attributes are
  1876. # properly dealt with
  1877. a = array([b'3', b'4', b'5'])
  1878. a._optinfo.update({'comment':"updated!"})
  1879. b = array(a, dtype=int)
  1880. assert_equal(b._data, [3, 4, 5])
  1881. assert_equal(b.fill_value, default_fill_value(0))
  1882. b = array(a, dtype=float)
  1883. assert_equal(b._data, [3, 4, 5])
  1884. assert_equal(b.fill_value, default_fill_value(0.))
  1885. b = a.astype(int)
  1886. assert_equal(b._data, [3, 4, 5])
  1887. assert_equal(b.fill_value, default_fill_value(0))
  1888. assert_equal(b._optinfo['comment'], "updated!")
  1889. b = a.astype([('a', '|S3')])
  1890. assert_equal(b['a']._data, a._data)
  1891. assert_equal(b['a'].fill_value, a.fill_value)
  1892. def test_default_fill_value(self):
  1893. # check all calling conventions
  1894. f1 = default_fill_value(1.)
  1895. f2 = default_fill_value(np.array(1.))
  1896. f3 = default_fill_value(np.array(1.).dtype)
  1897. assert_equal(f1, f2)
  1898. assert_equal(f1, f3)
  1899. def test_default_fill_value_structured(self):
  1900. fields = array([(1, 1, 1)],
  1901. dtype=[('i', int), ('s', '|S8'), ('f', float)])
  1902. f1 = default_fill_value(fields)
  1903. f2 = default_fill_value(fields.dtype)
  1904. expected = np.array((default_fill_value(0),
  1905. default_fill_value('0'),
  1906. default_fill_value(0.)), dtype=fields.dtype)
  1907. assert_equal(f1, expected)
  1908. assert_equal(f2, expected)
  1909. def test_default_fill_value_void(self):
  1910. dt = np.dtype([('v', 'V7')])
  1911. f = default_fill_value(dt)
  1912. assert_equal(f['v'], np.array(default_fill_value(dt['v']), dt['v']))
  1913. def test_fillvalue(self):
  1914. # Yet more fun with the fill_value
  1915. data = masked_array([1, 2, 3], fill_value=-999)
  1916. series = data[[0, 2, 1]]
  1917. assert_equal(series._fill_value, data._fill_value)
  1918. mtype = [('f', float), ('s', '|S3')]
  1919. x = array([(1, 'a'), (2, 'b'), (pi, 'pi')], dtype=mtype)
  1920. x.fill_value = 999
  1921. assert_equal(x.fill_value.item(), [999., b'999'])
  1922. assert_equal(x['f'].fill_value, 999)
  1923. assert_equal(x['s'].fill_value, b'999')
  1924. x.fill_value = (9, '???')
  1925. assert_equal(x.fill_value.item(), (9, b'???'))
  1926. assert_equal(x['f'].fill_value, 9)
  1927. assert_equal(x['s'].fill_value, b'???')
  1928. x = array([1, 2, 3.1])
  1929. x.fill_value = 999
  1930. assert_equal(np.asarray(x.fill_value).dtype, float)
  1931. assert_equal(x.fill_value, 999.)
  1932. assert_equal(x._fill_value, np.array(999.))
  1933. def test_subarray_fillvalue(self):
  1934. # gh-10483 test multi-field index fill value
  1935. fields = array([(1, 1, 1)],
  1936. dtype=[('i', int), ('s', '|S8'), ('f', float)])
  1937. with suppress_warnings() as sup:
  1938. sup.filter(FutureWarning, "Numpy has detected")
  1939. subfields = fields[['i', 'f']]
  1940. assert_equal(tuple(subfields.fill_value), (999999, 1.e+20))
  1941. # test comparison does not raise:
  1942. subfields[1:] == subfields[:-1]
  1943. def test_fillvalue_exotic_dtype(self):
  1944. # Tests yet more exotic flexible dtypes
  1945. _check_fill_value = np.ma.core._check_fill_value
  1946. ndtype = [('i', int), ('s', '|S8'), ('f', float)]
  1947. control = np.array((default_fill_value(0),
  1948. default_fill_value('0'),
  1949. default_fill_value(0.),),
  1950. dtype=ndtype)
  1951. assert_equal(_check_fill_value(None, ndtype), control)
  1952. # The shape shouldn't matter
  1953. ndtype = [('f0', float, (2, 2))]
  1954. control = np.array((default_fill_value(0.),),
  1955. dtype=[('f0', float)]).astype(ndtype)
  1956. assert_equal(_check_fill_value(None, ndtype), control)
  1957. control = np.array((0,), dtype=[('f0', float)]).astype(ndtype)
  1958. assert_equal(_check_fill_value(0, ndtype), control)
  1959. ndtype = np.dtype("int, (2,3)float, float")
  1960. control = np.array((default_fill_value(0),
  1961. default_fill_value(0.),
  1962. default_fill_value(0.),),
  1963. dtype="int, float, float").astype(ndtype)
  1964. test = _check_fill_value(None, ndtype)
  1965. assert_equal(test, control)
  1966. control = np.array((0, 0, 0), dtype="int, float, float").astype(ndtype)
  1967. assert_equal(_check_fill_value(0, ndtype), control)
  1968. # but when indexing, fill value should become scalar not tuple
  1969. # See issue #6723
  1970. M = masked_array(control)
  1971. assert_equal(M["f1"].fill_value.ndim, 0)
  1972. def test_fillvalue_datetime_timedelta(self):
  1973. # Test default fillvalue for datetime64 and timedelta64 types.
  1974. # See issue #4476, this would return '?' which would cause errors
  1975. # elsewhere
  1976. for timecode in ("as", "fs", "ps", "ns", "us", "ms", "s", "m",
  1977. "h", "D", "W", "M", "Y"):
  1978. control = numpy.datetime64("NaT", timecode)
  1979. test = default_fill_value(numpy.dtype("<M8[" + timecode + "]"))
  1980. np.testing.assert_equal(test, control)
  1981. control = numpy.timedelta64("NaT", timecode)
  1982. test = default_fill_value(numpy.dtype("<m8[" + timecode + "]"))
  1983. np.testing.assert_equal(test, control)
  1984. def test_extremum_fill_value(self):
  1985. # Tests extremum fill values for flexible type.
  1986. a = array([(1, (2, 3)), (4, (5, 6))],
  1987. dtype=[('A', int), ('B', [('BA', int), ('BB', int)])])
  1988. test = a.fill_value
  1989. assert_equal(test.dtype, a.dtype)
  1990. assert_equal(test['A'], default_fill_value(a['A']))
  1991. assert_equal(test['B']['BA'], default_fill_value(a['B']['BA']))
  1992. assert_equal(test['B']['BB'], default_fill_value(a['B']['BB']))
  1993. test = minimum_fill_value(a)
  1994. assert_equal(test.dtype, a.dtype)
  1995. assert_equal(test[0], minimum_fill_value(a['A']))
  1996. assert_equal(test[1][0], minimum_fill_value(a['B']['BA']))
  1997. assert_equal(test[1][1], minimum_fill_value(a['B']['BB']))
  1998. assert_equal(test[1], minimum_fill_value(a['B']))
  1999. test = maximum_fill_value(a)
  2000. assert_equal(test.dtype, a.dtype)
  2001. assert_equal(test[0], maximum_fill_value(a['A']))
  2002. assert_equal(test[1][0], maximum_fill_value(a['B']['BA']))
  2003. assert_equal(test[1][1], maximum_fill_value(a['B']['BB']))
  2004. assert_equal(test[1], maximum_fill_value(a['B']))
  2005. def test_extremum_fill_value_subdtype(self):
  2006. a = array(([2, 3, 4],), dtype=[('value', np.int8, 3)])
  2007. test = minimum_fill_value(a)
  2008. assert_equal(test.dtype, a.dtype)
  2009. assert_equal(test[0], np.full(3, minimum_fill_value(a['value'])))
  2010. test = maximum_fill_value(a)
  2011. assert_equal(test.dtype, a.dtype)
  2012. assert_equal(test[0], np.full(3, maximum_fill_value(a['value'])))
  2013. def test_fillvalue_individual_fields(self):
  2014. # Test setting fill_value on individual fields
  2015. ndtype = [('a', int), ('b', int)]
  2016. # Explicit fill_value
  2017. a = array(list(zip([1, 2, 3], [4, 5, 6])),
  2018. fill_value=(-999, -999), dtype=ndtype)
  2019. aa = a['a']
  2020. aa.set_fill_value(10)
  2021. assert_equal(aa._fill_value, np.array(10))
  2022. assert_equal(tuple(a.fill_value), (10, -999))
  2023. a.fill_value['b'] = -10
  2024. assert_equal(tuple(a.fill_value), (10, -10))
  2025. # Implicit fill_value
  2026. t = array(list(zip([1, 2, 3], [4, 5, 6])), dtype=ndtype)
  2027. tt = t['a']
  2028. tt.set_fill_value(10)
  2029. assert_equal(tt._fill_value, np.array(10))
  2030. assert_equal(tuple(t.fill_value), (10, default_fill_value(0)))
  2031. def test_fillvalue_implicit_structured_array(self):
  2032. # Check that fill_value is always defined for structured arrays
  2033. ndtype = ('b', float)
  2034. adtype = ('a', float)
  2035. a = array([(1.,), (2.,)], mask=[(False,), (False,)],
  2036. fill_value=(np.nan,), dtype=np.dtype([adtype]))
  2037. b = empty(a.shape, dtype=[adtype, ndtype])
  2038. b['a'] = a['a']
  2039. b['a'].set_fill_value(a['a'].fill_value)
  2040. f = b._fill_value[()]
  2041. assert_(np.isnan(f[0]))
  2042. assert_equal(f[-1], default_fill_value(1.))
  2043. def test_fillvalue_as_arguments(self):
  2044. # Test adding a fill_value parameter to empty/ones/zeros
  2045. a = empty(3, fill_value=999.)
  2046. assert_equal(a.fill_value, 999.)
  2047. a = ones(3, fill_value=999., dtype=float)
  2048. assert_equal(a.fill_value, 999.)
  2049. a = zeros(3, fill_value=0., dtype=complex)
  2050. assert_equal(a.fill_value, 0.)
  2051. a = identity(3, fill_value=0., dtype=complex)
  2052. assert_equal(a.fill_value, 0.)
  2053. def test_shape_argument(self):
  2054. # Test that shape can be provides as an argument
  2055. # GH issue 6106
  2056. a = empty(shape=(3, ))
  2057. assert_equal(a.shape, (3, ))
  2058. a = ones(shape=(3, ), dtype=float)
  2059. assert_equal(a.shape, (3, ))
  2060. a = zeros(shape=(3, ), dtype=complex)
  2061. assert_equal(a.shape, (3, ))
  2062. def test_fillvalue_in_view(self):
  2063. # Test the behavior of fill_value in view
  2064. # Create initial masked array
  2065. x = array([1, 2, 3], fill_value=1, dtype=np.int64)
  2066. # Check that fill_value is preserved by default
  2067. y = x.view()
  2068. assert_(y.fill_value == 1)
  2069. # Check that fill_value is preserved if dtype is specified and the
  2070. # dtype is an ndarray sub-class and has a _fill_value attribute
  2071. y = x.view(MaskedArray)
  2072. assert_(y.fill_value == 1)
  2073. # Check that fill_value is preserved if type is specified and the
  2074. # dtype is an ndarray sub-class and has a _fill_value attribute (by
  2075. # default, the first argument is dtype, not type)
  2076. y = x.view(type=MaskedArray)
  2077. assert_(y.fill_value == 1)
  2078. # Check that code does not crash if passed an ndarray sub-class that
  2079. # does not have a _fill_value attribute
  2080. y = x.view(np.ndarray)
  2081. y = x.view(type=np.ndarray)
  2082. # Check that fill_value can be overridden with view
  2083. y = x.view(MaskedArray, fill_value=2)
  2084. assert_(y.fill_value == 2)
  2085. # Check that fill_value can be overridden with view (using type=)
  2086. y = x.view(type=MaskedArray, fill_value=2)
  2087. assert_(y.fill_value == 2)
  2088. # Check that fill_value gets reset if passed a dtype but not a
  2089. # fill_value. This is because even though in some cases one can safely
  2090. # cast the fill_value, e.g. if taking an int64 view of an int32 array,
  2091. # in other cases, this cannot be done (e.g. int32 view of an int64
  2092. # array with a large fill_value).
  2093. y = x.view(dtype=np.int32)
  2094. assert_(y.fill_value == 999999)
  2095. def test_fillvalue_bytes_or_str(self):
  2096. # Test whether fill values work as expected for structured dtypes
  2097. # containing bytes or str. See issue #7259.
  2098. a = empty(shape=(3, ), dtype="(2)3S,(2)3U")
  2099. assert_equal(a["f0"].fill_value, default_fill_value(b"spam"))
  2100. assert_equal(a["f1"].fill_value, default_fill_value("eggs"))
  2101. class TestUfuncs:
  2102. # Test class for the application of ufuncs on MaskedArrays.
  2103. def setup_method(self):
  2104. # Base data definition.
  2105. self.d = (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6),
  2106. array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),)
  2107. self.err_status = np.geterr()
  2108. np.seterr(divide='ignore', invalid='ignore')
  2109. def teardown_method(self):
  2110. np.seterr(**self.err_status)
  2111. def test_testUfuncRegression(self):
  2112. # Tests new ufuncs on MaskedArrays.
  2113. for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
  2114. 'sin', 'cos', 'tan',
  2115. 'arcsin', 'arccos', 'arctan',
  2116. 'sinh', 'cosh', 'tanh',
  2117. 'arcsinh',
  2118. 'arccosh',
  2119. 'arctanh',
  2120. 'absolute', 'fabs', 'negative',
  2121. 'floor', 'ceil',
  2122. 'logical_not',
  2123. 'add', 'subtract', 'multiply',
  2124. 'divide', 'true_divide', 'floor_divide',
  2125. 'remainder', 'fmod', 'hypot', 'arctan2',
  2126. 'equal', 'not_equal', 'less_equal', 'greater_equal',
  2127. 'less', 'greater',
  2128. 'logical_and', 'logical_or', 'logical_xor',
  2129. ]:
  2130. try:
  2131. uf = getattr(umath, f)
  2132. except AttributeError:
  2133. uf = getattr(fromnumeric, f)
  2134. mf = getattr(numpy.ma.core, f)
  2135. args = self.d[:uf.nin]
  2136. ur = uf(*args)
  2137. mr = mf(*args)
  2138. assert_equal(ur.filled(0), mr.filled(0), f)
  2139. assert_mask_equal(ur.mask, mr.mask, err_msg=f)
  2140. def test_reduce(self):
  2141. # Tests reduce on MaskedArrays.
  2142. a = self.d[0]
  2143. assert_(not alltrue(a, axis=0))
  2144. assert_(sometrue(a, axis=0))
  2145. assert_equal(sum(a[:3], axis=0), 0)
  2146. assert_equal(product(a, axis=0), 0)
  2147. assert_equal(add.reduce(a), pi)
  2148. def test_minmax(self):
  2149. # Tests extrema on MaskedArrays.
  2150. a = arange(1, 13).reshape(3, 4)
  2151. amask = masked_where(a < 5, a)
  2152. assert_equal(amask.max(), a.max())
  2153. assert_equal(amask.min(), 5)
  2154. assert_equal(amask.max(0), a.max(0))
  2155. assert_equal(amask.min(0), [5, 6, 7, 8])
  2156. assert_(amask.max(1)[0].mask)
  2157. assert_(amask.min(1)[0].mask)
  2158. def test_ndarray_mask(self):
  2159. # Check that the mask of the result is a ndarray (not a MaskedArray...)
  2160. a = masked_array([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1])
  2161. test = np.sqrt(a)
  2162. control = masked_array([-1, 0, 1, np.sqrt(2), -1],
  2163. mask=[1, 0, 0, 0, 1])
  2164. assert_equal(test, control)
  2165. assert_equal(test.mask, control.mask)
  2166. assert_(not isinstance(test.mask, MaskedArray))
  2167. def test_treatment_of_NotImplemented(self):
  2168. # Check that NotImplemented is returned at appropriate places
  2169. a = masked_array([1., 2.], mask=[1, 0])
  2170. assert_raises(TypeError, operator.mul, a, "abc")
  2171. assert_raises(TypeError, operator.truediv, a, "abc")
  2172. class MyClass:
  2173. __array_priority__ = a.__array_priority__ + 1
  2174. def __mul__(self, other):
  2175. return "My mul"
  2176. def __rmul__(self, other):
  2177. return "My rmul"
  2178. me = MyClass()
  2179. assert_(me * a == "My mul")
  2180. assert_(a * me == "My rmul")
  2181. # and that __array_priority__ is respected
  2182. class MyClass2:
  2183. __array_priority__ = 100
  2184. def __mul__(self, other):
  2185. return "Me2mul"
  2186. def __rmul__(self, other):
  2187. return "Me2rmul"
  2188. def __rdiv__(self, other):
  2189. return "Me2rdiv"
  2190. __rtruediv__ = __rdiv__
  2191. me_too = MyClass2()
  2192. assert_(a.__mul__(me_too) is NotImplemented)
  2193. assert_(all(multiply.outer(a, me_too) == "Me2rmul"))
  2194. assert_(a.__truediv__(me_too) is NotImplemented)
  2195. assert_(me_too * a == "Me2mul")
  2196. assert_(a * me_too == "Me2rmul")
  2197. assert_(a / me_too == "Me2rdiv")
  2198. def test_no_masked_nan_warnings(self):
  2199. # check that a nan in masked position does not
  2200. # cause ufunc warnings
  2201. m = np.ma.array([0.5, np.nan], mask=[0,1])
  2202. with warnings.catch_warnings():
  2203. warnings.filterwarnings("error")
  2204. # test unary and binary ufuncs
  2205. exp(m)
  2206. add(m, 1)
  2207. m > 0
  2208. # test different unary domains
  2209. sqrt(m)
  2210. log(m)
  2211. tan(m)
  2212. arcsin(m)
  2213. arccos(m)
  2214. arccosh(m)
  2215. # test binary domains
  2216. divide(m, 2)
  2217. # also check that allclose uses ma ufuncs, to avoid warning
  2218. allclose(m, 0.5)
  2219. class TestMaskedArrayInPlaceArithmetic:
  2220. # Test MaskedArray Arithmetic
  2221. def setup_method(self):
  2222. x = arange(10)
  2223. y = arange(10)
  2224. xm = arange(10)
  2225. xm[2] = masked
  2226. self.intdata = (x, y, xm)
  2227. self.floatdata = (x.astype(float), y.astype(float), xm.astype(float))
  2228. self.othertypes = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
  2229. self.othertypes = [np.dtype(_).type for _ in self.othertypes]
  2230. self.uint8data = (
  2231. x.astype(np.uint8),
  2232. y.astype(np.uint8),
  2233. xm.astype(np.uint8)
  2234. )
  2235. def test_inplace_addition_scalar(self):
  2236. # Test of inplace additions
  2237. (x, y, xm) = self.intdata
  2238. xm[2] = masked
  2239. x += 1
  2240. assert_equal(x, y + 1)
  2241. xm += 1
  2242. assert_equal(xm, y + 1)
  2243. (x, _, xm) = self.floatdata
  2244. id1 = x.data.ctypes.data
  2245. x += 1.
  2246. assert_(id1 == x.data.ctypes.data)
  2247. assert_equal(x, y + 1.)
  2248. def test_inplace_addition_array(self):
  2249. # Test of inplace additions
  2250. (x, y, xm) = self.intdata
  2251. m = xm.mask
  2252. a = arange(10, dtype=np.int16)
  2253. a[-1] = masked
  2254. x += a
  2255. xm += a
  2256. assert_equal(x, y + a)
  2257. assert_equal(xm, y + a)
  2258. assert_equal(xm.mask, mask_or(m, a.mask))
  2259. def test_inplace_subtraction_scalar(self):
  2260. # Test of inplace subtractions
  2261. (x, y, xm) = self.intdata
  2262. x -= 1
  2263. assert_equal(x, y - 1)
  2264. xm -= 1
  2265. assert_equal(xm, y - 1)
  2266. def test_inplace_subtraction_array(self):
  2267. # Test of inplace subtractions
  2268. (x, y, xm) = self.floatdata
  2269. m = xm.mask
  2270. a = arange(10, dtype=float)
  2271. a[-1] = masked
  2272. x -= a
  2273. xm -= a
  2274. assert_equal(x, y - a)
  2275. assert_equal(xm, y - a)
  2276. assert_equal(xm.mask, mask_or(m, a.mask))
  2277. def test_inplace_multiplication_scalar(self):
  2278. # Test of inplace multiplication
  2279. (x, y, xm) = self.floatdata
  2280. x *= 2.0
  2281. assert_equal(x, y * 2)
  2282. xm *= 2.0
  2283. assert_equal(xm, y * 2)
  2284. def test_inplace_multiplication_array(self):
  2285. # Test of inplace multiplication
  2286. (x, y, xm) = self.floatdata
  2287. m = xm.mask
  2288. a = arange(10, dtype=float)
  2289. a[-1] = masked
  2290. x *= a
  2291. xm *= a
  2292. assert_equal(x, y * a)
  2293. assert_equal(xm, y * a)
  2294. assert_equal(xm.mask, mask_or(m, a.mask))
  2295. def test_inplace_division_scalar_int(self):
  2296. # Test of inplace division
  2297. (x, y, xm) = self.intdata
  2298. x = arange(10) * 2
  2299. xm = arange(10) * 2
  2300. xm[2] = masked
  2301. x //= 2
  2302. assert_equal(x, y)
  2303. xm //= 2
  2304. assert_equal(xm, y)
  2305. def test_inplace_division_scalar_float(self):
  2306. # Test of inplace division
  2307. (x, y, xm) = self.floatdata
  2308. x /= 2.0
  2309. assert_equal(x, y / 2.0)
  2310. xm /= arange(10)
  2311. assert_equal(xm, ones((10,)))
  2312. def test_inplace_division_array_float(self):
  2313. # Test of inplace division
  2314. (x, y, xm) = self.floatdata
  2315. m = xm.mask
  2316. a = arange(10, dtype=float)
  2317. a[-1] = masked
  2318. x /= a
  2319. xm /= a
  2320. assert_equal(x, y / a)
  2321. assert_equal(xm, y / a)
  2322. assert_equal(xm.mask, mask_or(mask_or(m, a.mask), (a == 0)))
  2323. def test_inplace_division_misc(self):
  2324. x = [1., 1., 1., -2., pi / 2., 4., 5., -10., 10., 1., 2., 3.]
  2325. y = [5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]
  2326. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
  2327. m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
  2328. xm = masked_array(x, mask=m1)
  2329. ym = masked_array(y, mask=m2)
  2330. z = xm / ym
  2331. assert_equal(z._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1])
  2332. assert_equal(z._data,
  2333. [1., 1., 1., -1., -pi / 2., 4., 5., 1., 1., 1., 2., 3.])
  2334. xm = xm.copy()
  2335. xm /= ym
  2336. assert_equal(xm._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1])
  2337. assert_equal(z._data,
  2338. [1., 1., 1., -1., -pi / 2., 4., 5., 1., 1., 1., 2., 3.])
  2339. def test_datafriendly_add(self):
  2340. # Test keeping data w/ (inplace) addition
  2341. x = array([1, 2, 3], mask=[0, 0, 1])
  2342. # Test add w/ scalar
  2343. xx = x + 1
  2344. assert_equal(xx.data, [2, 3, 3])
  2345. assert_equal(xx.mask, [0, 0, 1])
  2346. # Test iadd w/ scalar
  2347. x += 1
  2348. assert_equal(x.data, [2, 3, 3])
  2349. assert_equal(x.mask, [0, 0, 1])
  2350. # Test add w/ array
  2351. x = array([1, 2, 3], mask=[0, 0, 1])
  2352. xx = x + array([1, 2, 3], mask=[1, 0, 0])
  2353. assert_equal(xx.data, [1, 4, 3])
  2354. assert_equal(xx.mask, [1, 0, 1])
  2355. # Test iadd w/ array
  2356. x = array([1, 2, 3], mask=[0, 0, 1])
  2357. x += array([1, 2, 3], mask=[1, 0, 0])
  2358. assert_equal(x.data, [1, 4, 3])
  2359. assert_equal(x.mask, [1, 0, 1])
  2360. def test_datafriendly_sub(self):
  2361. # Test keeping data w/ (inplace) subtraction
  2362. # Test sub w/ scalar
  2363. x = array([1, 2, 3], mask=[0, 0, 1])
  2364. xx = x - 1
  2365. assert_equal(xx.data, [0, 1, 3])
  2366. assert_equal(xx.mask, [0, 0, 1])
  2367. # Test isub w/ scalar
  2368. x = array([1, 2, 3], mask=[0, 0, 1])
  2369. x -= 1
  2370. assert_equal(x.data, [0, 1, 3])
  2371. assert_equal(x.mask, [0, 0, 1])
  2372. # Test sub w/ array
  2373. x = array([1, 2, 3], mask=[0, 0, 1])
  2374. xx = x - array([1, 2, 3], mask=[1, 0, 0])
  2375. assert_equal(xx.data, [1, 0, 3])
  2376. assert_equal(xx.mask, [1, 0, 1])
  2377. # Test isub w/ array
  2378. x = array([1, 2, 3], mask=[0, 0, 1])
  2379. x -= array([1, 2, 3], mask=[1, 0, 0])
  2380. assert_equal(x.data, [1, 0, 3])
  2381. assert_equal(x.mask, [1, 0, 1])
  2382. def test_datafriendly_mul(self):
  2383. # Test keeping data w/ (inplace) multiplication
  2384. # Test mul w/ scalar
  2385. x = array([1, 2, 3], mask=[0, 0, 1])
  2386. xx = x * 2
  2387. assert_equal(xx.data, [2, 4, 3])
  2388. assert_equal(xx.mask, [0, 0, 1])
  2389. # Test imul w/ scalar
  2390. x = array([1, 2, 3], mask=[0, 0, 1])
  2391. x *= 2
  2392. assert_equal(x.data, [2, 4, 3])
  2393. assert_equal(x.mask, [0, 0, 1])
  2394. # Test mul w/ array
  2395. x = array([1, 2, 3], mask=[0, 0, 1])
  2396. xx = x * array([10, 20, 30], mask=[1, 0, 0])
  2397. assert_equal(xx.data, [1, 40, 3])
  2398. assert_equal(xx.mask, [1, 0, 1])
  2399. # Test imul w/ array
  2400. x = array([1, 2, 3], mask=[0, 0, 1])
  2401. x *= array([10, 20, 30], mask=[1, 0, 0])
  2402. assert_equal(x.data, [1, 40, 3])
  2403. assert_equal(x.mask, [1, 0, 1])
  2404. def test_datafriendly_div(self):
  2405. # Test keeping data w/ (inplace) division
  2406. # Test div on scalar
  2407. x = array([1, 2, 3], mask=[0, 0, 1])
  2408. xx = x / 2.
  2409. assert_equal(xx.data, [1 / 2., 2 / 2., 3])
  2410. assert_equal(xx.mask, [0, 0, 1])
  2411. # Test idiv on scalar
  2412. x = array([1., 2., 3.], mask=[0, 0, 1])
  2413. x /= 2.
  2414. assert_equal(x.data, [1 / 2., 2 / 2., 3])
  2415. assert_equal(x.mask, [0, 0, 1])
  2416. # Test div on array
  2417. x = array([1., 2., 3.], mask=[0, 0, 1])
  2418. xx = x / array([10., 20., 30.], mask=[1, 0, 0])
  2419. assert_equal(xx.data, [1., 2. / 20., 3.])
  2420. assert_equal(xx.mask, [1, 0, 1])
  2421. # Test idiv on array
  2422. x = array([1., 2., 3.], mask=[0, 0, 1])
  2423. x /= array([10., 20., 30.], mask=[1, 0, 0])
  2424. assert_equal(x.data, [1., 2 / 20., 3.])
  2425. assert_equal(x.mask, [1, 0, 1])
  2426. def test_datafriendly_pow(self):
  2427. # Test keeping data w/ (inplace) power
  2428. # Test pow on scalar
  2429. x = array([1., 2., 3.], mask=[0, 0, 1])
  2430. xx = x ** 2.5
  2431. assert_equal(xx.data, [1., 2. ** 2.5, 3.])
  2432. assert_equal(xx.mask, [0, 0, 1])
  2433. # Test ipow on scalar
  2434. x **= 2.5
  2435. assert_equal(x.data, [1., 2. ** 2.5, 3])
  2436. assert_equal(x.mask, [0, 0, 1])
  2437. def test_datafriendly_add_arrays(self):
  2438. a = array([[1, 1], [3, 3]])
  2439. b = array([1, 1], mask=[0, 0])
  2440. a += b
  2441. assert_equal(a, [[2, 2], [4, 4]])
  2442. if a.mask is not nomask:
  2443. assert_equal(a.mask, [[0, 0], [0, 0]])
  2444. a = array([[1, 1], [3, 3]])
  2445. b = array([1, 1], mask=[0, 1])
  2446. a += b
  2447. assert_equal(a, [[2, 2], [4, 4]])
  2448. assert_equal(a.mask, [[0, 1], [0, 1]])
  2449. def test_datafriendly_sub_arrays(self):
  2450. a = array([[1, 1], [3, 3]])
  2451. b = array([1, 1], mask=[0, 0])
  2452. a -= b
  2453. assert_equal(a, [[0, 0], [2, 2]])
  2454. if a.mask is not nomask:
  2455. assert_equal(a.mask, [[0, 0], [0, 0]])
  2456. a = array([[1, 1], [3, 3]])
  2457. b = array([1, 1], mask=[0, 1])
  2458. a -= b
  2459. assert_equal(a, [[0, 0], [2, 2]])
  2460. assert_equal(a.mask, [[0, 1], [0, 1]])
  2461. def test_datafriendly_mul_arrays(self):
  2462. a = array([[1, 1], [3, 3]])
  2463. b = array([1, 1], mask=[0, 0])
  2464. a *= b
  2465. assert_equal(a, [[1, 1], [3, 3]])
  2466. if a.mask is not nomask:
  2467. assert_equal(a.mask, [[0, 0], [0, 0]])
  2468. a = array([[1, 1], [3, 3]])
  2469. b = array([1, 1], mask=[0, 1])
  2470. a *= b
  2471. assert_equal(a, [[1, 1], [3, 3]])
  2472. assert_equal(a.mask, [[0, 1], [0, 1]])
  2473. def test_inplace_addition_scalar_type(self):
  2474. # Test of inplace additions
  2475. for t in self.othertypes:
  2476. with warnings.catch_warnings():
  2477. warnings.filterwarnings("error")
  2478. (x, y, xm) = (_.astype(t) for _ in self.uint8data)
  2479. xm[2] = masked
  2480. x += t(1)
  2481. assert_equal(x, y + t(1))
  2482. xm += t(1)
  2483. assert_equal(xm, y + t(1))
  2484. def test_inplace_addition_array_type(self):
  2485. # Test of inplace additions
  2486. for t in self.othertypes:
  2487. with warnings.catch_warnings():
  2488. warnings.filterwarnings("error")
  2489. (x, y, xm) = (_.astype(t) for _ in self.uint8data)
  2490. m = xm.mask
  2491. a = arange(10, dtype=t)
  2492. a[-1] = masked
  2493. x += a
  2494. xm += a
  2495. assert_equal(x, y + a)
  2496. assert_equal(xm, y + a)
  2497. assert_equal(xm.mask, mask_or(m, a.mask))
  2498. def test_inplace_subtraction_scalar_type(self):
  2499. # Test of inplace subtractions
  2500. for t in self.othertypes:
  2501. with warnings.catch_warnings():
  2502. warnings.filterwarnings("error")
  2503. (x, y, xm) = (_.astype(t) for _ in self.uint8data)
  2504. x -= t(1)
  2505. assert_equal(x, y - t(1))
  2506. xm -= t(1)
  2507. assert_equal(xm, y - t(1))
  2508. def test_inplace_subtraction_array_type(self):
  2509. # Test of inplace subtractions
  2510. for t in self.othertypes:
  2511. with warnings.catch_warnings():
  2512. warnings.filterwarnings("error")
  2513. (x, y, xm) = (_.astype(t) for _ in self.uint8data)
  2514. m = xm.mask
  2515. a = arange(10, dtype=t)
  2516. a[-1] = masked
  2517. x -= a
  2518. xm -= a
  2519. assert_equal(x, y - a)
  2520. assert_equal(xm, y - a)
  2521. assert_equal(xm.mask, mask_or(m, a.mask))
  2522. def test_inplace_multiplication_scalar_type(self):
  2523. # Test of inplace multiplication
  2524. for t in self.othertypes:
  2525. with warnings.catch_warnings():
  2526. warnings.filterwarnings("error")
  2527. (x, y, xm) = (_.astype(t) for _ in self.uint8data)
  2528. x *= t(2)
  2529. assert_equal(x, y * t(2))
  2530. xm *= t(2)
  2531. assert_equal(xm, y * t(2))
  2532. def test_inplace_multiplication_array_type(self):
  2533. # Test of inplace multiplication
  2534. for t in self.othertypes:
  2535. with warnings.catch_warnings():
  2536. warnings.filterwarnings("error")
  2537. (x, y, xm) = (_.astype(t) for _ in self.uint8data)
  2538. m = xm.mask
  2539. a = arange(10, dtype=t)
  2540. a[-1] = masked
  2541. x *= a
  2542. xm *= a
  2543. assert_equal(x, y * a)
  2544. assert_equal(xm, y * a)
  2545. assert_equal(xm.mask, mask_or(m, a.mask))
  2546. def test_inplace_floor_division_scalar_type(self):
  2547. # Test of inplace division
  2548. # Check for TypeError in case of unsupported types
  2549. unsupported = {np.dtype(t).type for t in np.typecodes["Complex"]}
  2550. for t in self.othertypes:
  2551. with warnings.catch_warnings():
  2552. warnings.filterwarnings("error")
  2553. (x, y, xm) = (_.astype(t) for _ in self.uint8data)
  2554. x = arange(10, dtype=t) * t(2)
  2555. xm = arange(10, dtype=t) * t(2)
  2556. xm[2] = masked
  2557. try:
  2558. x //= t(2)
  2559. xm //= t(2)
  2560. assert_equal(x, y)
  2561. assert_equal(xm, y)
  2562. except TypeError:
  2563. msg = f"Supported type {t} throwing TypeError"
  2564. assert t in unsupported, msg
  2565. def test_inplace_floor_division_array_type(self):
  2566. # Test of inplace division
  2567. # Check for TypeError in case of unsupported types
  2568. unsupported = {np.dtype(t).type for t in np.typecodes["Complex"]}
  2569. for t in self.othertypes:
  2570. with warnings.catch_warnings():
  2571. warnings.filterwarnings("error")
  2572. (x, y, xm) = (_.astype(t) for _ in self.uint8data)
  2573. m = xm.mask
  2574. a = arange(10, dtype=t)
  2575. a[-1] = masked
  2576. try:
  2577. x //= a
  2578. xm //= a
  2579. assert_equal(x, y // a)
  2580. assert_equal(xm, y // a)
  2581. assert_equal(
  2582. xm.mask,
  2583. mask_or(mask_or(m, a.mask), (a == t(0)))
  2584. )
  2585. except TypeError:
  2586. msg = f"Supported type {t} throwing TypeError"
  2587. assert t in unsupported, msg
  2588. def test_inplace_division_scalar_type(self):
  2589. # Test of inplace division
  2590. for t in self.othertypes:
  2591. with suppress_warnings() as sup:
  2592. sup.record(UserWarning)
  2593. (x, y, xm) = (_.astype(t) for _ in self.uint8data)
  2594. x = arange(10, dtype=t) * t(2)
  2595. xm = arange(10, dtype=t) * t(2)
  2596. xm[2] = masked
  2597. # May get a DeprecationWarning or a TypeError.
  2598. #
  2599. # This is a consequence of the fact that this is true divide
  2600. # and will require casting to float for calculation and
  2601. # casting back to the original type. This will only be raised
  2602. # with integers. Whether it is an error or warning is only
  2603. # dependent on how stringent the casting rules are.
  2604. #
  2605. # Will handle the same way.
  2606. try:
  2607. x /= t(2)
  2608. assert_equal(x, y)
  2609. except (DeprecationWarning, TypeError) as e:
  2610. warnings.warn(str(e), stacklevel=1)
  2611. try:
  2612. xm /= t(2)
  2613. assert_equal(xm, y)
  2614. except (DeprecationWarning, TypeError) as e:
  2615. warnings.warn(str(e), stacklevel=1)
  2616. if issubclass(t, np.integer):
  2617. assert_equal(len(sup.log), 2, f'Failed on type={t}.')
  2618. else:
  2619. assert_equal(len(sup.log), 0, f'Failed on type={t}.')
  2620. def test_inplace_division_array_type(self):
  2621. # Test of inplace division
  2622. for t in self.othertypes:
  2623. with suppress_warnings() as sup:
  2624. sup.record(UserWarning)
  2625. (x, y, xm) = (_.astype(t) for _ in self.uint8data)
  2626. m = xm.mask
  2627. a = arange(10, dtype=t)
  2628. a[-1] = masked
  2629. # May get a DeprecationWarning or a TypeError.
  2630. #
  2631. # This is a consequence of the fact that this is true divide
  2632. # and will require casting to float for calculation and
  2633. # casting back to the original type. This will only be raised
  2634. # with integers. Whether it is an error or warning is only
  2635. # dependent on how stringent the casting rules are.
  2636. #
  2637. # Will handle the same way.
  2638. try:
  2639. x /= a
  2640. assert_equal(x, y / a)
  2641. except (DeprecationWarning, TypeError) as e:
  2642. warnings.warn(str(e), stacklevel=1)
  2643. try:
  2644. xm /= a
  2645. assert_equal(xm, y / a)
  2646. assert_equal(
  2647. xm.mask,
  2648. mask_or(mask_or(m, a.mask), (a == t(0)))
  2649. )
  2650. except (DeprecationWarning, TypeError) as e:
  2651. warnings.warn(str(e), stacklevel=1)
  2652. if issubclass(t, np.integer):
  2653. assert_equal(len(sup.log), 2, f'Failed on type={t}.')
  2654. else:
  2655. assert_equal(len(sup.log), 0, f'Failed on type={t}.')
  2656. def test_inplace_pow_type(self):
  2657. # Test keeping data w/ (inplace) power
  2658. for t in self.othertypes:
  2659. with warnings.catch_warnings():
  2660. warnings.filterwarnings("error")
  2661. # Test pow on scalar
  2662. x = array([1, 2, 3], mask=[0, 0, 1], dtype=t)
  2663. xx = x ** t(2)
  2664. xx_r = array([1, 2 ** 2, 3], mask=[0, 0, 1], dtype=t)
  2665. assert_equal(xx.data, xx_r.data)
  2666. assert_equal(xx.mask, xx_r.mask)
  2667. # Test ipow on scalar
  2668. x **= t(2)
  2669. assert_equal(x.data, xx_r.data)
  2670. assert_equal(x.mask, xx_r.mask)
  2671. class TestMaskedArrayMethods:
  2672. # Test class for miscellaneous MaskedArrays methods.
  2673. def setup_method(self):
  2674. # Base data definition.
  2675. x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
  2676. 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
  2677. 3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
  2678. 6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
  2679. 7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
  2680. 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
  2681. X = x.reshape(6, 6)
  2682. XX = x.reshape(3, 2, 2, 3)
  2683. m = np.array([0, 1, 0, 1, 0, 0,
  2684. 1, 0, 1, 1, 0, 1,
  2685. 0, 0, 0, 1, 0, 1,
  2686. 0, 0, 0, 1, 1, 1,
  2687. 1, 0, 0, 1, 0, 0,
  2688. 0, 0, 1, 0, 1, 0])
  2689. mx = array(data=x, mask=m)
  2690. mX = array(data=X, mask=m.reshape(X.shape))
  2691. mXX = array(data=XX, mask=m.reshape(XX.shape))
  2692. m2 = np.array([1, 1, 0, 1, 0, 0,
  2693. 1, 1, 1, 1, 0, 1,
  2694. 0, 0, 1, 1, 0, 1,
  2695. 0, 0, 0, 1, 1, 1,
  2696. 1, 0, 0, 1, 1, 0,
  2697. 0, 0, 1, 0, 1, 1])
  2698. m2x = array(data=x, mask=m2)
  2699. m2X = array(data=X, mask=m2.reshape(X.shape))
  2700. m2XX = array(data=XX, mask=m2.reshape(XX.shape))
  2701. self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX)
  2702. def test_generic_methods(self):
  2703. # Tests some MaskedArray methods.
  2704. a = array([1, 3, 2])
  2705. assert_equal(a.any(), a._data.any())
  2706. assert_equal(a.all(), a._data.all())
  2707. assert_equal(a.argmax(), a._data.argmax())
  2708. assert_equal(a.argmin(), a._data.argmin())
  2709. assert_equal(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))
  2710. assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))
  2711. assert_equal(a.conj(), a._data.conj())
  2712. assert_equal(a.conjugate(), a._data.conjugate())
  2713. m = array([[1, 2], [3, 4]])
  2714. assert_equal(m.diagonal(), m._data.diagonal())
  2715. assert_equal(a.sum(), a._data.sum())
  2716. assert_equal(a.take([1, 2]), a._data.take([1, 2]))
  2717. assert_equal(m.transpose(), m._data.transpose())
  2718. def test_allclose(self):
  2719. # Tests allclose on arrays
  2720. a = np.random.rand(10)
  2721. b = a + np.random.rand(10) * 1e-8
  2722. assert_(allclose(a, b))
  2723. # Test allclose w/ infs
  2724. a[0] = np.inf
  2725. assert_(not allclose(a, b))
  2726. b[0] = np.inf
  2727. assert_(allclose(a, b))
  2728. # Test allclose w/ masked
  2729. a = masked_array(a)
  2730. a[-1] = masked
  2731. assert_(allclose(a, b, masked_equal=True))
  2732. assert_(not allclose(a, b, masked_equal=False))
  2733. # Test comparison w/ scalar
  2734. a *= 1e-8
  2735. a[0] = 0
  2736. assert_(allclose(a, 0, masked_equal=True))
  2737. # Test that the function works for MIN_INT integer typed arrays
  2738. a = masked_array([np.iinfo(np.int_).min], dtype=np.int_)
  2739. assert_(allclose(a, a))
  2740. def test_allclose_timedelta(self):
  2741. # Allclose currently works for timedelta64 as long as `atol` is
  2742. # an integer or also a timedelta64
  2743. a = np.array([[1, 2, 3, 4]], dtype="m8[ns]")
  2744. assert allclose(a, a, atol=0)
  2745. assert allclose(a, a, atol=np.timedelta64(1, "ns"))
  2746. def test_allany(self):
  2747. # Checks the any/all methods/functions.
  2748. x = np.array([[0.13, 0.26, 0.90],
  2749. [0.28, 0.33, 0.63],
  2750. [0.31, 0.87, 0.70]])
  2751. m = np.array([[True, False, False],
  2752. [False, False, False],
  2753. [True, True, False]], dtype=np.bool_)
  2754. mx = masked_array(x, mask=m)
  2755. mxbig = (mx > 0.5)
  2756. mxsmall = (mx < 0.5)
  2757. assert_(not mxbig.all())
  2758. assert_(mxbig.any())
  2759. assert_equal(mxbig.all(0), [False, False, True])
  2760. assert_equal(mxbig.all(1), [False, False, True])
  2761. assert_equal(mxbig.any(0), [False, False, True])
  2762. assert_equal(mxbig.any(1), [True, True, True])
  2763. assert_(not mxsmall.all())
  2764. assert_(mxsmall.any())
  2765. assert_equal(mxsmall.all(0), [True, True, False])
  2766. assert_equal(mxsmall.all(1), [False, False, False])
  2767. assert_equal(mxsmall.any(0), [True, True, False])
  2768. assert_equal(mxsmall.any(1), [True, True, False])
  2769. def test_allany_oddities(self):
  2770. # Some fun with all and any
  2771. store = empty((), dtype=bool)
  2772. full = array([1, 2, 3], mask=True)
  2773. assert_(full.all() is masked)
  2774. full.all(out=store)
  2775. assert_(store)
  2776. assert_(store._mask, True)
  2777. assert_(store is not masked)
  2778. store = empty((), dtype=bool)
  2779. assert_(full.any() is masked)
  2780. full.any(out=store)
  2781. assert_(not store)
  2782. assert_(store._mask, True)
  2783. assert_(store is not masked)
  2784. def test_argmax_argmin(self):
  2785. # Tests argmin & argmax on MaskedArrays.
  2786. (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
  2787. assert_equal(mx.argmin(), 35)
  2788. assert_equal(mX.argmin(), 35)
  2789. assert_equal(m2x.argmin(), 4)
  2790. assert_equal(m2X.argmin(), 4)
  2791. assert_equal(mx.argmax(), 28)
  2792. assert_equal(mX.argmax(), 28)
  2793. assert_equal(m2x.argmax(), 31)
  2794. assert_equal(m2X.argmax(), 31)
  2795. assert_equal(mX.argmin(0), [2, 2, 2, 5, 0, 5])
  2796. assert_equal(m2X.argmin(0), [2, 2, 4, 5, 0, 4])
  2797. assert_equal(mX.argmax(0), [0, 5, 0, 5, 4, 0])
  2798. assert_equal(m2X.argmax(0), [5, 5, 0, 5, 1, 0])
  2799. assert_equal(mX.argmin(1), [4, 1, 0, 0, 5, 5, ])
  2800. assert_equal(m2X.argmin(1), [4, 4, 0, 0, 5, 3])
  2801. assert_equal(mX.argmax(1), [2, 4, 1, 1, 4, 1])
  2802. assert_equal(m2X.argmax(1), [2, 4, 1, 1, 1, 1])
  2803. def test_clip(self):
  2804. # Tests clip on MaskedArrays.
  2805. x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
  2806. 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
  2807. 3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
  2808. 6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
  2809. 7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
  2810. 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
  2811. m = np.array([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1,
  2812. 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1,
  2813. 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0])
  2814. mx = array(x, mask=m)
  2815. clipped = mx.clip(2, 8)
  2816. assert_equal(clipped.mask, mx.mask)
  2817. assert_equal(clipped._data, x.clip(2, 8))
  2818. assert_equal(clipped._data, mx._data.clip(2, 8))
  2819. def test_clip_out(self):
  2820. # gh-14140
  2821. a = np.arange(10)
  2822. m = np.ma.MaskedArray(a, mask=[0, 1] * 5)
  2823. m.clip(0, 5, out=m)
  2824. assert_equal(m.mask, [0, 1] * 5)
  2825. def test_compress(self):
  2826. # test compress
  2827. a = masked_array([1., 2., 3., 4., 5.], fill_value=9999)
  2828. condition = (a > 1.5) & (a < 3.5)
  2829. assert_equal(a.compress(condition), [2., 3.])
  2830. a[[2, 3]] = masked
  2831. b = a.compress(condition)
  2832. assert_equal(b._data, [2., 3.])
  2833. assert_equal(b._mask, [0, 1])
  2834. assert_equal(b.fill_value, 9999)
  2835. assert_equal(b, a[condition])
  2836. condition = (a < 4.)
  2837. b = a.compress(condition)
  2838. assert_equal(b._data, [1., 2., 3.])
  2839. assert_equal(b._mask, [0, 0, 1])
  2840. assert_equal(b.fill_value, 9999)
  2841. assert_equal(b, a[condition])
  2842. a = masked_array([[10, 20, 30], [40, 50, 60]],
  2843. mask=[[0, 0, 1], [1, 0, 0]])
  2844. b = a.compress(a.ravel() >= 22)
  2845. assert_equal(b._data, [30, 40, 50, 60])
  2846. assert_equal(b._mask, [1, 1, 0, 0])
  2847. x = np.array([3, 1, 2])
  2848. b = a.compress(x >= 2, axis=1)
  2849. assert_equal(b._data, [[10, 30], [40, 60]])
  2850. assert_equal(b._mask, [[0, 1], [1, 0]])
  2851. def test_compressed(self):
  2852. # Tests compressed
  2853. a = array([1, 2, 3, 4], mask=[0, 0, 0, 0])
  2854. b = a.compressed()
  2855. assert_equal(b, a)
  2856. a[0] = masked
  2857. b = a.compressed()
  2858. assert_equal(b, [2, 3, 4])
  2859. def test_empty(self):
  2860. # Tests empty/like
  2861. datatype = [('a', int), ('b', float), ('c', '|S8')]
  2862. a = masked_array([(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')],
  2863. dtype=datatype)
  2864. assert_equal(len(a.fill_value.item()), len(datatype))
  2865. b = empty_like(a)
  2866. assert_equal(b.shape, a.shape)
  2867. assert_equal(b.fill_value, a.fill_value)
  2868. b = empty(len(a), dtype=datatype)
  2869. assert_equal(b.shape, a.shape)
  2870. assert_equal(b.fill_value, a.fill_value)
  2871. # check empty_like mask handling
  2872. a = masked_array([1, 2, 3], mask=[False, True, False])
  2873. b = empty_like(a)
  2874. assert_(not np.may_share_memory(a.mask, b.mask))
  2875. b = a.view(masked_array)
  2876. assert_(np.may_share_memory(a.mask, b.mask))
  2877. def test_zeros(self):
  2878. # Tests zeros/like
  2879. datatype = [('a', int), ('b', float), ('c', '|S8')]
  2880. a = masked_array([(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')],
  2881. dtype=datatype)
  2882. assert_equal(len(a.fill_value.item()), len(datatype))
  2883. b = zeros(len(a), dtype=datatype)
  2884. assert_equal(b.shape, a.shape)
  2885. assert_equal(b.fill_value, a.fill_value)
  2886. b = zeros_like(a)
  2887. assert_equal(b.shape, a.shape)
  2888. assert_equal(b.fill_value, a.fill_value)
  2889. # check zeros_like mask handling
  2890. a = masked_array([1, 2, 3], mask=[False, True, False])
  2891. b = zeros_like(a)
  2892. assert_(not np.may_share_memory(a.mask, b.mask))
  2893. b = a.view()
  2894. assert_(np.may_share_memory(a.mask, b.mask))
  2895. def test_ones(self):
  2896. # Tests ones/like
  2897. datatype = [('a', int), ('b', float), ('c', '|S8')]
  2898. a = masked_array([(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')],
  2899. dtype=datatype)
  2900. assert_equal(len(a.fill_value.item()), len(datatype))
  2901. b = ones(len(a), dtype=datatype)
  2902. assert_equal(b.shape, a.shape)
  2903. assert_equal(b.fill_value, a.fill_value)
  2904. b = ones_like(a)
  2905. assert_equal(b.shape, a.shape)
  2906. assert_equal(b.fill_value, a.fill_value)
  2907. # check ones_like mask handling
  2908. a = masked_array([1, 2, 3], mask=[False, True, False])
  2909. b = ones_like(a)
  2910. assert_(not np.may_share_memory(a.mask, b.mask))
  2911. b = a.view()
  2912. assert_(np.may_share_memory(a.mask, b.mask))
  2913. @suppress_copy_mask_on_assignment
  2914. def test_put(self):
  2915. # Tests put.
  2916. d = arange(5)
  2917. n = [0, 0, 0, 1, 1]
  2918. m = make_mask(n)
  2919. x = array(d, mask=m)
  2920. assert_(x[3] is masked)
  2921. assert_(x[4] is masked)
  2922. x[[1, 4]] = [10, 40]
  2923. assert_(x[3] is masked)
  2924. assert_(x[4] is not masked)
  2925. assert_equal(x, [0, 10, 2, -1, 40])
  2926. x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2)
  2927. i = [0, 2, 4, 6]
  2928. x.put(i, [6, 4, 2, 0])
  2929. assert_equal(x, asarray([6, 1, 4, 3, 2, 5, 0, 7, 8, 9, ]))
  2930. assert_equal(x.mask, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0])
  2931. x.put(i, masked_array([0, 2, 4, 6], [1, 0, 1, 0]))
  2932. assert_array_equal(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ])
  2933. assert_equal(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0])
  2934. x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2)
  2935. put(x, i, [6, 4, 2, 0])
  2936. assert_equal(x, asarray([6, 1, 4, 3, 2, 5, 0, 7, 8, 9, ]))
  2937. assert_equal(x.mask, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0])
  2938. put(x, i, masked_array([0, 2, 4, 6], [1, 0, 1, 0]))
  2939. assert_array_equal(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ])
  2940. assert_equal(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0])
  2941. def test_put_nomask(self):
  2942. # GitHub issue 6425
  2943. x = zeros(10)
  2944. z = array([3., -1.], mask=[False, True])
  2945. x.put([1, 2], z)
  2946. assert_(x[0] is not masked)
  2947. assert_equal(x[0], 0)
  2948. assert_(x[1] is not masked)
  2949. assert_equal(x[1], 3)
  2950. assert_(x[2] is masked)
  2951. assert_(x[3] is not masked)
  2952. assert_equal(x[3], 0)
  2953. def test_put_hardmask(self):
  2954. # Tests put on hardmask
  2955. d = arange(5)
  2956. n = [0, 0, 0, 1, 1]
  2957. m = make_mask(n)
  2958. xh = array(d + 1, mask=m, hard_mask=True, copy=True)
  2959. xh.put([4, 2, 0, 1, 3], [1, 2, 3, 4, 5])
  2960. assert_equal(xh._data, [3, 4, 2, 4, 5])
  2961. def test_putmask(self):
  2962. x = arange(6) + 1
  2963. mx = array(x, mask=[0, 0, 0, 1, 1, 1])
  2964. mask = [0, 0, 1, 0, 0, 1]
  2965. # w/o mask, w/o masked values
  2966. xx = x.copy()
  2967. putmask(xx, mask, 99)
  2968. assert_equal(xx, [1, 2, 99, 4, 5, 99])
  2969. # w/ mask, w/o masked values
  2970. mxx = mx.copy()
  2971. putmask(mxx, mask, 99)
  2972. assert_equal(mxx._data, [1, 2, 99, 4, 5, 99])
  2973. assert_equal(mxx._mask, [0, 0, 0, 1, 1, 0])
  2974. # w/o mask, w/ masked values
  2975. values = array([10, 20, 30, 40, 50, 60], mask=[1, 1, 1, 0, 0, 0])
  2976. xx = x.copy()
  2977. putmask(xx, mask, values)
  2978. assert_equal(xx._data, [1, 2, 30, 4, 5, 60])
  2979. assert_equal(xx._mask, [0, 0, 1, 0, 0, 0])
  2980. # w/ mask, w/ masked values
  2981. mxx = mx.copy()
  2982. putmask(mxx, mask, values)
  2983. assert_equal(mxx._data, [1, 2, 30, 4, 5, 60])
  2984. assert_equal(mxx._mask, [0, 0, 1, 1, 1, 0])
  2985. # w/ mask, w/ masked values + hardmask
  2986. mxx = mx.copy()
  2987. mxx.harden_mask()
  2988. putmask(mxx, mask, values)
  2989. assert_equal(mxx, [1, 2, 30, 4, 5, 60])
  2990. def test_ravel(self):
  2991. # Tests ravel
  2992. a = array([[1, 2, 3, 4, 5]], mask=[[0, 1, 0, 0, 0]])
  2993. aravel = a.ravel()
  2994. assert_equal(aravel._mask.shape, aravel.shape)
  2995. a = array([0, 0], mask=[1, 1])
  2996. aravel = a.ravel()
  2997. assert_equal(aravel._mask.shape, a.shape)
  2998. # Checks that small_mask is preserved
  2999. a = array([1, 2, 3, 4], mask=[0, 0, 0, 0], shrink=False)
  3000. assert_equal(a.ravel()._mask, [0, 0, 0, 0])
  3001. # Test that the fill_value is preserved
  3002. a.fill_value = -99
  3003. a.shape = (2, 2)
  3004. ar = a.ravel()
  3005. assert_equal(ar._mask, [0, 0, 0, 0])
  3006. assert_equal(ar._data, [1, 2, 3, 4])
  3007. assert_equal(ar.fill_value, -99)
  3008. # Test index ordering
  3009. assert_equal(a.ravel(order='C'), [1, 2, 3, 4])
  3010. assert_equal(a.ravel(order='F'), [1, 3, 2, 4])
  3011. @pytest.mark.parametrize("order", "AKCF")
  3012. @pytest.mark.parametrize("data_order", "CF")
  3013. def test_ravel_order(self, order, data_order):
  3014. # Ravelling must ravel mask and data in the same order always to avoid
  3015. # misaligning the two in the ravel result.
  3016. arr = np.ones((5, 10), order=data_order)
  3017. arr[0, :] = 0
  3018. mask = np.ones((10, 5), dtype=bool, order=data_order).T
  3019. mask[0, :] = False
  3020. x = array(arr, mask=mask)
  3021. assert x._data.flags.fnc != x._mask.flags.fnc
  3022. assert (x.filled(0) == 0).all()
  3023. raveled = x.ravel(order)
  3024. assert (raveled.filled(0) == 0).all()
  3025. # NOTE: Can be wrong if arr order is neither C nor F and `order="K"`
  3026. assert_array_equal(arr.ravel(order), x.ravel(order)._data)
  3027. def test_reshape(self):
  3028. # Tests reshape
  3029. x = arange(4)
  3030. x[0] = masked
  3031. y = x.reshape(2, 2)
  3032. assert_equal(y.shape, (2, 2,))
  3033. assert_equal(y._mask.shape, (2, 2,))
  3034. assert_equal(x.shape, (4,))
  3035. assert_equal(x._mask.shape, (4,))
  3036. def test_sort(self):
  3037. # Test sort
  3038. x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8)
  3039. sortedx = sort(x)
  3040. assert_equal(sortedx._data, [1, 2, 3, 4])
  3041. assert_equal(sortedx._mask, [0, 0, 0, 1])
  3042. sortedx = sort(x, endwith=False)
  3043. assert_equal(sortedx._data, [4, 1, 2, 3])
  3044. assert_equal(sortedx._mask, [1, 0, 0, 0])
  3045. x.sort()
  3046. assert_equal(x._data, [1, 2, 3, 4])
  3047. assert_equal(x._mask, [0, 0, 0, 1])
  3048. x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8)
  3049. x.sort(endwith=False)
  3050. assert_equal(x._data, [4, 1, 2, 3])
  3051. assert_equal(x._mask, [1, 0, 0, 0])
  3052. x = [1, 4, 2, 3]
  3053. sortedx = sort(x)
  3054. assert_(not isinstance(sorted, MaskedArray))
  3055. x = array([0, 1, -1, -2, 2], mask=nomask, dtype=np.int8)
  3056. sortedx = sort(x, endwith=False)
  3057. assert_equal(sortedx._data, [-2, -1, 0, 1, 2])
  3058. x = array([0, 1, -1, -2, 2], mask=[0, 1, 0, 0, 1], dtype=np.int8)
  3059. sortedx = sort(x, endwith=False)
  3060. assert_equal(sortedx._data, [1, 2, -2, -1, 0])
  3061. assert_equal(sortedx._mask, [1, 1, 0, 0, 0])
  3062. x = array([0, -1], dtype=np.int8)
  3063. sortedx = sort(x, kind="stable")
  3064. assert_equal(sortedx, array([-1, 0], dtype=np.int8))
  3065. def test_stable_sort(self):
  3066. x = array([1, 2, 3, 1, 2, 3], dtype=np.uint8)
  3067. expected = array([0, 3, 1, 4, 2, 5])
  3068. computed = argsort(x, kind='stable')
  3069. assert_equal(computed, expected)
  3070. def test_argsort_matches_sort(self):
  3071. x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8)
  3072. for kwargs in [dict(),
  3073. dict(endwith=True),
  3074. dict(endwith=False),
  3075. dict(fill_value=2),
  3076. dict(fill_value=2, endwith=True),
  3077. dict(fill_value=2, endwith=False)]:
  3078. sortedx = sort(x, **kwargs)
  3079. argsortedx = x[argsort(x, **kwargs)]
  3080. assert_equal(sortedx._data, argsortedx._data)
  3081. assert_equal(sortedx._mask, argsortedx._mask)
  3082. def test_sort_2d(self):
  3083. # Check sort of 2D array.
  3084. # 2D array w/o mask
  3085. a = masked_array([[8, 4, 1], [2, 0, 9]])
  3086. a.sort(0)
  3087. assert_equal(a, [[2, 0, 1], [8, 4, 9]])
  3088. a = masked_array([[8, 4, 1], [2, 0, 9]])
  3089. a.sort(1)
  3090. assert_equal(a, [[1, 4, 8], [0, 2, 9]])
  3091. # 2D array w/mask
  3092. a = masked_array([[8, 4, 1], [2, 0, 9]], mask=[[1, 0, 0], [0, 0, 1]])
  3093. a.sort(0)
  3094. assert_equal(a, [[2, 0, 1], [8, 4, 9]])
  3095. assert_equal(a._mask, [[0, 0, 0], [1, 0, 1]])
  3096. a = masked_array([[8, 4, 1], [2, 0, 9]], mask=[[1, 0, 0], [0, 0, 1]])
  3097. a.sort(1)
  3098. assert_equal(a, [[1, 4, 8], [0, 2, 9]])
  3099. assert_equal(a._mask, [[0, 0, 1], [0, 0, 1]])
  3100. # 3D
  3101. a = masked_array([[[7, 8, 9], [4, 5, 6], [1, 2, 3]],
  3102. [[1, 2, 3], [7, 8, 9], [4, 5, 6]],
  3103. [[7, 8, 9], [1, 2, 3], [4, 5, 6]],
  3104. [[4, 5, 6], [1, 2, 3], [7, 8, 9]]])
  3105. a[a % 4 == 0] = masked
  3106. am = a.copy()
  3107. an = a.filled(99)
  3108. am.sort(0)
  3109. an.sort(0)
  3110. assert_equal(am, an)
  3111. am = a.copy()
  3112. an = a.filled(99)
  3113. am.sort(1)
  3114. an.sort(1)
  3115. assert_equal(am, an)
  3116. am = a.copy()
  3117. an = a.filled(99)
  3118. am.sort(2)
  3119. an.sort(2)
  3120. assert_equal(am, an)
  3121. def test_sort_flexible(self):
  3122. # Test sort on structured dtype.
  3123. a = array(
  3124. data=[(3, 3), (3, 2), (2, 2), (2, 1), (1, 0), (1, 1), (1, 2)],
  3125. mask=[(0, 0), (0, 1), (0, 0), (0, 0), (1, 0), (0, 0), (0, 0)],
  3126. dtype=[('A', int), ('B', int)])
  3127. mask_last = array(
  3128. data=[(1, 1), (1, 2), (2, 1), (2, 2), (3, 3), (3, 2), (1, 0)],
  3129. mask=[(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (1, 0)],
  3130. dtype=[('A', int), ('B', int)])
  3131. mask_first = array(
  3132. data=[(1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (3, 2), (3, 3)],
  3133. mask=[(1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (0, 0)],
  3134. dtype=[('A', int), ('B', int)])
  3135. test = sort(a)
  3136. assert_equal(test, mask_last)
  3137. assert_equal(test.mask, mask_last.mask)
  3138. test = sort(a, endwith=False)
  3139. assert_equal(test, mask_first)
  3140. assert_equal(test.mask, mask_first.mask)
  3141. # Test sort on dtype with subarray (gh-8069)
  3142. # Just check that the sort does not error, structured array subarrays
  3143. # are treated as byte strings and that leads to differing behavior
  3144. # depending on endianness and `endwith`.
  3145. dt = np.dtype([('v', int, 2)])
  3146. a = a.view(dt)
  3147. test = sort(a)
  3148. test = sort(a, endwith=False)
  3149. def test_argsort(self):
  3150. # Test argsort
  3151. a = array([1, 5, 2, 4, 3], mask=[1, 0, 0, 1, 0])
  3152. assert_equal(np.argsort(a), argsort(a))
  3153. def test_squeeze(self):
  3154. # Check squeeze
  3155. data = masked_array([[1, 2, 3]])
  3156. assert_equal(data.squeeze(), [1, 2, 3])
  3157. data = masked_array([[1, 2, 3]], mask=[[1, 1, 1]])
  3158. assert_equal(data.squeeze(), [1, 2, 3])
  3159. assert_equal(data.squeeze()._mask, [1, 1, 1])
  3160. # normal ndarrays return a view
  3161. arr = np.array([[1]])
  3162. arr_sq = arr.squeeze()
  3163. assert_equal(arr_sq, 1)
  3164. arr_sq[...] = 2
  3165. assert_equal(arr[0,0], 2)
  3166. # so maskedarrays should too
  3167. m_arr = masked_array([[1]], mask=True)
  3168. m_arr_sq = m_arr.squeeze()
  3169. assert_(m_arr_sq is not np.ma.masked)
  3170. assert_equal(m_arr_sq.mask, True)
  3171. m_arr_sq[...] = 2
  3172. assert_equal(m_arr[0,0], 2)
  3173. def test_swapaxes(self):
  3174. # Tests swapaxes on MaskedArrays.
  3175. x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
  3176. 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
  3177. 3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
  3178. 6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
  3179. 7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
  3180. 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
  3181. m = np.array([0, 1, 0, 1, 0, 0,
  3182. 1, 0, 1, 1, 0, 1,
  3183. 0, 0, 0, 1, 0, 1,
  3184. 0, 0, 0, 1, 1, 1,
  3185. 1, 0, 0, 1, 0, 0,
  3186. 0, 0, 1, 0, 1, 0])
  3187. mX = array(x, mask=m).reshape(6, 6)
  3188. mXX = mX.reshape(3, 2, 2, 3)
  3189. mXswapped = mX.swapaxes(0, 1)
  3190. assert_equal(mXswapped[-1], mX[:, -1])
  3191. mXXswapped = mXX.swapaxes(0, 2)
  3192. assert_equal(mXXswapped.shape, (2, 2, 3, 3))
  3193. def test_take(self):
  3194. # Tests take
  3195. x = masked_array([10, 20, 30, 40], [0, 1, 0, 1])
  3196. assert_equal(x.take([0, 0, 3]), masked_array([10, 10, 40], [0, 0, 1]))
  3197. assert_equal(x.take([0, 0, 3]), x[[0, 0, 3]])
  3198. assert_equal(x.take([[0, 1], [0, 1]]),
  3199. masked_array([[10, 20], [10, 20]], [[0, 1], [0, 1]]))
  3200. # assert_equal crashes when passed np.ma.mask
  3201. assert_(x[1] is np.ma.masked)
  3202. assert_(x.take(1) is np.ma.masked)
  3203. x = array([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0, ]])
  3204. assert_equal(x.take([0, 2], axis=1),
  3205. array([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]]))
  3206. assert_equal(take(x, [0, 2], axis=1),
  3207. array([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]]))
  3208. def test_take_masked_indices(self):
  3209. # Test take w/ masked indices
  3210. a = np.array((40, 18, 37, 9, 22))
  3211. indices = np.arange(3)[None,:] + np.arange(5)[:, None]
  3212. mindices = array(indices, mask=(indices >= len(a)))
  3213. # No mask
  3214. test = take(a, mindices, mode='clip')
  3215. ctrl = array([[40, 18, 37],
  3216. [18, 37, 9],
  3217. [37, 9, 22],
  3218. [9, 22, 22],
  3219. [22, 22, 22]])
  3220. assert_equal(test, ctrl)
  3221. # Masked indices
  3222. test = take(a, mindices)
  3223. ctrl = array([[40, 18, 37],
  3224. [18, 37, 9],
  3225. [37, 9, 22],
  3226. [9, 22, 40],
  3227. [22, 40, 40]])
  3228. ctrl[3, 2] = ctrl[4, 1] = ctrl[4, 2] = masked
  3229. assert_equal(test, ctrl)
  3230. assert_equal(test.mask, ctrl.mask)
  3231. # Masked input + masked indices
  3232. a = array((40, 18, 37, 9, 22), mask=(0, 1, 0, 0, 0))
  3233. test = take(a, mindices)
  3234. ctrl[0, 1] = ctrl[1, 0] = masked
  3235. assert_equal(test, ctrl)
  3236. assert_equal(test.mask, ctrl.mask)
  3237. def test_tolist(self):
  3238. # Tests to list
  3239. # ... on 1D
  3240. x = array(np.arange(12))
  3241. x[[1, -2]] = masked
  3242. xlist = x.tolist()
  3243. assert_(xlist[1] is None)
  3244. assert_(xlist[-2] is None)
  3245. # ... on 2D
  3246. x.shape = (3, 4)
  3247. xlist = x.tolist()
  3248. ctrl = [[0, None, 2, 3], [4, 5, 6, 7], [8, 9, None, 11]]
  3249. assert_equal(xlist[0], [0, None, 2, 3])
  3250. assert_equal(xlist[1], [4, 5, 6, 7])
  3251. assert_equal(xlist[2], [8, 9, None, 11])
  3252. assert_equal(xlist, ctrl)
  3253. # ... on structured array w/ masked records
  3254. x = array(list(zip([1, 2, 3],
  3255. [1.1, 2.2, 3.3],
  3256. ['one', 'two', 'thr'])),
  3257. dtype=[('a', int), ('b', float), ('c', '|S8')])
  3258. x[-1] = masked
  3259. assert_equal(x.tolist(),
  3260. [(1, 1.1, b'one'),
  3261. (2, 2.2, b'two'),
  3262. (None, None, None)])
  3263. # ... on structured array w/ masked fields
  3264. a = array([(1, 2,), (3, 4)], mask=[(0, 1), (0, 0)],
  3265. dtype=[('a', int), ('b', int)])
  3266. test = a.tolist()
  3267. assert_equal(test, [[1, None], [3, 4]])
  3268. # ... on mvoid
  3269. a = a[0]
  3270. test = a.tolist()
  3271. assert_equal(test, [1, None])
  3272. def test_tolist_specialcase(self):
  3273. # Test mvoid.tolist: make sure we return a standard Python object
  3274. a = array([(0, 1), (2, 3)], dtype=[('a', int), ('b', int)])
  3275. # w/o mask: each entry is a np.void whose elements are standard Python
  3276. for entry in a:
  3277. for item in entry.tolist():
  3278. assert_(not isinstance(item, np.generic))
  3279. # w/ mask: each entry is a ma.void whose elements should be
  3280. # standard Python
  3281. a.mask[0] = (0, 1)
  3282. for entry in a:
  3283. for item in entry.tolist():
  3284. assert_(not isinstance(item, np.generic))
  3285. def test_toflex(self):
  3286. # Test the conversion to records
  3287. data = arange(10)
  3288. record = data.toflex()
  3289. assert_equal(record['_data'], data._data)
  3290. assert_equal(record['_mask'], data._mask)
  3291. data[[0, 1, 2, -1]] = masked
  3292. record = data.toflex()
  3293. assert_equal(record['_data'], data._data)
  3294. assert_equal(record['_mask'], data._mask)
  3295. ndtype = [('i', int), ('s', '|S3'), ('f', float)]
  3296. data = array([(i, s, f) for (i, s, f) in zip(np.arange(10),
  3297. 'ABCDEFGHIJKLM',
  3298. np.random.rand(10))],
  3299. dtype=ndtype)
  3300. data[[0, 1, 2, -1]] = masked
  3301. record = data.toflex()
  3302. assert_equal(record['_data'], data._data)
  3303. assert_equal(record['_mask'], data._mask)
  3304. ndtype = np.dtype("int, (2,3)float, float")
  3305. data = array([(i, f, ff) for (i, f, ff) in zip(np.arange(10),
  3306. np.random.rand(10),
  3307. np.random.rand(10))],
  3308. dtype=ndtype)
  3309. data[[0, 1, 2, -1]] = masked
  3310. record = data.toflex()
  3311. assert_equal_records(record['_data'], data._data)
  3312. assert_equal_records(record['_mask'], data._mask)
  3313. def test_fromflex(self):
  3314. # Test the reconstruction of a masked_array from a record
  3315. a = array([1, 2, 3])
  3316. test = fromflex(a.toflex())
  3317. assert_equal(test, a)
  3318. assert_equal(test.mask, a.mask)
  3319. a = array([1, 2, 3], mask=[0, 0, 1])
  3320. test = fromflex(a.toflex())
  3321. assert_equal(test, a)
  3322. assert_equal(test.mask, a.mask)
  3323. a = array([(1, 1.), (2, 2.), (3, 3.)], mask=[(1, 0), (0, 0), (0, 1)],
  3324. dtype=[('A', int), ('B', float)])
  3325. test = fromflex(a.toflex())
  3326. assert_equal(test, a)
  3327. assert_equal(test.data, a.data)
  3328. def test_arraymethod(self):
  3329. # Test a _arraymethod w/ n argument
  3330. marray = masked_array([[1, 2, 3, 4, 5]], mask=[0, 0, 1, 0, 0])
  3331. control = masked_array([[1], [2], [3], [4], [5]],
  3332. mask=[0, 0, 1, 0, 0])
  3333. assert_equal(marray.T, control)
  3334. assert_equal(marray.transpose(), control)
  3335. assert_equal(MaskedArray.cumsum(marray.T, 0), control.cumsum(0))
  3336. def test_arraymethod_0d(self):
  3337. # gh-9430
  3338. x = np.ma.array(42, mask=True)
  3339. assert_equal(x.T.mask, x.mask)
  3340. assert_equal(x.T.data, x.data)
  3341. def test_transpose_view(self):
  3342. x = np.ma.array([[1, 2, 3], [4, 5, 6]])
  3343. x[0,1] = np.ma.masked
  3344. xt = x.T
  3345. xt[1,0] = 10
  3346. xt[0,1] = np.ma.masked
  3347. assert_equal(x.data, xt.T.data)
  3348. assert_equal(x.mask, xt.T.mask)
  3349. def test_diagonal_view(self):
  3350. x = np.ma.zeros((3,3))
  3351. x[0,0] = 10
  3352. x[1,1] = np.ma.masked
  3353. x[2,2] = 20
  3354. xd = x.diagonal()
  3355. x[1,1] = 15
  3356. assert_equal(xd.mask, x.diagonal().mask)
  3357. assert_equal(xd.data, x.diagonal().data)
  3358. class TestMaskedArrayMathMethods:
  3359. def setup_method(self):
  3360. # Base data definition.
  3361. x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
  3362. 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
  3363. 3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
  3364. 6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
  3365. 7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
  3366. 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
  3367. X = x.reshape(6, 6)
  3368. XX = x.reshape(3, 2, 2, 3)
  3369. m = np.array([0, 1, 0, 1, 0, 0,
  3370. 1, 0, 1, 1, 0, 1,
  3371. 0, 0, 0, 1, 0, 1,
  3372. 0, 0, 0, 1, 1, 1,
  3373. 1, 0, 0, 1, 0, 0,
  3374. 0, 0, 1, 0, 1, 0])
  3375. mx = array(data=x, mask=m)
  3376. mX = array(data=X, mask=m.reshape(X.shape))
  3377. mXX = array(data=XX, mask=m.reshape(XX.shape))
  3378. m2 = np.array([1, 1, 0, 1, 0, 0,
  3379. 1, 1, 1, 1, 0, 1,
  3380. 0, 0, 1, 1, 0, 1,
  3381. 0, 0, 0, 1, 1, 1,
  3382. 1, 0, 0, 1, 1, 0,
  3383. 0, 0, 1, 0, 1, 1])
  3384. m2x = array(data=x, mask=m2)
  3385. m2X = array(data=X, mask=m2.reshape(X.shape))
  3386. m2XX = array(data=XX, mask=m2.reshape(XX.shape))
  3387. self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX)
  3388. def test_cumsumprod(self):
  3389. # Tests cumsum & cumprod on MaskedArrays.
  3390. (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
  3391. mXcp = mX.cumsum(0)
  3392. assert_equal(mXcp._data, mX.filled(0).cumsum(0))
  3393. mXcp = mX.cumsum(1)
  3394. assert_equal(mXcp._data, mX.filled(0).cumsum(1))
  3395. mXcp = mX.cumprod(0)
  3396. assert_equal(mXcp._data, mX.filled(1).cumprod(0))
  3397. mXcp = mX.cumprod(1)
  3398. assert_equal(mXcp._data, mX.filled(1).cumprod(1))
  3399. def test_cumsumprod_with_output(self):
  3400. # Tests cumsum/cumprod w/ output
  3401. xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4)
  3402. xm[:, 0] = xm[0] = xm[-1, -1] = masked
  3403. for funcname in ('cumsum', 'cumprod'):
  3404. npfunc = getattr(np, funcname)
  3405. xmmeth = getattr(xm, funcname)
  3406. # A ndarray as explicit input
  3407. output = np.empty((3, 4), dtype=float)
  3408. output.fill(-9999)
  3409. result = npfunc(xm, axis=0, out=output)
  3410. # ... the result should be the given output
  3411. assert_(result is output)
  3412. assert_equal(result, xmmeth(axis=0, out=output))
  3413. output = empty((3, 4), dtype=int)
  3414. result = xmmeth(axis=0, out=output)
  3415. assert_(result is output)
  3416. def test_ptp(self):
  3417. # Tests ptp on MaskedArrays.
  3418. (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
  3419. (n, m) = X.shape
  3420. assert_equal(mx.ptp(), mx.compressed().ptp())
  3421. rows = np.zeros(n, float)
  3422. cols = np.zeros(m, float)
  3423. for k in range(m):
  3424. cols[k] = mX[:, k].compressed().ptp()
  3425. for k in range(n):
  3426. rows[k] = mX[k].compressed().ptp()
  3427. assert_equal(mX.ptp(0), cols)
  3428. assert_equal(mX.ptp(1), rows)
  3429. def test_add_object(self):
  3430. x = masked_array(['a', 'b'], mask=[1, 0], dtype=object)
  3431. y = x + 'x'
  3432. assert_equal(y[1], 'bx')
  3433. assert_(y.mask[0])
  3434. def test_sum_object(self):
  3435. # Test sum on object dtype
  3436. a = masked_array([1, 2, 3], mask=[1, 0, 0], dtype=object)
  3437. assert_equal(a.sum(), 5)
  3438. a = masked_array([[1, 2, 3], [4, 5, 6]], dtype=object)
  3439. assert_equal(a.sum(axis=0), [5, 7, 9])
  3440. def test_prod_object(self):
  3441. # Test prod on object dtype
  3442. a = masked_array([1, 2, 3], mask=[1, 0, 0], dtype=object)
  3443. assert_equal(a.prod(), 2 * 3)
  3444. a = masked_array([[1, 2, 3], [4, 5, 6]], dtype=object)
  3445. assert_equal(a.prod(axis=0), [4, 10, 18])
  3446. def test_meananom_object(self):
  3447. # Test mean/anom on object dtype
  3448. a = masked_array([1, 2, 3], dtype=object)
  3449. assert_equal(a.mean(), 2)
  3450. assert_equal(a.anom(), [-1, 0, 1])
  3451. def test_anom_shape(self):
  3452. a = masked_array([1, 2, 3])
  3453. assert_equal(a.anom().shape, a.shape)
  3454. a.mask = True
  3455. assert_equal(a.anom().shape, a.shape)
  3456. assert_(np.ma.is_masked(a.anom()))
  3457. def test_anom(self):
  3458. a = masked_array(np.arange(1, 7).reshape(2, 3))
  3459. assert_almost_equal(a.anom(),
  3460. [[-2.5, -1.5, -0.5], [0.5, 1.5, 2.5]])
  3461. assert_almost_equal(a.anom(axis=0),
  3462. [[-1.5, -1.5, -1.5], [1.5, 1.5, 1.5]])
  3463. assert_almost_equal(a.anom(axis=1),
  3464. [[-1., 0., 1.], [-1., 0., 1.]])
  3465. a.mask = [[0, 0, 1], [0, 1, 0]]
  3466. mval = -99
  3467. assert_almost_equal(a.anom().filled(mval),
  3468. [[-2.25, -1.25, mval], [0.75, mval, 2.75]])
  3469. assert_almost_equal(a.anom(axis=0).filled(mval),
  3470. [[-1.5, 0.0, mval], [1.5, mval, 0.0]])
  3471. assert_almost_equal(a.anom(axis=1).filled(mval),
  3472. [[-0.5, 0.5, mval], [-1.0, mval, 1.0]])
  3473. def test_trace(self):
  3474. # Tests trace on MaskedArrays.
  3475. (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
  3476. mXdiag = mX.diagonal()
  3477. assert_equal(mX.trace(), mX.diagonal().compressed().sum())
  3478. assert_almost_equal(mX.trace(),
  3479. X.trace() - sum(mXdiag.mask * X.diagonal(),
  3480. axis=0))
  3481. assert_equal(np.trace(mX), mX.trace())
  3482. # gh-5560
  3483. arr = np.arange(2*4*4).reshape(2,4,4)
  3484. m_arr = np.ma.masked_array(arr, False)
  3485. assert_equal(arr.trace(axis1=1, axis2=2), m_arr.trace(axis1=1, axis2=2))
  3486. def test_dot(self):
  3487. # Tests dot on MaskedArrays.
  3488. (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
  3489. fx = mx.filled(0)
  3490. r = mx.dot(mx)
  3491. assert_almost_equal(r.filled(0), fx.dot(fx))
  3492. assert_(r.mask is nomask)
  3493. fX = mX.filled(0)
  3494. r = mX.dot(mX)
  3495. assert_almost_equal(r.filled(0), fX.dot(fX))
  3496. assert_(r.mask[1,3])
  3497. r1 = empty_like(r)
  3498. mX.dot(mX, out=r1)
  3499. assert_almost_equal(r, r1)
  3500. mYY = mXX.swapaxes(-1, -2)
  3501. fXX, fYY = mXX.filled(0), mYY.filled(0)
  3502. r = mXX.dot(mYY)
  3503. assert_almost_equal(r.filled(0), fXX.dot(fYY))
  3504. r1 = empty_like(r)
  3505. mXX.dot(mYY, out=r1)
  3506. assert_almost_equal(r, r1)
  3507. def test_dot_shape_mismatch(self):
  3508. # regression test
  3509. x = masked_array([[1,2],[3,4]], mask=[[0,1],[0,0]])
  3510. y = masked_array([[1,2],[3,4]], mask=[[0,1],[0,0]])
  3511. z = masked_array([[0,1],[3,3]])
  3512. x.dot(y, out=z)
  3513. assert_almost_equal(z.filled(0), [[1, 0], [15, 16]])
  3514. assert_almost_equal(z.mask, [[0, 1], [0, 0]])
  3515. def test_varmean_nomask(self):
  3516. # gh-5769
  3517. foo = array([1,2,3,4], dtype='f8')
  3518. bar = array([1,2,3,4], dtype='f8')
  3519. assert_equal(type(foo.mean()), np.float64)
  3520. assert_equal(type(foo.var()), np.float64)
  3521. assert((foo.mean() == bar.mean()) is np.bool_(True))
  3522. # check array type is preserved and out works
  3523. foo = array(np.arange(16).reshape((4,4)), dtype='f8')
  3524. bar = empty(4, dtype='f4')
  3525. assert_equal(type(foo.mean(axis=1)), MaskedArray)
  3526. assert_equal(type(foo.var(axis=1)), MaskedArray)
  3527. assert_(foo.mean(axis=1, out=bar) is bar)
  3528. assert_(foo.var(axis=1, out=bar) is bar)
  3529. def test_varstd(self):
  3530. # Tests var & std on MaskedArrays.
  3531. (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
  3532. assert_almost_equal(mX.var(axis=None), mX.compressed().var())
  3533. assert_almost_equal(mX.std(axis=None), mX.compressed().std())
  3534. assert_almost_equal(mX.std(axis=None, ddof=1),
  3535. mX.compressed().std(ddof=1))
  3536. assert_almost_equal(mX.var(axis=None, ddof=1),
  3537. mX.compressed().var(ddof=1))
  3538. assert_equal(mXX.var(axis=3).shape, XX.var(axis=3).shape)
  3539. assert_equal(mX.var().shape, X.var().shape)
  3540. (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))
  3541. assert_almost_equal(mX.var(axis=None, ddof=2),
  3542. mX.compressed().var(ddof=2))
  3543. assert_almost_equal(mX.std(axis=None, ddof=2),
  3544. mX.compressed().std(ddof=2))
  3545. for k in range(6):
  3546. assert_almost_equal(mXvar1[k], mX[k].compressed().var())
  3547. assert_almost_equal(mXvar0[k], mX[:, k].compressed().var())
  3548. assert_almost_equal(np.sqrt(mXvar0[k]),
  3549. mX[:, k].compressed().std())
  3550. @suppress_copy_mask_on_assignment
  3551. def test_varstd_specialcases(self):
  3552. # Test a special case for var
  3553. nout = np.array(-1, dtype=float)
  3554. mout = array(-1, dtype=float)
  3555. x = array(arange(10), mask=True)
  3556. for methodname in ('var', 'std'):
  3557. method = getattr(x, methodname)
  3558. assert_(method() is masked)
  3559. assert_(method(0) is masked)
  3560. assert_(method(-1) is masked)
  3561. # Using a masked array as explicit output
  3562. method(out=mout)
  3563. assert_(mout is not masked)
  3564. assert_equal(mout.mask, True)
  3565. # Using a ndarray as explicit output
  3566. method(out=nout)
  3567. assert_(np.isnan(nout))
  3568. x = array(arange(10), mask=True)
  3569. x[-1] = 9
  3570. for methodname in ('var', 'std'):
  3571. method = getattr(x, methodname)
  3572. assert_(method(ddof=1) is masked)
  3573. assert_(method(0, ddof=1) is masked)
  3574. assert_(method(-1, ddof=1) is masked)
  3575. # Using a masked array as explicit output
  3576. method(out=mout, ddof=1)
  3577. assert_(mout is not masked)
  3578. assert_equal(mout.mask, True)
  3579. # Using a ndarray as explicit output
  3580. method(out=nout, ddof=1)
  3581. assert_(np.isnan(nout))
  3582. def test_varstd_ddof(self):
  3583. a = array([[1, 1, 0], [1, 1, 0]], mask=[[0, 0, 1], [0, 0, 1]])
  3584. test = a.std(axis=0, ddof=0)
  3585. assert_equal(test.filled(0), [0, 0, 0])
  3586. assert_equal(test.mask, [0, 0, 1])
  3587. test = a.std(axis=0, ddof=1)
  3588. assert_equal(test.filled(0), [0, 0, 0])
  3589. assert_equal(test.mask, [0, 0, 1])
  3590. test = a.std(axis=0, ddof=2)
  3591. assert_equal(test.filled(0), [0, 0, 0])
  3592. assert_equal(test.mask, [1, 1, 1])
  3593. def test_diag(self):
  3594. # Test diag
  3595. x = arange(9).reshape((3, 3))
  3596. x[1, 1] = masked
  3597. out = np.diag(x)
  3598. assert_equal(out, [0, 4, 8])
  3599. out = diag(x)
  3600. assert_equal(out, [0, 4, 8])
  3601. assert_equal(out.mask, [0, 1, 0])
  3602. out = diag(out)
  3603. control = array([[0, 0, 0], [0, 4, 0], [0, 0, 8]],
  3604. mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]])
  3605. assert_equal(out, control)
  3606. def test_axis_methods_nomask(self):
  3607. # Test the combination nomask & methods w/ axis
  3608. a = array([[1, 2, 3], [4, 5, 6]])
  3609. assert_equal(a.sum(0), [5, 7, 9])
  3610. assert_equal(a.sum(-1), [6, 15])
  3611. assert_equal(a.sum(1), [6, 15])
  3612. assert_equal(a.prod(0), [4, 10, 18])
  3613. assert_equal(a.prod(-1), [6, 120])
  3614. assert_equal(a.prod(1), [6, 120])
  3615. assert_equal(a.min(0), [1, 2, 3])
  3616. assert_equal(a.min(-1), [1, 4])
  3617. assert_equal(a.min(1), [1, 4])
  3618. assert_equal(a.max(0), [4, 5, 6])
  3619. assert_equal(a.max(-1), [3, 6])
  3620. assert_equal(a.max(1), [3, 6])
  3621. @requires_memory(free_bytes=2 * 10000 * 1000 * 2)
  3622. def test_mean_overflow(self):
  3623. # Test overflow in masked arrays
  3624. # gh-20272
  3625. a = masked_array(np.full((10000, 10000), 65535, dtype=np.uint16),
  3626. mask=np.zeros((10000, 10000)))
  3627. assert_equal(a.mean(), 65535.0)
  3628. class TestMaskedArrayMathMethodsComplex:
  3629. # Test class for miscellaneous MaskedArrays methods.
  3630. def setup_method(self):
  3631. # Base data definition.
  3632. x = np.array([8.375j, 7.545j, 8.828j, 8.5j, 1.757j, 5.928,
  3633. 8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
  3634. 3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
  3635. 6.04, 9.63, 7.712, 3.382, 4.489, 6.479j,
  3636. 7.189j, 9.645, 5.395, 4.961, 9.894, 2.893,
  3637. 7.357, 9.828, 6.272, 3.758, 6.693, 0.993j])
  3638. X = x.reshape(6, 6)
  3639. XX = x.reshape(3, 2, 2, 3)
  3640. m = np.array([0, 1, 0, 1, 0, 0,
  3641. 1, 0, 1, 1, 0, 1,
  3642. 0, 0, 0, 1, 0, 1,
  3643. 0, 0, 0, 1, 1, 1,
  3644. 1, 0, 0, 1, 0, 0,
  3645. 0, 0, 1, 0, 1, 0])
  3646. mx = array(data=x, mask=m)
  3647. mX = array(data=X, mask=m.reshape(X.shape))
  3648. mXX = array(data=XX, mask=m.reshape(XX.shape))
  3649. m2 = np.array([1, 1, 0, 1, 0, 0,
  3650. 1, 1, 1, 1, 0, 1,
  3651. 0, 0, 1, 1, 0, 1,
  3652. 0, 0, 0, 1, 1, 1,
  3653. 1, 0, 0, 1, 1, 0,
  3654. 0, 0, 1, 0, 1, 1])
  3655. m2x = array(data=x, mask=m2)
  3656. m2X = array(data=X, mask=m2.reshape(X.shape))
  3657. m2XX = array(data=XX, mask=m2.reshape(XX.shape))
  3658. self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX)
  3659. def test_varstd(self):
  3660. # Tests var & std on MaskedArrays.
  3661. (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
  3662. assert_almost_equal(mX.var(axis=None), mX.compressed().var())
  3663. assert_almost_equal(mX.std(axis=None), mX.compressed().std())
  3664. assert_equal(mXX.var(axis=3).shape, XX.var(axis=3).shape)
  3665. assert_equal(mX.var().shape, X.var().shape)
  3666. (mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))
  3667. assert_almost_equal(mX.var(axis=None, ddof=2),
  3668. mX.compressed().var(ddof=2))
  3669. assert_almost_equal(mX.std(axis=None, ddof=2),
  3670. mX.compressed().std(ddof=2))
  3671. for k in range(6):
  3672. assert_almost_equal(mXvar1[k], mX[k].compressed().var())
  3673. assert_almost_equal(mXvar0[k], mX[:, k].compressed().var())
  3674. assert_almost_equal(np.sqrt(mXvar0[k]),
  3675. mX[:, k].compressed().std())
  3676. class TestMaskedArrayFunctions:
  3677. # Test class for miscellaneous functions.
  3678. def setup_method(self):
  3679. x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
  3680. y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
  3681. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
  3682. m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
  3683. xm = masked_array(x, mask=m1)
  3684. ym = masked_array(y, mask=m2)
  3685. xm.set_fill_value(1e+20)
  3686. self.info = (xm, ym)
  3687. def test_masked_where_bool(self):
  3688. x = [1, 2]
  3689. y = masked_where(False, x)
  3690. assert_equal(y, [1, 2])
  3691. assert_equal(y[1], 2)
  3692. def test_masked_equal_wlist(self):
  3693. x = [1, 2, 3]
  3694. mx = masked_equal(x, 3)
  3695. assert_equal(mx, x)
  3696. assert_equal(mx._mask, [0, 0, 1])
  3697. mx = masked_not_equal(x, 3)
  3698. assert_equal(mx, x)
  3699. assert_equal(mx._mask, [1, 1, 0])
  3700. def test_masked_equal_fill_value(self):
  3701. x = [1, 2, 3]
  3702. mx = masked_equal(x, 3)
  3703. assert_equal(mx._mask, [0, 0, 1])
  3704. assert_equal(mx.fill_value, 3)
  3705. def test_masked_where_condition(self):
  3706. # Tests masking functions.
  3707. x = array([1., 2., 3., 4., 5.])
  3708. x[2] = masked
  3709. assert_equal(masked_where(greater(x, 2), x), masked_greater(x, 2))
  3710. assert_equal(masked_where(greater_equal(x, 2), x),
  3711. masked_greater_equal(x, 2))
  3712. assert_equal(masked_where(less(x, 2), x), masked_less(x, 2))
  3713. assert_equal(masked_where(less_equal(x, 2), x),
  3714. masked_less_equal(x, 2))
  3715. assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))
  3716. assert_equal(masked_where(equal(x, 2), x), masked_equal(x, 2))
  3717. assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))
  3718. assert_equal(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]),
  3719. [99, 99, 3, 4, 5])
  3720. def test_masked_where_oddities(self):
  3721. # Tests some generic features.
  3722. atest = ones((10, 10, 10), dtype=float)
  3723. btest = zeros(atest.shape, MaskType)
  3724. ctest = masked_where(btest, atest)
  3725. assert_equal(atest, ctest)
  3726. def test_masked_where_shape_constraint(self):
  3727. a = arange(10)
  3728. with assert_raises(IndexError):
  3729. masked_equal(1, a)
  3730. test = masked_equal(a, 1)
  3731. assert_equal(test.mask, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
  3732. def test_masked_where_structured(self):
  3733. # test that masked_where on a structured array sets a structured
  3734. # mask (see issue #2972)
  3735. a = np.zeros(10, dtype=[("A", "<f2"), ("B", "<f4")])
  3736. with np.errstate(over="ignore"):
  3737. # NOTE: The float16 "uses" 1e20 as mask, which overflows to inf
  3738. # and warns. Unrelated to this test, but probably undesired.
  3739. # But NumPy previously did not warn for this overflow.
  3740. am = np.ma.masked_where(a["A"] < 5, a)
  3741. assert_equal(am.mask.dtype.names, am.dtype.names)
  3742. assert_equal(am["A"],
  3743. np.ma.masked_array(np.zeros(10), np.ones(10)))
  3744. def test_masked_where_mismatch(self):
  3745. # gh-4520
  3746. x = np.arange(10)
  3747. y = np.arange(5)
  3748. assert_raises(IndexError, np.ma.masked_where, y > 6, x)
  3749. def test_masked_otherfunctions(self):
  3750. assert_equal(masked_inside(list(range(5)), 1, 3),
  3751. [0, 199, 199, 199, 4])
  3752. assert_equal(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199])
  3753. assert_equal(masked_inside(array(list(range(5)),
  3754. mask=[1, 0, 0, 0, 0]), 1, 3).mask,
  3755. [1, 1, 1, 1, 0])
  3756. assert_equal(masked_outside(array(list(range(5)),
  3757. mask=[0, 1, 0, 0, 0]), 1, 3).mask,
  3758. [1, 1, 0, 0, 1])
  3759. assert_equal(masked_equal(array(list(range(5)),
  3760. mask=[1, 0, 0, 0, 0]), 2).mask,
  3761. [1, 0, 1, 0, 0])
  3762. assert_equal(masked_not_equal(array([2, 2, 1, 2, 1],
  3763. mask=[1, 0, 0, 0, 0]), 2).mask,
  3764. [1, 0, 1, 0, 1])
  3765. def test_round(self):
  3766. a = array([1.23456, 2.34567, 3.45678, 4.56789, 5.67890],
  3767. mask=[0, 1, 0, 0, 0])
  3768. assert_equal(a.round(), [1., 2., 3., 5., 6.])
  3769. assert_equal(a.round(1), [1.2, 2.3, 3.5, 4.6, 5.7])
  3770. assert_equal(a.round(3), [1.235, 2.346, 3.457, 4.568, 5.679])
  3771. b = empty_like(a)
  3772. a.round(out=b)
  3773. assert_equal(b, [1., 2., 3., 5., 6.])
  3774. x = array([1., 2., 3., 4., 5.])
  3775. c = array([1, 1, 1, 0, 0])
  3776. x[2] = masked
  3777. z = where(c, x, -x)
  3778. assert_equal(z, [1., 2., 0., -4., -5])
  3779. c[0] = masked
  3780. z = where(c, x, -x)
  3781. assert_equal(z, [1., 2., 0., -4., -5])
  3782. assert_(z[0] is masked)
  3783. assert_(z[1] is not masked)
  3784. assert_(z[2] is masked)
  3785. def test_round_with_output(self):
  3786. # Testing round with an explicit output
  3787. xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4)
  3788. xm[:, 0] = xm[0] = xm[-1, -1] = masked
  3789. # A ndarray as explicit input
  3790. output = np.empty((3, 4), dtype=float)
  3791. output.fill(-9999)
  3792. result = np.round(xm, decimals=2, out=output)
  3793. # ... the result should be the given output
  3794. assert_(result is output)
  3795. assert_equal(result, xm.round(decimals=2, out=output))
  3796. output = empty((3, 4), dtype=float)
  3797. result = xm.round(decimals=2, out=output)
  3798. assert_(result is output)
  3799. def test_round_with_scalar(self):
  3800. # Testing round with scalar/zero dimension input
  3801. # GH issue 2244
  3802. a = array(1.1, mask=[False])
  3803. assert_equal(a.round(), 1)
  3804. a = array(1.1, mask=[True])
  3805. assert_(a.round() is masked)
  3806. a = array(1.1, mask=[False])
  3807. output = np.empty(1, dtype=float)
  3808. output.fill(-9999)
  3809. a.round(out=output)
  3810. assert_equal(output, 1)
  3811. a = array(1.1, mask=[False])
  3812. output = array(-9999., mask=[True])
  3813. a.round(out=output)
  3814. assert_equal(output[()], 1)
  3815. a = array(1.1, mask=[True])
  3816. output = array(-9999., mask=[False])
  3817. a.round(out=output)
  3818. assert_(output[()] is masked)
  3819. def test_identity(self):
  3820. a = identity(5)
  3821. assert_(isinstance(a, MaskedArray))
  3822. assert_equal(a, np.identity(5))
  3823. def test_power(self):
  3824. x = -1.1
  3825. assert_almost_equal(power(x, 2.), 1.21)
  3826. assert_(power(x, masked) is masked)
  3827. x = array([-1.1, -1.1, 1.1, 1.1, 0.])
  3828. b = array([0.5, 2., 0.5, 2., -1.], mask=[0, 0, 0, 0, 1])
  3829. y = power(x, b)
  3830. assert_almost_equal(y, [0, 1.21, 1.04880884817, 1.21, 0.])
  3831. assert_equal(y._mask, [1, 0, 0, 0, 1])
  3832. b.mask = nomask
  3833. y = power(x, b)
  3834. assert_equal(y._mask, [1, 0, 0, 0, 1])
  3835. z = x ** b
  3836. assert_equal(z._mask, y._mask)
  3837. assert_almost_equal(z, y)
  3838. assert_almost_equal(z._data, y._data)
  3839. x **= b
  3840. assert_equal(x._mask, y._mask)
  3841. assert_almost_equal(x, y)
  3842. assert_almost_equal(x._data, y._data)
  3843. def test_power_with_broadcasting(self):
  3844. # Test power w/ broadcasting
  3845. a2 = np.array([[1., 2., 3.], [4., 5., 6.]])
  3846. a2m = array(a2, mask=[[1, 0, 0], [0, 0, 1]])
  3847. b1 = np.array([2, 4, 3])
  3848. b2 = np.array([b1, b1])
  3849. b2m = array(b2, mask=[[0, 1, 0], [0, 1, 0]])
  3850. ctrl = array([[1 ** 2, 2 ** 4, 3 ** 3], [4 ** 2, 5 ** 4, 6 ** 3]],
  3851. mask=[[1, 1, 0], [0, 1, 1]])
  3852. # No broadcasting, base & exp w/ mask
  3853. test = a2m ** b2m
  3854. assert_equal(test, ctrl)
  3855. assert_equal(test.mask, ctrl.mask)
  3856. # No broadcasting, base w/ mask, exp w/o mask
  3857. test = a2m ** b2
  3858. assert_equal(test, ctrl)
  3859. assert_equal(test.mask, a2m.mask)
  3860. # No broadcasting, base w/o mask, exp w/ mask
  3861. test = a2 ** b2m
  3862. assert_equal(test, ctrl)
  3863. assert_equal(test.mask, b2m.mask)
  3864. ctrl = array([[2 ** 2, 4 ** 4, 3 ** 3], [2 ** 2, 4 ** 4, 3 ** 3]],
  3865. mask=[[0, 1, 0], [0, 1, 0]])
  3866. test = b1 ** b2m
  3867. assert_equal(test, ctrl)
  3868. assert_equal(test.mask, ctrl.mask)
  3869. test = b2m ** b1
  3870. assert_equal(test, ctrl)
  3871. assert_equal(test.mask, ctrl.mask)
  3872. @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
  3873. def test_where(self):
  3874. # Test the where function
  3875. x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
  3876. y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
  3877. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
  3878. m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
  3879. xm = masked_array(x, mask=m1)
  3880. ym = masked_array(y, mask=m2)
  3881. xm.set_fill_value(1e+20)
  3882. d = where(xm > 2, xm, -9)
  3883. assert_equal(d, [-9., -9., -9., -9., -9., 4.,
  3884. -9., -9., 10., -9., -9., 3.])
  3885. assert_equal(d._mask, xm._mask)
  3886. d = where(xm > 2, -9, ym)
  3887. assert_equal(d, [5., 0., 3., 2., -1., -9.,
  3888. -9., -10., -9., 1., 0., -9.])
  3889. assert_equal(d._mask, [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0])
  3890. d = where(xm > 2, xm, masked)
  3891. assert_equal(d, [-9., -9., -9., -9., -9., 4.,
  3892. -9., -9., 10., -9., -9., 3.])
  3893. tmp = xm._mask.copy()
  3894. tmp[(xm <= 2).filled(True)] = True
  3895. assert_equal(d._mask, tmp)
  3896. with np.errstate(invalid="warn"):
  3897. # The fill value is 1e20, it cannot be converted to `int`:
  3898. with pytest.warns(RuntimeWarning, match="invalid value"):
  3899. ixm = xm.astype(int)
  3900. d = where(ixm > 2, ixm, masked)
  3901. assert_equal(d, [-9, -9, -9, -9, -9, 4, -9, -9, 10, -9, -9, 3])
  3902. assert_equal(d.dtype, ixm.dtype)
  3903. def test_where_object(self):
  3904. a = np.array(None)
  3905. b = masked_array(None)
  3906. r = b.copy()
  3907. assert_equal(np.ma.where(True, a, a), r)
  3908. assert_equal(np.ma.where(True, b, b), r)
  3909. def test_where_with_masked_choice(self):
  3910. x = arange(10)
  3911. x[3] = masked
  3912. c = x >= 8
  3913. # Set False to masked
  3914. z = where(c, x, masked)
  3915. assert_(z.dtype is x.dtype)
  3916. assert_(z[3] is masked)
  3917. assert_(z[4] is masked)
  3918. assert_(z[7] is masked)
  3919. assert_(z[8] is not masked)
  3920. assert_(z[9] is not masked)
  3921. assert_equal(x, z)
  3922. # Set True to masked
  3923. z = where(c, masked, x)
  3924. assert_(z.dtype is x.dtype)
  3925. assert_(z[3] is masked)
  3926. assert_(z[4] is not masked)
  3927. assert_(z[7] is not masked)
  3928. assert_(z[8] is masked)
  3929. assert_(z[9] is masked)
  3930. def test_where_with_masked_condition(self):
  3931. x = array([1., 2., 3., 4., 5.])
  3932. c = array([1, 1, 1, 0, 0])
  3933. x[2] = masked
  3934. z = where(c, x, -x)
  3935. assert_equal(z, [1., 2., 0., -4., -5])
  3936. c[0] = masked
  3937. z = where(c, x, -x)
  3938. assert_equal(z, [1., 2., 0., -4., -5])
  3939. assert_(z[0] is masked)
  3940. assert_(z[1] is not masked)
  3941. assert_(z[2] is masked)
  3942. x = arange(1, 6)
  3943. x[-1] = masked
  3944. y = arange(1, 6) * 10
  3945. y[2] = masked
  3946. c = array([1, 1, 1, 0, 0], mask=[1, 0, 0, 0, 0])
  3947. cm = c.filled(1)
  3948. z = where(c, x, y)
  3949. zm = where(cm, x, y)
  3950. assert_equal(z, zm)
  3951. assert_(getmask(zm) is nomask)
  3952. assert_equal(zm, [1, 2, 3, 40, 50])
  3953. z = where(c, masked, 1)
  3954. assert_equal(z, [99, 99, 99, 1, 1])
  3955. z = where(c, 1, masked)
  3956. assert_equal(z, [99, 1, 1, 99, 99])
  3957. def test_where_type(self):
  3958. # Test the type conservation with where
  3959. x = np.arange(4, dtype=np.int32)
  3960. y = np.arange(4, dtype=np.float32) * 2.2
  3961. test = where(x > 1.5, y, x).dtype
  3962. control = np.find_common_type([np.int32, np.float32], [])
  3963. assert_equal(test, control)
  3964. def test_where_broadcast(self):
  3965. # Issue 8599
  3966. x = np.arange(9).reshape(3, 3)
  3967. y = np.zeros(3)
  3968. core = np.where([1, 0, 1], x, y)
  3969. ma = where([1, 0, 1], x, y)
  3970. assert_equal(core, ma)
  3971. assert_equal(core.dtype, ma.dtype)
  3972. def test_where_structured(self):
  3973. # Issue 8600
  3974. dt = np.dtype([('a', int), ('b', int)])
  3975. x = np.array([(1, 2), (3, 4), (5, 6)], dtype=dt)
  3976. y = np.array((10, 20), dtype=dt)
  3977. core = np.where([0, 1, 1], x, y)
  3978. ma = np.where([0, 1, 1], x, y)
  3979. assert_equal(core, ma)
  3980. assert_equal(core.dtype, ma.dtype)
  3981. def test_where_structured_masked(self):
  3982. dt = np.dtype([('a', int), ('b', int)])
  3983. x = np.array([(1, 2), (3, 4), (5, 6)], dtype=dt)
  3984. ma = where([0, 1, 1], x, masked)
  3985. expected = masked_where([1, 0, 0], x)
  3986. assert_equal(ma.dtype, expected.dtype)
  3987. assert_equal(ma, expected)
  3988. assert_equal(ma.mask, expected.mask)
  3989. def test_masked_invalid_error(self):
  3990. a = np.arange(5, dtype=object)
  3991. a[3] = np.PINF
  3992. a[2] = np.NaN
  3993. with pytest.raises(TypeError,
  3994. match="not supported for the input types"):
  3995. np.ma.masked_invalid(a)
  3996. def test_masked_invalid_pandas(self):
  3997. # getdata() used to be bad for pandas series due to its _data
  3998. # attribute. This test is a regression test mainly and may be
  3999. # removed if getdata() is adjusted.
  4000. class Series():
  4001. _data = "nonsense"
  4002. def __array__(self):
  4003. return np.array([5, np.nan, np.inf])
  4004. arr = np.ma.masked_invalid(Series())
  4005. assert_array_equal(arr._data, np.array(Series()))
  4006. assert_array_equal(arr._mask, [False, True, True])
  4007. @pytest.mark.parametrize("copy", [True, False])
  4008. def test_masked_invalid_full_mask(self, copy):
  4009. # Matplotlib relied on masked_invalid always returning a full mask
  4010. # (Also astropy projects, but were ok with it gh-22720 and gh-22842)
  4011. a = np.ma.array([1, 2, 3, 4])
  4012. assert a._mask is nomask
  4013. res = np.ma.masked_invalid(a, copy=copy)
  4014. assert res.mask is not nomask
  4015. # mask of a should not be mutated
  4016. assert a.mask is nomask
  4017. assert np.may_share_memory(a._data, res._data) != copy
  4018. def test_choose(self):
  4019. # Test choose
  4020. choices = [[0, 1, 2, 3], [10, 11, 12, 13],
  4021. [20, 21, 22, 23], [30, 31, 32, 33]]
  4022. chosen = choose([2, 3, 1, 0], choices)
  4023. assert_equal(chosen, array([20, 31, 12, 3]))
  4024. chosen = choose([2, 4, 1, 0], choices, mode='clip')
  4025. assert_equal(chosen, array([20, 31, 12, 3]))
  4026. chosen = choose([2, 4, 1, 0], choices, mode='wrap')
  4027. assert_equal(chosen, array([20, 1, 12, 3]))
  4028. # Check with some masked indices
  4029. indices_ = array([2, 4, 1, 0], mask=[1, 0, 0, 1])
  4030. chosen = choose(indices_, choices, mode='wrap')
  4031. assert_equal(chosen, array([99, 1, 12, 99]))
  4032. assert_equal(chosen.mask, [1, 0, 0, 1])
  4033. # Check with some masked choices
  4034. choices = array(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1],
  4035. [1, 0, 0, 0], [0, 0, 0, 0]])
  4036. indices_ = [2, 3, 1, 0]
  4037. chosen = choose(indices_, choices, mode='wrap')
  4038. assert_equal(chosen, array([20, 31, 12, 3]))
  4039. assert_equal(chosen.mask, [1, 0, 0, 1])
  4040. def test_choose_with_out(self):
  4041. # Test choose with an explicit out keyword
  4042. choices = [[0, 1, 2, 3], [10, 11, 12, 13],
  4043. [20, 21, 22, 23], [30, 31, 32, 33]]
  4044. store = empty(4, dtype=int)
  4045. chosen = choose([2, 3, 1, 0], choices, out=store)
  4046. assert_equal(store, array([20, 31, 12, 3]))
  4047. assert_(store is chosen)
  4048. # Check with some masked indices + out
  4049. store = empty(4, dtype=int)
  4050. indices_ = array([2, 3, 1, 0], mask=[1, 0, 0, 1])
  4051. chosen = choose(indices_, choices, mode='wrap', out=store)
  4052. assert_equal(store, array([99, 31, 12, 99]))
  4053. assert_equal(store.mask, [1, 0, 0, 1])
  4054. # Check with some masked choices + out ina ndarray !
  4055. choices = array(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1],
  4056. [1, 0, 0, 0], [0, 0, 0, 0]])
  4057. indices_ = [2, 3, 1, 0]
  4058. store = empty(4, dtype=int).view(ndarray)
  4059. chosen = choose(indices_, choices, mode='wrap', out=store)
  4060. assert_equal(store, array([999999, 31, 12, 999999]))
  4061. def test_reshape(self):
  4062. a = arange(10)
  4063. a[0] = masked
  4064. # Try the default
  4065. b = a.reshape((5, 2))
  4066. assert_equal(b.shape, (5, 2))
  4067. assert_(b.flags['C'])
  4068. # Try w/ arguments as list instead of tuple
  4069. b = a.reshape(5, 2)
  4070. assert_equal(b.shape, (5, 2))
  4071. assert_(b.flags['C'])
  4072. # Try w/ order
  4073. b = a.reshape((5, 2), order='F')
  4074. assert_equal(b.shape, (5, 2))
  4075. assert_(b.flags['F'])
  4076. # Try w/ order
  4077. b = a.reshape(5, 2, order='F')
  4078. assert_equal(b.shape, (5, 2))
  4079. assert_(b.flags['F'])
  4080. c = np.reshape(a, (2, 5))
  4081. assert_(isinstance(c, MaskedArray))
  4082. assert_equal(c.shape, (2, 5))
  4083. assert_(c[0, 0] is masked)
  4084. assert_(c.flags['C'])
  4085. def test_make_mask_descr(self):
  4086. # Flexible
  4087. ntype = [('a', float), ('b', float)]
  4088. test = make_mask_descr(ntype)
  4089. assert_equal(test, [('a', bool), ('b', bool)])
  4090. assert_(test is make_mask_descr(test))
  4091. # Standard w/ shape
  4092. ntype = (float, 2)
  4093. test = make_mask_descr(ntype)
  4094. assert_equal(test, (bool, 2))
  4095. assert_(test is make_mask_descr(test))
  4096. # Standard standard
  4097. ntype = float
  4098. test = make_mask_descr(ntype)
  4099. assert_equal(test, np.dtype(bool))
  4100. assert_(test is make_mask_descr(test))
  4101. # Nested
  4102. ntype = [('a', float), ('b', [('ba', float), ('bb', float)])]
  4103. test = make_mask_descr(ntype)
  4104. control = np.dtype([('a', 'b1'), ('b', [('ba', 'b1'), ('bb', 'b1')])])
  4105. assert_equal(test, control)
  4106. assert_(test is make_mask_descr(test))
  4107. # Named+ shape
  4108. ntype = [('a', (float, 2))]
  4109. test = make_mask_descr(ntype)
  4110. assert_equal(test, np.dtype([('a', (bool, 2))]))
  4111. assert_(test is make_mask_descr(test))
  4112. # 2 names
  4113. ntype = [(('A', 'a'), float)]
  4114. test = make_mask_descr(ntype)
  4115. assert_equal(test, np.dtype([(('A', 'a'), bool)]))
  4116. assert_(test is make_mask_descr(test))
  4117. # nested boolean types should preserve identity
  4118. base_type = np.dtype([('a', int, 3)])
  4119. base_mtype = make_mask_descr(base_type)
  4120. sub_type = np.dtype([('a', int), ('b', base_mtype)])
  4121. test = make_mask_descr(sub_type)
  4122. assert_equal(test, np.dtype([('a', bool), ('b', [('a', bool, 3)])]))
  4123. assert_(test.fields['b'][0] is base_mtype)
  4124. def test_make_mask(self):
  4125. # Test make_mask
  4126. # w/ a list as an input
  4127. mask = [0, 1]
  4128. test = make_mask(mask)
  4129. assert_equal(test.dtype, MaskType)
  4130. assert_equal(test, [0, 1])
  4131. # w/ a ndarray as an input
  4132. mask = np.array([0, 1], dtype=bool)
  4133. test = make_mask(mask)
  4134. assert_equal(test.dtype, MaskType)
  4135. assert_equal(test, [0, 1])
  4136. # w/ a flexible-type ndarray as an input - use default
  4137. mdtype = [('a', bool), ('b', bool)]
  4138. mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
  4139. test = make_mask(mask)
  4140. assert_equal(test.dtype, MaskType)
  4141. assert_equal(test, [1, 1])
  4142. # w/ a flexible-type ndarray as an input - use input dtype
  4143. mdtype = [('a', bool), ('b', bool)]
  4144. mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
  4145. test = make_mask(mask, dtype=mask.dtype)
  4146. assert_equal(test.dtype, mdtype)
  4147. assert_equal(test, mask)
  4148. # w/ a flexible-type ndarray as an input - use input dtype
  4149. mdtype = [('a', float), ('b', float)]
  4150. bdtype = [('a', bool), ('b', bool)]
  4151. mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
  4152. test = make_mask(mask, dtype=mask.dtype)
  4153. assert_equal(test.dtype, bdtype)
  4154. assert_equal(test, np.array([(0, 0), (0, 1)], dtype=bdtype))
  4155. # Ensure this also works for void
  4156. mask = np.array((False, True), dtype='?,?')[()]
  4157. assert_(isinstance(mask, np.void))
  4158. test = make_mask(mask, dtype=mask.dtype)
  4159. assert_equal(test, mask)
  4160. assert_(test is not mask)
  4161. mask = np.array((0, 1), dtype='i4,i4')[()]
  4162. test2 = make_mask(mask, dtype=mask.dtype)
  4163. assert_equal(test2, test)
  4164. # test that nomask is returned when m is nomask.
  4165. bools = [True, False]
  4166. dtypes = [MaskType, float]
  4167. msgformat = 'copy=%s, shrink=%s, dtype=%s'
  4168. for cpy, shr, dt in itertools.product(bools, bools, dtypes):
  4169. res = make_mask(nomask, copy=cpy, shrink=shr, dtype=dt)
  4170. assert_(res is nomask, msgformat % (cpy, shr, dt))
  4171. def test_mask_or(self):
  4172. # Initialize
  4173. mtype = [('a', bool), ('b', bool)]
  4174. mask = np.array([(0, 0), (0, 1), (1, 0), (0, 0)], dtype=mtype)
  4175. # Test using nomask as input
  4176. test = mask_or(mask, nomask)
  4177. assert_equal(test, mask)
  4178. test = mask_or(nomask, mask)
  4179. assert_equal(test, mask)
  4180. # Using False as input
  4181. test = mask_or(mask, False)
  4182. assert_equal(test, mask)
  4183. # Using another array w / the same dtype
  4184. other = np.array([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=mtype)
  4185. test = mask_or(mask, other)
  4186. control = np.array([(0, 1), (0, 1), (1, 1), (0, 1)], dtype=mtype)
  4187. assert_equal(test, control)
  4188. # Using another array w / a different dtype
  4189. othertype = [('A', bool), ('B', bool)]
  4190. other = np.array([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=othertype)
  4191. try:
  4192. test = mask_or(mask, other)
  4193. except ValueError:
  4194. pass
  4195. # Using nested arrays
  4196. dtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
  4197. amask = np.array([(0, (1, 0)), (0, (1, 0))], dtype=dtype)
  4198. bmask = np.array([(1, (0, 1)), (0, (0, 0))], dtype=dtype)
  4199. cntrl = np.array([(1, (1, 1)), (0, (1, 0))], dtype=dtype)
  4200. assert_equal(mask_or(amask, bmask), cntrl)
  4201. def test_flatten_mask(self):
  4202. # Tests flatten mask
  4203. # Standard dtype
  4204. mask = np.array([0, 0, 1], dtype=bool)
  4205. assert_equal(flatten_mask(mask), mask)
  4206. # Flexible dtype
  4207. mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
  4208. test = flatten_mask(mask)
  4209. control = np.array([0, 0, 0, 1], dtype=bool)
  4210. assert_equal(test, control)
  4211. mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
  4212. data = [(0, (0, 0)), (0, (0, 1))]
  4213. mask = np.array(data, dtype=mdtype)
  4214. test = flatten_mask(mask)
  4215. control = np.array([0, 0, 0, 0, 0, 1], dtype=bool)
  4216. assert_equal(test, control)
  4217. def test_on_ndarray(self):
  4218. # Test functions on ndarrays
  4219. a = np.array([1, 2, 3, 4])
  4220. m = array(a, mask=False)
  4221. test = anom(a)
  4222. assert_equal(test, m.anom())
  4223. test = reshape(a, (2, 2))
  4224. assert_equal(test, m.reshape(2, 2))
  4225. def test_compress(self):
  4226. # Test compress function on ndarray and masked array
  4227. # Address Github #2495.
  4228. arr = np.arange(8)
  4229. arr.shape = 4, 2
  4230. cond = np.array([True, False, True, True])
  4231. control = arr[[0, 2, 3]]
  4232. test = np.ma.compress(cond, arr, axis=0)
  4233. assert_equal(test, control)
  4234. marr = np.ma.array(arr)
  4235. test = np.ma.compress(cond, marr, axis=0)
  4236. assert_equal(test, control)
  4237. def test_compressed(self):
  4238. # Test ma.compressed function.
  4239. # Address gh-4026
  4240. a = np.ma.array([1, 2])
  4241. test = np.ma.compressed(a)
  4242. assert_(type(test) is np.ndarray)
  4243. # Test case when input data is ndarray subclass
  4244. class A(np.ndarray):
  4245. pass
  4246. a = np.ma.array(A(shape=0))
  4247. test = np.ma.compressed(a)
  4248. assert_(type(test) is A)
  4249. # Test that compress flattens
  4250. test = np.ma.compressed([[1],[2]])
  4251. assert_equal(test.ndim, 1)
  4252. test = np.ma.compressed([[[[[1]]]]])
  4253. assert_equal(test.ndim, 1)
  4254. # Test case when input is MaskedArray subclass
  4255. class M(MaskedArray):
  4256. pass
  4257. test = np.ma.compressed(M([[[]], [[]]]))
  4258. assert_equal(test.ndim, 1)
  4259. # with .compressed() overridden
  4260. class M(MaskedArray):
  4261. def compressed(self):
  4262. return 42
  4263. test = np.ma.compressed(M([[[]], [[]]]))
  4264. assert_equal(test, 42)
  4265. def test_convolve(self):
  4266. a = masked_equal(np.arange(5), 2)
  4267. b = np.array([1, 1])
  4268. test = np.ma.convolve(a, b)
  4269. assert_equal(test, masked_equal([0, 1, -1, -1, 7, 4], -1))
  4270. test = np.ma.convolve(a, b, propagate_mask=False)
  4271. assert_equal(test, masked_equal([0, 1, 1, 3, 7, 4], -1))
  4272. test = np.ma.convolve([1, 1], [1, 1, 1])
  4273. assert_equal(test, masked_equal([1, 2, 2, 1], -1))
  4274. a = [1, 1]
  4275. b = masked_equal([1, -1, -1, 1], -1)
  4276. test = np.ma.convolve(a, b, propagate_mask=False)
  4277. assert_equal(test, masked_equal([1, 1, -1, 1, 1], -1))
  4278. test = np.ma.convolve(a, b, propagate_mask=True)
  4279. assert_equal(test, masked_equal([-1, -1, -1, -1, -1], -1))
  4280. class TestMaskedFields:
  4281. def setup_method(self):
  4282. ilist = [1, 2, 3, 4, 5]
  4283. flist = [1.1, 2.2, 3.3, 4.4, 5.5]
  4284. slist = ['one', 'two', 'three', 'four', 'five']
  4285. ddtype = [('a', int), ('b', float), ('c', '|S8')]
  4286. mdtype = [('a', bool), ('b', bool), ('c', bool)]
  4287. mask = [0, 1, 0, 0, 1]
  4288. base = array(list(zip(ilist, flist, slist)), mask=mask, dtype=ddtype)
  4289. self.data = dict(base=base, mask=mask, ddtype=ddtype, mdtype=mdtype)
  4290. def test_set_records_masks(self):
  4291. base = self.data['base']
  4292. mdtype = self.data['mdtype']
  4293. # Set w/ nomask or masked
  4294. base.mask = nomask
  4295. assert_equal_records(base._mask, np.zeros(base.shape, dtype=mdtype))
  4296. base.mask = masked
  4297. assert_equal_records(base._mask, np.ones(base.shape, dtype=mdtype))
  4298. # Set w/ simple boolean
  4299. base.mask = False
  4300. assert_equal_records(base._mask, np.zeros(base.shape, dtype=mdtype))
  4301. base.mask = True
  4302. assert_equal_records(base._mask, np.ones(base.shape, dtype=mdtype))
  4303. # Set w/ list
  4304. base.mask = [0, 0, 0, 1, 1]
  4305. assert_equal_records(base._mask,
  4306. np.array([(x, x, x) for x in [0, 0, 0, 1, 1]],
  4307. dtype=mdtype))
  4308. def test_set_record_element(self):
  4309. # Check setting an element of a record)
  4310. base = self.data['base']
  4311. (base_a, base_b, base_c) = (base['a'], base['b'], base['c'])
  4312. base[0] = (pi, pi, 'pi')
  4313. assert_equal(base_a.dtype, int)
  4314. assert_equal(base_a._data, [3, 2, 3, 4, 5])
  4315. assert_equal(base_b.dtype, float)
  4316. assert_equal(base_b._data, [pi, 2.2, 3.3, 4.4, 5.5])
  4317. assert_equal(base_c.dtype, '|S8')
  4318. assert_equal(base_c._data,
  4319. [b'pi', b'two', b'three', b'four', b'five'])
  4320. def test_set_record_slice(self):
  4321. base = self.data['base']
  4322. (base_a, base_b, base_c) = (base['a'], base['b'], base['c'])
  4323. base[:3] = (pi, pi, 'pi')
  4324. assert_equal(base_a.dtype, int)
  4325. assert_equal(base_a._data, [3, 3, 3, 4, 5])
  4326. assert_equal(base_b.dtype, float)
  4327. assert_equal(base_b._data, [pi, pi, pi, 4.4, 5.5])
  4328. assert_equal(base_c.dtype, '|S8')
  4329. assert_equal(base_c._data,
  4330. [b'pi', b'pi', b'pi', b'four', b'five'])
  4331. def test_mask_element(self):
  4332. "Check record access"
  4333. base = self.data['base']
  4334. base[0] = masked
  4335. for n in ('a', 'b', 'c'):
  4336. assert_equal(base[n].mask, [1, 1, 0, 0, 1])
  4337. assert_equal(base[n]._data, base._data[n])
  4338. def test_getmaskarray(self):
  4339. # Test getmaskarray on flexible dtype
  4340. ndtype = [('a', int), ('b', float)]
  4341. test = empty(3, dtype=ndtype)
  4342. assert_equal(getmaskarray(test),
  4343. np.array([(0, 0), (0, 0), (0, 0)],
  4344. dtype=[('a', '|b1'), ('b', '|b1')]))
  4345. test[:] = masked
  4346. assert_equal(getmaskarray(test),
  4347. np.array([(1, 1), (1, 1), (1, 1)],
  4348. dtype=[('a', '|b1'), ('b', '|b1')]))
  4349. def test_view(self):
  4350. # Test view w/ flexible dtype
  4351. iterator = list(zip(np.arange(10), np.random.rand(10)))
  4352. data = np.array(iterator)
  4353. a = array(iterator, dtype=[('a', float), ('b', float)])
  4354. a.mask[0] = (1, 0)
  4355. controlmask = np.array([1] + 19 * [0], dtype=bool)
  4356. # Transform globally to simple dtype
  4357. test = a.view(float)
  4358. assert_equal(test, data.ravel())
  4359. assert_equal(test.mask, controlmask)
  4360. # Transform globally to dty
  4361. test = a.view((float, 2))
  4362. assert_equal(test, data)
  4363. assert_equal(test.mask, controlmask.reshape(-1, 2))
  4364. def test_getitem(self):
  4365. ndtype = [('a', float), ('b', float)]
  4366. a = array(list(zip(np.random.rand(10), np.arange(10))), dtype=ndtype)
  4367. a.mask = np.array(list(zip([0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
  4368. [1, 0, 0, 0, 0, 0, 0, 0, 1, 0])),
  4369. dtype=[('a', bool), ('b', bool)])
  4370. def _test_index(i):
  4371. assert_equal(type(a[i]), mvoid)
  4372. assert_equal_records(a[i]._data, a._data[i])
  4373. assert_equal_records(a[i]._mask, a._mask[i])
  4374. assert_equal(type(a[i, ...]), MaskedArray)
  4375. assert_equal_records(a[i,...]._data, a._data[i,...])
  4376. assert_equal_records(a[i,...]._mask, a._mask[i,...])
  4377. _test_index(1) # No mask
  4378. _test_index(0) # One element masked
  4379. _test_index(-2) # All element masked
  4380. def test_setitem(self):
  4381. # Issue 4866: check that one can set individual items in [record][col]
  4382. # and [col][record] order
  4383. ndtype = np.dtype([('a', float), ('b', int)])
  4384. ma = np.ma.MaskedArray([(1.0, 1), (2.0, 2)], dtype=ndtype)
  4385. ma['a'][1] = 3.0
  4386. assert_equal(ma['a'], np.array([1.0, 3.0]))
  4387. ma[1]['a'] = 4.0
  4388. assert_equal(ma['a'], np.array([1.0, 4.0]))
  4389. # Issue 2403
  4390. mdtype = np.dtype([('a', bool), ('b', bool)])
  4391. # soft mask
  4392. control = np.array([(False, True), (True, True)], dtype=mdtype)
  4393. a = np.ma.masked_all((2,), dtype=ndtype)
  4394. a['a'][0] = 2
  4395. assert_equal(a.mask, control)
  4396. a = np.ma.masked_all((2,), dtype=ndtype)
  4397. a[0]['a'] = 2
  4398. assert_equal(a.mask, control)
  4399. # hard mask
  4400. control = np.array([(True, True), (True, True)], dtype=mdtype)
  4401. a = np.ma.masked_all((2,), dtype=ndtype)
  4402. a.harden_mask()
  4403. a['a'][0] = 2
  4404. assert_equal(a.mask, control)
  4405. a = np.ma.masked_all((2,), dtype=ndtype)
  4406. a.harden_mask()
  4407. a[0]['a'] = 2
  4408. assert_equal(a.mask, control)
  4409. def test_setitem_scalar(self):
  4410. # 8510
  4411. mask_0d = np.ma.masked_array(1, mask=True)
  4412. arr = np.ma.arange(3)
  4413. arr[0] = mask_0d
  4414. assert_array_equal(arr.mask, [True, False, False])
  4415. def test_element_len(self):
  4416. # check that len() works for mvoid (Github issue #576)
  4417. for rec in self.data['base']:
  4418. assert_equal(len(rec), len(self.data['ddtype']))
  4419. class TestMaskedObjectArray:
  4420. def test_getitem(self):
  4421. arr = np.ma.array([None, None])
  4422. for dt in [float, object]:
  4423. a0 = np.eye(2).astype(dt)
  4424. a1 = np.eye(3).astype(dt)
  4425. arr[0] = a0
  4426. arr[1] = a1
  4427. assert_(arr[0] is a0)
  4428. assert_(arr[1] is a1)
  4429. assert_(isinstance(arr[0,...], MaskedArray))
  4430. assert_(isinstance(arr[1,...], MaskedArray))
  4431. assert_(arr[0,...][()] is a0)
  4432. assert_(arr[1,...][()] is a1)
  4433. arr[0] = np.ma.masked
  4434. assert_(arr[1] is a1)
  4435. assert_(isinstance(arr[0,...], MaskedArray))
  4436. assert_(isinstance(arr[1,...], MaskedArray))
  4437. assert_equal(arr[0,...].mask, True)
  4438. assert_(arr[1,...][()] is a1)
  4439. # gh-5962 - object arrays of arrays do something special
  4440. assert_equal(arr[0].data, a0)
  4441. assert_equal(arr[0].mask, True)
  4442. assert_equal(arr[0,...][()].data, a0)
  4443. assert_equal(arr[0,...][()].mask, True)
  4444. def test_nested_ma(self):
  4445. arr = np.ma.array([None, None])
  4446. # set the first object to be an unmasked masked constant. A little fiddly
  4447. arr[0,...] = np.array([np.ma.masked], object)[0,...]
  4448. # check the above line did what we were aiming for
  4449. assert_(arr.data[0] is np.ma.masked)
  4450. # test that getitem returned the value by identity
  4451. assert_(arr[0] is np.ma.masked)
  4452. # now mask the masked value!
  4453. arr[0] = np.ma.masked
  4454. assert_(arr[0] is np.ma.masked)
  4455. class TestMaskedView:
  4456. def setup_method(self):
  4457. iterator = list(zip(np.arange(10), np.random.rand(10)))
  4458. data = np.array(iterator)
  4459. a = array(iterator, dtype=[('a', float), ('b', float)])
  4460. a.mask[0] = (1, 0)
  4461. controlmask = np.array([1] + 19 * [0], dtype=bool)
  4462. self.data = (data, a, controlmask)
  4463. def test_view_to_nothing(self):
  4464. (data, a, controlmask) = self.data
  4465. test = a.view()
  4466. assert_(isinstance(test, MaskedArray))
  4467. assert_equal(test._data, a._data)
  4468. assert_equal(test._mask, a._mask)
  4469. def test_view_to_type(self):
  4470. (data, a, controlmask) = self.data
  4471. test = a.view(np.ndarray)
  4472. assert_(not isinstance(test, MaskedArray))
  4473. assert_equal(test, a._data)
  4474. assert_equal_records(test, data.view(a.dtype).squeeze())
  4475. def test_view_to_simple_dtype(self):
  4476. (data, a, controlmask) = self.data
  4477. # View globally
  4478. test = a.view(float)
  4479. assert_(isinstance(test, MaskedArray))
  4480. assert_equal(test, data.ravel())
  4481. assert_equal(test.mask, controlmask)
  4482. def test_view_to_flexible_dtype(self):
  4483. (data, a, controlmask) = self.data
  4484. test = a.view([('A', float), ('B', float)])
  4485. assert_equal(test.mask.dtype.names, ('A', 'B'))
  4486. assert_equal(test['A'], a['a'])
  4487. assert_equal(test['B'], a['b'])
  4488. test = a[0].view([('A', float), ('B', float)])
  4489. assert_(isinstance(test, MaskedArray))
  4490. assert_equal(test.mask.dtype.names, ('A', 'B'))
  4491. assert_equal(test['A'], a['a'][0])
  4492. assert_equal(test['B'], a['b'][0])
  4493. test = a[-1].view([('A', float), ('B', float)])
  4494. assert_(isinstance(test, MaskedArray))
  4495. assert_equal(test.dtype.names, ('A', 'B'))
  4496. assert_equal(test['A'], a['a'][-1])
  4497. assert_equal(test['B'], a['b'][-1])
  4498. def test_view_to_subdtype(self):
  4499. (data, a, controlmask) = self.data
  4500. # View globally
  4501. test = a.view((float, 2))
  4502. assert_(isinstance(test, MaskedArray))
  4503. assert_equal(test, data)
  4504. assert_equal(test.mask, controlmask.reshape(-1, 2))
  4505. # View on 1 masked element
  4506. test = a[0].view((float, 2))
  4507. assert_(isinstance(test, MaskedArray))
  4508. assert_equal(test, data[0])
  4509. assert_equal(test.mask, (1, 0))
  4510. # View on 1 unmasked element
  4511. test = a[-1].view((float, 2))
  4512. assert_(isinstance(test, MaskedArray))
  4513. assert_equal(test, data[-1])
  4514. def test_view_to_dtype_and_type(self):
  4515. (data, a, controlmask) = self.data
  4516. test = a.view((float, 2), np.recarray)
  4517. assert_equal(test, data)
  4518. assert_(isinstance(test, np.recarray))
  4519. assert_(not isinstance(test, MaskedArray))
  4520. class TestOptionalArgs:
  4521. def test_ndarrayfuncs(self):
  4522. # test axis arg behaves the same as ndarray (including multiple axes)
  4523. d = np.arange(24.0).reshape((2,3,4))
  4524. m = np.zeros(24, dtype=bool).reshape((2,3,4))
  4525. # mask out last element of last dimension
  4526. m[:,:,-1] = True
  4527. a = np.ma.array(d, mask=m)
  4528. def testaxis(f, a, d):
  4529. numpy_f = numpy.__getattribute__(f)
  4530. ma_f = np.ma.__getattribute__(f)
  4531. # test axis arg
  4532. assert_equal(ma_f(a, axis=1)[...,:-1], numpy_f(d[...,:-1], axis=1))
  4533. assert_equal(ma_f(a, axis=(0,1))[...,:-1],
  4534. numpy_f(d[...,:-1], axis=(0,1)))
  4535. def testkeepdims(f, a, d):
  4536. numpy_f = numpy.__getattribute__(f)
  4537. ma_f = np.ma.__getattribute__(f)
  4538. # test keepdims arg
  4539. assert_equal(ma_f(a, keepdims=True).shape,
  4540. numpy_f(d, keepdims=True).shape)
  4541. assert_equal(ma_f(a, keepdims=False).shape,
  4542. numpy_f(d, keepdims=False).shape)
  4543. # test both at once
  4544. assert_equal(ma_f(a, axis=1, keepdims=True)[...,:-1],
  4545. numpy_f(d[...,:-1], axis=1, keepdims=True))
  4546. assert_equal(ma_f(a, axis=(0,1), keepdims=True)[...,:-1],
  4547. numpy_f(d[...,:-1], axis=(0,1), keepdims=True))
  4548. for f in ['sum', 'prod', 'mean', 'var', 'std']:
  4549. testaxis(f, a, d)
  4550. testkeepdims(f, a, d)
  4551. for f in ['min', 'max']:
  4552. testaxis(f, a, d)
  4553. d = (np.arange(24).reshape((2,3,4))%2 == 0)
  4554. a = np.ma.array(d, mask=m)
  4555. for f in ['all', 'any']:
  4556. testaxis(f, a, d)
  4557. testkeepdims(f, a, d)
  4558. def test_count(self):
  4559. # test np.ma.count specially
  4560. d = np.arange(24.0).reshape((2,3,4))
  4561. m = np.zeros(24, dtype=bool).reshape((2,3,4))
  4562. m[:,0,:] = True
  4563. a = np.ma.array(d, mask=m)
  4564. assert_equal(count(a), 16)
  4565. assert_equal(count(a, axis=1), 2*ones((2,4)))
  4566. assert_equal(count(a, axis=(0,1)), 4*ones((4,)))
  4567. assert_equal(count(a, keepdims=True), 16*ones((1,1,1)))
  4568. assert_equal(count(a, axis=1, keepdims=True), 2*ones((2,1,4)))
  4569. assert_equal(count(a, axis=(0,1), keepdims=True), 4*ones((1,1,4)))
  4570. assert_equal(count(a, axis=-2), 2*ones((2,4)))
  4571. assert_raises(ValueError, count, a, axis=(1,1))
  4572. assert_raises(np.AxisError, count, a, axis=3)
  4573. # check the 'nomask' path
  4574. a = np.ma.array(d, mask=nomask)
  4575. assert_equal(count(a), 24)
  4576. assert_equal(count(a, axis=1), 3*ones((2,4)))
  4577. assert_equal(count(a, axis=(0,1)), 6*ones((4,)))
  4578. assert_equal(count(a, keepdims=True), 24*ones((1,1,1)))
  4579. assert_equal(np.ndim(count(a, keepdims=True)), 3)
  4580. assert_equal(count(a, axis=1, keepdims=True), 3*ones((2,1,4)))
  4581. assert_equal(count(a, axis=(0,1), keepdims=True), 6*ones((1,1,4)))
  4582. assert_equal(count(a, axis=-2), 3*ones((2,4)))
  4583. assert_raises(ValueError, count, a, axis=(1,1))
  4584. assert_raises(np.AxisError, count, a, axis=3)
  4585. # check the 'masked' singleton
  4586. assert_equal(count(np.ma.masked), 0)
  4587. # check 0-d arrays do not allow axis > 0
  4588. assert_raises(np.AxisError, count, np.ma.array(1), axis=1)
  4589. class TestMaskedConstant:
  4590. def _do_add_test(self, add):
  4591. # sanity check
  4592. assert_(add(np.ma.masked, 1) is np.ma.masked)
  4593. # now try with a vector
  4594. vector = np.array([1, 2, 3])
  4595. result = add(np.ma.masked, vector)
  4596. # lots of things could go wrong here
  4597. assert_(result is not np.ma.masked)
  4598. assert_(not isinstance(result, np.ma.core.MaskedConstant))
  4599. assert_equal(result.shape, vector.shape)
  4600. assert_equal(np.ma.getmask(result), np.ones(vector.shape, dtype=bool))
  4601. def test_ufunc(self):
  4602. self._do_add_test(np.add)
  4603. def test_operator(self):
  4604. self._do_add_test(lambda a, b: a + b)
  4605. def test_ctor(self):
  4606. m = np.ma.array(np.ma.masked)
  4607. # most importantly, we do not want to create a new MaskedConstant
  4608. # instance
  4609. assert_(not isinstance(m, np.ma.core.MaskedConstant))
  4610. assert_(m is not np.ma.masked)
  4611. def test_repr(self):
  4612. # copies should not exist, but if they do, it should be obvious that
  4613. # something is wrong
  4614. assert_equal(repr(np.ma.masked), 'masked')
  4615. # create a new instance in a weird way
  4616. masked2 = np.ma.MaskedArray.__new__(np.ma.core.MaskedConstant)
  4617. assert_not_equal(repr(masked2), 'masked')
  4618. def test_pickle(self):
  4619. from io import BytesIO
  4620. for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
  4621. with BytesIO() as f:
  4622. pickle.dump(np.ma.masked, f, protocol=proto)
  4623. f.seek(0)
  4624. res = pickle.load(f)
  4625. assert_(res is np.ma.masked)
  4626. def test_copy(self):
  4627. # gh-9328
  4628. # copy is a no-op, like it is with np.True_
  4629. assert_equal(
  4630. np.ma.masked.copy() is np.ma.masked,
  4631. np.True_.copy() is np.True_)
  4632. def test__copy(self):
  4633. import copy
  4634. assert_(
  4635. copy.copy(np.ma.masked) is np.ma.masked)
  4636. def test_deepcopy(self):
  4637. import copy
  4638. assert_(
  4639. copy.deepcopy(np.ma.masked) is np.ma.masked)
  4640. def test_immutable(self):
  4641. orig = np.ma.masked
  4642. assert_raises(np.ma.core.MaskError, operator.setitem, orig, (), 1)
  4643. assert_raises(ValueError,operator.setitem, orig.data, (), 1)
  4644. assert_raises(ValueError, operator.setitem, orig.mask, (), False)
  4645. view = np.ma.masked.view(np.ma.MaskedArray)
  4646. assert_raises(ValueError, operator.setitem, view, (), 1)
  4647. assert_raises(ValueError, operator.setitem, view.data, (), 1)
  4648. assert_raises(ValueError, operator.setitem, view.mask, (), False)
  4649. def test_coercion_int(self):
  4650. a_i = np.zeros((), int)
  4651. assert_raises(MaskError, operator.setitem, a_i, (), np.ma.masked)
  4652. assert_raises(MaskError, int, np.ma.masked)
  4653. def test_coercion_float(self):
  4654. a_f = np.zeros((), float)
  4655. assert_warns(UserWarning, operator.setitem, a_f, (), np.ma.masked)
  4656. assert_(np.isnan(a_f[()]))
  4657. @pytest.mark.xfail(reason="See gh-9750")
  4658. def test_coercion_unicode(self):
  4659. a_u = np.zeros((), 'U10')
  4660. a_u[()] = np.ma.masked
  4661. assert_equal(a_u[()], '--')
  4662. @pytest.mark.xfail(reason="See gh-9750")
  4663. def test_coercion_bytes(self):
  4664. a_b = np.zeros((), 'S10')
  4665. a_b[()] = np.ma.masked
  4666. assert_equal(a_b[()], b'--')
  4667. def test_subclass(self):
  4668. # https://github.com/astropy/astropy/issues/6645
  4669. class Sub(type(np.ma.masked)): pass
  4670. a = Sub()
  4671. assert_(a is Sub())
  4672. assert_(a is not np.ma.masked)
  4673. assert_not_equal(repr(a), 'masked')
  4674. def test_attributes_readonly(self):
  4675. assert_raises(AttributeError, setattr, np.ma.masked, 'shape', (1,))
  4676. assert_raises(AttributeError, setattr, np.ma.masked, 'dtype', np.int64)
  4677. class TestMaskedWhereAliases:
  4678. # TODO: Test masked_object, masked_equal, ...
  4679. def test_masked_values(self):
  4680. res = masked_values(np.array([-32768.0]), np.int16(-32768))
  4681. assert_equal(res.mask, [True])
  4682. res = masked_values(np.inf, np.inf)
  4683. assert_equal(res.mask, True)
  4684. res = np.ma.masked_values(np.inf, -np.inf)
  4685. assert_equal(res.mask, False)
  4686. res = np.ma.masked_values([1, 2, 3, 4], 5, shrink=True)
  4687. assert_(res.mask is np.ma.nomask)
  4688. res = np.ma.masked_values([1, 2, 3, 4], 5, shrink=False)
  4689. assert_equal(res.mask, [False] * 4)
  4690. def test_masked_array():
  4691. a = np.ma.array([0, 1, 2, 3], mask=[0, 0, 1, 0])
  4692. assert_equal(np.argwhere(a), [[1], [3]])
  4693. def test_masked_array_no_copy():
  4694. # check nomask array is updated in place
  4695. a = np.ma.array([1, 2, 3, 4])
  4696. _ = np.ma.masked_where(a == 3, a, copy=False)
  4697. assert_array_equal(a.mask, [False, False, True, False])
  4698. # check masked array is updated in place
  4699. a = np.ma.array([1, 2, 3, 4], mask=[1, 0, 0, 0])
  4700. _ = np.ma.masked_where(a == 3, a, copy=False)
  4701. assert_array_equal(a.mask, [True, False, True, False])
  4702. # check masked array with masked_invalid is updated in place
  4703. a = np.ma.array([np.inf, 1, 2, 3, 4])
  4704. _ = np.ma.masked_invalid(a, copy=False)
  4705. assert_array_equal(a.mask, [True, False, False, False, False])
  4706. def test_append_masked_array():
  4707. a = np.ma.masked_equal([1,2,3], value=2)
  4708. b = np.ma.masked_equal([4,3,2], value=2)
  4709. result = np.ma.append(a, b)
  4710. expected_data = [1, 2, 3, 4, 3, 2]
  4711. expected_mask = [False, True, False, False, False, True]
  4712. assert_array_equal(result.data, expected_data)
  4713. assert_array_equal(result.mask, expected_mask)
  4714. a = np.ma.masked_all((2,2))
  4715. b = np.ma.ones((3,1))
  4716. result = np.ma.append(a, b)
  4717. expected_data = [1] * 3
  4718. expected_mask = [True] * 4 + [False] * 3
  4719. assert_array_equal(result.data[-3], expected_data)
  4720. assert_array_equal(result.mask, expected_mask)
  4721. result = np.ma.append(a, b, axis=None)
  4722. assert_array_equal(result.data[-3], expected_data)
  4723. assert_array_equal(result.mask, expected_mask)
  4724. def test_append_masked_array_along_axis():
  4725. a = np.ma.masked_equal([1,2,3], value=2)
  4726. b = np.ma.masked_values([[4, 5, 6], [7, 8, 9]], 7)
  4727. # When `axis` is specified, `values` must have the correct shape.
  4728. assert_raises(ValueError, np.ma.append, a, b, axis=0)
  4729. result = np.ma.append(a[np.newaxis,:], b, axis=0)
  4730. expected = np.ma.arange(1, 10)
  4731. expected[[1, 6]] = np.ma.masked
  4732. expected = expected.reshape((3,3))
  4733. assert_array_equal(result.data, expected.data)
  4734. assert_array_equal(result.mask, expected.mask)
  4735. def test_default_fill_value_complex():
  4736. # regression test for Python 3, where 'unicode' was not defined
  4737. assert_(default_fill_value(1 + 1j) == 1.e20 + 0.0j)
  4738. def test_ufunc_with_output():
  4739. # check that giving an output argument always returns that output.
  4740. # Regression test for gh-8416.
  4741. x = array([1., 2., 3.], mask=[0, 0, 1])
  4742. y = np.add(x, 1., out=x)
  4743. assert_(y is x)
  4744. def test_ufunc_with_out_varied():
  4745. """ Test that masked arrays are immune to gh-10459 """
  4746. # the mask of the output should not affect the result, however it is passed
  4747. a = array([ 1, 2, 3], mask=[1, 0, 0])
  4748. b = array([10, 20, 30], mask=[1, 0, 0])
  4749. out = array([ 0, 0, 0], mask=[0, 0, 1])
  4750. expected = array([11, 22, 33], mask=[1, 0, 0])
  4751. out_pos = out.copy()
  4752. res_pos = np.add(a, b, out_pos)
  4753. out_kw = out.copy()
  4754. res_kw = np.add(a, b, out=out_kw)
  4755. out_tup = out.copy()
  4756. res_tup = np.add(a, b, out=(out_tup,))
  4757. assert_equal(res_kw.mask, expected.mask)
  4758. assert_equal(res_kw.data, expected.data)
  4759. assert_equal(res_tup.mask, expected.mask)
  4760. assert_equal(res_tup.data, expected.data)
  4761. assert_equal(res_pos.mask, expected.mask)
  4762. assert_equal(res_pos.data, expected.data)
  4763. def test_astype_mask_ordering():
  4764. descr = np.dtype([('v', int, 3), ('x', [('y', float)])])
  4765. x = array([
  4766. [([1, 2, 3], (1.0,)), ([1, 2, 3], (2.0,))],
  4767. [([1, 2, 3], (3.0,)), ([1, 2, 3], (4.0,))]], dtype=descr)
  4768. x[0]['v'][0] = np.ma.masked
  4769. x_a = x.astype(descr)
  4770. assert x_a.dtype.names == np.dtype(descr).names
  4771. assert x_a.mask.dtype.names == np.dtype(descr).names
  4772. assert_equal(x, x_a)
  4773. assert_(x is x.astype(x.dtype, copy=False))
  4774. assert_equal(type(x.astype(x.dtype, subok=False)), np.ndarray)
  4775. x_f = x.astype(x.dtype, order='F')
  4776. assert_(x_f.flags.f_contiguous)
  4777. assert_(x_f.mask.flags.f_contiguous)
  4778. # Also test the same indirectly, via np.array
  4779. x_a2 = np.array(x, dtype=descr, subok=True)
  4780. assert x_a2.dtype.names == np.dtype(descr).names
  4781. assert x_a2.mask.dtype.names == np.dtype(descr).names
  4782. assert_equal(x, x_a2)
  4783. assert_(x is np.array(x, dtype=descr, copy=False, subok=True))
  4784. x_f2 = np.array(x, dtype=x.dtype, order='F', subok=True)
  4785. assert_(x_f2.flags.f_contiguous)
  4786. assert_(x_f2.mask.flags.f_contiguous)
  4787. @pytest.mark.parametrize('dt1', num_dts, ids=num_ids)
  4788. @pytest.mark.parametrize('dt2', num_dts, ids=num_ids)
  4789. @pytest.mark.filterwarnings('ignore::numpy.ComplexWarning')
  4790. def test_astype_basic(dt1, dt2):
  4791. # See gh-12070
  4792. src = np.ma.array(ones(3, dt1), fill_value=1)
  4793. dst = src.astype(dt2)
  4794. assert_(src.fill_value == 1)
  4795. assert_(src.dtype == dt1)
  4796. assert_(src.fill_value.dtype == dt1)
  4797. assert_(dst.fill_value == 1)
  4798. assert_(dst.dtype == dt2)
  4799. assert_(dst.fill_value.dtype == dt2)
  4800. assert_equal(src, dst)
  4801. def test_fieldless_void():
  4802. dt = np.dtype([]) # a void dtype with no fields
  4803. x = np.empty(4, dt)
  4804. # these arrays contain no values, so there's little to test - but this
  4805. # shouldn't crash
  4806. mx = np.ma.array(x)
  4807. assert_equal(mx.dtype, x.dtype)
  4808. assert_equal(mx.shape, x.shape)
  4809. mx = np.ma.array(x, mask=x)
  4810. assert_equal(mx.dtype, x.dtype)
  4811. assert_equal(mx.shape, x.shape)
  4812. def test_mask_shape_assignment_does_not_break_masked():
  4813. a = np.ma.masked
  4814. b = np.ma.array(1, mask=a.mask)
  4815. b.shape = (1,)
  4816. assert_equal(a.mask.shape, ())
  4817. @pytest.mark.skipif(sys.flags.optimize > 1,
  4818. reason="no docstrings present to inspect when PYTHONOPTIMIZE/Py_OptimizeFlag > 1")
  4819. def test_doc_note():
  4820. def method(self):
  4821. """This docstring
  4822. Has multiple lines
  4823. And notes
  4824. Notes
  4825. -----
  4826. original note
  4827. """
  4828. pass
  4829. expected_doc = """This docstring
  4830. Has multiple lines
  4831. And notes
  4832. Notes
  4833. -----
  4834. note
  4835. original note"""
  4836. assert_equal(np.ma.core.doc_note(method.__doc__, "note"), expected_doc)