test_core.py 214 KB

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