core.py 254 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084
  1. """
  2. numpy.ma : a package to handle missing or invalid values.
  3. This package was initially written for numarray by Paul F. Dubois
  4. at Lawrence Livermore National Laboratory.
  5. In 2006, the package was completely rewritten by Pierre Gerard-Marchant
  6. (University of Georgia) to make the MaskedArray class a subclass of ndarray,
  7. and to improve support of structured arrays.
  8. Copyright 1999, 2000, 2001 Regents of the University of California.
  9. Released for unlimited redistribution.
  10. * Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois.
  11. * Subclassing of the base `ndarray` 2006 by Pierre Gerard-Marchant
  12. (pgmdevlist_AT_gmail_DOT_com)
  13. * Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com)
  14. .. moduleauthor:: Pierre Gerard-Marchant
  15. """
  16. # pylint: disable-msg=E1002
  17. from __future__ import division, absolute_import, print_function
  18. import sys
  19. import operator
  20. import warnings
  21. import textwrap
  22. import re
  23. from functools import reduce
  24. if sys.version_info[0] >= 3:
  25. import builtins
  26. else:
  27. import __builtin__ as builtins
  28. import numpy as np
  29. import numpy.core.umath as umath
  30. import numpy.core.numerictypes as ntypes
  31. from numpy import ndarray, amax, amin, iscomplexobj, bool_, _NoValue
  32. from numpy import array as narray
  33. from numpy.lib.function_base import angle
  34. from numpy.compat import (
  35. getargspec, formatargspec, long, basestring, unicode, bytes
  36. )
  37. from numpy import expand_dims
  38. from numpy.core.numeric import normalize_axis_tuple
  39. from numpy.core._internal import recursive
  40. from numpy.compat import pickle
  41. __all__ = [
  42. 'MAError', 'MaskError', 'MaskType', 'MaskedArray', 'abs', 'absolute',
  43. 'add', 'all', 'allclose', 'allequal', 'alltrue', 'amax', 'amin',
  44. 'angle', 'anom', 'anomalies', 'any', 'append', 'arange', 'arccos',
  45. 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh',
  46. 'argmax', 'argmin', 'argsort', 'around', 'array', 'asanyarray',
  47. 'asarray', 'bitwise_and', 'bitwise_or', 'bitwise_xor', 'bool_', 'ceil',
  48. 'choose', 'clip', 'common_fill_value', 'compress', 'compressed',
  49. 'concatenate', 'conjugate', 'convolve', 'copy', 'correlate', 'cos', 'cosh',
  50. 'count', 'cumprod', 'cumsum', 'default_fill_value', 'diag', 'diagonal',
  51. 'diff', 'divide', 'empty', 'empty_like', 'equal', 'exp',
  52. 'expand_dims', 'fabs', 'filled', 'fix_invalid', 'flatten_mask',
  53. 'flatten_structured_array', 'floor', 'floor_divide', 'fmod',
  54. 'frombuffer', 'fromflex', 'fromfunction', 'getdata', 'getmask',
  55. 'getmaskarray', 'greater', 'greater_equal', 'harden_mask', 'hypot',
  56. 'identity', 'ids', 'indices', 'inner', 'innerproduct', 'isMA',
  57. 'isMaskedArray', 'is_mask', 'is_masked', 'isarray', 'left_shift',
  58. 'less', 'less_equal', 'log', 'log10', 'log2',
  59. 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'make_mask',
  60. 'make_mask_descr', 'make_mask_none', 'mask_or', 'masked',
  61. 'masked_array', 'masked_equal', 'masked_greater',
  62. 'masked_greater_equal', 'masked_inside', 'masked_invalid',
  63. 'masked_less', 'masked_less_equal', 'masked_not_equal',
  64. 'masked_object', 'masked_outside', 'masked_print_option',
  65. 'masked_singleton', 'masked_values', 'masked_where', 'max', 'maximum',
  66. 'maximum_fill_value', 'mean', 'min', 'minimum', 'minimum_fill_value',
  67. 'mod', 'multiply', 'mvoid', 'ndim', 'negative', 'nomask', 'nonzero',
  68. 'not_equal', 'ones', 'outer', 'outerproduct', 'power', 'prod',
  69. 'product', 'ptp', 'put', 'putmask', 'ravel', 'remainder',
  70. 'repeat', 'reshape', 'resize', 'right_shift', 'round', 'round_',
  71. 'set_fill_value', 'shape', 'sin', 'sinh', 'size', 'soften_mask',
  72. 'sometrue', 'sort', 'sqrt', 'squeeze', 'std', 'subtract', 'sum',
  73. 'swapaxes', 'take', 'tan', 'tanh', 'trace', 'transpose', 'true_divide',
  74. 'var', 'where', 'zeros',
  75. ]
  76. MaskType = np.bool_
  77. nomask = MaskType(0)
  78. class MaskedArrayFutureWarning(FutureWarning):
  79. pass
  80. def _deprecate_argsort_axis(arr):
  81. """
  82. Adjust the axis passed to argsort, warning if necessary
  83. Parameters
  84. ----------
  85. arr
  86. The array which argsort was called on
  87. np.ma.argsort has a long-term bug where the default of the axis argument
  88. is wrong (gh-8701), which now must be kept for backwards compatibiity.
  89. Thankfully, this only makes a difference when arrays are 2- or more-
  90. dimensional, so we only need a warning then.
  91. """
  92. if arr.ndim <= 1:
  93. # no warning needed - but switch to -1 anyway, to avoid surprising
  94. # subclasses, which are more likely to implement scalar axes.
  95. return -1
  96. else:
  97. # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default
  98. warnings.warn(
  99. "In the future the default for argsort will be axis=-1, not the "
  100. "current None, to match its documentation and np.argsort. "
  101. "Explicitly pass -1 or None to silence this warning.",
  102. MaskedArrayFutureWarning, stacklevel=3)
  103. return None
  104. def doc_note(initialdoc, note):
  105. """
  106. Adds a Notes section to an existing docstring.
  107. """
  108. if initialdoc is None:
  109. return
  110. if note is None:
  111. return initialdoc
  112. notesplit = re.split(r'\n\s*?Notes\n\s*?-----', initialdoc)
  113. notedoc = """\
  114. Notes
  115. -----
  116. %s""" % note
  117. if len(notesplit) > 1:
  118. notedoc = '\n\n ' + notedoc + '\n'
  119. return ''.join(notesplit[:1] + [notedoc] + notesplit[1:])
  120. def get_object_signature(obj):
  121. """
  122. Get the signature from obj
  123. """
  124. try:
  125. sig = formatargspec(*getargspec(obj))
  126. except TypeError:
  127. sig = ''
  128. return sig
  129. ###############################################################################
  130. # Exceptions #
  131. ###############################################################################
  132. class MAError(Exception):
  133. """
  134. Class for masked array related errors.
  135. """
  136. pass
  137. class MaskError(MAError):
  138. """
  139. Class for mask related errors.
  140. """
  141. pass
  142. ###############################################################################
  143. # Filling options #
  144. ###############################################################################
  145. # b: boolean - c: complex - f: floats - i: integer - O: object - S: string
  146. default_filler = {'b': True,
  147. 'c': 1.e20 + 0.0j,
  148. 'f': 1.e20,
  149. 'i': 999999,
  150. 'O': '?',
  151. 'S': b'N/A',
  152. 'u': 999999,
  153. 'V': b'???',
  154. 'U': u'N/A'
  155. }
  156. # Add datetime64 and timedelta64 types
  157. for v in ["Y", "M", "W", "D", "h", "m", "s", "ms", "us", "ns", "ps",
  158. "fs", "as"]:
  159. default_filler["M8[" + v + "]"] = np.datetime64("NaT", v)
  160. default_filler["m8[" + v + "]"] = np.timedelta64("NaT", v)
  161. max_filler = ntypes._minvals
  162. max_filler.update([(k, -np.inf) for k in [np.float32, np.float64]])
  163. min_filler = ntypes._maxvals
  164. min_filler.update([(k, +np.inf) for k in [np.float32, np.float64]])
  165. if 'float128' in ntypes.typeDict:
  166. max_filler.update([(np.float128, -np.inf)])
  167. min_filler.update([(np.float128, +np.inf)])
  168. def _recursive_fill_value(dtype, f):
  169. """
  170. Recursively produce a fill value for `dtype`, calling f on scalar dtypes
  171. """
  172. if dtype.names is not None:
  173. vals = tuple(_recursive_fill_value(dtype[name], f) for name in dtype.names)
  174. return np.array(vals, dtype=dtype)[()] # decay to void scalar from 0d
  175. elif dtype.subdtype:
  176. subtype, shape = dtype.subdtype
  177. subval = _recursive_fill_value(subtype, f)
  178. return np.full(shape, subval)
  179. else:
  180. return f(dtype)
  181. def _get_dtype_of(obj):
  182. """ Convert the argument for *_fill_value into a dtype """
  183. if isinstance(obj, np.dtype):
  184. return obj
  185. elif hasattr(obj, 'dtype'):
  186. return obj.dtype
  187. else:
  188. return np.asanyarray(obj).dtype
  189. def default_fill_value(obj):
  190. """
  191. Return the default fill value for the argument object.
  192. The default filling value depends on the datatype of the input
  193. array or the type of the input scalar:
  194. ======== ========
  195. datatype default
  196. ======== ========
  197. bool True
  198. int 999999
  199. float 1.e20
  200. complex 1.e20+0j
  201. object '?'
  202. string 'N/A'
  203. ======== ========
  204. For structured types, a structured scalar is returned, with each field the
  205. default fill value for its type.
  206. For subarray types, the fill value is an array of the same size containing
  207. the default scalar fill value.
  208. Parameters
  209. ----------
  210. obj : ndarray, dtype or scalar
  211. The array data-type or scalar for which the default fill value
  212. is returned.
  213. Returns
  214. -------
  215. fill_value : scalar
  216. The default fill value.
  217. Examples
  218. --------
  219. >>> np.ma.default_fill_value(1)
  220. 999999
  221. >>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
  222. 1e+20
  223. >>> np.ma.default_fill_value(np.dtype(complex))
  224. (1e+20+0j)
  225. """
  226. def _scalar_fill_value(dtype):
  227. if dtype.kind in 'Mm':
  228. return default_filler.get(dtype.str[1:], '?')
  229. else:
  230. return default_filler.get(dtype.kind, '?')
  231. dtype = _get_dtype_of(obj)
  232. return _recursive_fill_value(dtype, _scalar_fill_value)
  233. def _extremum_fill_value(obj, extremum, extremum_name):
  234. def _scalar_fill_value(dtype):
  235. try:
  236. return extremum[dtype]
  237. except KeyError:
  238. raise TypeError(
  239. "Unsuitable type {} for calculating {}."
  240. .format(dtype, extremum_name)
  241. )
  242. dtype = _get_dtype_of(obj)
  243. return _recursive_fill_value(dtype, _scalar_fill_value)
  244. def minimum_fill_value(obj):
  245. """
  246. Return the maximum value that can be represented by the dtype of an object.
  247. This function is useful for calculating a fill value suitable for
  248. taking the minimum of an array with a given dtype.
  249. Parameters
  250. ----------
  251. obj : ndarray, dtype or scalar
  252. An object that can be queried for it's numeric type.
  253. Returns
  254. -------
  255. val : scalar
  256. The maximum representable value.
  257. Raises
  258. ------
  259. TypeError
  260. If `obj` isn't a suitable numeric type.
  261. See Also
  262. --------
  263. maximum_fill_value : The inverse function.
  264. set_fill_value : Set the filling value of a masked array.
  265. MaskedArray.fill_value : Return current fill value.
  266. Examples
  267. --------
  268. >>> import numpy.ma as ma
  269. >>> a = np.int8()
  270. >>> ma.minimum_fill_value(a)
  271. 127
  272. >>> a = np.int32()
  273. >>> ma.minimum_fill_value(a)
  274. 2147483647
  275. An array of numeric data can also be passed.
  276. >>> a = np.array([1, 2, 3], dtype=np.int8)
  277. >>> ma.minimum_fill_value(a)
  278. 127
  279. >>> a = np.array([1, 2, 3], dtype=np.float32)
  280. >>> ma.minimum_fill_value(a)
  281. inf
  282. """
  283. return _extremum_fill_value(obj, min_filler, "minimum")
  284. def maximum_fill_value(obj):
  285. """
  286. Return the minimum value that can be represented by the dtype of an object.
  287. This function is useful for calculating a fill value suitable for
  288. taking the maximum of an array with a given dtype.
  289. Parameters
  290. ----------
  291. obj : ndarray, dtype or scalar
  292. An object that can be queried for it's numeric type.
  293. Returns
  294. -------
  295. val : scalar
  296. The minimum representable value.
  297. Raises
  298. ------
  299. TypeError
  300. If `obj` isn't a suitable numeric type.
  301. See Also
  302. --------
  303. minimum_fill_value : The inverse function.
  304. set_fill_value : Set the filling value of a masked array.
  305. MaskedArray.fill_value : Return current fill value.
  306. Examples
  307. --------
  308. >>> import numpy.ma as ma
  309. >>> a = np.int8()
  310. >>> ma.maximum_fill_value(a)
  311. -128
  312. >>> a = np.int32()
  313. >>> ma.maximum_fill_value(a)
  314. -2147483648
  315. An array of numeric data can also be passed.
  316. >>> a = np.array([1, 2, 3], dtype=np.int8)
  317. >>> ma.maximum_fill_value(a)
  318. -128
  319. >>> a = np.array([1, 2, 3], dtype=np.float32)
  320. >>> ma.maximum_fill_value(a)
  321. -inf
  322. """
  323. return _extremum_fill_value(obj, max_filler, "maximum")
  324. def _recursive_set_fill_value(fillvalue, dt):
  325. """
  326. Create a fill value for a structured dtype.
  327. Parameters
  328. ----------
  329. fillvalue: scalar or array_like
  330. Scalar or array representing the fill value. If it is of shorter
  331. length than the number of fields in dt, it will be resized.
  332. dt: dtype
  333. The structured dtype for which to create the fill value.
  334. Returns
  335. -------
  336. val: tuple
  337. A tuple of values corresponding to the structured fill value.
  338. """
  339. fillvalue = np.resize(fillvalue, len(dt.names))
  340. output_value = []
  341. for (fval, name) in zip(fillvalue, dt.names):
  342. cdtype = dt[name]
  343. if cdtype.subdtype:
  344. cdtype = cdtype.subdtype[0]
  345. if cdtype.names is not None:
  346. output_value.append(tuple(_recursive_set_fill_value(fval, cdtype)))
  347. else:
  348. output_value.append(np.array(fval, dtype=cdtype).item())
  349. return tuple(output_value)
  350. def _check_fill_value(fill_value, ndtype):
  351. """
  352. Private function validating the given `fill_value` for the given dtype.
  353. If fill_value is None, it is set to the default corresponding to the dtype.
  354. If fill_value is not None, its value is forced to the given dtype.
  355. The result is always a 0d array.
  356. """
  357. ndtype = np.dtype(ndtype)
  358. if fill_value is None:
  359. fill_value = default_fill_value(ndtype)
  360. elif ndtype.names is not None:
  361. if isinstance(fill_value, (ndarray, np.void)):
  362. try:
  363. fill_value = np.array(fill_value, copy=False, dtype=ndtype)
  364. except ValueError:
  365. err_msg = "Unable to transform %s to dtype %s"
  366. raise ValueError(err_msg % (fill_value, ndtype))
  367. else:
  368. fill_value = np.asarray(fill_value, dtype=object)
  369. fill_value = np.array(_recursive_set_fill_value(fill_value, ndtype),
  370. dtype=ndtype)
  371. else:
  372. if isinstance(fill_value, basestring) and (ndtype.char not in 'OSVU'):
  373. # Note this check doesn't work if fill_value is not a scalar
  374. err_msg = "Cannot set fill value of string with array of dtype %s"
  375. raise TypeError(err_msg % ndtype)
  376. else:
  377. # In case we want to convert 1e20 to int.
  378. # Also in case of converting string arrays.
  379. try:
  380. fill_value = np.array(fill_value, copy=False, dtype=ndtype)
  381. except (OverflowError, ValueError):
  382. # Raise TypeError instead of OverflowError or ValueError.
  383. # OverflowError is seldom used, and the real problem here is
  384. # that the passed fill_value is not compatible with the ndtype.
  385. err_msg = "Cannot convert fill_value %s to dtype %s"
  386. raise TypeError(err_msg % (fill_value, ndtype))
  387. return np.array(fill_value)
  388. def set_fill_value(a, fill_value):
  389. """
  390. Set the filling value of a, if a is a masked array.
  391. This function changes the fill value of the masked array `a` in place.
  392. If `a` is not a masked array, the function returns silently, without
  393. doing anything.
  394. Parameters
  395. ----------
  396. a : array_like
  397. Input array.
  398. fill_value : dtype
  399. Filling value. A consistency test is performed to make sure
  400. the value is compatible with the dtype of `a`.
  401. Returns
  402. -------
  403. None
  404. Nothing returned by this function.
  405. See Also
  406. --------
  407. maximum_fill_value : Return the default fill value for a dtype.
  408. MaskedArray.fill_value : Return current fill value.
  409. MaskedArray.set_fill_value : Equivalent method.
  410. Examples
  411. --------
  412. >>> import numpy.ma as ma
  413. >>> a = np.arange(5)
  414. >>> a
  415. array([0, 1, 2, 3, 4])
  416. >>> a = ma.masked_where(a < 3, a)
  417. >>> a
  418. masked_array(data=[--, --, --, 3, 4],
  419. mask=[ True, True, True, False, False],
  420. fill_value=999999)
  421. >>> ma.set_fill_value(a, -999)
  422. >>> a
  423. masked_array(data=[--, --, --, 3, 4],
  424. mask=[ True, True, True, False, False],
  425. fill_value=-999)
  426. Nothing happens if `a` is not a masked array.
  427. >>> a = list(range(5))
  428. >>> a
  429. [0, 1, 2, 3, 4]
  430. >>> ma.set_fill_value(a, 100)
  431. >>> a
  432. [0, 1, 2, 3, 4]
  433. >>> a = np.arange(5)
  434. >>> a
  435. array([0, 1, 2, 3, 4])
  436. >>> ma.set_fill_value(a, 100)
  437. >>> a
  438. array([0, 1, 2, 3, 4])
  439. """
  440. if isinstance(a, MaskedArray):
  441. a.set_fill_value(fill_value)
  442. return
  443. def get_fill_value(a):
  444. """
  445. Return the filling value of a, if any. Otherwise, returns the
  446. default filling value for that type.
  447. """
  448. if isinstance(a, MaskedArray):
  449. result = a.fill_value
  450. else:
  451. result = default_fill_value(a)
  452. return result
  453. def common_fill_value(a, b):
  454. """
  455. Return the common filling value of two masked arrays, if any.
  456. If ``a.fill_value == b.fill_value``, return the fill value,
  457. otherwise return None.
  458. Parameters
  459. ----------
  460. a, b : MaskedArray
  461. The masked arrays for which to compare fill values.
  462. Returns
  463. -------
  464. fill_value : scalar or None
  465. The common fill value, or None.
  466. Examples
  467. --------
  468. >>> x = np.ma.array([0, 1.], fill_value=3)
  469. >>> y = np.ma.array([0, 1.], fill_value=3)
  470. >>> np.ma.common_fill_value(x, y)
  471. 3.0
  472. """
  473. t1 = get_fill_value(a)
  474. t2 = get_fill_value(b)
  475. if t1 == t2:
  476. return t1
  477. return None
  478. def filled(a, fill_value=None):
  479. """
  480. Return input as an array with masked data replaced by a fill value.
  481. If `a` is not a `MaskedArray`, `a` itself is returned.
  482. If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to
  483. ``a.fill_value``.
  484. Parameters
  485. ----------
  486. a : MaskedArray or array_like
  487. An input object.
  488. fill_value : array_like, optional.
  489. Can be scalar or non-scalar. If non-scalar, the
  490. resulting filled array should be broadcastable
  491. over input array. Default is None.
  492. Returns
  493. -------
  494. a : ndarray
  495. The filled array.
  496. See Also
  497. --------
  498. compressed
  499. Examples
  500. --------
  501. >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
  502. ... [1, 0, 0],
  503. ... [0, 0, 0]])
  504. >>> x.filled()
  505. array([[999999, 1, 2],
  506. [999999, 4, 5],
  507. [ 6, 7, 8]])
  508. >>> x.filled(fill_value=333)
  509. array([[333, 1, 2],
  510. [333, 4, 5],
  511. [ 6, 7, 8]])
  512. >>> x.filled(fill_value=np.arange(3))
  513. array([[0, 1, 2],
  514. [0, 4, 5],
  515. [6, 7, 8]])
  516. """
  517. if hasattr(a, 'filled'):
  518. return a.filled(fill_value)
  519. elif isinstance(a, ndarray):
  520. # Should we check for contiguity ? and a.flags['CONTIGUOUS']:
  521. return a
  522. elif isinstance(a, dict):
  523. return np.array(a, 'O')
  524. else:
  525. return np.array(a)
  526. def get_masked_subclass(*arrays):
  527. """
  528. Return the youngest subclass of MaskedArray from a list of (masked) arrays.
  529. In case of siblings, the first listed takes over.
  530. """
  531. if len(arrays) == 1:
  532. arr = arrays[0]
  533. if isinstance(arr, MaskedArray):
  534. rcls = type(arr)
  535. else:
  536. rcls = MaskedArray
  537. else:
  538. arrcls = [type(a) for a in arrays]
  539. rcls = arrcls[0]
  540. if not issubclass(rcls, MaskedArray):
  541. rcls = MaskedArray
  542. for cls in arrcls[1:]:
  543. if issubclass(cls, rcls):
  544. rcls = cls
  545. # Don't return MaskedConstant as result: revert to MaskedArray
  546. if rcls.__name__ == 'MaskedConstant':
  547. return MaskedArray
  548. return rcls
  549. def getdata(a, subok=True):
  550. """
  551. Return the data of a masked array as an ndarray.
  552. Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``,
  553. else return `a` as a ndarray or subclass (depending on `subok`) if not.
  554. Parameters
  555. ----------
  556. a : array_like
  557. Input ``MaskedArray``, alternatively a ndarray or a subclass thereof.
  558. subok : bool
  559. Whether to force the output to be a `pure` ndarray (False) or to
  560. return a subclass of ndarray if appropriate (True, default).
  561. See Also
  562. --------
  563. getmask : Return the mask of a masked array, or nomask.
  564. getmaskarray : Return the mask of a masked array, or full array of False.
  565. Examples
  566. --------
  567. >>> import numpy.ma as ma
  568. >>> a = ma.masked_equal([[1,2],[3,4]], 2)
  569. >>> a
  570. masked_array(
  571. data=[[1, --],
  572. [3, 4]],
  573. mask=[[False, True],
  574. [False, False]],
  575. fill_value=2)
  576. >>> ma.getdata(a)
  577. array([[1, 2],
  578. [3, 4]])
  579. Equivalently use the ``MaskedArray`` `data` attribute.
  580. >>> a.data
  581. array([[1, 2],
  582. [3, 4]])
  583. """
  584. try:
  585. data = a._data
  586. except AttributeError:
  587. data = np.array(a, copy=False, subok=subok)
  588. if not subok:
  589. return data.view(ndarray)
  590. return data
  591. get_data = getdata
  592. def fix_invalid(a, mask=nomask, copy=True, fill_value=None):
  593. """
  594. Return input with invalid data masked and replaced by a fill value.
  595. Invalid data means values of `nan`, `inf`, etc.
  596. Parameters
  597. ----------
  598. a : array_like
  599. Input array, a (subclass of) ndarray.
  600. mask : sequence, optional
  601. Mask. Must be convertible to an array of booleans with the same
  602. shape as `data`. True indicates a masked (i.e. invalid) data.
  603. copy : bool, optional
  604. Whether to use a copy of `a` (True) or to fix `a` in place (False).
  605. Default is True.
  606. fill_value : scalar, optional
  607. Value used for fixing invalid data. Default is None, in which case
  608. the ``a.fill_value`` is used.
  609. Returns
  610. -------
  611. b : MaskedArray
  612. The input array with invalid entries fixed.
  613. Notes
  614. -----
  615. A copy is performed by default.
  616. Examples
  617. --------
  618. >>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3)
  619. >>> x
  620. masked_array(data=[--, -1.0, nan, inf],
  621. mask=[ True, False, False, False],
  622. fill_value=1e+20)
  623. >>> np.ma.fix_invalid(x)
  624. masked_array(data=[--, -1.0, --, --],
  625. mask=[ True, False, True, True],
  626. fill_value=1e+20)
  627. >>> fixed = np.ma.fix_invalid(x)
  628. >>> fixed.data
  629. array([ 1.e+00, -1.e+00, 1.e+20, 1.e+20])
  630. >>> x.data
  631. array([ 1., -1., nan, inf])
  632. """
  633. a = masked_array(a, copy=copy, mask=mask, subok=True)
  634. invalid = np.logical_not(np.isfinite(a._data))
  635. if not invalid.any():
  636. return a
  637. a._mask |= invalid
  638. if fill_value is None:
  639. fill_value = a.fill_value
  640. a._data[invalid] = fill_value
  641. return a
  642. def is_string_or_list_of_strings(val):
  643. return (isinstance(val, basestring) or
  644. (isinstance(val, list) and val and
  645. builtins.all(isinstance(s, basestring) for s in val)))
  646. ###############################################################################
  647. # Ufuncs #
  648. ###############################################################################
  649. ufunc_domain = {}
  650. ufunc_fills = {}
  651. class _DomainCheckInterval(object):
  652. """
  653. Define a valid interval, so that :
  654. ``domain_check_interval(a,b)(x) == True`` where
  655. ``x < a`` or ``x > b``.
  656. """
  657. def __init__(self, a, b):
  658. "domain_check_interval(a,b)(x) = true where x < a or y > b"
  659. if a > b:
  660. (a, b) = (b, a)
  661. self.a = a
  662. self.b = b
  663. def __call__(self, x):
  664. "Execute the call behavior."
  665. # nans at masked positions cause RuntimeWarnings, even though
  666. # they are masked. To avoid this we suppress warnings.
  667. with np.errstate(invalid='ignore'):
  668. return umath.logical_or(umath.greater(x, self.b),
  669. umath.less(x, self.a))
  670. class _DomainTan(object):
  671. """
  672. Define a valid interval for the `tan` function, so that:
  673. ``domain_tan(eps) = True`` where ``abs(cos(x)) < eps``
  674. """
  675. def __init__(self, eps):
  676. "domain_tan(eps) = true where abs(cos(x)) < eps)"
  677. self.eps = eps
  678. def __call__(self, x):
  679. "Executes the call behavior."
  680. with np.errstate(invalid='ignore'):
  681. return umath.less(umath.absolute(umath.cos(x)), self.eps)
  682. class _DomainSafeDivide(object):
  683. """
  684. Define a domain for safe division.
  685. """
  686. def __init__(self, tolerance=None):
  687. self.tolerance = tolerance
  688. def __call__(self, a, b):
  689. # Delay the selection of the tolerance to here in order to reduce numpy
  690. # import times. The calculation of these parameters is a substantial
  691. # component of numpy's import time.
  692. if self.tolerance is None:
  693. self.tolerance = np.finfo(float).tiny
  694. # don't call ma ufuncs from __array_wrap__ which would fail for scalars
  695. a, b = np.asarray(a), np.asarray(b)
  696. with np.errstate(invalid='ignore'):
  697. return umath.absolute(a) * self.tolerance >= umath.absolute(b)
  698. class _DomainGreater(object):
  699. """
  700. DomainGreater(v)(x) is True where x <= v.
  701. """
  702. def __init__(self, critical_value):
  703. "DomainGreater(v)(x) = true where x <= v"
  704. self.critical_value = critical_value
  705. def __call__(self, x):
  706. "Executes the call behavior."
  707. with np.errstate(invalid='ignore'):
  708. return umath.less_equal(x, self.critical_value)
  709. class _DomainGreaterEqual(object):
  710. """
  711. DomainGreaterEqual(v)(x) is True where x < v.
  712. """
  713. def __init__(self, critical_value):
  714. "DomainGreaterEqual(v)(x) = true where x < v"
  715. self.critical_value = critical_value
  716. def __call__(self, x):
  717. "Executes the call behavior."
  718. with np.errstate(invalid='ignore'):
  719. return umath.less(x, self.critical_value)
  720. class _MaskedUFunc(object):
  721. def __init__(self, ufunc):
  722. self.f = ufunc
  723. self.__doc__ = ufunc.__doc__
  724. self.__name__ = ufunc.__name__
  725. def __str__(self):
  726. return "Masked version of {}".format(self.f)
  727. class _MaskedUnaryOperation(_MaskedUFunc):
  728. """
  729. Defines masked version of unary operations, where invalid values are
  730. pre-masked.
  731. Parameters
  732. ----------
  733. mufunc : callable
  734. The function for which to define a masked version. Made available
  735. as ``_MaskedUnaryOperation.f``.
  736. fill : scalar, optional
  737. Filling value, default is 0.
  738. domain : class instance
  739. Domain for the function. Should be one of the ``_Domain*``
  740. classes. Default is None.
  741. """
  742. def __init__(self, mufunc, fill=0, domain=None):
  743. super(_MaskedUnaryOperation, self).__init__(mufunc)
  744. self.fill = fill
  745. self.domain = domain
  746. ufunc_domain[mufunc] = domain
  747. ufunc_fills[mufunc] = fill
  748. def __call__(self, a, *args, **kwargs):
  749. """
  750. Execute the call behavior.
  751. """
  752. d = getdata(a)
  753. # Deal with domain
  754. if self.domain is not None:
  755. # Case 1.1. : Domained function
  756. # nans at masked positions cause RuntimeWarnings, even though
  757. # they are masked. To avoid this we suppress warnings.
  758. with np.errstate(divide='ignore', invalid='ignore'):
  759. result = self.f(d, *args, **kwargs)
  760. # Make a mask
  761. m = ~umath.isfinite(result)
  762. m |= self.domain(d)
  763. m |= getmask(a)
  764. else:
  765. # Case 1.2. : Function without a domain
  766. # Get the result and the mask
  767. with np.errstate(divide='ignore', invalid='ignore'):
  768. result = self.f(d, *args, **kwargs)
  769. m = getmask(a)
  770. if not result.ndim:
  771. # Case 2.1. : The result is scalarscalar
  772. if m:
  773. return masked
  774. return result
  775. if m is not nomask:
  776. # Case 2.2. The result is an array
  777. # We need to fill the invalid data back w/ the input Now,
  778. # that's plain silly: in C, we would just skip the element and
  779. # keep the original, but we do have to do it that way in Python
  780. # In case result has a lower dtype than the inputs (as in
  781. # equal)
  782. try:
  783. np.copyto(result, d, where=m)
  784. except TypeError:
  785. pass
  786. # Transform to
  787. masked_result = result.view(get_masked_subclass(a))
  788. masked_result._mask = m
  789. masked_result._update_from(a)
  790. return masked_result
  791. class _MaskedBinaryOperation(_MaskedUFunc):
  792. """
  793. Define masked version of binary operations, where invalid
  794. values are pre-masked.
  795. Parameters
  796. ----------
  797. mbfunc : function
  798. The function for which to define a masked version. Made available
  799. as ``_MaskedBinaryOperation.f``.
  800. domain : class instance
  801. Default domain for the function. Should be one of the ``_Domain*``
  802. classes. Default is None.
  803. fillx : scalar, optional
  804. Filling value for the first argument, default is 0.
  805. filly : scalar, optional
  806. Filling value for the second argument, default is 0.
  807. """
  808. def __init__(self, mbfunc, fillx=0, filly=0):
  809. """
  810. abfunc(fillx, filly) must be defined.
  811. abfunc(x, filly) = x for all x to enable reduce.
  812. """
  813. super(_MaskedBinaryOperation, self).__init__(mbfunc)
  814. self.fillx = fillx
  815. self.filly = filly
  816. ufunc_domain[mbfunc] = None
  817. ufunc_fills[mbfunc] = (fillx, filly)
  818. def __call__(self, a, b, *args, **kwargs):
  819. """
  820. Execute the call behavior.
  821. """
  822. # Get the data, as ndarray
  823. (da, db) = (getdata(a), getdata(b))
  824. # Get the result
  825. with np.errstate():
  826. np.seterr(divide='ignore', invalid='ignore')
  827. result = self.f(da, db, *args, **kwargs)
  828. # Get the mask for the result
  829. (ma, mb) = (getmask(a), getmask(b))
  830. if ma is nomask:
  831. if mb is nomask:
  832. m = nomask
  833. else:
  834. m = umath.logical_or(getmaskarray(a), mb)
  835. elif mb is nomask:
  836. m = umath.logical_or(ma, getmaskarray(b))
  837. else:
  838. m = umath.logical_or(ma, mb)
  839. # Case 1. : scalar
  840. if not result.ndim:
  841. if m:
  842. return masked
  843. return result
  844. # Case 2. : array
  845. # Revert result to da where masked
  846. if m is not nomask and m.any():
  847. # any errors, just abort; impossible to guarantee masked values
  848. try:
  849. np.copyto(result, da, casting='unsafe', where=m)
  850. except Exception:
  851. pass
  852. # Transforms to a (subclass of) MaskedArray
  853. masked_result = result.view(get_masked_subclass(a, b))
  854. masked_result._mask = m
  855. if isinstance(a, MaskedArray):
  856. masked_result._update_from(a)
  857. elif isinstance(b, MaskedArray):
  858. masked_result._update_from(b)
  859. return masked_result
  860. def reduce(self, target, axis=0, dtype=None):
  861. """
  862. Reduce `target` along the given `axis`.
  863. """
  864. tclass = get_masked_subclass(target)
  865. m = getmask(target)
  866. t = filled(target, self.filly)
  867. if t.shape == ():
  868. t = t.reshape(1)
  869. if m is not nomask:
  870. m = make_mask(m, copy=True)
  871. m.shape = (1,)
  872. if m is nomask:
  873. tr = self.f.reduce(t, axis)
  874. mr = nomask
  875. else:
  876. tr = self.f.reduce(t, axis, dtype=dtype or t.dtype)
  877. mr = umath.logical_and.reduce(m, axis)
  878. if not tr.shape:
  879. if mr:
  880. return masked
  881. else:
  882. return tr
  883. masked_tr = tr.view(tclass)
  884. masked_tr._mask = mr
  885. return masked_tr
  886. def outer(self, a, b):
  887. """
  888. Return the function applied to the outer product of a and b.
  889. """
  890. (da, db) = (getdata(a), getdata(b))
  891. d = self.f.outer(da, db)
  892. ma = getmask(a)
  893. mb = getmask(b)
  894. if ma is nomask and mb is nomask:
  895. m = nomask
  896. else:
  897. ma = getmaskarray(a)
  898. mb = getmaskarray(b)
  899. m = umath.logical_or.outer(ma, mb)
  900. if (not m.ndim) and m:
  901. return masked
  902. if m is not nomask:
  903. np.copyto(d, da, where=m)
  904. if not d.shape:
  905. return d
  906. masked_d = d.view(get_masked_subclass(a, b))
  907. masked_d._mask = m
  908. return masked_d
  909. def accumulate(self, target, axis=0):
  910. """Accumulate `target` along `axis` after filling with y fill
  911. value.
  912. """
  913. tclass = get_masked_subclass(target)
  914. t = filled(target, self.filly)
  915. result = self.f.accumulate(t, axis)
  916. masked_result = result.view(tclass)
  917. return masked_result
  918. class _DomainedBinaryOperation(_MaskedUFunc):
  919. """
  920. Define binary operations that have a domain, like divide.
  921. They have no reduce, outer or accumulate.
  922. Parameters
  923. ----------
  924. mbfunc : function
  925. The function for which to define a masked version. Made available
  926. as ``_DomainedBinaryOperation.f``.
  927. domain : class instance
  928. Default domain for the function. Should be one of the ``_Domain*``
  929. classes.
  930. fillx : scalar, optional
  931. Filling value for the first argument, default is 0.
  932. filly : scalar, optional
  933. Filling value for the second argument, default is 0.
  934. """
  935. def __init__(self, dbfunc, domain, fillx=0, filly=0):
  936. """abfunc(fillx, filly) must be defined.
  937. abfunc(x, filly) = x for all x to enable reduce.
  938. """
  939. super(_DomainedBinaryOperation, self).__init__(dbfunc)
  940. self.domain = domain
  941. self.fillx = fillx
  942. self.filly = filly
  943. ufunc_domain[dbfunc] = domain
  944. ufunc_fills[dbfunc] = (fillx, filly)
  945. def __call__(self, a, b, *args, **kwargs):
  946. "Execute the call behavior."
  947. # Get the data
  948. (da, db) = (getdata(a), getdata(b))
  949. # Get the result
  950. with np.errstate(divide='ignore', invalid='ignore'):
  951. result = self.f(da, db, *args, **kwargs)
  952. # Get the mask as a combination of the source masks and invalid
  953. m = ~umath.isfinite(result)
  954. m |= getmask(a)
  955. m |= getmask(b)
  956. # Apply the domain
  957. domain = ufunc_domain.get(self.f, None)
  958. if domain is not None:
  959. m |= domain(da, db)
  960. # Take care of the scalar case first
  961. if not m.ndim:
  962. if m:
  963. return masked
  964. else:
  965. return result
  966. # When the mask is True, put back da if possible
  967. # any errors, just abort; impossible to guarantee masked values
  968. try:
  969. np.copyto(result, 0, casting='unsafe', where=m)
  970. # avoid using "*" since this may be overlaid
  971. masked_da = umath.multiply(m, da)
  972. # only add back if it can be cast safely
  973. if np.can_cast(masked_da.dtype, result.dtype, casting='safe'):
  974. result += masked_da
  975. except Exception:
  976. pass
  977. # Transforms to a (subclass of) MaskedArray
  978. masked_result = result.view(get_masked_subclass(a, b))
  979. masked_result._mask = m
  980. if isinstance(a, MaskedArray):
  981. masked_result._update_from(a)
  982. elif isinstance(b, MaskedArray):
  983. masked_result._update_from(b)
  984. return masked_result
  985. # Unary ufuncs
  986. exp = _MaskedUnaryOperation(umath.exp)
  987. conjugate = _MaskedUnaryOperation(umath.conjugate)
  988. sin = _MaskedUnaryOperation(umath.sin)
  989. cos = _MaskedUnaryOperation(umath.cos)
  990. arctan = _MaskedUnaryOperation(umath.arctan)
  991. arcsinh = _MaskedUnaryOperation(umath.arcsinh)
  992. sinh = _MaskedUnaryOperation(umath.sinh)
  993. cosh = _MaskedUnaryOperation(umath.cosh)
  994. tanh = _MaskedUnaryOperation(umath.tanh)
  995. abs = absolute = _MaskedUnaryOperation(umath.absolute)
  996. angle = _MaskedUnaryOperation(angle) # from numpy.lib.function_base
  997. fabs = _MaskedUnaryOperation(umath.fabs)
  998. negative = _MaskedUnaryOperation(umath.negative)
  999. floor = _MaskedUnaryOperation(umath.floor)
  1000. ceil = _MaskedUnaryOperation(umath.ceil)
  1001. around = _MaskedUnaryOperation(np.round_)
  1002. logical_not = _MaskedUnaryOperation(umath.logical_not)
  1003. # Domained unary ufuncs
  1004. sqrt = _MaskedUnaryOperation(umath.sqrt, 0.0,
  1005. _DomainGreaterEqual(0.0))
  1006. log = _MaskedUnaryOperation(umath.log, 1.0,
  1007. _DomainGreater(0.0))
  1008. log2 = _MaskedUnaryOperation(umath.log2, 1.0,
  1009. _DomainGreater(0.0))
  1010. log10 = _MaskedUnaryOperation(umath.log10, 1.0,
  1011. _DomainGreater(0.0))
  1012. tan = _MaskedUnaryOperation(umath.tan, 0.0,
  1013. _DomainTan(1e-35))
  1014. arcsin = _MaskedUnaryOperation(umath.arcsin, 0.0,
  1015. _DomainCheckInterval(-1.0, 1.0))
  1016. arccos = _MaskedUnaryOperation(umath.arccos, 0.0,
  1017. _DomainCheckInterval(-1.0, 1.0))
  1018. arccosh = _MaskedUnaryOperation(umath.arccosh, 1.0,
  1019. _DomainGreaterEqual(1.0))
  1020. arctanh = _MaskedUnaryOperation(umath.arctanh, 0.0,
  1021. _DomainCheckInterval(-1.0 + 1e-15, 1.0 - 1e-15))
  1022. # Binary ufuncs
  1023. add = _MaskedBinaryOperation(umath.add)
  1024. subtract = _MaskedBinaryOperation(umath.subtract)
  1025. multiply = _MaskedBinaryOperation(umath.multiply, 1, 1)
  1026. arctan2 = _MaskedBinaryOperation(umath.arctan2, 0.0, 1.0)
  1027. equal = _MaskedBinaryOperation(umath.equal)
  1028. equal.reduce = None
  1029. not_equal = _MaskedBinaryOperation(umath.not_equal)
  1030. not_equal.reduce = None
  1031. less_equal = _MaskedBinaryOperation(umath.less_equal)
  1032. less_equal.reduce = None
  1033. greater_equal = _MaskedBinaryOperation(umath.greater_equal)
  1034. greater_equal.reduce = None
  1035. less = _MaskedBinaryOperation(umath.less)
  1036. less.reduce = None
  1037. greater = _MaskedBinaryOperation(umath.greater)
  1038. greater.reduce = None
  1039. logical_and = _MaskedBinaryOperation(umath.logical_and)
  1040. alltrue = _MaskedBinaryOperation(umath.logical_and, 1, 1).reduce
  1041. logical_or = _MaskedBinaryOperation(umath.logical_or)
  1042. sometrue = logical_or.reduce
  1043. logical_xor = _MaskedBinaryOperation(umath.logical_xor)
  1044. bitwise_and = _MaskedBinaryOperation(umath.bitwise_and)
  1045. bitwise_or = _MaskedBinaryOperation(umath.bitwise_or)
  1046. bitwise_xor = _MaskedBinaryOperation(umath.bitwise_xor)
  1047. hypot = _MaskedBinaryOperation(umath.hypot)
  1048. # Domained binary ufuncs
  1049. divide = _DomainedBinaryOperation(umath.divide, _DomainSafeDivide(), 0, 1)
  1050. true_divide = _DomainedBinaryOperation(umath.true_divide,
  1051. _DomainSafeDivide(), 0, 1)
  1052. floor_divide = _DomainedBinaryOperation(umath.floor_divide,
  1053. _DomainSafeDivide(), 0, 1)
  1054. remainder = _DomainedBinaryOperation(umath.remainder,
  1055. _DomainSafeDivide(), 0, 1)
  1056. fmod = _DomainedBinaryOperation(umath.fmod, _DomainSafeDivide(), 0, 1)
  1057. mod = _DomainedBinaryOperation(umath.mod, _DomainSafeDivide(), 0, 1)
  1058. ###############################################################################
  1059. # Mask creation functions #
  1060. ###############################################################################
  1061. def _replace_dtype_fields_recursive(dtype, primitive_dtype):
  1062. "Private function allowing recursion in _replace_dtype_fields."
  1063. _recurse = _replace_dtype_fields_recursive
  1064. # Do we have some name fields ?
  1065. if dtype.names is not None:
  1066. descr = []
  1067. for name in dtype.names:
  1068. field = dtype.fields[name]
  1069. if len(field) == 3:
  1070. # Prepend the title to the name
  1071. name = (field[-1], name)
  1072. descr.append((name, _recurse(field[0], primitive_dtype)))
  1073. new_dtype = np.dtype(descr)
  1074. # Is this some kind of composite a la (float,2)
  1075. elif dtype.subdtype:
  1076. descr = list(dtype.subdtype)
  1077. descr[0] = _recurse(dtype.subdtype[0], primitive_dtype)
  1078. new_dtype = np.dtype(tuple(descr))
  1079. # this is a primitive type, so do a direct replacement
  1080. else:
  1081. new_dtype = primitive_dtype
  1082. # preserve identity of dtypes
  1083. if new_dtype == dtype:
  1084. new_dtype = dtype
  1085. return new_dtype
  1086. def _replace_dtype_fields(dtype, primitive_dtype):
  1087. """
  1088. Construct a dtype description list from a given dtype.
  1089. Returns a new dtype object, with all fields and subtypes in the given type
  1090. recursively replaced with `primitive_dtype`.
  1091. Arguments are coerced to dtypes first.
  1092. """
  1093. dtype = np.dtype(dtype)
  1094. primitive_dtype = np.dtype(primitive_dtype)
  1095. return _replace_dtype_fields_recursive(dtype, primitive_dtype)
  1096. def make_mask_descr(ndtype):
  1097. """
  1098. Construct a dtype description list from a given dtype.
  1099. Returns a new dtype object, with the type of all fields in `ndtype` to a
  1100. boolean type. Field names are not altered.
  1101. Parameters
  1102. ----------
  1103. ndtype : dtype
  1104. The dtype to convert.
  1105. Returns
  1106. -------
  1107. result : dtype
  1108. A dtype that looks like `ndtype`, the type of all fields is boolean.
  1109. Examples
  1110. --------
  1111. >>> import numpy.ma as ma
  1112. >>> dtype = np.dtype({'names':['foo', 'bar'],
  1113. ... 'formats':[np.float32, np.int64]})
  1114. >>> dtype
  1115. dtype([('foo', '<f4'), ('bar', '<i8')])
  1116. >>> ma.make_mask_descr(dtype)
  1117. dtype([('foo', '|b1'), ('bar', '|b1')])
  1118. >>> ma.make_mask_descr(np.float32)
  1119. dtype('bool')
  1120. """
  1121. return _replace_dtype_fields(ndtype, MaskType)
  1122. def getmask(a):
  1123. """
  1124. Return the mask of a masked array, or nomask.
  1125. Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the
  1126. mask is not `nomask`, else return `nomask`. To guarantee a full array
  1127. of booleans of the same shape as a, use `getmaskarray`.
  1128. Parameters
  1129. ----------
  1130. a : array_like
  1131. Input `MaskedArray` for which the mask is required.
  1132. See Also
  1133. --------
  1134. getdata : Return the data of a masked array as an ndarray.
  1135. getmaskarray : Return the mask of a masked array, or full array of False.
  1136. Examples
  1137. --------
  1138. >>> import numpy.ma as ma
  1139. >>> a = ma.masked_equal([[1,2],[3,4]], 2)
  1140. >>> a
  1141. masked_array(
  1142. data=[[1, --],
  1143. [3, 4]],
  1144. mask=[[False, True],
  1145. [False, False]],
  1146. fill_value=2)
  1147. >>> ma.getmask(a)
  1148. array([[False, True],
  1149. [False, False]])
  1150. Equivalently use the `MaskedArray` `mask` attribute.
  1151. >>> a.mask
  1152. array([[False, True],
  1153. [False, False]])
  1154. Result when mask == `nomask`
  1155. >>> b = ma.masked_array([[1,2],[3,4]])
  1156. >>> b
  1157. masked_array(
  1158. data=[[1, 2],
  1159. [3, 4]],
  1160. mask=False,
  1161. fill_value=999999)
  1162. >>> ma.nomask
  1163. False
  1164. >>> ma.getmask(b) == ma.nomask
  1165. True
  1166. >>> b.mask == ma.nomask
  1167. True
  1168. """
  1169. return getattr(a, '_mask', nomask)
  1170. get_mask = getmask
  1171. def getmaskarray(arr):
  1172. """
  1173. Return the mask of a masked array, or full boolean array of False.
  1174. Return the mask of `arr` as an ndarray if `arr` is a `MaskedArray` and
  1175. the mask is not `nomask`, else return a full boolean array of False of
  1176. the same shape as `arr`.
  1177. Parameters
  1178. ----------
  1179. arr : array_like
  1180. Input `MaskedArray` for which the mask is required.
  1181. See Also
  1182. --------
  1183. getmask : Return the mask of a masked array, or nomask.
  1184. getdata : Return the data of a masked array as an ndarray.
  1185. Examples
  1186. --------
  1187. >>> import numpy.ma as ma
  1188. >>> a = ma.masked_equal([[1,2],[3,4]], 2)
  1189. >>> a
  1190. masked_array(
  1191. data=[[1, --],
  1192. [3, 4]],
  1193. mask=[[False, True],
  1194. [False, False]],
  1195. fill_value=2)
  1196. >>> ma.getmaskarray(a)
  1197. array([[False, True],
  1198. [False, False]])
  1199. Result when mask == ``nomask``
  1200. >>> b = ma.masked_array([[1,2],[3,4]])
  1201. >>> b
  1202. masked_array(
  1203. data=[[1, 2],
  1204. [3, 4]],
  1205. mask=False,
  1206. fill_value=999999)
  1207. >>> ma.getmaskarray(b)
  1208. array([[False, False],
  1209. [False, False]])
  1210. """
  1211. mask = getmask(arr)
  1212. if mask is nomask:
  1213. mask = make_mask_none(np.shape(arr), getattr(arr, 'dtype', None))
  1214. return mask
  1215. def is_mask(m):
  1216. """
  1217. Return True if m is a valid, standard mask.
  1218. This function does not check the contents of the input, only that the
  1219. type is MaskType. In particular, this function returns False if the
  1220. mask has a flexible dtype.
  1221. Parameters
  1222. ----------
  1223. m : array_like
  1224. Array to test.
  1225. Returns
  1226. -------
  1227. result : bool
  1228. True if `m.dtype.type` is MaskType, False otherwise.
  1229. See Also
  1230. --------
  1231. isMaskedArray : Test whether input is an instance of MaskedArray.
  1232. Examples
  1233. --------
  1234. >>> import numpy.ma as ma
  1235. >>> m = ma.masked_equal([0, 1, 0, 2, 3], 0)
  1236. >>> m
  1237. masked_array(data=[--, 1, --, 2, 3],
  1238. mask=[ True, False, True, False, False],
  1239. fill_value=0)
  1240. >>> ma.is_mask(m)
  1241. False
  1242. >>> ma.is_mask(m.mask)
  1243. True
  1244. Input must be an ndarray (or have similar attributes)
  1245. for it to be considered a valid mask.
  1246. >>> m = [False, True, False]
  1247. >>> ma.is_mask(m)
  1248. False
  1249. >>> m = np.array([False, True, False])
  1250. >>> m
  1251. array([False, True, False])
  1252. >>> ma.is_mask(m)
  1253. True
  1254. Arrays with complex dtypes don't return True.
  1255. >>> dtype = np.dtype({'names':['monty', 'pithon'],
  1256. ... 'formats':[bool, bool]})
  1257. >>> dtype
  1258. dtype([('monty', '|b1'), ('pithon', '|b1')])
  1259. >>> m = np.array([(True, False), (False, True), (True, False)],
  1260. ... dtype=dtype)
  1261. >>> m
  1262. array([( True, False), (False, True), ( True, False)],
  1263. dtype=[('monty', '?'), ('pithon', '?')])
  1264. >>> ma.is_mask(m)
  1265. False
  1266. """
  1267. try:
  1268. return m.dtype.type is MaskType
  1269. except AttributeError:
  1270. return False
  1271. def _shrink_mask(m):
  1272. """
  1273. Shrink a mask to nomask if possible
  1274. """
  1275. if m.dtype.names is None and not m.any():
  1276. return nomask
  1277. else:
  1278. return m
  1279. def make_mask(m, copy=False, shrink=True, dtype=MaskType):
  1280. """
  1281. Create a boolean mask from an array.
  1282. Return `m` as a boolean mask, creating a copy if necessary or requested.
  1283. The function can accept any sequence that is convertible to integers,
  1284. or ``nomask``. Does not require that contents must be 0s and 1s, values
  1285. of 0 are interpreted as False, everything else as True.
  1286. Parameters
  1287. ----------
  1288. m : array_like
  1289. Potential mask.
  1290. copy : bool, optional
  1291. Whether to return a copy of `m` (True) or `m` itself (False).
  1292. shrink : bool, optional
  1293. Whether to shrink `m` to ``nomask`` if all its values are False.
  1294. dtype : dtype, optional
  1295. Data-type of the output mask. By default, the output mask has a
  1296. dtype of MaskType (bool). If the dtype is flexible, each field has
  1297. a boolean dtype. This is ignored when `m` is ``nomask``, in which
  1298. case ``nomask`` is always returned.
  1299. Returns
  1300. -------
  1301. result : ndarray
  1302. A boolean mask derived from `m`.
  1303. Examples
  1304. --------
  1305. >>> import numpy.ma as ma
  1306. >>> m = [True, False, True, True]
  1307. >>> ma.make_mask(m)
  1308. array([ True, False, True, True])
  1309. >>> m = [1, 0, 1, 1]
  1310. >>> ma.make_mask(m)
  1311. array([ True, False, True, True])
  1312. >>> m = [1, 0, 2, -3]
  1313. >>> ma.make_mask(m)
  1314. array([ True, False, True, True])
  1315. Effect of the `shrink` parameter.
  1316. >>> m = np.zeros(4)
  1317. >>> m
  1318. array([0., 0., 0., 0.])
  1319. >>> ma.make_mask(m)
  1320. False
  1321. >>> ma.make_mask(m, shrink=False)
  1322. array([False, False, False, False])
  1323. Using a flexible `dtype`.
  1324. >>> m = [1, 0, 1, 1]
  1325. >>> n = [0, 1, 0, 0]
  1326. >>> arr = []
  1327. >>> for man, mouse in zip(m, n):
  1328. ... arr.append((man, mouse))
  1329. >>> arr
  1330. [(1, 0), (0, 1), (1, 0), (1, 0)]
  1331. >>> dtype = np.dtype({'names':['man', 'mouse'],
  1332. ... 'formats':[np.int64, np.int64]})
  1333. >>> arr = np.array(arr, dtype=dtype)
  1334. >>> arr
  1335. array([(1, 0), (0, 1), (1, 0), (1, 0)],
  1336. dtype=[('man', '<i8'), ('mouse', '<i8')])
  1337. >>> ma.make_mask(arr, dtype=dtype)
  1338. array([(True, False), (False, True), (True, False), (True, False)],
  1339. dtype=[('man', '|b1'), ('mouse', '|b1')])
  1340. """
  1341. if m is nomask:
  1342. return nomask
  1343. # Make sure the input dtype is valid.
  1344. dtype = make_mask_descr(dtype)
  1345. # legacy boolean special case: "existence of fields implies true"
  1346. if isinstance(m, ndarray) and m.dtype.fields and dtype == np.bool_:
  1347. return np.ones(m.shape, dtype=dtype)
  1348. # Fill the mask in case there are missing data; turn it into an ndarray.
  1349. result = np.array(filled(m, True), copy=copy, dtype=dtype, subok=True)
  1350. # Bas les masques !
  1351. if shrink:
  1352. result = _shrink_mask(result)
  1353. return result
  1354. def make_mask_none(newshape, dtype=None):
  1355. """
  1356. Return a boolean mask of the given shape, filled with False.
  1357. This function returns a boolean ndarray with all entries False, that can
  1358. be used in common mask manipulations. If a complex dtype is specified, the
  1359. type of each field is converted to a boolean type.
  1360. Parameters
  1361. ----------
  1362. newshape : tuple
  1363. A tuple indicating the shape of the mask.
  1364. dtype : {None, dtype}, optional
  1365. If None, use a MaskType instance. Otherwise, use a new datatype with
  1366. the same fields as `dtype`, converted to boolean types.
  1367. Returns
  1368. -------
  1369. result : ndarray
  1370. An ndarray of appropriate shape and dtype, filled with False.
  1371. See Also
  1372. --------
  1373. make_mask : Create a boolean mask from an array.
  1374. make_mask_descr : Construct a dtype description list from a given dtype.
  1375. Examples
  1376. --------
  1377. >>> import numpy.ma as ma
  1378. >>> ma.make_mask_none((3,))
  1379. array([False, False, False])
  1380. Defining a more complex dtype.
  1381. >>> dtype = np.dtype({'names':['foo', 'bar'],
  1382. ... 'formats':[np.float32, np.int64]})
  1383. >>> dtype
  1384. dtype([('foo', '<f4'), ('bar', '<i8')])
  1385. >>> ma.make_mask_none((3,), dtype=dtype)
  1386. array([(False, False), (False, False), (False, False)],
  1387. dtype=[('foo', '|b1'), ('bar', '|b1')])
  1388. """
  1389. if dtype is None:
  1390. result = np.zeros(newshape, dtype=MaskType)
  1391. else:
  1392. result = np.zeros(newshape, dtype=make_mask_descr(dtype))
  1393. return result
  1394. def mask_or(m1, m2, copy=False, shrink=True):
  1395. """
  1396. Combine two masks with the ``logical_or`` operator.
  1397. The result may be a view on `m1` or `m2` if the other is `nomask`
  1398. (i.e. False).
  1399. Parameters
  1400. ----------
  1401. m1, m2 : array_like
  1402. Input masks.
  1403. copy : bool, optional
  1404. If copy is False and one of the inputs is `nomask`, return a view
  1405. of the other input mask. Defaults to False.
  1406. shrink : bool, optional
  1407. Whether to shrink the output to `nomask` if all its values are
  1408. False. Defaults to True.
  1409. Returns
  1410. -------
  1411. mask : output mask
  1412. The result masks values that are masked in either `m1` or `m2`.
  1413. Raises
  1414. ------
  1415. ValueError
  1416. If `m1` and `m2` have different flexible dtypes.
  1417. Examples
  1418. --------
  1419. >>> m1 = np.ma.make_mask([0, 1, 1, 0])
  1420. >>> m2 = np.ma.make_mask([1, 0, 0, 0])
  1421. >>> np.ma.mask_or(m1, m2)
  1422. array([ True, True, True, False])
  1423. """
  1424. @recursive
  1425. def _recursive_mask_or(self, m1, m2, newmask):
  1426. names = m1.dtype.names
  1427. for name in names:
  1428. current1 = m1[name]
  1429. if current1.dtype.names is not None:
  1430. self(current1, m2[name], newmask[name])
  1431. else:
  1432. umath.logical_or(current1, m2[name], newmask[name])
  1433. return
  1434. if (m1 is nomask) or (m1 is False):
  1435. dtype = getattr(m2, 'dtype', MaskType)
  1436. return make_mask(m2, copy=copy, shrink=shrink, dtype=dtype)
  1437. if (m2 is nomask) or (m2 is False):
  1438. dtype = getattr(m1, 'dtype', MaskType)
  1439. return make_mask(m1, copy=copy, shrink=shrink, dtype=dtype)
  1440. if m1 is m2 and is_mask(m1):
  1441. return m1
  1442. (dtype1, dtype2) = (getattr(m1, 'dtype', None), getattr(m2, 'dtype', None))
  1443. if dtype1 != dtype2:
  1444. raise ValueError("Incompatible dtypes '%s'<>'%s'" % (dtype1, dtype2))
  1445. if dtype1.names is not None:
  1446. # Allocate an output mask array with the properly broadcast shape.
  1447. newmask = np.empty(np.broadcast(m1, m2).shape, dtype1)
  1448. _recursive_mask_or(m1, m2, newmask)
  1449. return newmask
  1450. return make_mask(umath.logical_or(m1, m2), copy=copy, shrink=shrink)
  1451. def flatten_mask(mask):
  1452. """
  1453. Returns a completely flattened version of the mask, where nested fields
  1454. are collapsed.
  1455. Parameters
  1456. ----------
  1457. mask : array_like
  1458. Input array, which will be interpreted as booleans.
  1459. Returns
  1460. -------
  1461. flattened_mask : ndarray of bools
  1462. The flattened input.
  1463. Examples
  1464. --------
  1465. >>> mask = np.array([0, 0, 1])
  1466. >>> np.ma.flatten_mask(mask)
  1467. array([False, False, True])
  1468. >>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
  1469. >>> np.ma.flatten_mask(mask)
  1470. array([False, False, False, True])
  1471. >>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
  1472. >>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype)
  1473. >>> np.ma.flatten_mask(mask)
  1474. array([False, False, False, False, False, True])
  1475. """
  1476. def _flatmask(mask):
  1477. "Flatten the mask and returns a (maybe nested) sequence of booleans."
  1478. mnames = mask.dtype.names
  1479. if mnames is not None:
  1480. return [flatten_mask(mask[name]) for name in mnames]
  1481. else:
  1482. return mask
  1483. def _flatsequence(sequence):
  1484. "Generates a flattened version of the sequence."
  1485. try:
  1486. for element in sequence:
  1487. if hasattr(element, '__iter__'):
  1488. for f in _flatsequence(element):
  1489. yield f
  1490. else:
  1491. yield element
  1492. except TypeError:
  1493. yield sequence
  1494. mask = np.asarray(mask)
  1495. flattened = _flatsequence(_flatmask(mask))
  1496. return np.array([_ for _ in flattened], dtype=bool)
  1497. def _check_mask_axis(mask, axis, keepdims=np._NoValue):
  1498. "Check whether there are masked values along the given axis"
  1499. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  1500. if mask is not nomask:
  1501. return mask.all(axis=axis, **kwargs)
  1502. return nomask
  1503. ###############################################################################
  1504. # Masking functions #
  1505. ###############################################################################
  1506. def masked_where(condition, a, copy=True):
  1507. """
  1508. Mask an array where a condition is met.
  1509. Return `a` as an array masked where `condition` is True.
  1510. Any masked values of `a` or `condition` are also masked in the output.
  1511. Parameters
  1512. ----------
  1513. condition : array_like
  1514. Masking condition. When `condition` tests floating point values for
  1515. equality, consider using ``masked_values`` instead.
  1516. a : array_like
  1517. Array to mask.
  1518. copy : bool
  1519. If True (default) make a copy of `a` in the result. If False modify
  1520. `a` in place and return a view.
  1521. Returns
  1522. -------
  1523. result : MaskedArray
  1524. The result of masking `a` where `condition` is True.
  1525. See Also
  1526. --------
  1527. masked_values : Mask using floating point equality.
  1528. masked_equal : Mask where equal to a given value.
  1529. masked_not_equal : Mask where `not` equal to a given value.
  1530. masked_less_equal : Mask where less than or equal to a given value.
  1531. masked_greater_equal : Mask where greater than or equal to a given value.
  1532. masked_less : Mask where less than a given value.
  1533. masked_greater : Mask where greater than a given value.
  1534. masked_inside : Mask inside a given interval.
  1535. masked_outside : Mask outside a given interval.
  1536. masked_invalid : Mask invalid values (NaNs or infs).
  1537. Examples
  1538. --------
  1539. >>> import numpy.ma as ma
  1540. >>> a = np.arange(4)
  1541. >>> a
  1542. array([0, 1, 2, 3])
  1543. >>> ma.masked_where(a <= 2, a)
  1544. masked_array(data=[--, --, --, 3],
  1545. mask=[ True, True, True, False],
  1546. fill_value=999999)
  1547. Mask array `b` conditional on `a`.
  1548. >>> b = ['a', 'b', 'c', 'd']
  1549. >>> ma.masked_where(a == 2, b)
  1550. masked_array(data=['a', 'b', --, 'd'],
  1551. mask=[False, False, True, False],
  1552. fill_value='N/A',
  1553. dtype='<U1')
  1554. Effect of the `copy` argument.
  1555. >>> c = ma.masked_where(a <= 2, a)
  1556. >>> c
  1557. masked_array(data=[--, --, --, 3],
  1558. mask=[ True, True, True, False],
  1559. fill_value=999999)
  1560. >>> c[0] = 99
  1561. >>> c
  1562. masked_array(data=[99, --, --, 3],
  1563. mask=[False, True, True, False],
  1564. fill_value=999999)
  1565. >>> a
  1566. array([0, 1, 2, 3])
  1567. >>> c = ma.masked_where(a <= 2, a, copy=False)
  1568. >>> c[0] = 99
  1569. >>> c
  1570. masked_array(data=[99, --, --, 3],
  1571. mask=[False, True, True, False],
  1572. fill_value=999999)
  1573. >>> a
  1574. array([99, 1, 2, 3])
  1575. When `condition` or `a` contain masked values.
  1576. >>> a = np.arange(4)
  1577. >>> a = ma.masked_where(a == 2, a)
  1578. >>> a
  1579. masked_array(data=[0, 1, --, 3],
  1580. mask=[False, False, True, False],
  1581. fill_value=999999)
  1582. >>> b = np.arange(4)
  1583. >>> b = ma.masked_where(b == 0, b)
  1584. >>> b
  1585. masked_array(data=[--, 1, 2, 3],
  1586. mask=[ True, False, False, False],
  1587. fill_value=999999)
  1588. >>> ma.masked_where(a == 3, b)
  1589. masked_array(data=[--, 1, --, --],
  1590. mask=[ True, False, True, True],
  1591. fill_value=999999)
  1592. """
  1593. # Make sure that condition is a valid standard-type mask.
  1594. cond = make_mask(condition, shrink=False)
  1595. a = np.array(a, copy=copy, subok=True)
  1596. (cshape, ashape) = (cond.shape, a.shape)
  1597. if cshape and cshape != ashape:
  1598. raise IndexError("Inconsistent shape between the condition and the input"
  1599. " (got %s and %s)" % (cshape, ashape))
  1600. if hasattr(a, '_mask'):
  1601. cond = mask_or(cond, a._mask)
  1602. cls = type(a)
  1603. else:
  1604. cls = MaskedArray
  1605. result = a.view(cls)
  1606. # Assign to *.mask so that structured masks are handled correctly.
  1607. result.mask = _shrink_mask(cond)
  1608. return result
  1609. def masked_greater(x, value, copy=True):
  1610. """
  1611. Mask an array where greater than a given value.
  1612. This function is a shortcut to ``masked_where``, with
  1613. `condition` = (x > value).
  1614. See Also
  1615. --------
  1616. masked_where : Mask where a condition is met.
  1617. Examples
  1618. --------
  1619. >>> import numpy.ma as ma
  1620. >>> a = np.arange(4)
  1621. >>> a
  1622. array([0, 1, 2, 3])
  1623. >>> ma.masked_greater(a, 2)
  1624. masked_array(data=[0, 1, 2, --],
  1625. mask=[False, False, False, True],
  1626. fill_value=999999)
  1627. """
  1628. return masked_where(greater(x, value), x, copy=copy)
  1629. def masked_greater_equal(x, value, copy=True):
  1630. """
  1631. Mask an array where greater than or equal to a given value.
  1632. This function is a shortcut to ``masked_where``, with
  1633. `condition` = (x >= value).
  1634. See Also
  1635. --------
  1636. masked_where : Mask where a condition is met.
  1637. Examples
  1638. --------
  1639. >>> import numpy.ma as ma
  1640. >>> a = np.arange(4)
  1641. >>> a
  1642. array([0, 1, 2, 3])
  1643. >>> ma.masked_greater_equal(a, 2)
  1644. masked_array(data=[0, 1, --, --],
  1645. mask=[False, False, True, True],
  1646. fill_value=999999)
  1647. """
  1648. return masked_where(greater_equal(x, value), x, copy=copy)
  1649. def masked_less(x, value, copy=True):
  1650. """
  1651. Mask an array where less than a given value.
  1652. This function is a shortcut to ``masked_where``, with
  1653. `condition` = (x < value).
  1654. See Also
  1655. --------
  1656. masked_where : Mask where a condition is met.
  1657. Examples
  1658. --------
  1659. >>> import numpy.ma as ma
  1660. >>> a = np.arange(4)
  1661. >>> a
  1662. array([0, 1, 2, 3])
  1663. >>> ma.masked_less(a, 2)
  1664. masked_array(data=[--, --, 2, 3],
  1665. mask=[ True, True, False, False],
  1666. fill_value=999999)
  1667. """
  1668. return masked_where(less(x, value), x, copy=copy)
  1669. def masked_less_equal(x, value, copy=True):
  1670. """
  1671. Mask an array where less than or equal to a given value.
  1672. This function is a shortcut to ``masked_where``, with
  1673. `condition` = (x <= value).
  1674. See Also
  1675. --------
  1676. masked_where : Mask where a condition is met.
  1677. Examples
  1678. --------
  1679. >>> import numpy.ma as ma
  1680. >>> a = np.arange(4)
  1681. >>> a
  1682. array([0, 1, 2, 3])
  1683. >>> ma.masked_less_equal(a, 2)
  1684. masked_array(data=[--, --, --, 3],
  1685. mask=[ True, True, True, False],
  1686. fill_value=999999)
  1687. """
  1688. return masked_where(less_equal(x, value), x, copy=copy)
  1689. def masked_not_equal(x, value, copy=True):
  1690. """
  1691. Mask an array where `not` equal to a given value.
  1692. This function is a shortcut to ``masked_where``, with
  1693. `condition` = (x != value).
  1694. See Also
  1695. --------
  1696. masked_where : Mask where a condition is met.
  1697. Examples
  1698. --------
  1699. >>> import numpy.ma as ma
  1700. >>> a = np.arange(4)
  1701. >>> a
  1702. array([0, 1, 2, 3])
  1703. >>> ma.masked_not_equal(a, 2)
  1704. masked_array(data=[--, --, 2, --],
  1705. mask=[ True, True, False, True],
  1706. fill_value=999999)
  1707. """
  1708. return masked_where(not_equal(x, value), x, copy=copy)
  1709. def masked_equal(x, value, copy=True):
  1710. """
  1711. Mask an array where equal to a given value.
  1712. This function is a shortcut to ``masked_where``, with
  1713. `condition` = (x == value). For floating point arrays,
  1714. consider using ``masked_values(x, value)``.
  1715. See Also
  1716. --------
  1717. masked_where : Mask where a condition is met.
  1718. masked_values : Mask using floating point equality.
  1719. Examples
  1720. --------
  1721. >>> import numpy.ma as ma
  1722. >>> a = np.arange(4)
  1723. >>> a
  1724. array([0, 1, 2, 3])
  1725. >>> ma.masked_equal(a, 2)
  1726. masked_array(data=[0, 1, --, 3],
  1727. mask=[False, False, True, False],
  1728. fill_value=2)
  1729. """
  1730. output = masked_where(equal(x, value), x, copy=copy)
  1731. output.fill_value = value
  1732. return output
  1733. def masked_inside(x, v1, v2, copy=True):
  1734. """
  1735. Mask an array inside a given interval.
  1736. Shortcut to ``masked_where``, where `condition` is True for `x` inside
  1737. the interval [v1,v2] (v1 <= x <= v2). The boundaries `v1` and `v2`
  1738. can be given in either order.
  1739. See Also
  1740. --------
  1741. masked_where : Mask where a condition is met.
  1742. Notes
  1743. -----
  1744. The array `x` is prefilled with its filling value.
  1745. Examples
  1746. --------
  1747. >>> import numpy.ma as ma
  1748. >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
  1749. >>> ma.masked_inside(x, -0.3, 0.3)
  1750. masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
  1751. mask=[False, False, True, True, False, False],
  1752. fill_value=1e+20)
  1753. The order of `v1` and `v2` doesn't matter.
  1754. >>> ma.masked_inside(x, 0.3, -0.3)
  1755. masked_array(data=[0.31, 1.2, --, --, -0.4, -1.1],
  1756. mask=[False, False, True, True, False, False],
  1757. fill_value=1e+20)
  1758. """
  1759. if v2 < v1:
  1760. (v1, v2) = (v2, v1)
  1761. xf = filled(x)
  1762. condition = (xf >= v1) & (xf <= v2)
  1763. return masked_where(condition, x, copy=copy)
  1764. def masked_outside(x, v1, v2, copy=True):
  1765. """
  1766. Mask an array outside a given interval.
  1767. Shortcut to ``masked_where``, where `condition` is True for `x` outside
  1768. the interval [v1,v2] (x < v1)|(x > v2).
  1769. The boundaries `v1` and `v2` can be given in either order.
  1770. See Also
  1771. --------
  1772. masked_where : Mask where a condition is met.
  1773. Notes
  1774. -----
  1775. The array `x` is prefilled with its filling value.
  1776. Examples
  1777. --------
  1778. >>> import numpy.ma as ma
  1779. >>> x = [0.31, 1.2, 0.01, 0.2, -0.4, -1.1]
  1780. >>> ma.masked_outside(x, -0.3, 0.3)
  1781. masked_array(data=[--, --, 0.01, 0.2, --, --],
  1782. mask=[ True, True, False, False, True, True],
  1783. fill_value=1e+20)
  1784. The order of `v1` and `v2` doesn't matter.
  1785. >>> ma.masked_outside(x, 0.3, -0.3)
  1786. masked_array(data=[--, --, 0.01, 0.2, --, --],
  1787. mask=[ True, True, False, False, True, True],
  1788. fill_value=1e+20)
  1789. """
  1790. if v2 < v1:
  1791. (v1, v2) = (v2, v1)
  1792. xf = filled(x)
  1793. condition = (xf < v1) | (xf > v2)
  1794. return masked_where(condition, x, copy=copy)
  1795. def masked_object(x, value, copy=True, shrink=True):
  1796. """
  1797. Mask the array `x` where the data are exactly equal to value.
  1798. This function is similar to `masked_values`, but only suitable
  1799. for object arrays: for floating point, use `masked_values` instead.
  1800. Parameters
  1801. ----------
  1802. x : array_like
  1803. Array to mask
  1804. value : object
  1805. Comparison value
  1806. copy : {True, False}, optional
  1807. Whether to return a copy of `x`.
  1808. shrink : {True, False}, optional
  1809. Whether to collapse a mask full of False to nomask
  1810. Returns
  1811. -------
  1812. result : MaskedArray
  1813. The result of masking `x` where equal to `value`.
  1814. See Also
  1815. --------
  1816. masked_where : Mask where a condition is met.
  1817. masked_equal : Mask where equal to a given value (integers).
  1818. masked_values : Mask using floating point equality.
  1819. Examples
  1820. --------
  1821. >>> import numpy.ma as ma
  1822. >>> food = np.array(['green_eggs', 'ham'], dtype=object)
  1823. >>> # don't eat spoiled food
  1824. >>> eat = ma.masked_object(food, 'green_eggs')
  1825. >>> eat
  1826. masked_array(data=[--, 'ham'],
  1827. mask=[ True, False],
  1828. fill_value='green_eggs',
  1829. dtype=object)
  1830. >>> # plain ol` ham is boring
  1831. >>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object)
  1832. >>> eat = ma.masked_object(fresh_food, 'green_eggs')
  1833. >>> eat
  1834. masked_array(data=['cheese', 'ham', 'pineapple'],
  1835. mask=False,
  1836. fill_value='green_eggs',
  1837. dtype=object)
  1838. Note that `mask` is set to ``nomask`` if possible.
  1839. >>> eat
  1840. masked_array(data=['cheese', 'ham', 'pineapple'],
  1841. mask=False,
  1842. fill_value='green_eggs',
  1843. dtype=object)
  1844. """
  1845. if isMaskedArray(x):
  1846. condition = umath.equal(x._data, value)
  1847. mask = x._mask
  1848. else:
  1849. condition = umath.equal(np.asarray(x), value)
  1850. mask = nomask
  1851. mask = mask_or(mask, make_mask(condition, shrink=shrink))
  1852. return masked_array(x, mask=mask, copy=copy, fill_value=value)
  1853. def masked_values(x, value, rtol=1e-5, atol=1e-8, copy=True, shrink=True):
  1854. """
  1855. Mask using floating point equality.
  1856. Return a MaskedArray, masked where the data in array `x` are approximately
  1857. equal to `value`, determined using `isclose`. The default tolerances for
  1858. `masked_values` are the same as those for `isclose`.
  1859. For integer types, exact equality is used, in the same way as
  1860. `masked_equal`.
  1861. The fill_value is set to `value` and the mask is set to ``nomask`` if
  1862. possible.
  1863. Parameters
  1864. ----------
  1865. x : array_like
  1866. Array to mask.
  1867. value : float
  1868. Masking value.
  1869. rtol, atol : float, optional
  1870. Tolerance parameters passed on to `isclose`
  1871. copy : bool, optional
  1872. Whether to return a copy of `x`.
  1873. shrink : bool, optional
  1874. Whether to collapse a mask full of False to ``nomask``.
  1875. Returns
  1876. -------
  1877. result : MaskedArray
  1878. The result of masking `x` where approximately equal to `value`.
  1879. See Also
  1880. --------
  1881. masked_where : Mask where a condition is met.
  1882. masked_equal : Mask where equal to a given value (integers).
  1883. Examples
  1884. --------
  1885. >>> import numpy.ma as ma
  1886. >>> x = np.array([1, 1.1, 2, 1.1, 3])
  1887. >>> ma.masked_values(x, 1.1)
  1888. masked_array(data=[1.0, --, 2.0, --, 3.0],
  1889. mask=[False, True, False, True, False],
  1890. fill_value=1.1)
  1891. Note that `mask` is set to ``nomask`` if possible.
  1892. >>> ma.masked_values(x, 1.5)
  1893. masked_array(data=[1. , 1.1, 2. , 1.1, 3. ],
  1894. mask=False,
  1895. fill_value=1.5)
  1896. For integers, the fill value will be different in general to the
  1897. result of ``masked_equal``.
  1898. >>> x = np.arange(5)
  1899. >>> x
  1900. array([0, 1, 2, 3, 4])
  1901. >>> ma.masked_values(x, 2)
  1902. masked_array(data=[0, 1, --, 3, 4],
  1903. mask=[False, False, True, False, False],
  1904. fill_value=2)
  1905. >>> ma.masked_equal(x, 2)
  1906. masked_array(data=[0, 1, --, 3, 4],
  1907. mask=[False, False, True, False, False],
  1908. fill_value=2)
  1909. """
  1910. xnew = filled(x, value)
  1911. if np.issubdtype(xnew.dtype, np.floating):
  1912. mask = np.isclose(xnew, value, atol=atol, rtol=rtol)
  1913. else:
  1914. mask = umath.equal(xnew, value)
  1915. ret = masked_array(xnew, mask=mask, copy=copy, fill_value=value)
  1916. if shrink:
  1917. ret.shrink_mask()
  1918. return ret
  1919. def masked_invalid(a, copy=True):
  1920. """
  1921. Mask an array where invalid values occur (NaNs or infs).
  1922. This function is a shortcut to ``masked_where``, with
  1923. `condition` = ~(np.isfinite(a)). Any pre-existing mask is conserved.
  1924. Only applies to arrays with a dtype where NaNs or infs make sense
  1925. (i.e. floating point types), but accepts any array_like object.
  1926. See Also
  1927. --------
  1928. masked_where : Mask where a condition is met.
  1929. Examples
  1930. --------
  1931. >>> import numpy.ma as ma
  1932. >>> a = np.arange(5, dtype=float)
  1933. >>> a[2] = np.NaN
  1934. >>> a[3] = np.PINF
  1935. >>> a
  1936. array([ 0., 1., nan, inf, 4.])
  1937. >>> ma.masked_invalid(a)
  1938. masked_array(data=[0.0, 1.0, --, --, 4.0],
  1939. mask=[False, False, True, True, False],
  1940. fill_value=1e+20)
  1941. """
  1942. a = np.array(a, copy=copy, subok=True)
  1943. mask = getattr(a, '_mask', None)
  1944. if mask is not None:
  1945. condition = ~(np.isfinite(getdata(a)))
  1946. if mask is not nomask:
  1947. condition |= mask
  1948. cls = type(a)
  1949. else:
  1950. condition = ~(np.isfinite(a))
  1951. cls = MaskedArray
  1952. result = a.view(cls)
  1953. result._mask = condition
  1954. return result
  1955. ###############################################################################
  1956. # Printing options #
  1957. ###############################################################################
  1958. class _MaskedPrintOption(object):
  1959. """
  1960. Handle the string used to represent missing data in a masked array.
  1961. """
  1962. def __init__(self, display):
  1963. """
  1964. Create the masked_print_option object.
  1965. """
  1966. self._display = display
  1967. self._enabled = True
  1968. def display(self):
  1969. """
  1970. Display the string to print for masked values.
  1971. """
  1972. return self._display
  1973. def set_display(self, s):
  1974. """
  1975. Set the string to print for masked values.
  1976. """
  1977. self._display = s
  1978. def enabled(self):
  1979. """
  1980. Is the use of the display value enabled?
  1981. """
  1982. return self._enabled
  1983. def enable(self, shrink=1):
  1984. """
  1985. Set the enabling shrink to `shrink`.
  1986. """
  1987. self._enabled = shrink
  1988. def __str__(self):
  1989. return str(self._display)
  1990. __repr__ = __str__
  1991. # if you single index into a masked location you get this object.
  1992. masked_print_option = _MaskedPrintOption('--')
  1993. def _recursive_printoption(result, mask, printopt):
  1994. """
  1995. Puts printoptions in result where mask is True.
  1996. Private function allowing for recursion
  1997. """
  1998. names = result.dtype.names
  1999. if names is not None:
  2000. for name in names:
  2001. curdata = result[name]
  2002. curmask = mask[name]
  2003. _recursive_printoption(curdata, curmask, printopt)
  2004. else:
  2005. np.copyto(result, printopt, where=mask)
  2006. return
  2007. # For better or worse, these end in a newline
  2008. _legacy_print_templates = dict(
  2009. long_std=textwrap.dedent("""\
  2010. masked_%(name)s(data =
  2011. %(data)s,
  2012. %(nlen)s mask =
  2013. %(mask)s,
  2014. %(nlen)s fill_value = %(fill)s)
  2015. """),
  2016. long_flx=textwrap.dedent("""\
  2017. masked_%(name)s(data =
  2018. %(data)s,
  2019. %(nlen)s mask =
  2020. %(mask)s,
  2021. %(nlen)s fill_value = %(fill)s,
  2022. %(nlen)s dtype = %(dtype)s)
  2023. """),
  2024. short_std=textwrap.dedent("""\
  2025. masked_%(name)s(data = %(data)s,
  2026. %(nlen)s mask = %(mask)s,
  2027. %(nlen)s fill_value = %(fill)s)
  2028. """),
  2029. short_flx=textwrap.dedent("""\
  2030. masked_%(name)s(data = %(data)s,
  2031. %(nlen)s mask = %(mask)s,
  2032. %(nlen)s fill_value = %(fill)s,
  2033. %(nlen)s dtype = %(dtype)s)
  2034. """)
  2035. )
  2036. ###############################################################################
  2037. # MaskedArray class #
  2038. ###############################################################################
  2039. def _recursive_filled(a, mask, fill_value):
  2040. """
  2041. Recursively fill `a` with `fill_value`.
  2042. """
  2043. names = a.dtype.names
  2044. for name in names:
  2045. current = a[name]
  2046. if current.dtype.names is not None:
  2047. _recursive_filled(current, mask[name], fill_value[name])
  2048. else:
  2049. np.copyto(current, fill_value[name], where=mask[name])
  2050. def flatten_structured_array(a):
  2051. """
  2052. Flatten a structured array.
  2053. The data type of the output is chosen such that it can represent all of the
  2054. (nested) fields.
  2055. Parameters
  2056. ----------
  2057. a : structured array
  2058. Returns
  2059. -------
  2060. output : masked array or ndarray
  2061. A flattened masked array if the input is a masked array, otherwise a
  2062. standard ndarray.
  2063. Examples
  2064. --------
  2065. >>> ndtype = [('a', int), ('b', float)]
  2066. >>> a = np.array([(1, 1), (2, 2)], dtype=ndtype)
  2067. >>> np.ma.flatten_structured_array(a)
  2068. array([[1., 1.],
  2069. [2., 2.]])
  2070. """
  2071. def flatten_sequence(iterable):
  2072. """
  2073. Flattens a compound of nested iterables.
  2074. """
  2075. for elm in iter(iterable):
  2076. if hasattr(elm, '__iter__'):
  2077. for f in flatten_sequence(elm):
  2078. yield f
  2079. else:
  2080. yield elm
  2081. a = np.asanyarray(a)
  2082. inishape = a.shape
  2083. a = a.ravel()
  2084. if isinstance(a, MaskedArray):
  2085. out = np.array([tuple(flatten_sequence(d.item())) for d in a._data])
  2086. out = out.view(MaskedArray)
  2087. out._mask = np.array([tuple(flatten_sequence(d.item()))
  2088. for d in getmaskarray(a)])
  2089. else:
  2090. out = np.array([tuple(flatten_sequence(d.item())) for d in a])
  2091. if len(inishape) > 1:
  2092. newshape = list(out.shape)
  2093. newshape[0] = inishape
  2094. out.shape = tuple(flatten_sequence(newshape))
  2095. return out
  2096. def _arraymethod(funcname, onmask=True):
  2097. """
  2098. Return a class method wrapper around a basic array method.
  2099. Creates a class method which returns a masked array, where the new
  2100. ``_data`` array is the output of the corresponding basic method called
  2101. on the original ``_data``.
  2102. If `onmask` is True, the new mask is the output of the method called
  2103. on the initial mask. Otherwise, the new mask is just a reference
  2104. to the initial mask.
  2105. Parameters
  2106. ----------
  2107. funcname : str
  2108. Name of the function to apply on data.
  2109. onmask : bool
  2110. Whether the mask must be processed also (True) or left
  2111. alone (False). Default is True. Make available as `_onmask`
  2112. attribute.
  2113. Returns
  2114. -------
  2115. method : instancemethod
  2116. Class method wrapper of the specified basic array method.
  2117. """
  2118. def wrapped_method(self, *args, **params):
  2119. result = getattr(self._data, funcname)(*args, **params)
  2120. result = result.view(type(self))
  2121. result._update_from(self)
  2122. mask = self._mask
  2123. if not onmask:
  2124. result.__setmask__(mask)
  2125. elif mask is not nomask:
  2126. # __setmask__ makes a copy, which we don't want
  2127. result._mask = getattr(mask, funcname)(*args, **params)
  2128. return result
  2129. methdoc = getattr(ndarray, funcname, None) or getattr(np, funcname, None)
  2130. if methdoc is not None:
  2131. wrapped_method.__doc__ = methdoc.__doc__
  2132. wrapped_method.__name__ = funcname
  2133. return wrapped_method
  2134. class MaskedIterator(object):
  2135. """
  2136. Flat iterator object to iterate over masked arrays.
  2137. A `MaskedIterator` iterator is returned by ``x.flat`` for any masked array
  2138. `x`. It allows iterating over the array as if it were a 1-D array,
  2139. either in a for-loop or by calling its `next` method.
  2140. Iteration is done in C-contiguous style, with the last index varying the
  2141. fastest. The iterator can also be indexed using basic slicing or
  2142. advanced indexing.
  2143. See Also
  2144. --------
  2145. MaskedArray.flat : Return a flat iterator over an array.
  2146. MaskedArray.flatten : Returns a flattened copy of an array.
  2147. Notes
  2148. -----
  2149. `MaskedIterator` is not exported by the `ma` module. Instead of
  2150. instantiating a `MaskedIterator` directly, use `MaskedArray.flat`.
  2151. Examples
  2152. --------
  2153. >>> x = np.ma.array(arange(6).reshape(2, 3))
  2154. >>> fl = x.flat
  2155. >>> type(fl)
  2156. <class 'numpy.ma.core.MaskedIterator'>
  2157. >>> for item in fl:
  2158. ... print(item)
  2159. ...
  2160. 0
  2161. 1
  2162. 2
  2163. 3
  2164. 4
  2165. 5
  2166. Extracting more than a single element b indexing the `MaskedIterator`
  2167. returns a masked array:
  2168. >>> fl[2:4]
  2169. masked_array(data = [2 3],
  2170. mask = False,
  2171. fill_value = 999999)
  2172. """
  2173. def __init__(self, ma):
  2174. self.ma = ma
  2175. self.dataiter = ma._data.flat
  2176. if ma._mask is nomask:
  2177. self.maskiter = None
  2178. else:
  2179. self.maskiter = ma._mask.flat
  2180. def __iter__(self):
  2181. return self
  2182. def __getitem__(self, indx):
  2183. result = self.dataiter.__getitem__(indx).view(type(self.ma))
  2184. if self.maskiter is not None:
  2185. _mask = self.maskiter.__getitem__(indx)
  2186. if isinstance(_mask, ndarray):
  2187. # set shape to match that of data; this is needed for matrices
  2188. _mask.shape = result.shape
  2189. result._mask = _mask
  2190. elif isinstance(_mask, np.void):
  2191. return mvoid(result, mask=_mask, hardmask=self.ma._hardmask)
  2192. elif _mask: # Just a scalar, masked
  2193. return masked
  2194. return result
  2195. # This won't work if ravel makes a copy
  2196. def __setitem__(self, index, value):
  2197. self.dataiter[index] = getdata(value)
  2198. if self.maskiter is not None:
  2199. self.maskiter[index] = getmaskarray(value)
  2200. def __next__(self):
  2201. """
  2202. Return the next value, or raise StopIteration.
  2203. Examples
  2204. --------
  2205. >>> x = np.ma.array([3, 2], mask=[0, 1])
  2206. >>> fl = x.flat
  2207. >>> next(fl)
  2208. 3
  2209. >>> next(fl)
  2210. masked
  2211. >>> next(fl)
  2212. Traceback (most recent call last):
  2213. ...
  2214. StopIteration
  2215. """
  2216. d = next(self.dataiter)
  2217. if self.maskiter is not None:
  2218. m = next(self.maskiter)
  2219. if isinstance(m, np.void):
  2220. return mvoid(d, mask=m, hardmask=self.ma._hardmask)
  2221. elif m: # Just a scalar, masked
  2222. return masked
  2223. return d
  2224. next = __next__
  2225. class MaskedArray(ndarray):
  2226. """
  2227. An array class with possibly masked values.
  2228. Masked values of True exclude the corresponding element from any
  2229. computation.
  2230. Construction::
  2231. x = MaskedArray(data, mask=nomask, dtype=None, copy=False, subok=True,
  2232. ndmin=0, fill_value=None, keep_mask=True, hard_mask=None,
  2233. shrink=True, order=None)
  2234. Parameters
  2235. ----------
  2236. data : array_like
  2237. Input data.
  2238. mask : sequence, optional
  2239. Mask. Must be convertible to an array of booleans with the same
  2240. shape as `data`. True indicates a masked (i.e. invalid) data.
  2241. dtype : dtype, optional
  2242. Data type of the output.
  2243. If `dtype` is None, the type of the data argument (``data.dtype``)
  2244. is used. If `dtype` is not None and different from ``data.dtype``,
  2245. a copy is performed.
  2246. copy : bool, optional
  2247. Whether to copy the input data (True), or to use a reference instead.
  2248. Default is False.
  2249. subok : bool, optional
  2250. Whether to return a subclass of `MaskedArray` if possible (True) or a
  2251. plain `MaskedArray`. Default is True.
  2252. ndmin : int, optional
  2253. Minimum number of dimensions. Default is 0.
  2254. fill_value : scalar, optional
  2255. Value used to fill in the masked values when necessary.
  2256. If None, a default based on the data-type is used.
  2257. keep_mask : bool, optional
  2258. Whether to combine `mask` with the mask of the input data, if any
  2259. (True), or to use only `mask` for the output (False). Default is True.
  2260. hard_mask : bool, optional
  2261. Whether to use a hard mask or not. With a hard mask, masked values
  2262. cannot be unmasked. Default is False.
  2263. shrink : bool, optional
  2264. Whether to force compression of an empty mask. Default is True.
  2265. order : {'C', 'F', 'A'}, optional
  2266. Specify the order of the array. If order is 'C', then the array
  2267. will be in C-contiguous order (last-index varies the fastest).
  2268. If order is 'F', then the returned array will be in
  2269. Fortran-contiguous order (first-index varies the fastest).
  2270. If order is 'A' (default), then the returned array may be
  2271. in any order (either C-, Fortran-contiguous, or even discontiguous),
  2272. unless a copy is required, in which case it will be C-contiguous.
  2273. """
  2274. __array_priority__ = 15
  2275. _defaultmask = nomask
  2276. _defaulthardmask = False
  2277. _baseclass = ndarray
  2278. # Maximum number of elements per axis used when printing an array. The
  2279. # 1d case is handled separately because we need more values in this case.
  2280. _print_width = 100
  2281. _print_width_1d = 1500
  2282. def __new__(cls, data=None, mask=nomask, dtype=None, copy=False,
  2283. subok=True, ndmin=0, fill_value=None, keep_mask=True,
  2284. hard_mask=None, shrink=True, order=None, **options):
  2285. """
  2286. Create a new masked array from scratch.
  2287. Notes
  2288. -----
  2289. A masked array can also be created by taking a .view(MaskedArray).
  2290. """
  2291. # Process data.
  2292. _data = np.array(data, dtype=dtype, copy=copy,
  2293. order=order, subok=True, ndmin=ndmin)
  2294. _baseclass = getattr(data, '_baseclass', type(_data))
  2295. # Check that we're not erasing the mask.
  2296. if isinstance(data, MaskedArray) and (data.shape != _data.shape):
  2297. copy = True
  2298. # Here, we copy the _view_, so that we can attach new properties to it
  2299. # we must never do .view(MaskedConstant), as that would create a new
  2300. # instance of np.ma.masked, which make identity comparison fail
  2301. if isinstance(data, cls) and subok and not isinstance(data, MaskedConstant):
  2302. _data = ndarray.view(_data, type(data))
  2303. else:
  2304. _data = ndarray.view(_data, cls)
  2305. # Backwards compatibility w/ numpy.core.ma.
  2306. if hasattr(data, '_mask') and not isinstance(data, ndarray):
  2307. _data._mask = data._mask
  2308. # FIXME _sharedmask is never used.
  2309. _sharedmask = True
  2310. # Process mask.
  2311. # Type of the mask
  2312. mdtype = make_mask_descr(_data.dtype)
  2313. if mask is nomask:
  2314. # Case 1. : no mask in input.
  2315. # Erase the current mask ?
  2316. if not keep_mask:
  2317. # With a reduced version
  2318. if shrink:
  2319. _data._mask = nomask
  2320. # With full version
  2321. else:
  2322. _data._mask = np.zeros(_data.shape, dtype=mdtype)
  2323. # Check whether we missed something
  2324. elif isinstance(data, (tuple, list)):
  2325. try:
  2326. # If data is a sequence of masked array
  2327. mask = np.array([getmaskarray(m) for m in data],
  2328. dtype=mdtype)
  2329. except ValueError:
  2330. # If data is nested
  2331. mask = nomask
  2332. # Force shrinking of the mask if needed (and possible)
  2333. if (mdtype == MaskType) and mask.any():
  2334. _data._mask = mask
  2335. _data._sharedmask = False
  2336. else:
  2337. _data._sharedmask = not copy
  2338. if copy:
  2339. _data._mask = _data._mask.copy()
  2340. # Reset the shape of the original mask
  2341. if getmask(data) is not nomask:
  2342. data._mask.shape = data.shape
  2343. else:
  2344. # Case 2. : With a mask in input.
  2345. # If mask is boolean, create an array of True or False
  2346. if mask is True and mdtype == MaskType:
  2347. mask = np.ones(_data.shape, dtype=mdtype)
  2348. elif mask is False and mdtype == MaskType:
  2349. mask = np.zeros(_data.shape, dtype=mdtype)
  2350. else:
  2351. # Read the mask with the current mdtype
  2352. try:
  2353. mask = np.array(mask, copy=copy, dtype=mdtype)
  2354. # Or assume it's a sequence of bool/int
  2355. except TypeError:
  2356. mask = np.array([tuple([m] * len(mdtype)) for m in mask],
  2357. dtype=mdtype)
  2358. # Make sure the mask and the data have the same shape
  2359. if mask.shape != _data.shape:
  2360. (nd, nm) = (_data.size, mask.size)
  2361. if nm == 1:
  2362. mask = np.resize(mask, _data.shape)
  2363. elif nm == nd:
  2364. mask = np.reshape(mask, _data.shape)
  2365. else:
  2366. msg = "Mask and data not compatible: data size is %i, " + \
  2367. "mask size is %i."
  2368. raise MaskError(msg % (nd, nm))
  2369. copy = True
  2370. # Set the mask to the new value
  2371. if _data._mask is nomask:
  2372. _data._mask = mask
  2373. _data._sharedmask = not copy
  2374. else:
  2375. if not keep_mask:
  2376. _data._mask = mask
  2377. _data._sharedmask = not copy
  2378. else:
  2379. if _data.dtype.names is not None:
  2380. def _recursive_or(a, b):
  2381. "do a|=b on each field of a, recursively"
  2382. for name in a.dtype.names:
  2383. (af, bf) = (a[name], b[name])
  2384. if af.dtype.names is not None:
  2385. _recursive_or(af, bf)
  2386. else:
  2387. af |= bf
  2388. _recursive_or(_data._mask, mask)
  2389. else:
  2390. _data._mask = np.logical_or(mask, _data._mask)
  2391. _data._sharedmask = False
  2392. # Update fill_value.
  2393. if fill_value is None:
  2394. fill_value = getattr(data, '_fill_value', None)
  2395. # But don't run the check unless we have something to check.
  2396. if fill_value is not None:
  2397. _data._fill_value = _check_fill_value(fill_value, _data.dtype)
  2398. # Process extra options ..
  2399. if hard_mask is None:
  2400. _data._hardmask = getattr(data, '_hardmask', False)
  2401. else:
  2402. _data._hardmask = hard_mask
  2403. _data._baseclass = _baseclass
  2404. return _data
  2405. def _update_from(self, obj):
  2406. """
  2407. Copies some attributes of obj to self.
  2408. """
  2409. if isinstance(obj, ndarray):
  2410. _baseclass = type(obj)
  2411. else:
  2412. _baseclass = ndarray
  2413. # We need to copy the _basedict to avoid backward propagation
  2414. _optinfo = {}
  2415. _optinfo.update(getattr(obj, '_optinfo', {}))
  2416. _optinfo.update(getattr(obj, '_basedict', {}))
  2417. if not isinstance(obj, MaskedArray):
  2418. _optinfo.update(getattr(obj, '__dict__', {}))
  2419. _dict = dict(_fill_value=getattr(obj, '_fill_value', None),
  2420. _hardmask=getattr(obj, '_hardmask', False),
  2421. _sharedmask=getattr(obj, '_sharedmask', False),
  2422. _isfield=getattr(obj, '_isfield', False),
  2423. _baseclass=getattr(obj, '_baseclass', _baseclass),
  2424. _optinfo=_optinfo,
  2425. _basedict=_optinfo)
  2426. self.__dict__.update(_dict)
  2427. self.__dict__.update(_optinfo)
  2428. return
  2429. def __array_finalize__(self, obj):
  2430. """
  2431. Finalizes the masked array.
  2432. """
  2433. # Get main attributes.
  2434. self._update_from(obj)
  2435. # We have to decide how to initialize self.mask, based on
  2436. # obj.mask. This is very difficult. There might be some
  2437. # correspondence between the elements in the array we are being
  2438. # created from (= obj) and us. Or there might not. This method can
  2439. # be called in all kinds of places for all kinds of reasons -- could
  2440. # be empty_like, could be slicing, could be a ufunc, could be a view.
  2441. # The numpy subclassing interface simply doesn't give us any way
  2442. # to know, which means that at best this method will be based on
  2443. # guesswork and heuristics. To make things worse, there isn't even any
  2444. # clear consensus about what the desired behavior is. For instance,
  2445. # most users think that np.empty_like(marr) -- which goes via this
  2446. # method -- should return a masked array with an empty mask (see
  2447. # gh-3404 and linked discussions), but others disagree, and they have
  2448. # existing code which depends on empty_like returning an array that
  2449. # matches the input mask.
  2450. #
  2451. # Historically our algorithm was: if the template object mask had the
  2452. # same *number of elements* as us, then we used *it's mask object
  2453. # itself* as our mask, so that writes to us would also write to the
  2454. # original array. This is horribly broken in multiple ways.
  2455. #
  2456. # Now what we do instead is, if the template object mask has the same
  2457. # number of elements as us, and we do not have the same base pointer
  2458. # as the template object (b/c views like arr[...] should keep the same
  2459. # mask), then we make a copy of the template object mask and use
  2460. # that. This is also horribly broken but somewhat less so. Maybe.
  2461. if isinstance(obj, ndarray):
  2462. # XX: This looks like a bug -- shouldn't it check self.dtype
  2463. # instead?
  2464. if obj.dtype.names is not None:
  2465. _mask = getmaskarray(obj)
  2466. else:
  2467. _mask = getmask(obj)
  2468. # If self and obj point to exactly the same data, then probably
  2469. # self is a simple view of obj (e.g., self = obj[...]), so they
  2470. # should share the same mask. (This isn't 100% reliable, e.g. self
  2471. # could be the first row of obj, or have strange strides, but as a
  2472. # heuristic it's not bad.) In all other cases, we make a copy of
  2473. # the mask, so that future modifications to 'self' do not end up
  2474. # side-effecting 'obj' as well.
  2475. if (_mask is not nomask and obj.__array_interface__["data"][0]
  2476. != self.__array_interface__["data"][0]):
  2477. # We should make a copy. But we could get here via astype,
  2478. # in which case the mask might need a new dtype as well
  2479. # (e.g., changing to or from a structured dtype), and the
  2480. # order could have changed. So, change the mask type if
  2481. # needed and use astype instead of copy.
  2482. if self.dtype == obj.dtype:
  2483. _mask_dtype = _mask.dtype
  2484. else:
  2485. _mask_dtype = make_mask_descr(self.dtype)
  2486. if self.flags.c_contiguous:
  2487. order = "C"
  2488. elif self.flags.f_contiguous:
  2489. order = "F"
  2490. else:
  2491. order = "K"
  2492. _mask = _mask.astype(_mask_dtype, order)
  2493. else:
  2494. # Take a view so shape changes, etc., do not propagate back.
  2495. _mask = _mask.view()
  2496. else:
  2497. _mask = nomask
  2498. self._mask = _mask
  2499. # Finalize the mask
  2500. if self._mask is not nomask:
  2501. try:
  2502. self._mask.shape = self.shape
  2503. except ValueError:
  2504. self._mask = nomask
  2505. except (TypeError, AttributeError):
  2506. # When _mask.shape is not writable (because it's a void)
  2507. pass
  2508. # Finalize the fill_value
  2509. if self._fill_value is not None:
  2510. self._fill_value = _check_fill_value(self._fill_value, self.dtype)
  2511. elif self.dtype.names is not None:
  2512. # Finalize the default fill_value for structured arrays
  2513. self._fill_value = _check_fill_value(None, self.dtype)
  2514. def __array_wrap__(self, obj, context=None):
  2515. """
  2516. Special hook for ufuncs.
  2517. Wraps the numpy array and sets the mask according to context.
  2518. """
  2519. if obj is self: # for in-place operations
  2520. result = obj
  2521. else:
  2522. result = obj.view(type(self))
  2523. result._update_from(self)
  2524. if context is not None:
  2525. result._mask = result._mask.copy()
  2526. func, args, out_i = context
  2527. # args sometimes contains outputs (gh-10459), which we don't want
  2528. input_args = args[:func.nin]
  2529. m = reduce(mask_or, [getmaskarray(arg) for arg in input_args])
  2530. # Get the domain mask
  2531. domain = ufunc_domain.get(func, None)
  2532. if domain is not None:
  2533. # Take the domain, and make sure it's a ndarray
  2534. with np.errstate(divide='ignore', invalid='ignore'):
  2535. d = filled(domain(*input_args), True)
  2536. if d.any():
  2537. # Fill the result where the domain is wrong
  2538. try:
  2539. # Binary domain: take the last value
  2540. fill_value = ufunc_fills[func][-1]
  2541. except TypeError:
  2542. # Unary domain: just use this one
  2543. fill_value = ufunc_fills[func]
  2544. except KeyError:
  2545. # Domain not recognized, use fill_value instead
  2546. fill_value = self.fill_value
  2547. np.copyto(result, fill_value, where=d)
  2548. # Update the mask
  2549. if m is nomask:
  2550. m = d
  2551. else:
  2552. # Don't modify inplace, we risk back-propagation
  2553. m = (m | d)
  2554. # Make sure the mask has the proper size
  2555. if result is not self and result.shape == () and m:
  2556. return masked
  2557. else:
  2558. result._mask = m
  2559. result._sharedmask = False
  2560. return result
  2561. def view(self, dtype=None, type=None, fill_value=None):
  2562. """
  2563. Return a view of the MaskedArray data.
  2564. Parameters
  2565. ----------
  2566. dtype : data-type or ndarray sub-class, optional
  2567. Data-type descriptor of the returned view, e.g., float32 or int16.
  2568. The default, None, results in the view having the same data-type
  2569. as `a`. As with ``ndarray.view``, dtype can also be specified as
  2570. an ndarray sub-class, which then specifies the type of the
  2571. returned object (this is equivalent to setting the ``type``
  2572. parameter).
  2573. type : Python type, optional
  2574. Type of the returned view, either ndarray or a subclass. The
  2575. default None results in type preservation.
  2576. fill_value : scalar, optional
  2577. The value to use for invalid entries (None by default).
  2578. If None, then this argument is inferred from the passed `dtype`, or
  2579. in its absence the original array, as discussed in the notes below.
  2580. See Also
  2581. --------
  2582. numpy.ndarray.view : Equivalent method on ndarray object.
  2583. Notes
  2584. -----
  2585. ``a.view()`` is used two different ways:
  2586. ``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
  2587. of the array's memory with a different data-type. This can cause a
  2588. reinterpretation of the bytes of memory.
  2589. ``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
  2590. returns an instance of `ndarray_subclass` that looks at the same array
  2591. (same shape, dtype, etc.) This does not cause a reinterpretation of the
  2592. memory.
  2593. If `fill_value` is not specified, but `dtype` is specified (and is not
  2594. an ndarray sub-class), the `fill_value` of the MaskedArray will be
  2595. reset. If neither `fill_value` nor `dtype` are specified (or if
  2596. `dtype` is an ndarray sub-class), then the fill value is preserved.
  2597. Finally, if `fill_value` is specified, but `dtype` is not, the fill
  2598. value is set to the specified value.
  2599. For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
  2600. bytes per entry than the previous dtype (for example, converting a
  2601. regular array to a structured array), then the behavior of the view
  2602. cannot be predicted just from the superficial appearance of ``a`` (shown
  2603. by ``print(a)``). It also depends on exactly how ``a`` is stored in
  2604. memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus
  2605. defined as a slice or transpose, etc., the view may give different
  2606. results.
  2607. """
  2608. if dtype is None:
  2609. if type is None:
  2610. output = ndarray.view(self)
  2611. else:
  2612. output = ndarray.view(self, type)
  2613. elif type is None:
  2614. try:
  2615. if issubclass(dtype, ndarray):
  2616. output = ndarray.view(self, dtype)
  2617. dtype = None
  2618. else:
  2619. output = ndarray.view(self, dtype)
  2620. except TypeError:
  2621. output = ndarray.view(self, dtype)
  2622. else:
  2623. output = ndarray.view(self, dtype, type)
  2624. # also make the mask be a view (so attr changes to the view's
  2625. # mask do no affect original object's mask)
  2626. # (especially important to avoid affecting np.masked singleton)
  2627. if getmask(output) is not nomask:
  2628. output._mask = output._mask.view()
  2629. # Make sure to reset the _fill_value if needed
  2630. if getattr(output, '_fill_value', None) is not None:
  2631. if fill_value is None:
  2632. if dtype is None:
  2633. pass # leave _fill_value as is
  2634. else:
  2635. output._fill_value = None
  2636. else:
  2637. output.fill_value = fill_value
  2638. return output
  2639. def __getitem__(self, indx):
  2640. """
  2641. x.__getitem__(y) <==> x[y]
  2642. Return the item described by i, as a masked array.
  2643. """
  2644. # We could directly use ndarray.__getitem__ on self.
  2645. # But then we would have to modify __array_finalize__ to prevent the
  2646. # mask of being reshaped if it hasn't been set up properly yet
  2647. # So it's easier to stick to the current version
  2648. dout = self.data[indx]
  2649. _mask = self._mask
  2650. def _is_scalar(m):
  2651. return not isinstance(m, np.ndarray)
  2652. def _scalar_heuristic(arr, elem):
  2653. """
  2654. Return whether `elem` is a scalar result of indexing `arr`, or None
  2655. if undecidable without promoting nomask to a full mask
  2656. """
  2657. # obviously a scalar
  2658. if not isinstance(elem, np.ndarray):
  2659. return True
  2660. # object array scalar indexing can return anything
  2661. elif arr.dtype.type is np.object_:
  2662. if arr.dtype is not elem.dtype:
  2663. # elem is an array, but dtypes do not match, so must be
  2664. # an element
  2665. return True
  2666. # well-behaved subclass that only returns 0d arrays when
  2667. # expected - this is not a scalar
  2668. elif type(arr).__getitem__ == ndarray.__getitem__:
  2669. return False
  2670. return None
  2671. if _mask is not nomask:
  2672. # _mask cannot be a subclass, so it tells us whether we should
  2673. # expect a scalar. It also cannot be of dtype object.
  2674. mout = _mask[indx]
  2675. scalar_expected = _is_scalar(mout)
  2676. else:
  2677. # attempt to apply the heuristic to avoid constructing a full mask
  2678. mout = nomask
  2679. scalar_expected = _scalar_heuristic(self.data, dout)
  2680. if scalar_expected is None:
  2681. # heuristics have failed
  2682. # construct a full array, so we can be certain. This is costly.
  2683. # we could also fall back on ndarray.__getitem__(self.data, indx)
  2684. scalar_expected = _is_scalar(getmaskarray(self)[indx])
  2685. # Did we extract a single item?
  2686. if scalar_expected:
  2687. # A record
  2688. if isinstance(dout, np.void):
  2689. # We should always re-cast to mvoid, otherwise users can
  2690. # change masks on rows that already have masked values, but not
  2691. # on rows that have no masked values, which is inconsistent.
  2692. return mvoid(dout, mask=mout, hardmask=self._hardmask)
  2693. # special case introduced in gh-5962
  2694. elif (self.dtype.type is np.object_ and
  2695. isinstance(dout, np.ndarray) and
  2696. dout is not masked):
  2697. # If masked, turn into a MaskedArray, with everything masked.
  2698. if mout:
  2699. return MaskedArray(dout, mask=True)
  2700. else:
  2701. return dout
  2702. # Just a scalar
  2703. else:
  2704. if mout:
  2705. return masked
  2706. else:
  2707. return dout
  2708. else:
  2709. # Force dout to MA
  2710. dout = dout.view(type(self))
  2711. # Inherit attributes from self
  2712. dout._update_from(self)
  2713. # Check the fill_value
  2714. if is_string_or_list_of_strings(indx):
  2715. if self._fill_value is not None:
  2716. dout._fill_value = self._fill_value[indx]
  2717. # If we're indexing a multidimensional field in a
  2718. # structured array (such as dtype("(2,)i2,(2,)i1")),
  2719. # dimensionality goes up (M[field].ndim == M.ndim +
  2720. # M.dtype[field].ndim). That's fine for
  2721. # M[field] but problematic for M[field].fill_value
  2722. # which should have shape () to avoid breaking several
  2723. # methods. There is no great way out, so set to
  2724. # first element. See issue #6723.
  2725. if dout._fill_value.ndim > 0:
  2726. if not (dout._fill_value ==
  2727. dout._fill_value.flat[0]).all():
  2728. warnings.warn(
  2729. "Upon accessing multidimensional field "
  2730. "{indx:s}, need to keep dimensionality "
  2731. "of fill_value at 0. Discarding "
  2732. "heterogeneous fill_value and setting "
  2733. "all to {fv!s}.".format(indx=indx,
  2734. fv=dout._fill_value[0]),
  2735. stacklevel=2)
  2736. dout._fill_value = dout._fill_value.flat[0]
  2737. dout._isfield = True
  2738. # Update the mask if needed
  2739. if mout is not nomask:
  2740. # set shape to match that of data; this is needed for matrices
  2741. dout._mask = reshape(mout, dout.shape)
  2742. dout._sharedmask = True
  2743. # Note: Don't try to check for m.any(), that'll take too long
  2744. return dout
  2745. def __setitem__(self, indx, value):
  2746. """
  2747. x.__setitem__(i, y) <==> x[i]=y
  2748. Set item described by index. If value is masked, masks those
  2749. locations.
  2750. """
  2751. if self is masked:
  2752. raise MaskError('Cannot alter the masked element.')
  2753. _data = self._data
  2754. _mask = self._mask
  2755. if isinstance(indx, basestring):
  2756. _data[indx] = value
  2757. if _mask is nomask:
  2758. self._mask = _mask = make_mask_none(self.shape, self.dtype)
  2759. _mask[indx] = getmask(value)
  2760. return
  2761. _dtype = _data.dtype
  2762. if value is masked:
  2763. # The mask wasn't set: create a full version.
  2764. if _mask is nomask:
  2765. _mask = self._mask = make_mask_none(self.shape, _dtype)
  2766. # Now, set the mask to its value.
  2767. if _dtype.names is not None:
  2768. _mask[indx] = tuple([True] * len(_dtype.names))
  2769. else:
  2770. _mask[indx] = True
  2771. return
  2772. # Get the _data part of the new value
  2773. dval = getattr(value, '_data', value)
  2774. # Get the _mask part of the new value
  2775. mval = getmask(value)
  2776. if _dtype.names is not None and mval is nomask:
  2777. mval = tuple([False] * len(_dtype.names))
  2778. if _mask is nomask:
  2779. # Set the data, then the mask
  2780. _data[indx] = dval
  2781. if mval is not nomask:
  2782. _mask = self._mask = make_mask_none(self.shape, _dtype)
  2783. _mask[indx] = mval
  2784. elif not self._hardmask:
  2785. # Set the data, then the mask
  2786. _data[indx] = dval
  2787. _mask[indx] = mval
  2788. elif hasattr(indx, 'dtype') and (indx.dtype == MaskType):
  2789. indx = indx * umath.logical_not(_mask)
  2790. _data[indx] = dval
  2791. else:
  2792. if _dtype.names is not None:
  2793. err_msg = "Flexible 'hard' masks are not yet supported."
  2794. raise NotImplementedError(err_msg)
  2795. mindx = mask_or(_mask[indx], mval, copy=True)
  2796. dindx = self._data[indx]
  2797. if dindx.size > 1:
  2798. np.copyto(dindx, dval, where=~mindx)
  2799. elif mindx is nomask:
  2800. dindx = dval
  2801. _data[indx] = dindx
  2802. _mask[indx] = mindx
  2803. return
  2804. # Define so that we can overwrite the setter.
  2805. @property
  2806. def dtype(self):
  2807. return super(MaskedArray, self).dtype
  2808. @dtype.setter
  2809. def dtype(self, dtype):
  2810. super(MaskedArray, type(self)).dtype.__set__(self, dtype)
  2811. if self._mask is not nomask:
  2812. self._mask = self._mask.view(make_mask_descr(dtype), ndarray)
  2813. # Try to reset the shape of the mask (if we don't have a void).
  2814. # This raises a ValueError if the dtype change won't work.
  2815. try:
  2816. self._mask.shape = self.shape
  2817. except (AttributeError, TypeError):
  2818. pass
  2819. @property
  2820. def shape(self):
  2821. return super(MaskedArray, self).shape
  2822. @shape.setter
  2823. def shape(self, shape):
  2824. super(MaskedArray, type(self)).shape.__set__(self, shape)
  2825. # Cannot use self._mask, since it may not (yet) exist when a
  2826. # masked matrix sets the shape.
  2827. if getmask(self) is not nomask:
  2828. self._mask.shape = self.shape
  2829. def __setmask__(self, mask, copy=False):
  2830. """
  2831. Set the mask.
  2832. """
  2833. idtype = self.dtype
  2834. current_mask = self._mask
  2835. if mask is masked:
  2836. mask = True
  2837. if current_mask is nomask:
  2838. # Make sure the mask is set
  2839. # Just don't do anything if there's nothing to do.
  2840. if mask is nomask:
  2841. return
  2842. current_mask = self._mask = make_mask_none(self.shape, idtype)
  2843. if idtype.names is None:
  2844. # No named fields.
  2845. # Hardmask: don't unmask the data
  2846. if self._hardmask:
  2847. current_mask |= mask
  2848. # Softmask: set everything to False
  2849. # If it's obviously a compatible scalar, use a quick update
  2850. # method.
  2851. elif isinstance(mask, (int, float, np.bool_, np.number)):
  2852. current_mask[...] = mask
  2853. # Otherwise fall back to the slower, general purpose way.
  2854. else:
  2855. current_mask.flat = mask
  2856. else:
  2857. # Named fields w/
  2858. mdtype = current_mask.dtype
  2859. mask = np.array(mask, copy=False)
  2860. # Mask is a singleton
  2861. if not mask.ndim:
  2862. # It's a boolean : make a record
  2863. if mask.dtype.kind == 'b':
  2864. mask = np.array(tuple([mask.item()] * len(mdtype)),
  2865. dtype=mdtype)
  2866. # It's a record: make sure the dtype is correct
  2867. else:
  2868. mask = mask.astype(mdtype)
  2869. # Mask is a sequence
  2870. else:
  2871. # Make sure the new mask is a ndarray with the proper dtype
  2872. try:
  2873. mask = np.array(mask, copy=copy, dtype=mdtype)
  2874. # Or assume it's a sequence of bool/int
  2875. except TypeError:
  2876. mask = np.array([tuple([m] * len(mdtype)) for m in mask],
  2877. dtype=mdtype)
  2878. # Hardmask: don't unmask the data
  2879. if self._hardmask:
  2880. for n in idtype.names:
  2881. current_mask[n] |= mask[n]
  2882. # Softmask: set everything to False
  2883. # If it's obviously a compatible scalar, use a quick update
  2884. # method.
  2885. elif isinstance(mask, (int, float, np.bool_, np.number)):
  2886. current_mask[...] = mask
  2887. # Otherwise fall back to the slower, general purpose way.
  2888. else:
  2889. current_mask.flat = mask
  2890. # Reshape if needed
  2891. if current_mask.shape:
  2892. current_mask.shape = self.shape
  2893. return
  2894. _set_mask = __setmask__
  2895. @property
  2896. def mask(self):
  2897. """ Current mask. """
  2898. # We could try to force a reshape, but that wouldn't work in some
  2899. # cases.
  2900. # Return a view so that the dtype and shape cannot be changed in place
  2901. # This still preserves nomask by identity
  2902. return self._mask.view()
  2903. @mask.setter
  2904. def mask(self, value):
  2905. self.__setmask__(value)
  2906. @property
  2907. def recordmask(self):
  2908. """
  2909. Get or set the mask of the array if it has no named fields. For
  2910. structured arrays, returns a ndarray of booleans where entries are
  2911. ``True`` if **all** the fields are masked, ``False`` otherwise:
  2912. >>> x = np.ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
  2913. ... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)],
  2914. ... dtype=[('a', int), ('b', int)])
  2915. >>> x.recordmask
  2916. array([False, False, True, False, False])
  2917. """
  2918. _mask = self._mask.view(ndarray)
  2919. if _mask.dtype.names is None:
  2920. return _mask
  2921. return np.all(flatten_structured_array(_mask), axis=-1)
  2922. @recordmask.setter
  2923. def recordmask(self, mask):
  2924. raise NotImplementedError("Coming soon: setting the mask per records!")
  2925. def harden_mask(self):
  2926. """
  2927. Force the mask to hard.
  2928. Whether the mask of a masked array is hard or soft is determined by
  2929. its `hardmask` property. `harden_mask` sets `hardmask` to True.
  2930. See Also
  2931. --------
  2932. hardmask
  2933. """
  2934. self._hardmask = True
  2935. return self
  2936. def soften_mask(self):
  2937. """
  2938. Force the mask to soft.
  2939. Whether the mask of a masked array is hard or soft is determined by
  2940. its `hardmask` property. `soften_mask` sets `hardmask` to False.
  2941. See Also
  2942. --------
  2943. hardmask
  2944. """
  2945. self._hardmask = False
  2946. return self
  2947. @property
  2948. def hardmask(self):
  2949. """ Hardness of the mask """
  2950. return self._hardmask
  2951. def unshare_mask(self):
  2952. """
  2953. Copy the mask and set the sharedmask flag to False.
  2954. Whether the mask is shared between masked arrays can be seen from
  2955. the `sharedmask` property. `unshare_mask` ensures the mask is not shared.
  2956. A copy of the mask is only made if it was shared.
  2957. See Also
  2958. --------
  2959. sharedmask
  2960. """
  2961. if self._sharedmask:
  2962. self._mask = self._mask.copy()
  2963. self._sharedmask = False
  2964. return self
  2965. @property
  2966. def sharedmask(self):
  2967. """ Share status of the mask (read-only). """
  2968. return self._sharedmask
  2969. def shrink_mask(self):
  2970. """
  2971. Reduce a mask to nomask when possible.
  2972. Parameters
  2973. ----------
  2974. None
  2975. Returns
  2976. -------
  2977. None
  2978. Examples
  2979. --------
  2980. >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4)
  2981. >>> x.mask
  2982. array([[False, False],
  2983. [False, False]])
  2984. >>> x.shrink_mask()
  2985. masked_array(
  2986. data=[[1, 2],
  2987. [3, 4]],
  2988. mask=False,
  2989. fill_value=999999)
  2990. >>> x.mask
  2991. False
  2992. """
  2993. self._mask = _shrink_mask(self._mask)
  2994. return self
  2995. @property
  2996. def baseclass(self):
  2997. """ Class of the underlying data (read-only). """
  2998. return self._baseclass
  2999. def _get_data(self):
  3000. """
  3001. Returns the underlying data, as a view of the masked array.
  3002. If the underlying data is a subclass of :class:`numpy.ndarray`, it is
  3003. returned as such.
  3004. >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
  3005. >>> x.data
  3006. matrix([[1, 2],
  3007. [3, 4]])
  3008. The type of the data can be accessed through the :attr:`baseclass`
  3009. attribute.
  3010. """
  3011. return ndarray.view(self, self._baseclass)
  3012. _data = property(fget=_get_data)
  3013. data = property(fget=_get_data)
  3014. @property
  3015. def flat(self):
  3016. """ Return a flat iterator, or set a flattened version of self to value. """
  3017. return MaskedIterator(self)
  3018. @flat.setter
  3019. def flat(self, value):
  3020. y = self.ravel()
  3021. y[:] = value
  3022. @property
  3023. def fill_value(self):
  3024. """
  3025. The filling value of the masked array is a scalar. When setting, None
  3026. will set to a default based on the data type.
  3027. Examples
  3028. --------
  3029. >>> for dt in [np.int32, np.int64, np.float64, np.complex128]:
  3030. ... np.ma.array([0, 1], dtype=dt).get_fill_value()
  3031. ...
  3032. 999999
  3033. 999999
  3034. 1e+20
  3035. (1e+20+0j)
  3036. >>> x = np.ma.array([0, 1.], fill_value=-np.inf)
  3037. >>> x.fill_value
  3038. -inf
  3039. >>> x.fill_value = np.pi
  3040. >>> x.fill_value
  3041. 3.1415926535897931 # may vary
  3042. Reset to default:
  3043. >>> x.fill_value = None
  3044. >>> x.fill_value
  3045. 1e+20
  3046. """
  3047. if self._fill_value is None:
  3048. self._fill_value = _check_fill_value(None, self.dtype)
  3049. # Temporary workaround to account for the fact that str and bytes
  3050. # scalars cannot be indexed with (), whereas all other numpy
  3051. # scalars can. See issues #7259 and #7267.
  3052. # The if-block can be removed after #7267 has been fixed.
  3053. if isinstance(self._fill_value, ndarray):
  3054. return self._fill_value[()]
  3055. return self._fill_value
  3056. @fill_value.setter
  3057. def fill_value(self, value=None):
  3058. target = _check_fill_value(value, self.dtype)
  3059. if not target.ndim == 0:
  3060. # 2019-11-12, 1.18.0
  3061. warnings.warn(
  3062. "Non-scalar arrays for the fill value are deprecated. Use "
  3063. "arrays with scalar values instead. The filled function "
  3064. "still supports any array as `fill_value`.",
  3065. DeprecationWarning, stacklevel=2)
  3066. _fill_value = self._fill_value
  3067. if _fill_value is None:
  3068. # Create the attribute if it was undefined
  3069. self._fill_value = target
  3070. else:
  3071. # Don't overwrite the attribute, just fill it (for propagation)
  3072. _fill_value[()] = target
  3073. # kept for compatibility
  3074. get_fill_value = fill_value.fget
  3075. set_fill_value = fill_value.fset
  3076. def filled(self, fill_value=None):
  3077. """
  3078. Return a copy of self, with masked values filled with a given value.
  3079. **However**, if there are no masked values to fill, self will be
  3080. returned instead as an ndarray.
  3081. Parameters
  3082. ----------
  3083. fill_value : array_like, optional
  3084. The value to use for invalid entries. Can be scalar or non-scalar.
  3085. If non-scalar, the resulting ndarray must be broadcastable over
  3086. input array. Default is None, in which case, the `fill_value`
  3087. attribute of the array is used instead.
  3088. Returns
  3089. -------
  3090. filled_array : ndarray
  3091. A copy of ``self`` with invalid entries replaced by *fill_value*
  3092. (be it the function argument or the attribute of ``self``), or
  3093. ``self`` itself as an ndarray if there are no invalid entries to
  3094. be replaced.
  3095. Notes
  3096. -----
  3097. The result is **not** a MaskedArray!
  3098. Examples
  3099. --------
  3100. >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
  3101. >>> x.filled()
  3102. array([ 1, 2, -999, 4, -999])
  3103. >>> x.filled(fill_value=1000)
  3104. array([ 1, 2, 1000, 4, 1000])
  3105. >>> type(x.filled())
  3106. <class 'numpy.ndarray'>
  3107. Subclassing is preserved. This means that if, e.g., the data part of
  3108. the masked array is a recarray, `filled` returns a recarray:
  3109. >>> x = np.array([(-1, 2), (-3, 4)], dtype='i8,i8').view(np.recarray)
  3110. >>> m = np.ma.array(x, mask=[(True, False), (False, True)])
  3111. >>> m.filled()
  3112. rec.array([(999999, 2), ( -3, 999999)],
  3113. dtype=[('f0', '<i8'), ('f1', '<i8')])
  3114. """
  3115. m = self._mask
  3116. if m is nomask:
  3117. return self._data
  3118. if fill_value is None:
  3119. fill_value = self.fill_value
  3120. else:
  3121. fill_value = _check_fill_value(fill_value, self.dtype)
  3122. if self is masked_singleton:
  3123. return np.asanyarray(fill_value)
  3124. if m.dtype.names is not None:
  3125. result = self._data.copy('K')
  3126. _recursive_filled(result, self._mask, fill_value)
  3127. elif not m.any():
  3128. return self._data
  3129. else:
  3130. result = self._data.copy('K')
  3131. try:
  3132. np.copyto(result, fill_value, where=m)
  3133. except (TypeError, AttributeError):
  3134. fill_value = narray(fill_value, dtype=object)
  3135. d = result.astype(object)
  3136. result = np.choose(m, (d, fill_value))
  3137. except IndexError:
  3138. # ok, if scalar
  3139. if self._data.shape:
  3140. raise
  3141. elif m:
  3142. result = np.array(fill_value, dtype=self.dtype)
  3143. else:
  3144. result = self._data
  3145. return result
  3146. def compressed(self):
  3147. """
  3148. Return all the non-masked data as a 1-D array.
  3149. Returns
  3150. -------
  3151. data : ndarray
  3152. A new `ndarray` holding the non-masked data is returned.
  3153. Notes
  3154. -----
  3155. The result is **not** a MaskedArray!
  3156. Examples
  3157. --------
  3158. >>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3)
  3159. >>> x.compressed()
  3160. array([0, 1])
  3161. >>> type(x.compressed())
  3162. <class 'numpy.ndarray'>
  3163. """
  3164. data = ndarray.ravel(self._data)
  3165. if self._mask is not nomask:
  3166. data = data.compress(np.logical_not(ndarray.ravel(self._mask)))
  3167. return data
  3168. def compress(self, condition, axis=None, out=None):
  3169. """
  3170. Return `a` where condition is ``True``.
  3171. If condition is a `MaskedArray`, missing values are considered
  3172. as ``False``.
  3173. Parameters
  3174. ----------
  3175. condition : var
  3176. Boolean 1-d array selecting which entries to return. If len(condition)
  3177. is less than the size of a along the axis, then output is truncated
  3178. to length of condition array.
  3179. axis : {None, int}, optional
  3180. Axis along which the operation must be performed.
  3181. out : {None, ndarray}, optional
  3182. Alternative output array in which to place the result. It must have
  3183. the same shape as the expected output but the type will be cast if
  3184. necessary.
  3185. Returns
  3186. -------
  3187. result : MaskedArray
  3188. A :class:`MaskedArray` object.
  3189. Notes
  3190. -----
  3191. Please note the difference with :meth:`compressed` !
  3192. The output of :meth:`compress` has a mask, the output of
  3193. :meth:`compressed` does not.
  3194. Examples
  3195. --------
  3196. >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
  3197. >>> x
  3198. masked_array(
  3199. data=[[1, --, 3],
  3200. [--, 5, --],
  3201. [7, --, 9]],
  3202. mask=[[False, True, False],
  3203. [ True, False, True],
  3204. [False, True, False]],
  3205. fill_value=999999)
  3206. >>> x.compress([1, 0, 1])
  3207. masked_array(data=[1, 3],
  3208. mask=[False, False],
  3209. fill_value=999999)
  3210. >>> x.compress([1, 0, 1], axis=1)
  3211. masked_array(
  3212. data=[[1, 3],
  3213. [--, --],
  3214. [7, 9]],
  3215. mask=[[False, False],
  3216. [ True, True],
  3217. [False, False]],
  3218. fill_value=999999)
  3219. """
  3220. # Get the basic components
  3221. (_data, _mask) = (self._data, self._mask)
  3222. # Force the condition to a regular ndarray and forget the missing
  3223. # values.
  3224. condition = np.array(condition, copy=False, subok=False)
  3225. _new = _data.compress(condition, axis=axis, out=out).view(type(self))
  3226. _new._update_from(self)
  3227. if _mask is not nomask:
  3228. _new._mask = _mask.compress(condition, axis=axis)
  3229. return _new
  3230. def _insert_masked_print(self):
  3231. """
  3232. Replace masked values with masked_print_option, casting all innermost
  3233. dtypes to object.
  3234. """
  3235. if masked_print_option.enabled():
  3236. mask = self._mask
  3237. if mask is nomask:
  3238. res = self._data
  3239. else:
  3240. # convert to object array to make filled work
  3241. data = self._data
  3242. # For big arrays, to avoid a costly conversion to the
  3243. # object dtype, extract the corners before the conversion.
  3244. print_width = (self._print_width if self.ndim > 1
  3245. else self._print_width_1d)
  3246. for axis in range(self.ndim):
  3247. if data.shape[axis] > print_width:
  3248. ind = print_width // 2
  3249. arr = np.split(data, (ind, -ind), axis=axis)
  3250. data = np.concatenate((arr[0], arr[2]), axis=axis)
  3251. arr = np.split(mask, (ind, -ind), axis=axis)
  3252. mask = np.concatenate((arr[0], arr[2]), axis=axis)
  3253. rdtype = _replace_dtype_fields(self.dtype, "O")
  3254. res = data.astype(rdtype)
  3255. _recursive_printoption(res, mask, masked_print_option)
  3256. else:
  3257. res = self.filled(self.fill_value)
  3258. return res
  3259. def __str__(self):
  3260. return str(self._insert_masked_print())
  3261. if sys.version_info.major < 3:
  3262. def __unicode__(self):
  3263. return unicode(self._insert_masked_print())
  3264. def __repr__(self):
  3265. """
  3266. Literal string representation.
  3267. """
  3268. if self._baseclass is np.ndarray:
  3269. name = 'array'
  3270. else:
  3271. name = self._baseclass.__name__
  3272. # 2016-11-19: Demoted to legacy format
  3273. if np.get_printoptions()['legacy'] == '1.13':
  3274. is_long = self.ndim > 1
  3275. parameters = dict(
  3276. name=name,
  3277. nlen=" " * len(name),
  3278. data=str(self),
  3279. mask=str(self._mask),
  3280. fill=str(self.fill_value),
  3281. dtype=str(self.dtype)
  3282. )
  3283. is_structured = bool(self.dtype.names)
  3284. key = '{}_{}'.format(
  3285. 'long' if is_long else 'short',
  3286. 'flx' if is_structured else 'std'
  3287. )
  3288. return _legacy_print_templates[key] % parameters
  3289. prefix = 'masked_{}('.format(name)
  3290. dtype_needed = (
  3291. not np.core.arrayprint.dtype_is_implied(self.dtype) or
  3292. np.all(self.mask) or
  3293. self.size == 0
  3294. )
  3295. # determine which keyword args need to be shown
  3296. keys = ['data', 'mask', 'fill_value']
  3297. if dtype_needed:
  3298. keys.append('dtype')
  3299. # array has only one row (non-column)
  3300. is_one_row = builtins.all(dim == 1 for dim in self.shape[:-1])
  3301. # choose what to indent each keyword with
  3302. min_indent = 2
  3303. if is_one_row:
  3304. # first key on the same line as the type, remaining keys
  3305. # aligned by equals
  3306. indents = {}
  3307. indents[keys[0]] = prefix
  3308. for k in keys[1:]:
  3309. n = builtins.max(min_indent, len(prefix + keys[0]) - len(k))
  3310. indents[k] = ' ' * n
  3311. prefix = '' # absorbed into the first indent
  3312. else:
  3313. # each key on its own line, indented by two spaces
  3314. indents = {k: ' ' * min_indent for k in keys}
  3315. prefix = prefix + '\n' # first key on the next line
  3316. # format the field values
  3317. reprs = {}
  3318. reprs['data'] = np.array2string(
  3319. self._insert_masked_print(),
  3320. separator=", ",
  3321. prefix=indents['data'] + 'data=',
  3322. suffix=',')
  3323. reprs['mask'] = np.array2string(
  3324. self._mask,
  3325. separator=", ",
  3326. prefix=indents['mask'] + 'mask=',
  3327. suffix=',')
  3328. reprs['fill_value'] = repr(self.fill_value)
  3329. if dtype_needed:
  3330. reprs['dtype'] = np.core.arrayprint.dtype_short_repr(self.dtype)
  3331. # join keys with values and indentations
  3332. result = ',\n'.join(
  3333. '{}{}={}'.format(indents[k], k, reprs[k])
  3334. for k in keys
  3335. )
  3336. return prefix + result + ')'
  3337. def _delegate_binop(self, other):
  3338. # This emulates the logic in
  3339. # private/binop_override.h:forward_binop_should_defer
  3340. if isinstance(other, type(self)):
  3341. return False
  3342. array_ufunc = getattr(other, "__array_ufunc__", False)
  3343. if array_ufunc is False:
  3344. other_priority = getattr(other, "__array_priority__", -1000000)
  3345. return self.__array_priority__ < other_priority
  3346. else:
  3347. # If array_ufunc is not None, it will be called inside the ufunc;
  3348. # None explicitly tells us to not call the ufunc, i.e., defer.
  3349. return array_ufunc is None
  3350. def _comparison(self, other, compare):
  3351. """Compare self with other using operator.eq or operator.ne.
  3352. When either of the elements is masked, the result is masked as well,
  3353. but the underlying boolean data are still set, with self and other
  3354. considered equal if both are masked, and unequal otherwise.
  3355. For structured arrays, all fields are combined, with masked values
  3356. ignored. The result is masked if all fields were masked, with self
  3357. and other considered equal only if both were fully masked.
  3358. """
  3359. omask = getmask(other)
  3360. smask = self.mask
  3361. mask = mask_or(smask, omask, copy=True)
  3362. odata = getdata(other)
  3363. if mask.dtype.names is not None:
  3364. # For possibly masked structured arrays we need to be careful,
  3365. # since the standard structured array comparison will use all
  3366. # fields, masked or not. To avoid masked fields influencing the
  3367. # outcome, we set all masked fields in self to other, so they'll
  3368. # count as equal. To prepare, we ensure we have the right shape.
  3369. broadcast_shape = np.broadcast(self, odata).shape
  3370. sbroadcast = np.broadcast_to(self, broadcast_shape, subok=True)
  3371. sbroadcast._mask = mask
  3372. sdata = sbroadcast.filled(odata)
  3373. # Now take care of the mask; the merged mask should have an item
  3374. # masked if all fields were masked (in one and/or other).
  3375. mask = (mask == np.ones((), mask.dtype))
  3376. else:
  3377. # For regular arrays, just use the data as they come.
  3378. sdata = self.data
  3379. check = compare(sdata, odata)
  3380. if isinstance(check, (np.bool_, bool)):
  3381. return masked if mask else check
  3382. if mask is not nomask:
  3383. # Adjust elements that were masked, which should be treated
  3384. # as equal if masked in both, unequal if masked in one.
  3385. # Note that this works automatically for structured arrays too.
  3386. check = np.where(mask, compare(smask, omask), check)
  3387. if mask.shape != check.shape:
  3388. # Guarantee consistency of the shape, making a copy since the
  3389. # the mask may need to get written to later.
  3390. mask = np.broadcast_to(mask, check.shape).copy()
  3391. check = check.view(type(self))
  3392. check._update_from(self)
  3393. check._mask = mask
  3394. # Cast fill value to bool_ if needed. If it cannot be cast, the
  3395. # default boolean fill value is used.
  3396. if check._fill_value is not None:
  3397. try:
  3398. fill = _check_fill_value(check._fill_value, np.bool_)
  3399. except (TypeError, ValueError):
  3400. fill = _check_fill_value(None, np.bool_)
  3401. check._fill_value = fill
  3402. return check
  3403. def __eq__(self, other):
  3404. """Check whether other equals self elementwise.
  3405. When either of the elements is masked, the result is masked as well,
  3406. but the underlying boolean data are still set, with self and other
  3407. considered equal if both are masked, and unequal otherwise.
  3408. For structured arrays, all fields are combined, with masked values
  3409. ignored. The result is masked if all fields were masked, with self
  3410. and other considered equal only if both were fully masked.
  3411. """
  3412. return self._comparison(other, operator.eq)
  3413. def __ne__(self, other):
  3414. """Check whether other does not equal self elementwise.
  3415. When either of the elements is masked, the result is masked as well,
  3416. but the underlying boolean data are still set, with self and other
  3417. considered equal if both are masked, and unequal otherwise.
  3418. For structured arrays, all fields are combined, with masked values
  3419. ignored. The result is masked if all fields were masked, with self
  3420. and other considered equal only if both were fully masked.
  3421. """
  3422. return self._comparison(other, operator.ne)
  3423. def __add__(self, other):
  3424. """
  3425. Add self to other, and return a new masked array.
  3426. """
  3427. if self._delegate_binop(other):
  3428. return NotImplemented
  3429. return add(self, other)
  3430. def __radd__(self, other):
  3431. """
  3432. Add other to self, and return a new masked array.
  3433. """
  3434. # In analogy with __rsub__ and __rdiv__, use original order:
  3435. # we get here from `other + self`.
  3436. return add(other, self)
  3437. def __sub__(self, other):
  3438. """
  3439. Subtract other from self, and return a new masked array.
  3440. """
  3441. if self._delegate_binop(other):
  3442. return NotImplemented
  3443. return subtract(self, other)
  3444. def __rsub__(self, other):
  3445. """
  3446. Subtract self from other, and return a new masked array.
  3447. """
  3448. return subtract(other, self)
  3449. def __mul__(self, other):
  3450. "Multiply self by other, and return a new masked array."
  3451. if self._delegate_binop(other):
  3452. return NotImplemented
  3453. return multiply(self, other)
  3454. def __rmul__(self, other):
  3455. """
  3456. Multiply other by self, and return a new masked array.
  3457. """
  3458. # In analogy with __rsub__ and __rdiv__, use original order:
  3459. # we get here from `other * self`.
  3460. return multiply(other, self)
  3461. def __div__(self, other):
  3462. """
  3463. Divide other into self, and return a new masked array.
  3464. """
  3465. if self._delegate_binop(other):
  3466. return NotImplemented
  3467. return divide(self, other)
  3468. def __truediv__(self, other):
  3469. """
  3470. Divide other into self, and return a new masked array.
  3471. """
  3472. if self._delegate_binop(other):
  3473. return NotImplemented
  3474. return true_divide(self, other)
  3475. def __rtruediv__(self, other):
  3476. """
  3477. Divide self into other, and return a new masked array.
  3478. """
  3479. return true_divide(other, self)
  3480. def __floordiv__(self, other):
  3481. """
  3482. Divide other into self, and return a new masked array.
  3483. """
  3484. if self._delegate_binop(other):
  3485. return NotImplemented
  3486. return floor_divide(self, other)
  3487. def __rfloordiv__(self, other):
  3488. """
  3489. Divide self into other, and return a new masked array.
  3490. """
  3491. return floor_divide(other, self)
  3492. def __pow__(self, other):
  3493. """
  3494. Raise self to the power other, masking the potential NaNs/Infs
  3495. """
  3496. if self._delegate_binop(other):
  3497. return NotImplemented
  3498. return power(self, other)
  3499. def __rpow__(self, other):
  3500. """
  3501. Raise other to the power self, masking the potential NaNs/Infs
  3502. """
  3503. return power(other, self)
  3504. def __iadd__(self, other):
  3505. """
  3506. Add other to self in-place.
  3507. """
  3508. m = getmask(other)
  3509. if self._mask is nomask:
  3510. if m is not nomask and m.any():
  3511. self._mask = make_mask_none(self.shape, self.dtype)
  3512. self._mask += m
  3513. else:
  3514. if m is not nomask:
  3515. self._mask += m
  3516. self._data.__iadd__(np.where(self._mask, self.dtype.type(0),
  3517. getdata(other)))
  3518. return self
  3519. def __isub__(self, other):
  3520. """
  3521. Subtract other from self in-place.
  3522. """
  3523. m = getmask(other)
  3524. if self._mask is nomask:
  3525. if m is not nomask and m.any():
  3526. self._mask = make_mask_none(self.shape, self.dtype)
  3527. self._mask += m
  3528. elif m is not nomask:
  3529. self._mask += m
  3530. self._data.__isub__(np.where(self._mask, self.dtype.type(0),
  3531. getdata(other)))
  3532. return self
  3533. def __imul__(self, other):
  3534. """
  3535. Multiply self by other in-place.
  3536. """
  3537. m = getmask(other)
  3538. if self._mask is nomask:
  3539. if m is not nomask and m.any():
  3540. self._mask = make_mask_none(self.shape, self.dtype)
  3541. self._mask += m
  3542. elif m is not nomask:
  3543. self._mask += m
  3544. self._data.__imul__(np.where(self._mask, self.dtype.type(1),
  3545. getdata(other)))
  3546. return self
  3547. def __idiv__(self, other):
  3548. """
  3549. Divide self by other in-place.
  3550. """
  3551. other_data = getdata(other)
  3552. dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
  3553. other_mask = getmask(other)
  3554. new_mask = mask_or(other_mask, dom_mask)
  3555. # The following 3 lines control the domain filling
  3556. if dom_mask.any():
  3557. (_, fval) = ufunc_fills[np.divide]
  3558. other_data = np.where(dom_mask, fval, other_data)
  3559. self._mask |= new_mask
  3560. self._data.__idiv__(np.where(self._mask, self.dtype.type(1),
  3561. other_data))
  3562. return self
  3563. def __ifloordiv__(self, other):
  3564. """
  3565. Floor divide self by other in-place.
  3566. """
  3567. other_data = getdata(other)
  3568. dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
  3569. other_mask = getmask(other)
  3570. new_mask = mask_or(other_mask, dom_mask)
  3571. # The following 3 lines control the domain filling
  3572. if dom_mask.any():
  3573. (_, fval) = ufunc_fills[np.floor_divide]
  3574. other_data = np.where(dom_mask, fval, other_data)
  3575. self._mask |= new_mask
  3576. self._data.__ifloordiv__(np.where(self._mask, self.dtype.type(1),
  3577. other_data))
  3578. return self
  3579. def __itruediv__(self, other):
  3580. """
  3581. True divide self by other in-place.
  3582. """
  3583. other_data = getdata(other)
  3584. dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
  3585. other_mask = getmask(other)
  3586. new_mask = mask_or(other_mask, dom_mask)
  3587. # The following 3 lines control the domain filling
  3588. if dom_mask.any():
  3589. (_, fval) = ufunc_fills[np.true_divide]
  3590. other_data = np.where(dom_mask, fval, other_data)
  3591. self._mask |= new_mask
  3592. self._data.__itruediv__(np.where(self._mask, self.dtype.type(1),
  3593. other_data))
  3594. return self
  3595. def __ipow__(self, other):
  3596. """
  3597. Raise self to the power other, in place.
  3598. """
  3599. other_data = getdata(other)
  3600. other_mask = getmask(other)
  3601. with np.errstate(divide='ignore', invalid='ignore'):
  3602. self._data.__ipow__(np.where(self._mask, self.dtype.type(1),
  3603. other_data))
  3604. invalid = np.logical_not(np.isfinite(self._data))
  3605. if invalid.any():
  3606. if self._mask is not nomask:
  3607. self._mask |= invalid
  3608. else:
  3609. self._mask = invalid
  3610. np.copyto(self._data, self.fill_value, where=invalid)
  3611. new_mask = mask_or(other_mask, invalid)
  3612. self._mask = mask_or(self._mask, new_mask)
  3613. return self
  3614. def __float__(self):
  3615. """
  3616. Convert to float.
  3617. """
  3618. if self.size > 1:
  3619. raise TypeError("Only length-1 arrays can be converted "
  3620. "to Python scalars")
  3621. elif self._mask:
  3622. warnings.warn("Warning: converting a masked element to nan.", stacklevel=2)
  3623. return np.nan
  3624. return float(self.item())
  3625. def __int__(self):
  3626. """
  3627. Convert to int.
  3628. """
  3629. if self.size > 1:
  3630. raise TypeError("Only length-1 arrays can be converted "
  3631. "to Python scalars")
  3632. elif self._mask:
  3633. raise MaskError('Cannot convert masked element to a Python int.')
  3634. return int(self.item())
  3635. def __long__(self):
  3636. """
  3637. Convert to long.
  3638. """
  3639. if self.size > 1:
  3640. raise TypeError("Only length-1 arrays can be converted "
  3641. "to Python scalars")
  3642. elif self._mask:
  3643. raise MaskError('Cannot convert masked element to a Python long.')
  3644. return long(self.item())
  3645. @property
  3646. def imag(self):
  3647. """
  3648. The imaginary part of the masked array.
  3649. This property is a view on the imaginary part of this `MaskedArray`.
  3650. See Also
  3651. --------
  3652. real
  3653. Examples
  3654. --------
  3655. >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
  3656. >>> x.imag
  3657. masked_array(data=[1.0, --, 1.6],
  3658. mask=[False, True, False],
  3659. fill_value=1e+20)
  3660. """
  3661. result = self._data.imag.view(type(self))
  3662. result.__setmask__(self._mask)
  3663. return result
  3664. # kept for compatibility
  3665. get_imag = imag.fget
  3666. @property
  3667. def real(self):
  3668. """
  3669. The real part of the masked array.
  3670. This property is a view on the real part of this `MaskedArray`.
  3671. See Also
  3672. --------
  3673. imag
  3674. Examples
  3675. --------
  3676. >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
  3677. >>> x.real
  3678. masked_array(data=[1.0, --, 3.45],
  3679. mask=[False, True, False],
  3680. fill_value=1e+20)
  3681. """
  3682. result = self._data.real.view(type(self))
  3683. result.__setmask__(self._mask)
  3684. return result
  3685. # kept for compatibility
  3686. get_real = real.fget
  3687. def count(self, axis=None, keepdims=np._NoValue):
  3688. """
  3689. Count the non-masked elements of the array along the given axis.
  3690. Parameters
  3691. ----------
  3692. axis : None or int or tuple of ints, optional
  3693. Axis or axes along which the count is performed.
  3694. The default, None, performs the count over all
  3695. the dimensions of the input array. `axis` may be negative, in
  3696. which case it counts from the last to the first axis.
  3697. .. versionadded:: 1.10.0
  3698. If this is a tuple of ints, the count is performed on multiple
  3699. axes, instead of a single axis or all the axes as before.
  3700. keepdims : bool, optional
  3701. If this is set to True, the axes which are reduced are left
  3702. in the result as dimensions with size one. With this option,
  3703. the result will broadcast correctly against the array.
  3704. Returns
  3705. -------
  3706. result : ndarray or scalar
  3707. An array with the same shape as the input array, with the specified
  3708. axis removed. If the array is a 0-d array, or if `axis` is None, a
  3709. scalar is returned.
  3710. See Also
  3711. --------
  3712. count_masked : Count masked elements in array or along a given axis.
  3713. Examples
  3714. --------
  3715. >>> import numpy.ma as ma
  3716. >>> a = ma.arange(6).reshape((2, 3))
  3717. >>> a[1, :] = ma.masked
  3718. >>> a
  3719. masked_array(
  3720. data=[[0, 1, 2],
  3721. [--, --, --]],
  3722. mask=[[False, False, False],
  3723. [ True, True, True]],
  3724. fill_value=999999)
  3725. >>> a.count()
  3726. 3
  3727. When the `axis` keyword is specified an array of appropriate size is
  3728. returned.
  3729. >>> a.count(axis=0)
  3730. array([1, 1, 1])
  3731. >>> a.count(axis=1)
  3732. array([3, 0])
  3733. """
  3734. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  3735. m = self._mask
  3736. # special case for matrices (we assume no other subclasses modify
  3737. # their dimensions)
  3738. if isinstance(self.data, np.matrix):
  3739. if m is nomask:
  3740. m = np.zeros(self.shape, dtype=np.bool_)
  3741. m = m.view(type(self.data))
  3742. if m is nomask:
  3743. # compare to _count_reduce_items in _methods.py
  3744. if self.shape == ():
  3745. if axis not in (None, 0):
  3746. raise np.AxisError(axis=axis, ndim=self.ndim)
  3747. return 1
  3748. elif axis is None:
  3749. if kwargs.get('keepdims', False):
  3750. return np.array(self.size, dtype=np.intp, ndmin=self.ndim)
  3751. return self.size
  3752. axes = normalize_axis_tuple(axis, self.ndim)
  3753. items = 1
  3754. for ax in axes:
  3755. items *= self.shape[ax]
  3756. if kwargs.get('keepdims', False):
  3757. out_dims = list(self.shape)
  3758. for a in axes:
  3759. out_dims[a] = 1
  3760. else:
  3761. out_dims = [d for n, d in enumerate(self.shape)
  3762. if n not in axes]
  3763. # make sure to return a 0-d array if axis is supplied
  3764. return np.full(out_dims, items, dtype=np.intp)
  3765. # take care of the masked singleton
  3766. if self is masked:
  3767. return 0
  3768. return (~m).sum(axis=axis, dtype=np.intp, **kwargs)
  3769. def ravel(self, order='C'):
  3770. """
  3771. Returns a 1D version of self, as a view.
  3772. Parameters
  3773. ----------
  3774. order : {'C', 'F', 'A', 'K'}, optional
  3775. The elements of `a` are read using this index order. 'C' means to
  3776. index the elements in C-like order, with the last axis index
  3777. changing fastest, back to the first axis index changing slowest.
  3778. 'F' means to index the elements in Fortran-like index order, with
  3779. the first index changing fastest, and the last index changing
  3780. slowest. Note that the 'C' and 'F' options take no account of the
  3781. memory layout of the underlying array, and only refer to the order
  3782. of axis indexing. 'A' means to read the elements in Fortran-like
  3783. index order if `m` is Fortran *contiguous* in memory, C-like order
  3784. otherwise. 'K' means to read the elements in the order they occur
  3785. in memory, except for reversing the data when strides are negative.
  3786. By default, 'C' index order is used.
  3787. Returns
  3788. -------
  3789. MaskedArray
  3790. Output view is of shape ``(self.size,)`` (or
  3791. ``(np.ma.product(self.shape),)``).
  3792. Examples
  3793. --------
  3794. >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
  3795. >>> x
  3796. masked_array(
  3797. data=[[1, --, 3],
  3798. [--, 5, --],
  3799. [7, --, 9]],
  3800. mask=[[False, True, False],
  3801. [ True, False, True],
  3802. [False, True, False]],
  3803. fill_value=999999)
  3804. >>> x.ravel()
  3805. masked_array(data=[1, --, 3, --, 5, --, 7, --, 9],
  3806. mask=[False, True, False, True, False, True, False, True,
  3807. False],
  3808. fill_value=999999)
  3809. """
  3810. r = ndarray.ravel(self._data, order=order).view(type(self))
  3811. r._update_from(self)
  3812. if self._mask is not nomask:
  3813. r._mask = ndarray.ravel(self._mask, order=order).reshape(r.shape)
  3814. else:
  3815. r._mask = nomask
  3816. return r
  3817. def reshape(self, *s, **kwargs):
  3818. """
  3819. Give a new shape to the array without changing its data.
  3820. Returns a masked array containing the same data, but with a new shape.
  3821. The result is a view on the original array; if this is not possible, a
  3822. ValueError is raised.
  3823. Parameters
  3824. ----------
  3825. shape : int or tuple of ints
  3826. The new shape should be compatible with the original shape. If an
  3827. integer is supplied, then the result will be a 1-D array of that
  3828. length.
  3829. order : {'C', 'F'}, optional
  3830. Determines whether the array data should be viewed as in C
  3831. (row-major) or FORTRAN (column-major) order.
  3832. Returns
  3833. -------
  3834. reshaped_array : array
  3835. A new view on the array.
  3836. See Also
  3837. --------
  3838. reshape : Equivalent function in the masked array module.
  3839. numpy.ndarray.reshape : Equivalent method on ndarray object.
  3840. numpy.reshape : Equivalent function in the NumPy module.
  3841. Notes
  3842. -----
  3843. The reshaping operation cannot guarantee that a copy will not be made,
  3844. to modify the shape in place, use ``a.shape = s``
  3845. Examples
  3846. --------
  3847. >>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1])
  3848. >>> x
  3849. masked_array(
  3850. data=[[--, 2],
  3851. [3, --]],
  3852. mask=[[ True, False],
  3853. [False, True]],
  3854. fill_value=999999)
  3855. >>> x = x.reshape((4,1))
  3856. >>> x
  3857. masked_array(
  3858. data=[[--],
  3859. [2],
  3860. [3],
  3861. [--]],
  3862. mask=[[ True],
  3863. [False],
  3864. [False],
  3865. [ True]],
  3866. fill_value=999999)
  3867. """
  3868. kwargs.update(order=kwargs.get('order', 'C'))
  3869. result = self._data.reshape(*s, **kwargs).view(type(self))
  3870. result._update_from(self)
  3871. mask = self._mask
  3872. if mask is not nomask:
  3873. result._mask = mask.reshape(*s, **kwargs)
  3874. return result
  3875. def resize(self, newshape, refcheck=True, order=False):
  3876. """
  3877. .. warning::
  3878. This method does nothing, except raise a ValueError exception. A
  3879. masked array does not own its data and therefore cannot safely be
  3880. resized in place. Use the `numpy.ma.resize` function instead.
  3881. This method is difficult to implement safely and may be deprecated in
  3882. future releases of NumPy.
  3883. """
  3884. # Note : the 'order' keyword looks broken, let's just drop it
  3885. errmsg = "A masked array does not own its data "\
  3886. "and therefore cannot be resized.\n" \
  3887. "Use the numpy.ma.resize function instead."
  3888. raise ValueError(errmsg)
  3889. def put(self, indices, values, mode='raise'):
  3890. """
  3891. Set storage-indexed locations to corresponding values.
  3892. Sets self._data.flat[n] = values[n] for each n in indices.
  3893. If `values` is shorter than `indices` then it will repeat.
  3894. If `values` has some masked values, the initial mask is updated
  3895. in consequence, else the corresponding values are unmasked.
  3896. Parameters
  3897. ----------
  3898. indices : 1-D array_like
  3899. Target indices, interpreted as integers.
  3900. values : array_like
  3901. Values to place in self._data copy at target indices.
  3902. mode : {'raise', 'wrap', 'clip'}, optional
  3903. Specifies how out-of-bounds indices will behave.
  3904. 'raise' : raise an error.
  3905. 'wrap' : wrap around.
  3906. 'clip' : clip to the range.
  3907. Notes
  3908. -----
  3909. `values` can be a scalar or length 1 array.
  3910. Examples
  3911. --------
  3912. >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
  3913. >>> x
  3914. masked_array(
  3915. data=[[1, --, 3],
  3916. [--, 5, --],
  3917. [7, --, 9]],
  3918. mask=[[False, True, False],
  3919. [ True, False, True],
  3920. [False, True, False]],
  3921. fill_value=999999)
  3922. >>> x.put([0,4,8],[10,20,30])
  3923. >>> x
  3924. masked_array(
  3925. data=[[10, --, 3],
  3926. [--, 20, --],
  3927. [7, --, 30]],
  3928. mask=[[False, True, False],
  3929. [ True, False, True],
  3930. [False, True, False]],
  3931. fill_value=999999)
  3932. >>> x.put(4,999)
  3933. >>> x
  3934. masked_array(
  3935. data=[[10, --, 3],
  3936. [--, 999, --],
  3937. [7, --, 30]],
  3938. mask=[[False, True, False],
  3939. [ True, False, True],
  3940. [False, True, False]],
  3941. fill_value=999999)
  3942. """
  3943. # Hard mask: Get rid of the values/indices that fall on masked data
  3944. if self._hardmask and self._mask is not nomask:
  3945. mask = self._mask[indices]
  3946. indices = narray(indices, copy=False)
  3947. values = narray(values, copy=False, subok=True)
  3948. values.resize(indices.shape)
  3949. indices = indices[~mask]
  3950. values = values[~mask]
  3951. self._data.put(indices, values, mode=mode)
  3952. # short circuit if neither self nor values are masked
  3953. if self._mask is nomask and getmask(values) is nomask:
  3954. return
  3955. m = getmaskarray(self)
  3956. if getmask(values) is nomask:
  3957. m.put(indices, False, mode=mode)
  3958. else:
  3959. m.put(indices, values._mask, mode=mode)
  3960. m = make_mask(m, copy=False, shrink=True)
  3961. self._mask = m
  3962. return
  3963. def ids(self):
  3964. """
  3965. Return the addresses of the data and mask areas.
  3966. Parameters
  3967. ----------
  3968. None
  3969. Examples
  3970. --------
  3971. >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1])
  3972. >>> x.ids()
  3973. (166670640, 166659832) # may vary
  3974. If the array has no mask, the address of `nomask` is returned. This address
  3975. is typically not close to the data in memory:
  3976. >>> x = np.ma.array([1, 2, 3])
  3977. >>> x.ids()
  3978. (166691080, 3083169284L) # may vary
  3979. """
  3980. if self._mask is nomask:
  3981. return (self.ctypes.data, id(nomask))
  3982. return (self.ctypes.data, self._mask.ctypes.data)
  3983. def iscontiguous(self):
  3984. """
  3985. Return a boolean indicating whether the data is contiguous.
  3986. Parameters
  3987. ----------
  3988. None
  3989. Examples
  3990. --------
  3991. >>> x = np.ma.array([1, 2, 3])
  3992. >>> x.iscontiguous()
  3993. True
  3994. `iscontiguous` returns one of the flags of the masked array:
  3995. >>> x.flags
  3996. C_CONTIGUOUS : True
  3997. F_CONTIGUOUS : True
  3998. OWNDATA : False
  3999. WRITEABLE : True
  4000. ALIGNED : True
  4001. WRITEBACKIFCOPY : False
  4002. UPDATEIFCOPY : False
  4003. """
  4004. return self.flags['CONTIGUOUS']
  4005. def all(self, axis=None, out=None, keepdims=np._NoValue):
  4006. """
  4007. Returns True if all elements evaluate to True.
  4008. The output array is masked where all the values along the given axis
  4009. are masked: if the output would have been a scalar and that all the
  4010. values are masked, then the output is `masked`.
  4011. Refer to `numpy.all` for full documentation.
  4012. See Also
  4013. --------
  4014. numpy.ndarray.all : corresponding function for ndarrays
  4015. numpy.all : equivalent function
  4016. Examples
  4017. --------
  4018. >>> np.ma.array([1,2,3]).all()
  4019. True
  4020. >>> a = np.ma.array([1,2,3], mask=True)
  4021. >>> (a.all() is np.ma.masked)
  4022. True
  4023. """
  4024. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  4025. mask = _check_mask_axis(self._mask, axis, **kwargs)
  4026. if out is None:
  4027. d = self.filled(True).all(axis=axis, **kwargs).view(type(self))
  4028. if d.ndim:
  4029. d.__setmask__(mask)
  4030. elif mask:
  4031. return masked
  4032. return d
  4033. self.filled(True).all(axis=axis, out=out, **kwargs)
  4034. if isinstance(out, MaskedArray):
  4035. if out.ndim or mask:
  4036. out.__setmask__(mask)
  4037. return out
  4038. def any(self, axis=None, out=None, keepdims=np._NoValue):
  4039. """
  4040. Returns True if any of the elements of `a` evaluate to True.
  4041. Masked values are considered as False during computation.
  4042. Refer to `numpy.any` for full documentation.
  4043. See Also
  4044. --------
  4045. numpy.ndarray.any : corresponding function for ndarrays
  4046. numpy.any : equivalent function
  4047. """
  4048. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  4049. mask = _check_mask_axis(self._mask, axis, **kwargs)
  4050. if out is None:
  4051. d = self.filled(False).any(axis=axis, **kwargs).view(type(self))
  4052. if d.ndim:
  4053. d.__setmask__(mask)
  4054. elif mask:
  4055. d = masked
  4056. return d
  4057. self.filled(False).any(axis=axis, out=out, **kwargs)
  4058. if isinstance(out, MaskedArray):
  4059. if out.ndim or mask:
  4060. out.__setmask__(mask)
  4061. return out
  4062. def nonzero(self):
  4063. """
  4064. Return the indices of unmasked elements that are not zero.
  4065. Returns a tuple of arrays, one for each dimension, containing the
  4066. indices of the non-zero elements in that dimension. The corresponding
  4067. non-zero values can be obtained with::
  4068. a[a.nonzero()]
  4069. To group the indices by element, rather than dimension, use
  4070. instead::
  4071. np.transpose(a.nonzero())
  4072. The result of this is always a 2d array, with a row for each non-zero
  4073. element.
  4074. Parameters
  4075. ----------
  4076. None
  4077. Returns
  4078. -------
  4079. tuple_of_arrays : tuple
  4080. Indices of elements that are non-zero.
  4081. See Also
  4082. --------
  4083. numpy.nonzero :
  4084. Function operating on ndarrays.
  4085. flatnonzero :
  4086. Return indices that are non-zero in the flattened version of the input
  4087. array.
  4088. numpy.ndarray.nonzero :
  4089. Equivalent ndarray method.
  4090. count_nonzero :
  4091. Counts the number of non-zero elements in the input array.
  4092. Examples
  4093. --------
  4094. >>> import numpy.ma as ma
  4095. >>> x = ma.array(np.eye(3))
  4096. >>> x
  4097. masked_array(
  4098. data=[[1., 0., 0.],
  4099. [0., 1., 0.],
  4100. [0., 0., 1.]],
  4101. mask=False,
  4102. fill_value=1e+20)
  4103. >>> x.nonzero()
  4104. (array([0, 1, 2]), array([0, 1, 2]))
  4105. Masked elements are ignored.
  4106. >>> x[1, 1] = ma.masked
  4107. >>> x
  4108. masked_array(
  4109. data=[[1.0, 0.0, 0.0],
  4110. [0.0, --, 0.0],
  4111. [0.0, 0.0, 1.0]],
  4112. mask=[[False, False, False],
  4113. [False, True, False],
  4114. [False, False, False]],
  4115. fill_value=1e+20)
  4116. >>> x.nonzero()
  4117. (array([0, 2]), array([0, 2]))
  4118. Indices can also be grouped by element.
  4119. >>> np.transpose(x.nonzero())
  4120. array([[0, 0],
  4121. [2, 2]])
  4122. A common use for ``nonzero`` is to find the indices of an array, where
  4123. a condition is True. Given an array `a`, the condition `a` > 3 is a
  4124. boolean array and since False is interpreted as 0, ma.nonzero(a > 3)
  4125. yields the indices of the `a` where the condition is true.
  4126. >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
  4127. >>> a > 3
  4128. masked_array(
  4129. data=[[False, False, False],
  4130. [ True, True, True],
  4131. [ True, True, True]],
  4132. mask=False,
  4133. fill_value=True)
  4134. >>> ma.nonzero(a > 3)
  4135. (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
  4136. The ``nonzero`` method of the condition array can also be called.
  4137. >>> (a > 3).nonzero()
  4138. (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
  4139. """
  4140. return narray(self.filled(0), copy=False).nonzero()
  4141. def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None):
  4142. """
  4143. (this docstring should be overwritten)
  4144. """
  4145. #!!!: implement out + test!
  4146. m = self._mask
  4147. if m is nomask:
  4148. result = super(MaskedArray, self).trace(offset=offset, axis1=axis1,
  4149. axis2=axis2, out=out)
  4150. return result.astype(dtype)
  4151. else:
  4152. D = self.diagonal(offset=offset, axis1=axis1, axis2=axis2)
  4153. return D.astype(dtype).filled(0).sum(axis=-1, out=out)
  4154. trace.__doc__ = ndarray.trace.__doc__
  4155. def dot(self, b, out=None, strict=False):
  4156. """
  4157. a.dot(b, out=None)
  4158. Masked dot product of two arrays. Note that `out` and `strict` are
  4159. located in different positions than in `ma.dot`. In order to
  4160. maintain compatibility with the functional version, it is
  4161. recommended that the optional arguments be treated as keyword only.
  4162. At some point that may be mandatory.
  4163. .. versionadded:: 1.10.0
  4164. Parameters
  4165. ----------
  4166. b : masked_array_like
  4167. Inputs array.
  4168. out : masked_array, optional
  4169. Output argument. This must have the exact kind that would be
  4170. returned if it was not used. In particular, it must have the
  4171. right type, must be C-contiguous, and its dtype must be the
  4172. dtype that would be returned for `ma.dot(a,b)`. This is a
  4173. performance feature. Therefore, if these conditions are not
  4174. met, an exception is raised, instead of attempting to be
  4175. flexible.
  4176. strict : bool, optional
  4177. Whether masked data are propagated (True) or set to 0 (False)
  4178. for the computation. Default is False. Propagating the mask
  4179. means that if a masked value appears in a row or column, the
  4180. whole row or column is considered masked.
  4181. .. versionadded:: 1.10.2
  4182. See Also
  4183. --------
  4184. numpy.ma.dot : equivalent function
  4185. """
  4186. return dot(self, b, out=out, strict=strict)
  4187. def sum(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
  4188. """
  4189. Return the sum of the array elements over the given axis.
  4190. Masked elements are set to 0 internally.
  4191. Refer to `numpy.sum` for full documentation.
  4192. See Also
  4193. --------
  4194. numpy.ndarray.sum : corresponding function for ndarrays
  4195. numpy.sum : equivalent function
  4196. Examples
  4197. --------
  4198. >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
  4199. >>> x
  4200. masked_array(
  4201. data=[[1, --, 3],
  4202. [--, 5, --],
  4203. [7, --, 9]],
  4204. mask=[[False, True, False],
  4205. [ True, False, True],
  4206. [False, True, False]],
  4207. fill_value=999999)
  4208. >>> x.sum()
  4209. 25
  4210. >>> x.sum(axis=1)
  4211. masked_array(data=[4, 5, 16],
  4212. mask=[False, False, False],
  4213. fill_value=999999)
  4214. >>> x.sum(axis=0)
  4215. masked_array(data=[8, 5, 12],
  4216. mask=[False, False, False],
  4217. fill_value=999999)
  4218. >>> print(type(x.sum(axis=0, dtype=np.int64)[0]))
  4219. <class 'numpy.int64'>
  4220. """
  4221. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  4222. _mask = self._mask
  4223. newmask = _check_mask_axis(_mask, axis, **kwargs)
  4224. # No explicit output
  4225. if out is None:
  4226. result = self.filled(0).sum(axis, dtype=dtype, **kwargs)
  4227. rndim = getattr(result, 'ndim', 0)
  4228. if rndim:
  4229. result = result.view(type(self))
  4230. result.__setmask__(newmask)
  4231. elif newmask:
  4232. result = masked
  4233. return result
  4234. # Explicit output
  4235. result = self.filled(0).sum(axis, dtype=dtype, out=out, **kwargs)
  4236. if isinstance(out, MaskedArray):
  4237. outmask = getmask(out)
  4238. if outmask is nomask:
  4239. outmask = out._mask = make_mask_none(out.shape)
  4240. outmask.flat = newmask
  4241. return out
  4242. def cumsum(self, axis=None, dtype=None, out=None):
  4243. """
  4244. Return the cumulative sum of the array elements over the given axis.
  4245. Masked values are set to 0 internally during the computation.
  4246. However, their position is saved, and the result will be masked at
  4247. the same locations.
  4248. Refer to `numpy.cumsum` for full documentation.
  4249. Notes
  4250. -----
  4251. The mask is lost if `out` is not a valid :class:`MaskedArray` !
  4252. Arithmetic is modular when using integer types, and no error is
  4253. raised on overflow.
  4254. See Also
  4255. --------
  4256. numpy.ndarray.cumsum : corresponding function for ndarrays
  4257. numpy.cumsum : equivalent function
  4258. Examples
  4259. --------
  4260. >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
  4261. >>> marr.cumsum()
  4262. masked_array(data=[0, 1, 3, --, --, --, 9, 16, 24, 33],
  4263. mask=[False, False, False, True, True, True, False, False,
  4264. False, False],
  4265. fill_value=999999)
  4266. """
  4267. result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out)
  4268. if out is not None:
  4269. if isinstance(out, MaskedArray):
  4270. out.__setmask__(self.mask)
  4271. return out
  4272. result = result.view(type(self))
  4273. result.__setmask__(self._mask)
  4274. return result
  4275. def prod(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
  4276. """
  4277. Return the product of the array elements over the given axis.
  4278. Masked elements are set to 1 internally for computation.
  4279. Refer to `numpy.prod` for full documentation.
  4280. Notes
  4281. -----
  4282. Arithmetic is modular when using integer types, and no error is raised
  4283. on overflow.
  4284. See Also
  4285. --------
  4286. numpy.ndarray.prod : corresponding function for ndarrays
  4287. numpy.prod : equivalent function
  4288. """
  4289. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  4290. _mask = self._mask
  4291. newmask = _check_mask_axis(_mask, axis, **kwargs)
  4292. # No explicit output
  4293. if out is None:
  4294. result = self.filled(1).prod(axis, dtype=dtype, **kwargs)
  4295. rndim = getattr(result, 'ndim', 0)
  4296. if rndim:
  4297. result = result.view(type(self))
  4298. result.__setmask__(newmask)
  4299. elif newmask:
  4300. result = masked
  4301. return result
  4302. # Explicit output
  4303. result = self.filled(1).prod(axis, dtype=dtype, out=out, **kwargs)
  4304. if isinstance(out, MaskedArray):
  4305. outmask = getmask(out)
  4306. if outmask is nomask:
  4307. outmask = out._mask = make_mask_none(out.shape)
  4308. outmask.flat = newmask
  4309. return out
  4310. product = prod
  4311. def cumprod(self, axis=None, dtype=None, out=None):
  4312. """
  4313. Return the cumulative product of the array elements over the given axis.
  4314. Masked values are set to 1 internally during the computation.
  4315. However, their position is saved, and the result will be masked at
  4316. the same locations.
  4317. Refer to `numpy.cumprod` for full documentation.
  4318. Notes
  4319. -----
  4320. The mask is lost if `out` is not a valid MaskedArray !
  4321. Arithmetic is modular when using integer types, and no error is
  4322. raised on overflow.
  4323. See Also
  4324. --------
  4325. numpy.ndarray.cumprod : corresponding function for ndarrays
  4326. numpy.cumprod : equivalent function
  4327. """
  4328. result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out)
  4329. if out is not None:
  4330. if isinstance(out, MaskedArray):
  4331. out.__setmask__(self._mask)
  4332. return out
  4333. result = result.view(type(self))
  4334. result.__setmask__(self._mask)
  4335. return result
  4336. def mean(self, axis=None, dtype=None, out=None, keepdims=np._NoValue):
  4337. """
  4338. Returns the average of the array elements along given axis.
  4339. Masked entries are ignored, and result elements which are not
  4340. finite will be masked.
  4341. Refer to `numpy.mean` for full documentation.
  4342. See Also
  4343. --------
  4344. numpy.ndarray.mean : corresponding function for ndarrays
  4345. numpy.mean : Equivalent function
  4346. numpy.ma.average: Weighted average.
  4347. Examples
  4348. --------
  4349. >>> a = np.ma.array([1,2,3], mask=[False, False, True])
  4350. >>> a
  4351. masked_array(data=[1, 2, --],
  4352. mask=[False, False, True],
  4353. fill_value=999999)
  4354. >>> a.mean()
  4355. 1.5
  4356. """
  4357. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  4358. if self._mask is nomask:
  4359. result = super(MaskedArray, self).mean(axis=axis,
  4360. dtype=dtype, **kwargs)[()]
  4361. else:
  4362. dsum = self.sum(axis=axis, dtype=dtype, **kwargs)
  4363. cnt = self.count(axis=axis, **kwargs)
  4364. if cnt.shape == () and (cnt == 0):
  4365. result = masked
  4366. else:
  4367. result = dsum * 1. / cnt
  4368. if out is not None:
  4369. out.flat = result
  4370. if isinstance(out, MaskedArray):
  4371. outmask = getmask(out)
  4372. if outmask is nomask:
  4373. outmask = out._mask = make_mask_none(out.shape)
  4374. outmask.flat = getmask(result)
  4375. return out
  4376. return result
  4377. def anom(self, axis=None, dtype=None):
  4378. """
  4379. Compute the anomalies (deviations from the arithmetic mean)
  4380. along the given axis.
  4381. Returns an array of anomalies, with the same shape as the input and
  4382. where the arithmetic mean is computed along the given axis.
  4383. Parameters
  4384. ----------
  4385. axis : int, optional
  4386. Axis over which the anomalies are taken.
  4387. The default is to use the mean of the flattened array as reference.
  4388. dtype : dtype, optional
  4389. Type to use in computing the variance. For arrays of integer type
  4390. the default is float32; for arrays of float types it is the same as
  4391. the array type.
  4392. See Also
  4393. --------
  4394. mean : Compute the mean of the array.
  4395. Examples
  4396. --------
  4397. >>> a = np.ma.array([1,2,3])
  4398. >>> a.anom()
  4399. masked_array(data=[-1., 0., 1.],
  4400. mask=False,
  4401. fill_value=1e+20)
  4402. """
  4403. m = self.mean(axis, dtype)
  4404. if m is masked:
  4405. return m
  4406. if not axis:
  4407. return self - m
  4408. else:
  4409. return self - expand_dims(m, axis)
  4410. def var(self, axis=None, dtype=None, out=None, ddof=0,
  4411. keepdims=np._NoValue):
  4412. """
  4413. Returns the variance of the array elements along given axis.
  4414. Masked entries are ignored, and result elements which are not
  4415. finite will be masked.
  4416. Refer to `numpy.var` for full documentation.
  4417. See Also
  4418. --------
  4419. numpy.ndarray.var : corresponding function for ndarrays
  4420. numpy.var : Equivalent function
  4421. """
  4422. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  4423. # Easy case: nomask, business as usual
  4424. if self._mask is nomask:
  4425. ret = super(MaskedArray, self).var(axis=axis, dtype=dtype, out=out,
  4426. ddof=ddof, **kwargs)[()]
  4427. if out is not None:
  4428. if isinstance(out, MaskedArray):
  4429. out.__setmask__(nomask)
  4430. return out
  4431. return ret
  4432. # Some data are masked, yay!
  4433. cnt = self.count(axis=axis, **kwargs) - ddof
  4434. danom = self - self.mean(axis, dtype, keepdims=True)
  4435. if iscomplexobj(self):
  4436. danom = umath.absolute(danom) ** 2
  4437. else:
  4438. danom *= danom
  4439. dvar = divide(danom.sum(axis, **kwargs), cnt).view(type(self))
  4440. # Apply the mask if it's not a scalar
  4441. if dvar.ndim:
  4442. dvar._mask = mask_or(self._mask.all(axis, **kwargs), (cnt <= 0))
  4443. dvar._update_from(self)
  4444. elif getmask(dvar):
  4445. # Make sure that masked is returned when the scalar is masked.
  4446. dvar = masked
  4447. if out is not None:
  4448. if isinstance(out, MaskedArray):
  4449. out.flat = 0
  4450. out.__setmask__(True)
  4451. elif out.dtype.kind in 'biu':
  4452. errmsg = "Masked data information would be lost in one or "\
  4453. "more location."
  4454. raise MaskError(errmsg)
  4455. else:
  4456. out.flat = np.nan
  4457. return out
  4458. # In case with have an explicit output
  4459. if out is not None:
  4460. # Set the data
  4461. out.flat = dvar
  4462. # Set the mask if needed
  4463. if isinstance(out, MaskedArray):
  4464. out.__setmask__(dvar.mask)
  4465. return out
  4466. return dvar
  4467. var.__doc__ = np.var.__doc__
  4468. def std(self, axis=None, dtype=None, out=None, ddof=0,
  4469. keepdims=np._NoValue):
  4470. """
  4471. Returns the standard deviation of the array elements along given axis.
  4472. Masked entries are ignored.
  4473. Refer to `numpy.std` for full documentation.
  4474. See Also
  4475. --------
  4476. numpy.ndarray.std : corresponding function for ndarrays
  4477. numpy.std : Equivalent function
  4478. """
  4479. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  4480. dvar = self.var(axis, dtype, out, ddof, **kwargs)
  4481. if dvar is not masked:
  4482. if out is not None:
  4483. np.power(out, 0.5, out=out, casting='unsafe')
  4484. return out
  4485. dvar = sqrt(dvar)
  4486. return dvar
  4487. def round(self, decimals=0, out=None):
  4488. """
  4489. Return each element rounded to the given number of decimals.
  4490. Refer to `numpy.around` for full documentation.
  4491. See Also
  4492. --------
  4493. numpy.ndarray.around : corresponding function for ndarrays
  4494. numpy.around : equivalent function
  4495. """
  4496. result = self._data.round(decimals=decimals, out=out).view(type(self))
  4497. if result.ndim > 0:
  4498. result._mask = self._mask
  4499. result._update_from(self)
  4500. elif self._mask:
  4501. # Return masked when the scalar is masked
  4502. result = masked
  4503. # No explicit output: we're done
  4504. if out is None:
  4505. return result
  4506. if isinstance(out, MaskedArray):
  4507. out.__setmask__(self._mask)
  4508. return out
  4509. def argsort(self, axis=np._NoValue, kind=None, order=None,
  4510. endwith=True, fill_value=None):
  4511. """
  4512. Return an ndarray of indices that sort the array along the
  4513. specified axis. Masked values are filled beforehand to
  4514. `fill_value`.
  4515. Parameters
  4516. ----------
  4517. axis : int, optional
  4518. Axis along which to sort. If None, the default, the flattened array
  4519. is used.
  4520. .. versionchanged:: 1.13.0
  4521. Previously, the default was documented to be -1, but that was
  4522. in error. At some future date, the default will change to -1, as
  4523. originally intended.
  4524. Until then, the axis should be given explicitly when
  4525. ``arr.ndim > 1``, to avoid a FutureWarning.
  4526. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
  4527. The sorting algorithm used.
  4528. order : list, optional
  4529. When `a` is an array with fields defined, this argument specifies
  4530. which fields to compare first, second, etc. Not all fields need be
  4531. specified.
  4532. endwith : {True, False}, optional
  4533. Whether missing values (if any) should be treated as the largest values
  4534. (True) or the smallest values (False)
  4535. When the array contains unmasked values at the same extremes of the
  4536. datatype, the ordering of these values and the masked values is
  4537. undefined.
  4538. fill_value : {var}, optional
  4539. Value used internally for the masked values.
  4540. If ``fill_value`` is not None, it supersedes ``endwith``.
  4541. Returns
  4542. -------
  4543. index_array : ndarray, int
  4544. Array of indices that sort `a` along the specified axis.
  4545. In other words, ``a[index_array]`` yields a sorted `a`.
  4546. See Also
  4547. --------
  4548. MaskedArray.sort : Describes sorting algorithms used.
  4549. lexsort : Indirect stable sort with multiple keys.
  4550. numpy.ndarray.sort : Inplace sort.
  4551. Notes
  4552. -----
  4553. See `sort` for notes on the different sorting algorithms.
  4554. Examples
  4555. --------
  4556. >>> a = np.ma.array([3,2,1], mask=[False, False, True])
  4557. >>> a
  4558. masked_array(data=[3, 2, --],
  4559. mask=[False, False, True],
  4560. fill_value=999999)
  4561. >>> a.argsort()
  4562. array([1, 0, 2])
  4563. """
  4564. # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default
  4565. if axis is np._NoValue:
  4566. axis = _deprecate_argsort_axis(self)
  4567. if fill_value is None:
  4568. if endwith:
  4569. # nan > inf
  4570. if np.issubdtype(self.dtype, np.floating):
  4571. fill_value = np.nan
  4572. else:
  4573. fill_value = minimum_fill_value(self)
  4574. else:
  4575. fill_value = maximum_fill_value(self)
  4576. filled = self.filled(fill_value)
  4577. return filled.argsort(axis=axis, kind=kind, order=order)
  4578. def argmin(self, axis=None, fill_value=None, out=None):
  4579. """
  4580. Return array of indices to the minimum values along the given axis.
  4581. Parameters
  4582. ----------
  4583. axis : {None, integer}
  4584. If None, the index is into the flattened array, otherwise along
  4585. the specified axis
  4586. fill_value : {var}, optional
  4587. Value used to fill in the masked values. If None, the output of
  4588. minimum_fill_value(self._data) is used instead.
  4589. out : {None, array}, optional
  4590. Array into which the result can be placed. Its type is preserved
  4591. and it must be of the right shape to hold the output.
  4592. Returns
  4593. -------
  4594. ndarray or scalar
  4595. If multi-dimension input, returns a new ndarray of indices to the
  4596. minimum values along the given axis. Otherwise, returns a scalar
  4597. of index to the minimum values along the given axis.
  4598. Examples
  4599. --------
  4600. >>> x = np.ma.array(np.arange(4), mask=[1,1,0,0])
  4601. >>> x.shape = (2,2)
  4602. >>> x
  4603. masked_array(
  4604. data=[[--, --],
  4605. [2, 3]],
  4606. mask=[[ True, True],
  4607. [False, False]],
  4608. fill_value=999999)
  4609. >>> x.argmin(axis=0, fill_value=-1)
  4610. array([0, 0])
  4611. >>> x.argmin(axis=0, fill_value=9)
  4612. array([1, 1])
  4613. """
  4614. if fill_value is None:
  4615. fill_value = minimum_fill_value(self)
  4616. d = self.filled(fill_value).view(ndarray)
  4617. return d.argmin(axis, out=out)
  4618. def argmax(self, axis=None, fill_value=None, out=None):
  4619. """
  4620. Returns array of indices of the maximum values along the given axis.
  4621. Masked values are treated as if they had the value fill_value.
  4622. Parameters
  4623. ----------
  4624. axis : {None, integer}
  4625. If None, the index is into the flattened array, otherwise along
  4626. the specified axis
  4627. fill_value : {var}, optional
  4628. Value used to fill in the masked values. If None, the output of
  4629. maximum_fill_value(self._data) is used instead.
  4630. out : {None, array}, optional
  4631. Array into which the result can be placed. Its type is preserved
  4632. and it must be of the right shape to hold the output.
  4633. Returns
  4634. -------
  4635. index_array : {integer_array}
  4636. Examples
  4637. --------
  4638. >>> a = np.arange(6).reshape(2,3)
  4639. >>> a.argmax()
  4640. 5
  4641. >>> a.argmax(0)
  4642. array([1, 1, 1])
  4643. >>> a.argmax(1)
  4644. array([2, 2])
  4645. """
  4646. if fill_value is None:
  4647. fill_value = maximum_fill_value(self._data)
  4648. d = self.filled(fill_value).view(ndarray)
  4649. return d.argmax(axis, out=out)
  4650. def sort(self, axis=-1, kind=None, order=None,
  4651. endwith=True, fill_value=None):
  4652. """
  4653. Sort the array, in-place
  4654. Parameters
  4655. ----------
  4656. a : array_like
  4657. Array to be sorted.
  4658. axis : int, optional
  4659. Axis along which to sort. If None, the array is flattened before
  4660. sorting. The default is -1, which sorts along the last axis.
  4661. kind : {'quicksort', 'mergesort', 'heapsort', 'stable'}, optional
  4662. The sorting algorithm used.
  4663. order : list, optional
  4664. When `a` is a structured array, this argument specifies which fields
  4665. to compare first, second, and so on. This list does not need to
  4666. include all of the fields.
  4667. endwith : {True, False}, optional
  4668. Whether missing values (if any) should be treated as the largest values
  4669. (True) or the smallest values (False)
  4670. When the array contains unmasked values sorting at the same extremes of the
  4671. datatype, the ordering of these values and the masked values is
  4672. undefined.
  4673. fill_value : {var}, optional
  4674. Value used internally for the masked values.
  4675. If ``fill_value`` is not None, it supersedes ``endwith``.
  4676. Returns
  4677. -------
  4678. sorted_array : ndarray
  4679. Array of the same type and shape as `a`.
  4680. See Also
  4681. --------
  4682. numpy.ndarray.sort : Method to sort an array in-place.
  4683. argsort : Indirect sort.
  4684. lexsort : Indirect stable sort on multiple keys.
  4685. searchsorted : Find elements in a sorted array.
  4686. Notes
  4687. -----
  4688. See ``sort`` for notes on the different sorting algorithms.
  4689. Examples
  4690. --------
  4691. >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
  4692. >>> # Default
  4693. >>> a.sort()
  4694. >>> a
  4695. masked_array(data=[1, 3, 5, --, --],
  4696. mask=[False, False, False, True, True],
  4697. fill_value=999999)
  4698. >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
  4699. >>> # Put missing values in the front
  4700. >>> a.sort(endwith=False)
  4701. >>> a
  4702. masked_array(data=[--, --, 1, 3, 5],
  4703. mask=[ True, True, False, False, False],
  4704. fill_value=999999)
  4705. >>> a = np.ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
  4706. >>> # fill_value takes over endwith
  4707. >>> a.sort(endwith=False, fill_value=3)
  4708. >>> a
  4709. masked_array(data=[1, --, --, 3, 5],
  4710. mask=[False, True, True, False, False],
  4711. fill_value=999999)
  4712. """
  4713. if self._mask is nomask:
  4714. ndarray.sort(self, axis=axis, kind=kind, order=order)
  4715. return
  4716. if self is masked:
  4717. return
  4718. sidx = self.argsort(axis=axis, kind=kind, order=order,
  4719. fill_value=fill_value, endwith=endwith)
  4720. self[...] = np.take_along_axis(self, sidx, axis=axis)
  4721. def min(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
  4722. """
  4723. Return the minimum along a given axis.
  4724. Parameters
  4725. ----------
  4726. axis : {None, int}, optional
  4727. Axis along which to operate. By default, ``axis`` is None and the
  4728. flattened input is used.
  4729. out : array_like, optional
  4730. Alternative output array in which to place the result. Must be of
  4731. the same shape and buffer length as the expected output.
  4732. fill_value : {var}, optional
  4733. Value used to fill in the masked values.
  4734. If None, use the output of `minimum_fill_value`.
  4735. keepdims : bool, optional
  4736. If this is set to True, the axes which are reduced are left
  4737. in the result as dimensions with size one. With this option,
  4738. the result will broadcast correctly against the array.
  4739. Returns
  4740. -------
  4741. amin : array_like
  4742. New array holding the result.
  4743. If ``out`` was specified, ``out`` is returned.
  4744. See Also
  4745. --------
  4746. minimum_fill_value
  4747. Returns the minimum filling value for a given datatype.
  4748. """
  4749. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  4750. _mask = self._mask
  4751. newmask = _check_mask_axis(_mask, axis, **kwargs)
  4752. if fill_value is None:
  4753. fill_value = minimum_fill_value(self)
  4754. # No explicit output
  4755. if out is None:
  4756. result = self.filled(fill_value).min(
  4757. axis=axis, out=out, **kwargs).view(type(self))
  4758. if result.ndim:
  4759. # Set the mask
  4760. result.__setmask__(newmask)
  4761. # Get rid of Infs
  4762. if newmask.ndim:
  4763. np.copyto(result, result.fill_value, where=newmask)
  4764. elif newmask:
  4765. result = masked
  4766. return result
  4767. # Explicit output
  4768. result = self.filled(fill_value).min(axis=axis, out=out, **kwargs)
  4769. if isinstance(out, MaskedArray):
  4770. outmask = getmask(out)
  4771. if outmask is nomask:
  4772. outmask = out._mask = make_mask_none(out.shape)
  4773. outmask.flat = newmask
  4774. else:
  4775. if out.dtype.kind in 'biu':
  4776. errmsg = "Masked data information would be lost in one or more"\
  4777. " location."
  4778. raise MaskError(errmsg)
  4779. np.copyto(out, np.nan, where=newmask)
  4780. return out
  4781. # unique to masked arrays
  4782. def mini(self, axis=None):
  4783. """
  4784. Return the array minimum along the specified axis.
  4785. .. deprecated:: 1.13.0
  4786. This function is identical to both:
  4787. * ``self.min(keepdims=True, axis=axis).squeeze(axis=axis)``
  4788. * ``np.ma.minimum.reduce(self, axis=axis)``
  4789. Typically though, ``self.min(axis=axis)`` is sufficient.
  4790. Parameters
  4791. ----------
  4792. axis : int, optional
  4793. The axis along which to find the minima. Default is None, in which case
  4794. the minimum value in the whole array is returned.
  4795. Returns
  4796. -------
  4797. min : scalar or MaskedArray
  4798. If `axis` is None, the result is a scalar. Otherwise, if `axis` is
  4799. given and the array is at least 2-D, the result is a masked array with
  4800. dimension one smaller than the array on which `mini` is called.
  4801. Examples
  4802. --------
  4803. >>> x = np.ma.array(np.arange(6), mask=[0 ,1, 0, 0, 0 ,1]).reshape(3, 2)
  4804. >>> x
  4805. masked_array(
  4806. data=[[0, --],
  4807. [2, 3],
  4808. [4, --]],
  4809. mask=[[False, True],
  4810. [False, False],
  4811. [False, True]],
  4812. fill_value=999999)
  4813. >>> x.mini()
  4814. masked_array(data=0,
  4815. mask=False,
  4816. fill_value=999999)
  4817. >>> x.mini(axis=0)
  4818. masked_array(data=[0, 3],
  4819. mask=[False, False],
  4820. fill_value=999999)
  4821. >>> x.mini(axis=1)
  4822. masked_array(data=[0, 2, 4],
  4823. mask=[False, False, False],
  4824. fill_value=999999)
  4825. There is a small difference between `mini` and `min`:
  4826. >>> x[:,1].mini(axis=0)
  4827. masked_array(data=3,
  4828. mask=False,
  4829. fill_value=999999)
  4830. >>> x[:,1].min(axis=0)
  4831. 3
  4832. """
  4833. # 2016-04-13, 1.13.0, gh-8764
  4834. warnings.warn(
  4835. "`mini` is deprecated; use the `min` method or "
  4836. "`np.ma.minimum.reduce instead.",
  4837. DeprecationWarning, stacklevel=2)
  4838. return minimum.reduce(self, axis)
  4839. def max(self, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
  4840. """
  4841. Return the maximum along a given axis.
  4842. Parameters
  4843. ----------
  4844. axis : {None, int}, optional
  4845. Axis along which to operate. By default, ``axis`` is None and the
  4846. flattened input is used.
  4847. out : array_like, optional
  4848. Alternative output array in which to place the result. Must
  4849. be of the same shape and buffer length as the expected output.
  4850. fill_value : {var}, optional
  4851. Value used to fill in the masked values.
  4852. If None, use the output of maximum_fill_value().
  4853. keepdims : bool, optional
  4854. If this is set to True, the axes which are reduced are left
  4855. in the result as dimensions with size one. With this option,
  4856. the result will broadcast correctly against the array.
  4857. Returns
  4858. -------
  4859. amax : array_like
  4860. New array holding the result.
  4861. If ``out`` was specified, ``out`` is returned.
  4862. See Also
  4863. --------
  4864. maximum_fill_value
  4865. Returns the maximum filling value for a given datatype.
  4866. """
  4867. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  4868. _mask = self._mask
  4869. newmask = _check_mask_axis(_mask, axis, **kwargs)
  4870. if fill_value is None:
  4871. fill_value = maximum_fill_value(self)
  4872. # No explicit output
  4873. if out is None:
  4874. result = self.filled(fill_value).max(
  4875. axis=axis, out=out, **kwargs).view(type(self))
  4876. if result.ndim:
  4877. # Set the mask
  4878. result.__setmask__(newmask)
  4879. # Get rid of Infs
  4880. if newmask.ndim:
  4881. np.copyto(result, result.fill_value, where=newmask)
  4882. elif newmask:
  4883. result = masked
  4884. return result
  4885. # Explicit output
  4886. result = self.filled(fill_value).max(axis=axis, out=out, **kwargs)
  4887. if isinstance(out, MaskedArray):
  4888. outmask = getmask(out)
  4889. if outmask is nomask:
  4890. outmask = out._mask = make_mask_none(out.shape)
  4891. outmask.flat = newmask
  4892. else:
  4893. if out.dtype.kind in 'biu':
  4894. errmsg = "Masked data information would be lost in one or more"\
  4895. " location."
  4896. raise MaskError(errmsg)
  4897. np.copyto(out, np.nan, where=newmask)
  4898. return out
  4899. def ptp(self, axis=None, out=None, fill_value=None, keepdims=False):
  4900. """
  4901. Return (maximum - minimum) along the given dimension
  4902. (i.e. peak-to-peak value).
  4903. Parameters
  4904. ----------
  4905. axis : {None, int}, optional
  4906. Axis along which to find the peaks. If None (default) the
  4907. flattened array is used.
  4908. out : {None, array_like}, optional
  4909. Alternative output array in which to place the result. It must
  4910. have the same shape and buffer length as the expected output
  4911. but the type will be cast if necessary.
  4912. fill_value : {var}, optional
  4913. Value used to fill in the masked values.
  4914. keepdims : bool, optional
  4915. If this is set to True, the axes which are reduced are left
  4916. in the result as dimensions with size one. With this option,
  4917. the result will broadcast correctly against the array.
  4918. Returns
  4919. -------
  4920. ptp : ndarray.
  4921. A new array holding the result, unless ``out`` was
  4922. specified, in which case a reference to ``out`` is returned.
  4923. """
  4924. if out is None:
  4925. result = self.max(axis=axis, fill_value=fill_value,
  4926. keepdims=keepdims)
  4927. result -= self.min(axis=axis, fill_value=fill_value,
  4928. keepdims=keepdims)
  4929. return result
  4930. out.flat = self.max(axis=axis, out=out, fill_value=fill_value,
  4931. keepdims=keepdims)
  4932. min_value = self.min(axis=axis, fill_value=fill_value,
  4933. keepdims=keepdims)
  4934. np.subtract(out, min_value, out=out, casting='unsafe')
  4935. return out
  4936. def partition(self, *args, **kwargs):
  4937. warnings.warn("Warning: 'partition' will ignore the 'mask' "
  4938. "of the {}.".format(self.__class__.__name__),
  4939. stacklevel=2)
  4940. return super(MaskedArray, self).partition(*args, **kwargs)
  4941. def argpartition(self, *args, **kwargs):
  4942. warnings.warn("Warning: 'argpartition' will ignore the 'mask' "
  4943. "of the {}.".format(self.__class__.__name__),
  4944. stacklevel=2)
  4945. return super(MaskedArray, self).argpartition(*args, **kwargs)
  4946. def take(self, indices, axis=None, out=None, mode='raise'):
  4947. """
  4948. """
  4949. (_data, _mask) = (self._data, self._mask)
  4950. cls = type(self)
  4951. # Make sure the indices are not masked
  4952. maskindices = getmask(indices)
  4953. if maskindices is not nomask:
  4954. indices = indices.filled(0)
  4955. # Get the data, promoting scalars to 0d arrays with [...] so that
  4956. # .view works correctly
  4957. if out is None:
  4958. out = _data.take(indices, axis=axis, mode=mode)[...].view(cls)
  4959. else:
  4960. np.take(_data, indices, axis=axis, mode=mode, out=out)
  4961. # Get the mask
  4962. if isinstance(out, MaskedArray):
  4963. if _mask is nomask:
  4964. outmask = maskindices
  4965. else:
  4966. outmask = _mask.take(indices, axis=axis, mode=mode)
  4967. outmask |= maskindices
  4968. out.__setmask__(outmask)
  4969. # demote 0d arrays back to scalars, for consistency with ndarray.take
  4970. return out[()]
  4971. # Array methods
  4972. copy = _arraymethod('copy')
  4973. diagonal = _arraymethod('diagonal')
  4974. flatten = _arraymethod('flatten')
  4975. repeat = _arraymethod('repeat')
  4976. squeeze = _arraymethod('squeeze')
  4977. swapaxes = _arraymethod('swapaxes')
  4978. T = property(fget=lambda self: self.transpose())
  4979. transpose = _arraymethod('transpose')
  4980. def tolist(self, fill_value=None):
  4981. """
  4982. Return the data portion of the masked array as a hierarchical Python list.
  4983. Data items are converted to the nearest compatible Python type.
  4984. Masked values are converted to `fill_value`. If `fill_value` is None,
  4985. the corresponding entries in the output list will be ``None``.
  4986. Parameters
  4987. ----------
  4988. fill_value : scalar, optional
  4989. The value to use for invalid entries. Default is None.
  4990. Returns
  4991. -------
  4992. result : list
  4993. The Python list representation of the masked array.
  4994. Examples
  4995. --------
  4996. >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4)
  4997. >>> x.tolist()
  4998. [[1, None, 3], [None, 5, None], [7, None, 9]]
  4999. >>> x.tolist(-999)
  5000. [[1, -999, 3], [-999, 5, -999], [7, -999, 9]]
  5001. """
  5002. _mask = self._mask
  5003. # No mask ? Just return .data.tolist ?
  5004. if _mask is nomask:
  5005. return self._data.tolist()
  5006. # Explicit fill_value: fill the array and get the list
  5007. if fill_value is not None:
  5008. return self.filled(fill_value).tolist()
  5009. # Structured array.
  5010. names = self.dtype.names
  5011. if names:
  5012. result = self._data.astype([(_, object) for _ in names])
  5013. for n in names:
  5014. result[n][_mask[n]] = None
  5015. return result.tolist()
  5016. # Standard arrays.
  5017. if _mask is nomask:
  5018. return [None]
  5019. # Set temps to save time when dealing w/ marrays.
  5020. inishape = self.shape
  5021. result = np.array(self._data.ravel(), dtype=object)
  5022. result[_mask.ravel()] = None
  5023. result.shape = inishape
  5024. return result.tolist()
  5025. def tostring(self, fill_value=None, order='C'):
  5026. """
  5027. This function is a compatibility alias for tobytes. Despite its name it
  5028. returns bytes not strings.
  5029. """
  5030. return self.tobytes(fill_value, order=order)
  5031. def tobytes(self, fill_value=None, order='C'):
  5032. """
  5033. Return the array data as a string containing the raw bytes in the array.
  5034. The array is filled with a fill value before the string conversion.
  5035. .. versionadded:: 1.9.0
  5036. Parameters
  5037. ----------
  5038. fill_value : scalar, optional
  5039. Value used to fill in the masked values. Default is None, in which
  5040. case `MaskedArray.fill_value` is used.
  5041. order : {'C','F','A'}, optional
  5042. Order of the data item in the copy. Default is 'C'.
  5043. - 'C' -- C order (row major).
  5044. - 'F' -- Fortran order (column major).
  5045. - 'A' -- Any, current order of array.
  5046. - None -- Same as 'A'.
  5047. See Also
  5048. --------
  5049. numpy.ndarray.tobytes
  5050. tolist, tofile
  5051. Notes
  5052. -----
  5053. As for `ndarray.tobytes`, information about the shape, dtype, etc.,
  5054. but also about `fill_value`, will be lost.
  5055. Examples
  5056. --------
  5057. >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
  5058. >>> x.tobytes()
  5059. b'\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00?B\\x0f\\x00\\x00\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00'
  5060. """
  5061. return self.filled(fill_value).tobytes(order=order)
  5062. def tofile(self, fid, sep="", format="%s"):
  5063. """
  5064. Save a masked array to a file in binary format.
  5065. .. warning::
  5066. This function is not implemented yet.
  5067. Raises
  5068. ------
  5069. NotImplementedError
  5070. When `tofile` is called.
  5071. """
  5072. raise NotImplementedError("MaskedArray.tofile() not implemented yet.")
  5073. def toflex(self):
  5074. """
  5075. Transforms a masked array into a flexible-type array.
  5076. The flexible type array that is returned will have two fields:
  5077. * the ``_data`` field stores the ``_data`` part of the array.
  5078. * the ``_mask`` field stores the ``_mask`` part of the array.
  5079. Parameters
  5080. ----------
  5081. None
  5082. Returns
  5083. -------
  5084. record : ndarray
  5085. A new flexible-type `ndarray` with two fields: the first element
  5086. containing a value, the second element containing the corresponding
  5087. mask boolean. The returned record shape matches self.shape.
  5088. Notes
  5089. -----
  5090. A side-effect of transforming a masked array into a flexible `ndarray` is
  5091. that meta information (``fill_value``, ...) will be lost.
  5092. Examples
  5093. --------
  5094. >>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
  5095. >>> x
  5096. masked_array(
  5097. data=[[1, --, 3],
  5098. [--, 5, --],
  5099. [7, --, 9]],
  5100. mask=[[False, True, False],
  5101. [ True, False, True],
  5102. [False, True, False]],
  5103. fill_value=999999)
  5104. >>> x.toflex()
  5105. array([[(1, False), (2, True), (3, False)],
  5106. [(4, True), (5, False), (6, True)],
  5107. [(7, False), (8, True), (9, False)]],
  5108. dtype=[('_data', '<i8'), ('_mask', '?')])
  5109. """
  5110. # Get the basic dtype.
  5111. ddtype = self.dtype
  5112. # Make sure we have a mask
  5113. _mask = self._mask
  5114. if _mask is None:
  5115. _mask = make_mask_none(self.shape, ddtype)
  5116. # And get its dtype
  5117. mdtype = self._mask.dtype
  5118. record = np.ndarray(shape=self.shape,
  5119. dtype=[('_data', ddtype), ('_mask', mdtype)])
  5120. record['_data'] = self._data
  5121. record['_mask'] = self._mask
  5122. return record
  5123. torecords = toflex
  5124. # Pickling
  5125. def __getstate__(self):
  5126. """Return the internal state of the masked array, for pickling
  5127. purposes.
  5128. """
  5129. cf = 'CF'[self.flags.fnc]
  5130. data_state = super(MaskedArray, self).__reduce__()[2]
  5131. return data_state + (getmaskarray(self).tobytes(cf), self._fill_value)
  5132. def __setstate__(self, state):
  5133. """Restore the internal state of the masked array, for
  5134. pickling purposes. ``state`` is typically the output of the
  5135. ``__getstate__`` output, and is a 5-tuple:
  5136. - class name
  5137. - a tuple giving the shape of the data
  5138. - a typecode for the data
  5139. - a binary string for the data
  5140. - a binary string for the mask.
  5141. """
  5142. (_, shp, typ, isf, raw, msk, flv) = state
  5143. super(MaskedArray, self).__setstate__((shp, typ, isf, raw))
  5144. self._mask.__setstate__((shp, make_mask_descr(typ), isf, msk))
  5145. self.fill_value = flv
  5146. def __reduce__(self):
  5147. """Return a 3-tuple for pickling a MaskedArray.
  5148. """
  5149. return (_mareconstruct,
  5150. (self.__class__, self._baseclass, (0,), 'b',),
  5151. self.__getstate__())
  5152. def __deepcopy__(self, memo=None):
  5153. from copy import deepcopy
  5154. copied = MaskedArray.__new__(type(self), self, copy=True)
  5155. if memo is None:
  5156. memo = {}
  5157. memo[id(self)] = copied
  5158. for (k, v) in self.__dict__.items():
  5159. copied.__dict__[k] = deepcopy(v, memo)
  5160. return copied
  5161. def _mareconstruct(subtype, baseclass, baseshape, basetype,):
  5162. """Internal function that builds a new MaskedArray from the
  5163. information stored in a pickle.
  5164. """
  5165. _data = ndarray.__new__(baseclass, baseshape, basetype)
  5166. _mask = ndarray.__new__(ndarray, baseshape, make_mask_descr(basetype))
  5167. return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,)
  5168. class mvoid(MaskedArray):
  5169. """
  5170. Fake a 'void' object to use for masked array with structured dtypes.
  5171. """
  5172. def __new__(self, data, mask=nomask, dtype=None, fill_value=None,
  5173. hardmask=False, copy=False, subok=True):
  5174. _data = np.array(data, copy=copy, subok=subok, dtype=dtype)
  5175. _data = _data.view(self)
  5176. _data._hardmask = hardmask
  5177. if mask is not nomask:
  5178. if isinstance(mask, np.void):
  5179. _data._mask = mask
  5180. else:
  5181. try:
  5182. # Mask is already a 0D array
  5183. _data._mask = np.void(mask)
  5184. except TypeError:
  5185. # Transform the mask to a void
  5186. mdtype = make_mask_descr(dtype)
  5187. _data._mask = np.array(mask, dtype=mdtype)[()]
  5188. if fill_value is not None:
  5189. _data.fill_value = fill_value
  5190. return _data
  5191. @property
  5192. def _data(self):
  5193. # Make sure that the _data part is a np.void
  5194. return super(mvoid, self)._data[()]
  5195. def __getitem__(self, indx):
  5196. """
  5197. Get the index.
  5198. """
  5199. m = self._mask
  5200. if isinstance(m[indx], ndarray):
  5201. # Can happen when indx is a multi-dimensional field:
  5202. # A = ma.masked_array(data=[([0,1],)], mask=[([True,
  5203. # False],)], dtype=[("A", ">i2", (2,))])
  5204. # x = A[0]; y = x["A"]; then y.mask["A"].size==2
  5205. # and we can not say masked/unmasked.
  5206. # The result is no longer mvoid!
  5207. # See also issue #6724.
  5208. return masked_array(
  5209. data=self._data[indx], mask=m[indx],
  5210. fill_value=self._fill_value[indx],
  5211. hard_mask=self._hardmask)
  5212. if m is not nomask and m[indx]:
  5213. return masked
  5214. return self._data[indx]
  5215. def __setitem__(self, indx, value):
  5216. self._data[indx] = value
  5217. if self._hardmask:
  5218. self._mask[indx] |= getattr(value, "_mask", False)
  5219. else:
  5220. self._mask[indx] = getattr(value, "_mask", False)
  5221. def __str__(self):
  5222. m = self._mask
  5223. if m is nomask:
  5224. return str(self._data)
  5225. rdtype = _replace_dtype_fields(self._data.dtype, "O")
  5226. data_arr = super(mvoid, self)._data
  5227. res = data_arr.astype(rdtype)
  5228. _recursive_printoption(res, self._mask, masked_print_option)
  5229. return str(res)
  5230. __repr__ = __str__
  5231. def __iter__(self):
  5232. "Defines an iterator for mvoid"
  5233. (_data, _mask) = (self._data, self._mask)
  5234. if _mask is nomask:
  5235. for d in _data:
  5236. yield d
  5237. else:
  5238. for (d, m) in zip(_data, _mask):
  5239. if m:
  5240. yield masked
  5241. else:
  5242. yield d
  5243. def __len__(self):
  5244. return self._data.__len__()
  5245. def filled(self, fill_value=None):
  5246. """
  5247. Return a copy with masked fields filled with a given value.
  5248. Parameters
  5249. ----------
  5250. fill_value : array_like, optional
  5251. The value to use for invalid entries. Can be scalar or
  5252. non-scalar. If latter is the case, the filled array should
  5253. be broadcastable over input array. Default is None, in
  5254. which case the `fill_value` attribute is used instead.
  5255. Returns
  5256. -------
  5257. filled_void
  5258. A `np.void` object
  5259. See Also
  5260. --------
  5261. MaskedArray.filled
  5262. """
  5263. return asarray(self).filled(fill_value)[()]
  5264. def tolist(self):
  5265. """
  5266. Transforms the mvoid object into a tuple.
  5267. Masked fields are replaced by None.
  5268. Returns
  5269. -------
  5270. returned_tuple
  5271. Tuple of fields
  5272. """
  5273. _mask = self._mask
  5274. if _mask is nomask:
  5275. return self._data.tolist()
  5276. result = []
  5277. for (d, m) in zip(self._data, self._mask):
  5278. if m:
  5279. result.append(None)
  5280. else:
  5281. # .item() makes sure we return a standard Python object
  5282. result.append(d.item())
  5283. return tuple(result)
  5284. ##############################################################################
  5285. # Shortcuts #
  5286. ##############################################################################
  5287. def isMaskedArray(x):
  5288. """
  5289. Test whether input is an instance of MaskedArray.
  5290. This function returns True if `x` is an instance of MaskedArray
  5291. and returns False otherwise. Any object is accepted as input.
  5292. Parameters
  5293. ----------
  5294. x : object
  5295. Object to test.
  5296. Returns
  5297. -------
  5298. result : bool
  5299. True if `x` is a MaskedArray.
  5300. See Also
  5301. --------
  5302. isMA : Alias to isMaskedArray.
  5303. isarray : Alias to isMaskedArray.
  5304. Examples
  5305. --------
  5306. >>> import numpy.ma as ma
  5307. >>> a = np.eye(3, 3)
  5308. >>> a
  5309. array([[ 1., 0., 0.],
  5310. [ 0., 1., 0.],
  5311. [ 0., 0., 1.]])
  5312. >>> m = ma.masked_values(a, 0)
  5313. >>> m
  5314. masked_array(
  5315. data=[[1.0, --, --],
  5316. [--, 1.0, --],
  5317. [--, --, 1.0]],
  5318. mask=[[False, True, True],
  5319. [ True, False, True],
  5320. [ True, True, False]],
  5321. fill_value=0.0)
  5322. >>> ma.isMaskedArray(a)
  5323. False
  5324. >>> ma.isMaskedArray(m)
  5325. True
  5326. >>> ma.isMaskedArray([0, 1, 2])
  5327. False
  5328. """
  5329. return isinstance(x, MaskedArray)
  5330. isarray = isMaskedArray
  5331. isMA = isMaskedArray # backward compatibility
  5332. class MaskedConstant(MaskedArray):
  5333. # the lone np.ma.masked instance
  5334. __singleton = None
  5335. @classmethod
  5336. def __has_singleton(cls):
  5337. # second case ensures `cls.__singleton` is not just a view on the
  5338. # superclass singleton
  5339. return cls.__singleton is not None and type(cls.__singleton) is cls
  5340. def __new__(cls):
  5341. if not cls.__has_singleton():
  5342. # We define the masked singleton as a float for higher precedence.
  5343. # Note that it can be tricky sometimes w/ type comparison
  5344. data = np.array(0.)
  5345. mask = np.array(True)
  5346. # prevent any modifications
  5347. data.flags.writeable = False
  5348. mask.flags.writeable = False
  5349. # don't fall back on MaskedArray.__new__(MaskedConstant), since
  5350. # that might confuse it - this way, the construction is entirely
  5351. # within our control
  5352. cls.__singleton = MaskedArray(data, mask=mask).view(cls)
  5353. return cls.__singleton
  5354. def __array_finalize__(self, obj):
  5355. if not self.__has_singleton():
  5356. # this handles the `.view` in __new__, which we want to copy across
  5357. # properties normally
  5358. return super(MaskedConstant, self).__array_finalize__(obj)
  5359. elif self is self.__singleton:
  5360. # not clear how this can happen, play it safe
  5361. pass
  5362. else:
  5363. # everywhere else, we want to downcast to MaskedArray, to prevent a
  5364. # duplicate maskedconstant.
  5365. self.__class__ = MaskedArray
  5366. MaskedArray.__array_finalize__(self, obj)
  5367. def __array_prepare__(self, obj, context=None):
  5368. return self.view(MaskedArray).__array_prepare__(obj, context)
  5369. def __array_wrap__(self, obj, context=None):
  5370. return self.view(MaskedArray).__array_wrap__(obj, context)
  5371. def __str__(self):
  5372. return str(masked_print_option._display)
  5373. if sys.version_info.major < 3:
  5374. def __unicode__(self):
  5375. return unicode(masked_print_option._display)
  5376. def __repr__(self):
  5377. if self is MaskedConstant.__singleton:
  5378. return 'masked'
  5379. else:
  5380. # it's a subclass, or something is wrong, make it obvious
  5381. return object.__repr__(self)
  5382. def __reduce__(self):
  5383. """Override of MaskedArray's __reduce__.
  5384. """
  5385. return (self.__class__, ())
  5386. # inplace operations have no effect. We have to override them to avoid
  5387. # trying to modify the readonly data and mask arrays
  5388. def __iop__(self, other):
  5389. return self
  5390. __iadd__ = \
  5391. __isub__ = \
  5392. __imul__ = \
  5393. __ifloordiv__ = \
  5394. __itruediv__ = \
  5395. __ipow__ = \
  5396. __iop__
  5397. del __iop__ # don't leave this around
  5398. def copy(self, *args, **kwargs):
  5399. """ Copy is a no-op on the maskedconstant, as it is a scalar """
  5400. # maskedconstant is a scalar, so copy doesn't need to copy. There's
  5401. # precedent for this with `np.bool_` scalars.
  5402. return self
  5403. def __copy__(self):
  5404. return self
  5405. def __deepcopy__(self, memo):
  5406. return self
  5407. def __setattr__(self, attr, value):
  5408. if not self.__has_singleton():
  5409. # allow the singleton to be initialized
  5410. return super(MaskedConstant, self).__setattr__(attr, value)
  5411. elif self is self.__singleton:
  5412. raise AttributeError(
  5413. "attributes of {!r} are not writeable".format(self))
  5414. else:
  5415. # duplicate instance - we can end up here from __array_finalize__,
  5416. # where we set the __class__ attribute
  5417. return super(MaskedConstant, self).__setattr__(attr, value)
  5418. masked = masked_singleton = MaskedConstant()
  5419. masked_array = MaskedArray
  5420. def array(data, dtype=None, copy=False, order=None,
  5421. mask=nomask, fill_value=None, keep_mask=True,
  5422. hard_mask=False, shrink=True, subok=True, ndmin=0):
  5423. """
  5424. Shortcut to MaskedArray.
  5425. The options are in a different order for convenience and backwards
  5426. compatibility.
  5427. """
  5428. return MaskedArray(data, mask=mask, dtype=dtype, copy=copy,
  5429. subok=subok, keep_mask=keep_mask,
  5430. hard_mask=hard_mask, fill_value=fill_value,
  5431. ndmin=ndmin, shrink=shrink, order=order)
  5432. array.__doc__ = masked_array.__doc__
  5433. def is_masked(x):
  5434. """
  5435. Determine whether input has masked values.
  5436. Accepts any object as input, but always returns False unless the
  5437. input is a MaskedArray containing masked values.
  5438. Parameters
  5439. ----------
  5440. x : array_like
  5441. Array to check for masked values.
  5442. Returns
  5443. -------
  5444. result : bool
  5445. True if `x` is a MaskedArray with masked values, False otherwise.
  5446. Examples
  5447. --------
  5448. >>> import numpy.ma as ma
  5449. >>> x = ma.masked_equal([0, 1, 0, 2, 3], 0)
  5450. >>> x
  5451. masked_array(data=[--, 1, --, 2, 3],
  5452. mask=[ True, False, True, False, False],
  5453. fill_value=0)
  5454. >>> ma.is_masked(x)
  5455. True
  5456. >>> x = ma.masked_equal([0, 1, 0, 2, 3], 42)
  5457. >>> x
  5458. masked_array(data=[0, 1, 0, 2, 3],
  5459. mask=False,
  5460. fill_value=42)
  5461. >>> ma.is_masked(x)
  5462. False
  5463. Always returns False if `x` isn't a MaskedArray.
  5464. >>> x = [False, True, False]
  5465. >>> ma.is_masked(x)
  5466. False
  5467. >>> x = 'a string'
  5468. >>> ma.is_masked(x)
  5469. False
  5470. """
  5471. m = getmask(x)
  5472. if m is nomask:
  5473. return False
  5474. elif m.any():
  5475. return True
  5476. return False
  5477. ##############################################################################
  5478. # Extrema functions #
  5479. ##############################################################################
  5480. class _extrema_operation(_MaskedUFunc):
  5481. """
  5482. Generic class for maximum/minimum functions.
  5483. .. note::
  5484. This is the base class for `_maximum_operation` and
  5485. `_minimum_operation`.
  5486. """
  5487. def __init__(self, ufunc, compare, fill_value):
  5488. super(_extrema_operation, self).__init__(ufunc)
  5489. self.compare = compare
  5490. self.fill_value_func = fill_value
  5491. def __call__(self, a, b=None):
  5492. "Executes the call behavior."
  5493. if b is None:
  5494. # 2016-04-13, 1.13.0
  5495. warnings.warn(
  5496. "Single-argument form of np.ma.{0} is deprecated. Use "
  5497. "np.ma.{0}.reduce instead.".format(self.__name__),
  5498. DeprecationWarning, stacklevel=2)
  5499. return self.reduce(a)
  5500. return where(self.compare(a, b), a, b)
  5501. def reduce(self, target, axis=np._NoValue):
  5502. "Reduce target along the given axis."
  5503. target = narray(target, copy=False, subok=True)
  5504. m = getmask(target)
  5505. if axis is np._NoValue and target.ndim > 1:
  5506. # 2017-05-06, Numpy 1.13.0: warn on axis default
  5507. warnings.warn(
  5508. "In the future the default for ma.{0}.reduce will be axis=0, "
  5509. "not the current None, to match np.{0}.reduce. "
  5510. "Explicitly pass 0 or None to silence this warning.".format(
  5511. self.__name__
  5512. ),
  5513. MaskedArrayFutureWarning, stacklevel=2)
  5514. axis = None
  5515. if axis is not np._NoValue:
  5516. kwargs = dict(axis=axis)
  5517. else:
  5518. kwargs = dict()
  5519. if m is nomask:
  5520. t = self.f.reduce(target, **kwargs)
  5521. else:
  5522. target = target.filled(
  5523. self.fill_value_func(target)).view(type(target))
  5524. t = self.f.reduce(target, **kwargs)
  5525. m = umath.logical_and.reduce(m, **kwargs)
  5526. if hasattr(t, '_mask'):
  5527. t._mask = m
  5528. elif m:
  5529. t = masked
  5530. return t
  5531. def outer(self, a, b):
  5532. "Return the function applied to the outer product of a and b."
  5533. ma = getmask(a)
  5534. mb = getmask(b)
  5535. if ma is nomask and mb is nomask:
  5536. m = nomask
  5537. else:
  5538. ma = getmaskarray(a)
  5539. mb = getmaskarray(b)
  5540. m = logical_or.outer(ma, mb)
  5541. result = self.f.outer(filled(a), filled(b))
  5542. if not isinstance(result, MaskedArray):
  5543. result = result.view(MaskedArray)
  5544. result._mask = m
  5545. return result
  5546. def min(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
  5547. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  5548. try:
  5549. return obj.min(axis=axis, fill_value=fill_value, out=out, **kwargs)
  5550. except (AttributeError, TypeError):
  5551. # If obj doesn't have a min method, or if the method doesn't accept a
  5552. # fill_value argument
  5553. return asanyarray(obj).min(axis=axis, fill_value=fill_value,
  5554. out=out, **kwargs)
  5555. min.__doc__ = MaskedArray.min.__doc__
  5556. def max(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
  5557. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  5558. try:
  5559. return obj.max(axis=axis, fill_value=fill_value, out=out, **kwargs)
  5560. except (AttributeError, TypeError):
  5561. # If obj doesn't have a max method, or if the method doesn't accept a
  5562. # fill_value argument
  5563. return asanyarray(obj).max(axis=axis, fill_value=fill_value,
  5564. out=out, **kwargs)
  5565. max.__doc__ = MaskedArray.max.__doc__
  5566. def ptp(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
  5567. kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
  5568. try:
  5569. return obj.ptp(axis, out=out, fill_value=fill_value, **kwargs)
  5570. except (AttributeError, TypeError):
  5571. # If obj doesn't have a ptp method or if the method doesn't accept
  5572. # a fill_value argument
  5573. return asanyarray(obj).ptp(axis=axis, fill_value=fill_value,
  5574. out=out, **kwargs)
  5575. ptp.__doc__ = MaskedArray.ptp.__doc__
  5576. ##############################################################################
  5577. # Definition of functions from the corresponding methods #
  5578. ##############################################################################
  5579. class _frommethod(object):
  5580. """
  5581. Define functions from existing MaskedArray methods.
  5582. Parameters
  5583. ----------
  5584. methodname : str
  5585. Name of the method to transform.
  5586. """
  5587. def __init__(self, methodname, reversed=False):
  5588. self.__name__ = methodname
  5589. self.__doc__ = self.getdoc()
  5590. self.reversed = reversed
  5591. def getdoc(self):
  5592. "Return the doc of the function (from the doc of the method)."
  5593. meth = getattr(MaskedArray, self.__name__, None) or\
  5594. getattr(np, self.__name__, None)
  5595. signature = self.__name__ + get_object_signature(meth)
  5596. if meth is not None:
  5597. doc = """ %s\n%s""" % (
  5598. signature, getattr(meth, '__doc__', None))
  5599. return doc
  5600. def __call__(self, a, *args, **params):
  5601. if self.reversed:
  5602. args = list(args)
  5603. a, args[0] = args[0], a
  5604. marr = asanyarray(a)
  5605. method_name = self.__name__
  5606. method = getattr(type(marr), method_name, None)
  5607. if method is None:
  5608. # use the corresponding np function
  5609. method = getattr(np, method_name)
  5610. return method(marr, *args, **params)
  5611. all = _frommethod('all')
  5612. anomalies = anom = _frommethod('anom')
  5613. any = _frommethod('any')
  5614. compress = _frommethod('compress', reversed=True)
  5615. cumprod = _frommethod('cumprod')
  5616. cumsum = _frommethod('cumsum')
  5617. copy = _frommethod('copy')
  5618. diagonal = _frommethod('diagonal')
  5619. harden_mask = _frommethod('harden_mask')
  5620. ids = _frommethod('ids')
  5621. maximum = _extrema_operation(umath.maximum, greater, maximum_fill_value)
  5622. mean = _frommethod('mean')
  5623. minimum = _extrema_operation(umath.minimum, less, minimum_fill_value)
  5624. nonzero = _frommethod('nonzero')
  5625. prod = _frommethod('prod')
  5626. product = _frommethod('prod')
  5627. ravel = _frommethod('ravel')
  5628. repeat = _frommethod('repeat')
  5629. shrink_mask = _frommethod('shrink_mask')
  5630. soften_mask = _frommethod('soften_mask')
  5631. std = _frommethod('std')
  5632. sum = _frommethod('sum')
  5633. swapaxes = _frommethod('swapaxes')
  5634. #take = _frommethod('take')
  5635. trace = _frommethod('trace')
  5636. var = _frommethod('var')
  5637. count = _frommethod('count')
  5638. def take(a, indices, axis=None, out=None, mode='raise'):
  5639. """
  5640. """
  5641. a = masked_array(a)
  5642. return a.take(indices, axis=axis, out=out, mode=mode)
  5643. def power(a, b, third=None):
  5644. """
  5645. Returns element-wise base array raised to power from second array.
  5646. This is the masked array version of `numpy.power`. For details see
  5647. `numpy.power`.
  5648. See Also
  5649. --------
  5650. numpy.power
  5651. Notes
  5652. -----
  5653. The *out* argument to `numpy.power` is not supported, `third` has to be
  5654. None.
  5655. """
  5656. if third is not None:
  5657. raise MaskError("3-argument power not supported.")
  5658. # Get the masks
  5659. ma = getmask(a)
  5660. mb = getmask(b)
  5661. m = mask_or(ma, mb)
  5662. # Get the rawdata
  5663. fa = getdata(a)
  5664. fb = getdata(b)
  5665. # Get the type of the result (so that we preserve subclasses)
  5666. if isinstance(a, MaskedArray):
  5667. basetype = type(a)
  5668. else:
  5669. basetype = MaskedArray
  5670. # Get the result and view it as a (subclass of) MaskedArray
  5671. with np.errstate(divide='ignore', invalid='ignore'):
  5672. result = np.where(m, fa, umath.power(fa, fb)).view(basetype)
  5673. result._update_from(a)
  5674. # Find where we're in trouble w/ NaNs and Infs
  5675. invalid = np.logical_not(np.isfinite(result.view(ndarray)))
  5676. # Add the initial mask
  5677. if m is not nomask:
  5678. if not result.ndim:
  5679. return masked
  5680. result._mask = np.logical_or(m, invalid)
  5681. # Fix the invalid parts
  5682. if invalid.any():
  5683. if not result.ndim:
  5684. return masked
  5685. elif result._mask is nomask:
  5686. result._mask = invalid
  5687. result._data[invalid] = result.fill_value
  5688. return result
  5689. argmin = _frommethod('argmin')
  5690. argmax = _frommethod('argmax')
  5691. def argsort(a, axis=np._NoValue, kind=None, order=None, endwith=True, fill_value=None):
  5692. "Function version of the eponymous method."
  5693. a = np.asanyarray(a)
  5694. # 2017-04-11, Numpy 1.13.0, gh-8701: warn on axis default
  5695. if axis is np._NoValue:
  5696. axis = _deprecate_argsort_axis(a)
  5697. if isinstance(a, MaskedArray):
  5698. return a.argsort(axis=axis, kind=kind, order=order,
  5699. endwith=endwith, fill_value=fill_value)
  5700. else:
  5701. return a.argsort(axis=axis, kind=kind, order=order)
  5702. argsort.__doc__ = MaskedArray.argsort.__doc__
  5703. def sort(a, axis=-1, kind=None, order=None, endwith=True, fill_value=None):
  5704. "Function version of the eponymous method."
  5705. a = np.array(a, copy=True, subok=True)
  5706. if axis is None:
  5707. a = a.flatten()
  5708. axis = 0
  5709. if isinstance(a, MaskedArray):
  5710. a.sort(axis=axis, kind=kind, order=order,
  5711. endwith=endwith, fill_value=fill_value)
  5712. else:
  5713. a.sort(axis=axis, kind=kind, order=order)
  5714. return a
  5715. sort.__doc__ = MaskedArray.sort.__doc__
  5716. def compressed(x):
  5717. """
  5718. Return all the non-masked data as a 1-D array.
  5719. This function is equivalent to calling the "compressed" method of a
  5720. `MaskedArray`, see `MaskedArray.compressed` for details.
  5721. See Also
  5722. --------
  5723. MaskedArray.compressed
  5724. Equivalent method.
  5725. """
  5726. return asanyarray(x).compressed()
  5727. def concatenate(arrays, axis=0):
  5728. """
  5729. Concatenate a sequence of arrays along the given axis.
  5730. Parameters
  5731. ----------
  5732. arrays : sequence of array_like
  5733. The arrays must have the same shape, except in the dimension
  5734. corresponding to `axis` (the first, by default).
  5735. axis : int, optional
  5736. The axis along which the arrays will be joined. Default is 0.
  5737. Returns
  5738. -------
  5739. result : MaskedArray
  5740. The concatenated array with any masked entries preserved.
  5741. See Also
  5742. --------
  5743. numpy.concatenate : Equivalent function in the top-level NumPy module.
  5744. Examples
  5745. --------
  5746. >>> import numpy.ma as ma
  5747. >>> a = ma.arange(3)
  5748. >>> a[1] = ma.masked
  5749. >>> b = ma.arange(2, 5)
  5750. >>> a
  5751. masked_array(data=[0, --, 2],
  5752. mask=[False, True, False],
  5753. fill_value=999999)
  5754. >>> b
  5755. masked_array(data=[2, 3, 4],
  5756. mask=False,
  5757. fill_value=999999)
  5758. >>> ma.concatenate([a, b])
  5759. masked_array(data=[0, --, 2, 2, 3, 4],
  5760. mask=[False, True, False, False, False, False],
  5761. fill_value=999999)
  5762. """
  5763. d = np.concatenate([getdata(a) for a in arrays], axis)
  5764. rcls = get_masked_subclass(*arrays)
  5765. data = d.view(rcls)
  5766. # Check whether one of the arrays has a non-empty mask.
  5767. for x in arrays:
  5768. if getmask(x) is not nomask:
  5769. break
  5770. else:
  5771. return data
  5772. # OK, so we have to concatenate the masks
  5773. dm = np.concatenate([getmaskarray(a) for a in arrays], axis)
  5774. dm = dm.reshape(d.shape)
  5775. # If we decide to keep a '_shrinkmask' option, we want to check that
  5776. # all of them are True, and then check for dm.any()
  5777. data._mask = _shrink_mask(dm)
  5778. return data
  5779. def diag(v, k=0):
  5780. """
  5781. Extract a diagonal or construct a diagonal array.
  5782. This function is the equivalent of `numpy.diag` that takes masked
  5783. values into account, see `numpy.diag` for details.
  5784. See Also
  5785. --------
  5786. numpy.diag : Equivalent function for ndarrays.
  5787. """
  5788. output = np.diag(v, k).view(MaskedArray)
  5789. if getmask(v) is not nomask:
  5790. output._mask = np.diag(v._mask, k)
  5791. return output
  5792. def left_shift(a, n):
  5793. """
  5794. Shift the bits of an integer to the left.
  5795. This is the masked array version of `numpy.left_shift`, for details
  5796. see that function.
  5797. See Also
  5798. --------
  5799. numpy.left_shift
  5800. """
  5801. m = getmask(a)
  5802. if m is nomask:
  5803. d = umath.left_shift(filled(a), n)
  5804. return masked_array(d)
  5805. else:
  5806. d = umath.left_shift(filled(a, 0), n)
  5807. return masked_array(d, mask=m)
  5808. def right_shift(a, n):
  5809. """
  5810. Shift the bits of an integer to the right.
  5811. This is the masked array version of `numpy.right_shift`, for details
  5812. see that function.
  5813. See Also
  5814. --------
  5815. numpy.right_shift
  5816. """
  5817. m = getmask(a)
  5818. if m is nomask:
  5819. d = umath.right_shift(filled(a), n)
  5820. return masked_array(d)
  5821. else:
  5822. d = umath.right_shift(filled(a, 0), n)
  5823. return masked_array(d, mask=m)
  5824. def put(a, indices, values, mode='raise'):
  5825. """
  5826. Set storage-indexed locations to corresponding values.
  5827. This function is equivalent to `MaskedArray.put`, see that method
  5828. for details.
  5829. See Also
  5830. --------
  5831. MaskedArray.put
  5832. """
  5833. # We can't use 'frommethod', the order of arguments is different
  5834. try:
  5835. return a.put(indices, values, mode=mode)
  5836. except AttributeError:
  5837. return narray(a, copy=False).put(indices, values, mode=mode)
  5838. def putmask(a, mask, values): # , mode='raise'):
  5839. """
  5840. Changes elements of an array based on conditional and input values.
  5841. This is the masked array version of `numpy.putmask`, for details see
  5842. `numpy.putmask`.
  5843. See Also
  5844. --------
  5845. numpy.putmask
  5846. Notes
  5847. -----
  5848. Using a masked array as `values` will **not** transform a `ndarray` into
  5849. a `MaskedArray`.
  5850. """
  5851. # We can't use 'frommethod', the order of arguments is different
  5852. if not isinstance(a, MaskedArray):
  5853. a = a.view(MaskedArray)
  5854. (valdata, valmask) = (getdata(values), getmask(values))
  5855. if getmask(a) is nomask:
  5856. if valmask is not nomask:
  5857. a._sharedmask = True
  5858. a._mask = make_mask_none(a.shape, a.dtype)
  5859. np.copyto(a._mask, valmask, where=mask)
  5860. elif a._hardmask:
  5861. if valmask is not nomask:
  5862. m = a._mask.copy()
  5863. np.copyto(m, valmask, where=mask)
  5864. a.mask |= m
  5865. else:
  5866. if valmask is nomask:
  5867. valmask = getmaskarray(values)
  5868. np.copyto(a._mask, valmask, where=mask)
  5869. np.copyto(a._data, valdata, where=mask)
  5870. return
  5871. def transpose(a, axes=None):
  5872. """
  5873. Permute the dimensions of an array.
  5874. This function is exactly equivalent to `numpy.transpose`.
  5875. See Also
  5876. --------
  5877. numpy.transpose : Equivalent function in top-level NumPy module.
  5878. Examples
  5879. --------
  5880. >>> import numpy.ma as ma
  5881. >>> x = ma.arange(4).reshape((2,2))
  5882. >>> x[1, 1] = ma.masked
  5883. >>> x
  5884. masked_array(
  5885. data=[[0, 1],
  5886. [2, --]],
  5887. mask=[[False, False],
  5888. [False, True]],
  5889. fill_value=999999)
  5890. >>> ma.transpose(x)
  5891. masked_array(
  5892. data=[[0, 2],
  5893. [1, --]],
  5894. mask=[[False, False],
  5895. [False, True]],
  5896. fill_value=999999)
  5897. """
  5898. # We can't use 'frommethod', as 'transpose' doesn't take keywords
  5899. try:
  5900. return a.transpose(axes)
  5901. except AttributeError:
  5902. return narray(a, copy=False).transpose(axes).view(MaskedArray)
  5903. def reshape(a, new_shape, order='C'):
  5904. """
  5905. Returns an array containing the same data with a new shape.
  5906. Refer to `MaskedArray.reshape` for full documentation.
  5907. See Also
  5908. --------
  5909. MaskedArray.reshape : equivalent function
  5910. """
  5911. # We can't use 'frommethod', it whine about some parameters. Dmmit.
  5912. try:
  5913. return a.reshape(new_shape, order=order)
  5914. except AttributeError:
  5915. _tmp = narray(a, copy=False).reshape(new_shape, order=order)
  5916. return _tmp.view(MaskedArray)
  5917. def resize(x, new_shape):
  5918. """
  5919. Return a new masked array with the specified size and shape.
  5920. This is the masked equivalent of the `numpy.resize` function. The new
  5921. array is filled with repeated copies of `x` (in the order that the
  5922. data are stored in memory). If `x` is masked, the new array will be
  5923. masked, and the new mask will be a repetition of the old one.
  5924. See Also
  5925. --------
  5926. numpy.resize : Equivalent function in the top level NumPy module.
  5927. Examples
  5928. --------
  5929. >>> import numpy.ma as ma
  5930. >>> a = ma.array([[1, 2] ,[3, 4]])
  5931. >>> a[0, 1] = ma.masked
  5932. >>> a
  5933. masked_array(
  5934. data=[[1, --],
  5935. [3, 4]],
  5936. mask=[[False, True],
  5937. [False, False]],
  5938. fill_value=999999)
  5939. >>> np.resize(a, (3, 3))
  5940. masked_array(
  5941. data=[[1, 2, 3],
  5942. [4, 1, 2],
  5943. [3, 4, 1]],
  5944. mask=False,
  5945. fill_value=999999)
  5946. >>> ma.resize(a, (3, 3))
  5947. masked_array(
  5948. data=[[1, --, 3],
  5949. [4, 1, --],
  5950. [3, 4, 1]],
  5951. mask=[[False, True, False],
  5952. [False, False, True],
  5953. [False, False, False]],
  5954. fill_value=999999)
  5955. A MaskedArray is always returned, regardless of the input type.
  5956. >>> a = np.array([[1, 2] ,[3, 4]])
  5957. >>> ma.resize(a, (3, 3))
  5958. masked_array(
  5959. data=[[1, 2, 3],
  5960. [4, 1, 2],
  5961. [3, 4, 1]],
  5962. mask=False,
  5963. fill_value=999999)
  5964. """
  5965. # We can't use _frommethods here, as N.resize is notoriously whiny.
  5966. m = getmask(x)
  5967. if m is not nomask:
  5968. m = np.resize(m, new_shape)
  5969. result = np.resize(x, new_shape).view(get_masked_subclass(x))
  5970. if result.ndim:
  5971. result._mask = m
  5972. return result
  5973. def ndim(obj):
  5974. """
  5975. maskedarray version of the numpy function.
  5976. """
  5977. return np.ndim(getdata(obj))
  5978. ndim.__doc__ = np.ndim.__doc__
  5979. def shape(obj):
  5980. "maskedarray version of the numpy function."
  5981. return np.shape(getdata(obj))
  5982. shape.__doc__ = np.shape.__doc__
  5983. def size(obj, axis=None):
  5984. "maskedarray version of the numpy function."
  5985. return np.size(getdata(obj), axis)
  5986. size.__doc__ = np.size.__doc__
  5987. ##############################################################################
  5988. # Extra functions #
  5989. ##############################################################################
  5990. def where(condition, x=_NoValue, y=_NoValue):
  5991. """
  5992. Return a masked array with elements from `x` or `y`, depending on condition.
  5993. .. note::
  5994. When only `condition` is provided, this function is identical to
  5995. `nonzero`. The rest of this documentation covers only the case where
  5996. all three arguments are provided.
  5997. Parameters
  5998. ----------
  5999. condition : array_like, bool
  6000. Where True, yield `x`, otherwise yield `y`.
  6001. x, y : array_like, optional
  6002. Values from which to choose. `x`, `y` and `condition` need to be
  6003. broadcastable to some shape.
  6004. Returns
  6005. -------
  6006. out : MaskedArray
  6007. An masked array with `masked` elements where the condition is masked,
  6008. elements from `x` where `condition` is True, and elements from `y`
  6009. elsewhere.
  6010. See Also
  6011. --------
  6012. numpy.where : Equivalent function in the top-level NumPy module.
  6013. nonzero : The function that is called when x and y are omitted
  6014. Examples
  6015. --------
  6016. >>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0],
  6017. ... [1, 0, 1],
  6018. ... [0, 1, 0]])
  6019. >>> x
  6020. masked_array(
  6021. data=[[0.0, --, 2.0],
  6022. [--, 4.0, --],
  6023. [6.0, --, 8.0]],
  6024. mask=[[False, True, False],
  6025. [ True, False, True],
  6026. [False, True, False]],
  6027. fill_value=1e+20)
  6028. >>> np.ma.where(x > 5, x, -3.1416)
  6029. masked_array(
  6030. data=[[-3.1416, --, -3.1416],
  6031. [--, -3.1416, --],
  6032. [6.0, --, 8.0]],
  6033. mask=[[False, True, False],
  6034. [ True, False, True],
  6035. [False, True, False]],
  6036. fill_value=1e+20)
  6037. """
  6038. # handle the single-argument case
  6039. missing = (x is _NoValue, y is _NoValue).count(True)
  6040. if missing == 1:
  6041. raise ValueError("Must provide both 'x' and 'y' or neither.")
  6042. if missing == 2:
  6043. return nonzero(condition)
  6044. # we only care if the condition is true - false or masked pick y
  6045. cf = filled(condition, False)
  6046. xd = getdata(x)
  6047. yd = getdata(y)
  6048. # we need the full arrays here for correct final dimensions
  6049. cm = getmaskarray(condition)
  6050. xm = getmaskarray(x)
  6051. ym = getmaskarray(y)
  6052. # deal with the fact that masked.dtype == float64, but we don't actually
  6053. # want to treat it as that.
  6054. if x is masked and y is not masked:
  6055. xd = np.zeros((), dtype=yd.dtype)
  6056. xm = np.ones((), dtype=ym.dtype)
  6057. elif y is masked and x is not masked:
  6058. yd = np.zeros((), dtype=xd.dtype)
  6059. ym = np.ones((), dtype=xm.dtype)
  6060. data = np.where(cf, xd, yd)
  6061. mask = np.where(cf, xm, ym)
  6062. mask = np.where(cm, np.ones((), dtype=mask.dtype), mask)
  6063. # collapse the mask, for backwards compatibility
  6064. mask = _shrink_mask(mask)
  6065. return masked_array(data, mask=mask)
  6066. def choose(indices, choices, out=None, mode='raise'):
  6067. """
  6068. Use an index array to construct a new array from a set of choices.
  6069. Given an array of integers and a set of n choice arrays, this method
  6070. will create a new array that merges each of the choice arrays. Where a
  6071. value in `a` is i, the new array will have the value that choices[i]
  6072. contains in the same place.
  6073. Parameters
  6074. ----------
  6075. a : ndarray of ints
  6076. This array must contain integers in ``[0, n-1]``, where n is the
  6077. number of choices.
  6078. choices : sequence of arrays
  6079. Choice arrays. The index array and all of the choices should be
  6080. broadcastable to the same shape.
  6081. out : array, optional
  6082. If provided, the result will be inserted into this array. It should
  6083. be of the appropriate shape and `dtype`.
  6084. mode : {'raise', 'wrap', 'clip'}, optional
  6085. Specifies how out-of-bounds indices will behave.
  6086. * 'raise' : raise an error
  6087. * 'wrap' : wrap around
  6088. * 'clip' : clip to the range
  6089. Returns
  6090. -------
  6091. merged_array : array
  6092. See Also
  6093. --------
  6094. choose : equivalent function
  6095. Examples
  6096. --------
  6097. >>> choice = np.array([[1,1,1], [2,2,2], [3,3,3]])
  6098. >>> a = np.array([2, 1, 0])
  6099. >>> np.ma.choose(a, choice)
  6100. masked_array(data=[3, 2, 1],
  6101. mask=False,
  6102. fill_value=999999)
  6103. """
  6104. def fmask(x):
  6105. "Returns the filled array, or True if masked."
  6106. if x is masked:
  6107. return True
  6108. return filled(x)
  6109. def nmask(x):
  6110. "Returns the mask, True if ``masked``, False if ``nomask``."
  6111. if x is masked:
  6112. return True
  6113. return getmask(x)
  6114. # Get the indices.
  6115. c = filled(indices, 0)
  6116. # Get the masks.
  6117. masks = [nmask(x) for x in choices]
  6118. data = [fmask(x) for x in choices]
  6119. # Construct the mask
  6120. outputmask = np.choose(c, masks, mode=mode)
  6121. outputmask = make_mask(mask_or(outputmask, getmask(indices)),
  6122. copy=False, shrink=True)
  6123. # Get the choices.
  6124. d = np.choose(c, data, mode=mode, out=out).view(MaskedArray)
  6125. if out is not None:
  6126. if isinstance(out, MaskedArray):
  6127. out.__setmask__(outputmask)
  6128. return out
  6129. d.__setmask__(outputmask)
  6130. return d
  6131. def round_(a, decimals=0, out=None):
  6132. """
  6133. Return a copy of a, rounded to 'decimals' places.
  6134. When 'decimals' is negative, it specifies the number of positions
  6135. to the left of the decimal point. The real and imaginary parts of
  6136. complex numbers are rounded separately. Nothing is done if the
  6137. array is not of float type and 'decimals' is greater than or equal
  6138. to 0.
  6139. Parameters
  6140. ----------
  6141. decimals : int
  6142. Number of decimals to round to. May be negative.
  6143. out : array_like
  6144. Existing array to use for output.
  6145. If not given, returns a default copy of a.
  6146. Notes
  6147. -----
  6148. If out is given and does not have a mask attribute, the mask of a
  6149. is lost!
  6150. """
  6151. if out is None:
  6152. return np.round_(a, decimals, out)
  6153. else:
  6154. np.round_(getdata(a), decimals, out)
  6155. if hasattr(out, '_mask'):
  6156. out._mask = getmask(a)
  6157. return out
  6158. round = round_
  6159. # Needed by dot, so move here from extras.py. It will still be exported
  6160. # from extras.py for compatibility.
  6161. def mask_rowcols(a, axis=None):
  6162. """
  6163. Mask rows and/or columns of a 2D array that contain masked values.
  6164. Mask whole rows and/or columns of a 2D array that contain
  6165. masked values. The masking behavior is selected using the
  6166. `axis` parameter.
  6167. - If `axis` is None, rows *and* columns are masked.
  6168. - If `axis` is 0, only rows are masked.
  6169. - If `axis` is 1 or -1, only columns are masked.
  6170. Parameters
  6171. ----------
  6172. a : array_like, MaskedArray
  6173. The array to mask. If not a MaskedArray instance (or if no array
  6174. elements are masked). The result is a MaskedArray with `mask` set
  6175. to `nomask` (False). Must be a 2D array.
  6176. axis : int, optional
  6177. Axis along which to perform the operation. If None, applies to a
  6178. flattened version of the array.
  6179. Returns
  6180. -------
  6181. a : MaskedArray
  6182. A modified version of the input array, masked depending on the value
  6183. of the `axis` parameter.
  6184. Raises
  6185. ------
  6186. NotImplementedError
  6187. If input array `a` is not 2D.
  6188. See Also
  6189. --------
  6190. mask_rows : Mask rows of a 2D array that contain masked values.
  6191. mask_cols : Mask cols of a 2D array that contain masked values.
  6192. masked_where : Mask where a condition is met.
  6193. Notes
  6194. -----
  6195. The input array's mask is modified by this function.
  6196. Examples
  6197. --------
  6198. >>> import numpy.ma as ma
  6199. >>> a = np.zeros((3, 3), dtype=int)
  6200. >>> a[1, 1] = 1
  6201. >>> a
  6202. array([[0, 0, 0],
  6203. [0, 1, 0],
  6204. [0, 0, 0]])
  6205. >>> a = ma.masked_equal(a, 1)
  6206. >>> a
  6207. masked_array(
  6208. data=[[0, 0, 0],
  6209. [0, --, 0],
  6210. [0, 0, 0]],
  6211. mask=[[False, False, False],
  6212. [False, True, False],
  6213. [False, False, False]],
  6214. fill_value=1)
  6215. >>> ma.mask_rowcols(a)
  6216. masked_array(
  6217. data=[[0, --, 0],
  6218. [--, --, --],
  6219. [0, --, 0]],
  6220. mask=[[False, True, False],
  6221. [ True, True, True],
  6222. [False, True, False]],
  6223. fill_value=1)
  6224. """
  6225. a = array(a, subok=False)
  6226. if a.ndim != 2:
  6227. raise NotImplementedError("mask_rowcols works for 2D arrays only.")
  6228. m = getmask(a)
  6229. # Nothing is masked: return a
  6230. if m is nomask or not m.any():
  6231. return a
  6232. maskedval = m.nonzero()
  6233. a._mask = a._mask.copy()
  6234. if not axis:
  6235. a[np.unique(maskedval[0])] = masked
  6236. if axis in [None, 1, -1]:
  6237. a[:, np.unique(maskedval[1])] = masked
  6238. return a
  6239. # Include masked dot here to avoid import problems in getting it from
  6240. # extras.py. Note that it is not included in __all__, but rather exported
  6241. # from extras in order to avoid backward compatibility problems.
  6242. def dot(a, b, strict=False, out=None):
  6243. """
  6244. Return the dot product of two arrays.
  6245. This function is the equivalent of `numpy.dot` that takes masked values
  6246. into account. Note that `strict` and `out` are in different position
  6247. than in the method version. In order to maintain compatibility with the
  6248. corresponding method, it is recommended that the optional arguments be
  6249. treated as keyword only. At some point that may be mandatory.
  6250. .. note::
  6251. Works only with 2-D arrays at the moment.
  6252. Parameters
  6253. ----------
  6254. a, b : masked_array_like
  6255. Inputs arrays.
  6256. strict : bool, optional
  6257. Whether masked data are propagated (True) or set to 0 (False) for
  6258. the computation. Default is False. Propagating the mask means that
  6259. if a masked value appears in a row or column, the whole row or
  6260. column is considered masked.
  6261. out : masked_array, optional
  6262. Output argument. This must have the exact kind that would be returned
  6263. if it was not used. In particular, it must have the right type, must be
  6264. C-contiguous, and its dtype must be the dtype that would be returned
  6265. for `dot(a,b)`. This is a performance feature. Therefore, if these
  6266. conditions are not met, an exception is raised, instead of attempting
  6267. to be flexible.
  6268. .. versionadded:: 1.10.2
  6269. See Also
  6270. --------
  6271. numpy.dot : Equivalent function for ndarrays.
  6272. Examples
  6273. --------
  6274. >>> a = np.ma.array([[1, 2, 3], [4, 5, 6]], mask=[[1, 0, 0], [0, 0, 0]])
  6275. >>> b = np.ma.array([[1, 2], [3, 4], [5, 6]], mask=[[1, 0], [0, 0], [0, 0]])
  6276. >>> np.ma.dot(a, b)
  6277. masked_array(
  6278. data=[[21, 26],
  6279. [45, 64]],
  6280. mask=[[False, False],
  6281. [False, False]],
  6282. fill_value=999999)
  6283. >>> np.ma.dot(a, b, strict=True)
  6284. masked_array(
  6285. data=[[--, --],
  6286. [--, 64]],
  6287. mask=[[ True, True],
  6288. [ True, False]],
  6289. fill_value=999999)
  6290. """
  6291. # !!!: Works only with 2D arrays. There should be a way to get it to run
  6292. # with higher dimension
  6293. if strict and (a.ndim == 2) and (b.ndim == 2):
  6294. a = mask_rowcols(a, 0)
  6295. b = mask_rowcols(b, 1)
  6296. am = ~getmaskarray(a)
  6297. bm = ~getmaskarray(b)
  6298. if out is None:
  6299. d = np.dot(filled(a, 0), filled(b, 0))
  6300. m = ~np.dot(am, bm)
  6301. if d.ndim == 0:
  6302. d = np.asarray(d)
  6303. r = d.view(get_masked_subclass(a, b))
  6304. r.__setmask__(m)
  6305. return r
  6306. else:
  6307. d = np.dot(filled(a, 0), filled(b, 0), out._data)
  6308. if out.mask.shape != d.shape:
  6309. out._mask = np.empty(d.shape, MaskType)
  6310. np.dot(am, bm, out._mask)
  6311. np.logical_not(out._mask, out._mask)
  6312. return out
  6313. def inner(a, b):
  6314. """
  6315. Returns the inner product of a and b for arrays of floating point types.
  6316. Like the generic NumPy equivalent the product sum is over the last dimension
  6317. of a and b. The first argument is not conjugated.
  6318. """
  6319. fa = filled(a, 0)
  6320. fb = filled(b, 0)
  6321. if fa.ndim == 0:
  6322. fa.shape = (1,)
  6323. if fb.ndim == 0:
  6324. fb.shape = (1,)
  6325. return np.inner(fa, fb).view(MaskedArray)
  6326. inner.__doc__ = doc_note(np.inner.__doc__,
  6327. "Masked values are replaced by 0.")
  6328. innerproduct = inner
  6329. def outer(a, b):
  6330. "maskedarray version of the numpy function."
  6331. fa = filled(a, 0).ravel()
  6332. fb = filled(b, 0).ravel()
  6333. d = np.outer(fa, fb)
  6334. ma = getmask(a)
  6335. mb = getmask(b)
  6336. if ma is nomask and mb is nomask:
  6337. return masked_array(d)
  6338. ma = getmaskarray(a)
  6339. mb = getmaskarray(b)
  6340. m = make_mask(1 - np.outer(1 - ma, 1 - mb), copy=False)
  6341. return masked_array(d, mask=m)
  6342. outer.__doc__ = doc_note(np.outer.__doc__,
  6343. "Masked values are replaced by 0.")
  6344. outerproduct = outer
  6345. def _convolve_or_correlate(f, a, v, mode, propagate_mask):
  6346. """
  6347. Helper function for ma.correlate and ma.convolve
  6348. """
  6349. if propagate_mask:
  6350. # results which are contributed to by either item in any pair being invalid
  6351. mask = (
  6352. f(getmaskarray(a), np.ones(np.shape(v), dtype=bool), mode=mode)
  6353. | f(np.ones(np.shape(a), dtype=bool), getmaskarray(v), mode=mode)
  6354. )
  6355. data = f(getdata(a), getdata(v), mode=mode)
  6356. else:
  6357. # results which are not contributed to by any pair of valid elements
  6358. mask = ~f(~getmaskarray(a), ~getmaskarray(v))
  6359. data = f(filled(a, 0), filled(v, 0), mode=mode)
  6360. return masked_array(data, mask=mask)
  6361. def correlate(a, v, mode='valid', propagate_mask=True):
  6362. """
  6363. Cross-correlation of two 1-dimensional sequences.
  6364. Parameters
  6365. ----------
  6366. a, v : array_like
  6367. Input sequences.
  6368. mode : {'valid', 'same', 'full'}, optional
  6369. Refer to the `np.convolve` docstring. Note that the default
  6370. is 'valid', unlike `convolve`, which uses 'full'.
  6371. propagate_mask : bool
  6372. If True, then a result element is masked if any masked element contributes towards it.
  6373. If False, then a result element is only masked if no non-masked element
  6374. contribute towards it
  6375. Returns
  6376. -------
  6377. out : MaskedArray
  6378. Discrete cross-correlation of `a` and `v`.
  6379. See Also
  6380. --------
  6381. numpy.correlate : Equivalent function in the top-level NumPy module.
  6382. """
  6383. return _convolve_or_correlate(np.correlate, a, v, mode, propagate_mask)
  6384. def convolve(a, v, mode='full', propagate_mask=True):
  6385. """
  6386. Returns the discrete, linear convolution of two one-dimensional sequences.
  6387. Parameters
  6388. ----------
  6389. a, v : array_like
  6390. Input sequences.
  6391. mode : {'valid', 'same', 'full'}, optional
  6392. Refer to the `np.convolve` docstring.
  6393. propagate_mask : bool
  6394. If True, then if any masked element is included in the sum for a result
  6395. element, then the result is masked.
  6396. If False, then the result element is only masked if no non-masked cells
  6397. contribute towards it
  6398. Returns
  6399. -------
  6400. out : MaskedArray
  6401. Discrete, linear convolution of `a` and `v`.
  6402. See Also
  6403. --------
  6404. numpy.convolve : Equivalent function in the top-level NumPy module.
  6405. """
  6406. return _convolve_or_correlate(np.convolve, a, v, mode, propagate_mask)
  6407. def allequal(a, b, fill_value=True):
  6408. """
  6409. Return True if all entries of a and b are equal, using
  6410. fill_value as a truth value where either or both are masked.
  6411. Parameters
  6412. ----------
  6413. a, b : array_like
  6414. Input arrays to compare.
  6415. fill_value : bool, optional
  6416. Whether masked values in a or b are considered equal (True) or not
  6417. (False).
  6418. Returns
  6419. -------
  6420. y : bool
  6421. Returns True if the two arrays are equal within the given
  6422. tolerance, False otherwise. If either array contains NaN,
  6423. then False is returned.
  6424. See Also
  6425. --------
  6426. all, any
  6427. numpy.ma.allclose
  6428. Examples
  6429. --------
  6430. >>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
  6431. >>> a
  6432. masked_array(data=[10000000000.0, 1e-07, --],
  6433. mask=[False, False, True],
  6434. fill_value=1e+20)
  6435. >>> b = np.array([1e10, 1e-7, -42.0])
  6436. >>> b
  6437. array([ 1.00000000e+10, 1.00000000e-07, -4.20000000e+01])
  6438. >>> np.ma.allequal(a, b, fill_value=False)
  6439. False
  6440. >>> np.ma.allequal(a, b)
  6441. True
  6442. """
  6443. m = mask_or(getmask(a), getmask(b))
  6444. if m is nomask:
  6445. x = getdata(a)
  6446. y = getdata(b)
  6447. d = umath.equal(x, y)
  6448. return d.all()
  6449. elif fill_value:
  6450. x = getdata(a)
  6451. y = getdata(b)
  6452. d = umath.equal(x, y)
  6453. dm = array(d, mask=m, copy=False)
  6454. return dm.filled(True).all(None)
  6455. else:
  6456. return False
  6457. def allclose(a, b, masked_equal=True, rtol=1e-5, atol=1e-8):
  6458. """
  6459. Returns True if two arrays are element-wise equal within a tolerance.
  6460. This function is equivalent to `allclose` except that masked values
  6461. are treated as equal (default) or unequal, depending on the `masked_equal`
  6462. argument.
  6463. Parameters
  6464. ----------
  6465. a, b : array_like
  6466. Input arrays to compare.
  6467. masked_equal : bool, optional
  6468. Whether masked values in `a` and `b` are considered equal (True) or not
  6469. (False). They are considered equal by default.
  6470. rtol : float, optional
  6471. Relative tolerance. The relative difference is equal to ``rtol * b``.
  6472. Default is 1e-5.
  6473. atol : float, optional
  6474. Absolute tolerance. The absolute difference is equal to `atol`.
  6475. Default is 1e-8.
  6476. Returns
  6477. -------
  6478. y : bool
  6479. Returns True if the two arrays are equal within the given
  6480. tolerance, False otherwise. If either array contains NaN, then
  6481. False is returned.
  6482. See Also
  6483. --------
  6484. all, any
  6485. numpy.allclose : the non-masked `allclose`.
  6486. Notes
  6487. -----
  6488. If the following equation is element-wise True, then `allclose` returns
  6489. True::
  6490. absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
  6491. Return True if all elements of `a` and `b` are equal subject to
  6492. given tolerances.
  6493. Examples
  6494. --------
  6495. >>> a = np.ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
  6496. >>> a
  6497. masked_array(data=[10000000000.0, 1e-07, --],
  6498. mask=[False, False, True],
  6499. fill_value=1e+20)
  6500. >>> b = np.ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1])
  6501. >>> np.ma.allclose(a, b)
  6502. False
  6503. >>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
  6504. >>> b = np.ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1])
  6505. >>> np.ma.allclose(a, b)
  6506. True
  6507. >>> np.ma.allclose(a, b, masked_equal=False)
  6508. False
  6509. Masked values are not compared directly.
  6510. >>> a = np.ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
  6511. >>> b = np.ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1])
  6512. >>> np.ma.allclose(a, b)
  6513. True
  6514. >>> np.ma.allclose(a, b, masked_equal=False)
  6515. False
  6516. """
  6517. x = masked_array(a, copy=False)
  6518. y = masked_array(b, copy=False)
  6519. # make sure y is an inexact type to avoid abs(MIN_INT); will cause
  6520. # casting of x later.
  6521. dtype = np.result_type(y, 1.)
  6522. if y.dtype != dtype:
  6523. y = masked_array(y, dtype=dtype, copy=False)
  6524. m = mask_or(getmask(x), getmask(y))
  6525. xinf = np.isinf(masked_array(x, copy=False, mask=m)).filled(False)
  6526. # If we have some infs, they should fall at the same place.
  6527. if not np.all(xinf == filled(np.isinf(y), False)):
  6528. return False
  6529. # No infs at all
  6530. if not np.any(xinf):
  6531. d = filled(less_equal(absolute(x - y), atol + rtol * absolute(y)),
  6532. masked_equal)
  6533. return np.all(d)
  6534. if not np.all(filled(x[xinf] == y[xinf], masked_equal)):
  6535. return False
  6536. x = x[~xinf]
  6537. y = y[~xinf]
  6538. d = filled(less_equal(absolute(x - y), atol + rtol * absolute(y)),
  6539. masked_equal)
  6540. return np.all(d)
  6541. def asarray(a, dtype=None, order=None):
  6542. """
  6543. Convert the input to a masked array of the given data-type.
  6544. No copy is performed if the input is already an `ndarray`. If `a` is
  6545. a subclass of `MaskedArray`, a base class `MaskedArray` is returned.
  6546. Parameters
  6547. ----------
  6548. a : array_like
  6549. Input data, in any form that can be converted to a masked array. This
  6550. includes lists, lists of tuples, tuples, tuples of tuples, tuples
  6551. of lists, ndarrays and masked arrays.
  6552. dtype : dtype, optional
  6553. By default, the data-type is inferred from the input data.
  6554. order : {'C', 'F'}, optional
  6555. Whether to use row-major ('C') or column-major ('FORTRAN') memory
  6556. representation. Default is 'C'.
  6557. Returns
  6558. -------
  6559. out : MaskedArray
  6560. Masked array interpretation of `a`.
  6561. See Also
  6562. --------
  6563. asanyarray : Similar to `asarray`, but conserves subclasses.
  6564. Examples
  6565. --------
  6566. >>> x = np.arange(10.).reshape(2, 5)
  6567. >>> x
  6568. array([[0., 1., 2., 3., 4.],
  6569. [5., 6., 7., 8., 9.]])
  6570. >>> np.ma.asarray(x)
  6571. masked_array(
  6572. data=[[0., 1., 2., 3., 4.],
  6573. [5., 6., 7., 8., 9.]],
  6574. mask=False,
  6575. fill_value=1e+20)
  6576. >>> type(np.ma.asarray(x))
  6577. <class 'numpy.ma.core.MaskedArray'>
  6578. """
  6579. order = order or 'C'
  6580. return masked_array(a, dtype=dtype, copy=False, keep_mask=True,
  6581. subok=False, order=order)
  6582. def asanyarray(a, dtype=None):
  6583. """
  6584. Convert the input to a masked array, conserving subclasses.
  6585. If `a` is a subclass of `MaskedArray`, its class is conserved.
  6586. No copy is performed if the input is already an `ndarray`.
  6587. Parameters
  6588. ----------
  6589. a : array_like
  6590. Input data, in any form that can be converted to an array.
  6591. dtype : dtype, optional
  6592. By default, the data-type is inferred from the input data.
  6593. order : {'C', 'F'}, optional
  6594. Whether to use row-major ('C') or column-major ('FORTRAN') memory
  6595. representation. Default is 'C'.
  6596. Returns
  6597. -------
  6598. out : MaskedArray
  6599. MaskedArray interpretation of `a`.
  6600. See Also
  6601. --------
  6602. asarray : Similar to `asanyarray`, but does not conserve subclass.
  6603. Examples
  6604. --------
  6605. >>> x = np.arange(10.).reshape(2, 5)
  6606. >>> x
  6607. array([[0., 1., 2., 3., 4.],
  6608. [5., 6., 7., 8., 9.]])
  6609. >>> np.ma.asanyarray(x)
  6610. masked_array(
  6611. data=[[0., 1., 2., 3., 4.],
  6612. [5., 6., 7., 8., 9.]],
  6613. mask=False,
  6614. fill_value=1e+20)
  6615. >>> type(np.ma.asanyarray(x))
  6616. <class 'numpy.ma.core.MaskedArray'>
  6617. """
  6618. # workaround for #8666, to preserve identity. Ideally the bottom line
  6619. # would handle this for us.
  6620. if isinstance(a, MaskedArray) and (dtype is None or dtype == a.dtype):
  6621. return a
  6622. return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True)
  6623. ##############################################################################
  6624. # Pickling #
  6625. ##############################################################################
  6626. def _pickle_warn(method):
  6627. # NumPy 1.15.0, 2017-12-10
  6628. warnings.warn(
  6629. "np.ma.{method} is deprecated, use pickle.{method} instead"
  6630. .format(method=method),
  6631. DeprecationWarning,
  6632. stacklevel=3)
  6633. def fromfile(file, dtype=float, count=-1, sep=''):
  6634. raise NotImplementedError(
  6635. "fromfile() not yet implemented for a MaskedArray.")
  6636. def fromflex(fxarray):
  6637. """
  6638. Build a masked array from a suitable flexible-type array.
  6639. The input array has to have a data-type with ``_data`` and ``_mask``
  6640. fields. This type of array is output by `MaskedArray.toflex`.
  6641. Parameters
  6642. ----------
  6643. fxarray : ndarray
  6644. The structured input array, containing ``_data`` and ``_mask``
  6645. fields. If present, other fields are discarded.
  6646. Returns
  6647. -------
  6648. result : MaskedArray
  6649. The constructed masked array.
  6650. See Also
  6651. --------
  6652. MaskedArray.toflex : Build a flexible-type array from a masked array.
  6653. Examples
  6654. --------
  6655. >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[0] + [1, 0] * 4)
  6656. >>> rec = x.toflex()
  6657. >>> rec
  6658. array([[(0, False), (1, True), (2, False)],
  6659. [(3, True), (4, False), (5, True)],
  6660. [(6, False), (7, True), (8, False)]],
  6661. dtype=[('_data', '<i8'), ('_mask', '?')])
  6662. >>> x2 = np.ma.fromflex(rec)
  6663. >>> x2
  6664. masked_array(
  6665. data=[[0, --, 2],
  6666. [--, 4, --],
  6667. [6, --, 8]],
  6668. mask=[[False, True, False],
  6669. [ True, False, True],
  6670. [False, True, False]],
  6671. fill_value=999999)
  6672. Extra fields can be present in the structured array but are discarded:
  6673. >>> dt = [('_data', '<i4'), ('_mask', '|b1'), ('field3', '<f4')]
  6674. >>> rec2 = np.zeros((2, 2), dtype=dt)
  6675. >>> rec2
  6676. array([[(0, False, 0.), (0, False, 0.)],
  6677. [(0, False, 0.), (0, False, 0.)]],
  6678. dtype=[('_data', '<i4'), ('_mask', '?'), ('field3', '<f4')])
  6679. >>> y = np.ma.fromflex(rec2)
  6680. >>> y
  6681. masked_array(
  6682. data=[[0, 0],
  6683. [0, 0]],
  6684. mask=[[False, False],
  6685. [False, False]],
  6686. fill_value=999999,
  6687. dtype=int32)
  6688. """
  6689. return masked_array(fxarray['_data'], mask=fxarray['_mask'])
  6690. class _convert2ma(object):
  6691. """
  6692. Convert functions from numpy to numpy.ma.
  6693. Parameters
  6694. ----------
  6695. _methodname : string
  6696. Name of the method to transform.
  6697. """
  6698. __doc__ = None
  6699. def __init__(self, funcname, params=None):
  6700. self._func = getattr(np, funcname)
  6701. self.__doc__ = self.getdoc()
  6702. self._extras = params or {}
  6703. def getdoc(self):
  6704. "Return the doc of the function (from the doc of the method)."
  6705. doc = getattr(self._func, '__doc__', None)
  6706. sig = get_object_signature(self._func)
  6707. if doc:
  6708. # Add the signature of the function at the beginning of the doc
  6709. if sig:
  6710. sig = "%s%s\n" % (self._func.__name__, sig)
  6711. doc = sig + doc
  6712. return doc
  6713. def __call__(self, *args, **params):
  6714. # Find the common parameters to the call and the definition
  6715. _extras = self._extras
  6716. common_params = set(params).intersection(_extras)
  6717. # Drop the common parameters from the call
  6718. for p in common_params:
  6719. _extras[p] = params.pop(p)
  6720. # Get the result
  6721. result = self._func.__call__(*args, **params).view(MaskedArray)
  6722. if "fill_value" in common_params:
  6723. result.fill_value = _extras.get("fill_value", None)
  6724. if "hardmask" in common_params:
  6725. result._hardmask = bool(_extras.get("hard_mask", False))
  6726. return result
  6727. arange = _convert2ma('arange', params=dict(fill_value=None, hardmask=False))
  6728. clip = np.clip
  6729. diff = np.diff
  6730. empty = _convert2ma('empty', params=dict(fill_value=None, hardmask=False))
  6731. empty_like = _convert2ma('empty_like')
  6732. frombuffer = _convert2ma('frombuffer')
  6733. fromfunction = _convert2ma('fromfunction')
  6734. identity = _convert2ma(
  6735. 'identity', params=dict(fill_value=None, hardmask=False))
  6736. indices = np.indices
  6737. ones = _convert2ma('ones', params=dict(fill_value=None, hardmask=False))
  6738. ones_like = np.ones_like
  6739. squeeze = np.squeeze
  6740. zeros = _convert2ma('zeros', params=dict(fill_value=None, hardmask=False))
  6741. zeros_like = np.zeros_like
  6742. def append(a, b, axis=None):
  6743. """Append values to the end of an array.
  6744. .. versionadded:: 1.9.0
  6745. Parameters
  6746. ----------
  6747. a : array_like
  6748. Values are appended to a copy of this array.
  6749. b : array_like
  6750. These values are appended to a copy of `a`. It must be of the
  6751. correct shape (the same shape as `a`, excluding `axis`). If `axis`
  6752. is not specified, `b` can be any shape and will be flattened
  6753. before use.
  6754. axis : int, optional
  6755. The axis along which `v` are appended. If `axis` is not given,
  6756. both `a` and `b` are flattened before use.
  6757. Returns
  6758. -------
  6759. append : MaskedArray
  6760. A copy of `a` with `b` appended to `axis`. Note that `append`
  6761. does not occur in-place: a new array is allocated and filled. If
  6762. `axis` is None, the result is a flattened array.
  6763. See Also
  6764. --------
  6765. numpy.append : Equivalent function in the top-level NumPy module.
  6766. Examples
  6767. --------
  6768. >>> import numpy.ma as ma
  6769. >>> a = ma.masked_values([1, 2, 3], 2)
  6770. >>> b = ma.masked_values([[4, 5, 6], [7, 8, 9]], 7)
  6771. >>> ma.append(a, b)
  6772. masked_array(data=[1, --, 3, 4, 5, 6, --, 8, 9],
  6773. mask=[False, True, False, False, False, False, True, False,
  6774. False],
  6775. fill_value=999999)
  6776. """
  6777. return concatenate([a, b], axis)