_stats_py.py 409 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840
  1. # Copyright 2002 Gary Strangman. All rights reserved
  2. # Copyright 2002-2016 The SciPy Developers
  3. #
  4. # The original code from Gary Strangman was heavily adapted for
  5. # use in SciPy by Travis Oliphant. The original code came with the
  6. # following disclaimer:
  7. #
  8. # This software is provided "as-is". There are no expressed or implied
  9. # warranties of any kind, including, but not limited to, the warranties
  10. # of merchantability and fitness for a given application. In no event
  11. # shall Gary Strangman be liable for any direct, indirect, incidental,
  12. # special, exemplary or consequential damages (including, but not limited
  13. # to, loss of use, data or profits, or business interruption) however
  14. # caused and on any theory of liability, whether in contract, strict
  15. # liability or tort (including negligence or otherwise) arising in any way
  16. # out of the use of this software, even if advised of the possibility of
  17. # such damage.
  18. """
  19. A collection of basic statistical functions for Python.
  20. References
  21. ----------
  22. .. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
  23. Probability and Statistics Tables and Formulae. Chapman & Hall: New
  24. York. 2000.
  25. """
  26. import math
  27. import itertools
  28. import operator
  29. import warnings
  30. from collections import namedtuple
  31. from collections.abc import Sequence
  32. import numpy as np
  33. from numpy import array, asarray, ma
  34. from scipy import sparse
  35. from scipy.spatial import distance_matrix
  36. from scipy.optimize import milp, LinearConstraint
  37. from scipy._lib._util import _get_nan, _rename_parameter, _contains_nan, np_vecdot
  38. import scipy.special as special
  39. # Import unused here but needs to stay until end of deprecation periode
  40. # See https://github.com/scipy/scipy/issues/15765#issuecomment-1875564522
  41. from scipy import linalg # noqa: F401
  42. from . import distributions
  43. from . import _mstats_basic as mstats_basic
  44. from ._stats_mstats_common import theilslopes, siegelslopes
  45. from ._stats import _kendall_dis, _toint64, _weightedrankedtau
  46. from dataclasses import dataclass, field
  47. from ._stats_pythran import _compute_outer_prob_inside_method
  48. from ._resampling import (MonteCarloMethod, PermutationMethod, BootstrapMethod,
  49. monte_carlo_test, permutation_test, bootstrap,)
  50. from ._axis_nan_policy import (_axis_nan_policy_factory, _broadcast_shapes,
  51. _broadcast_array_shapes_remove_axis, SmallSampleWarning,
  52. too_small_1d_not_omit, too_small_1d_omit,
  53. too_small_nd_not_omit, too_small_nd_omit)
  54. from ._binomtest import _binary_search_for_binom_tst as _binary_search
  55. from scipy._lib._bunch import _make_tuple_bunch
  56. from scipy import stats
  57. from scipy.optimize import root_scalar
  58. from scipy._lib._array_api import (
  59. _asarray,
  60. array_namespace,
  61. is_lazy_array,
  62. is_dask,
  63. is_numpy,
  64. is_cupy,
  65. is_marray,
  66. xp_size,
  67. xp_vector_norm,
  68. xp_promote,
  69. xp_result_type,
  70. xp_capabilities,
  71. xp_ravel,
  72. _length_nonmasked,
  73. _share_masks,
  74. xp_swapaxes,
  75. xp_default_dtype,
  76. xp_device,
  77. )
  78. import scipy._lib.array_api_extra as xpx
  79. # Functions/classes in other files should be added in `__init__.py`, not here
  80. __all__ = ['gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar',
  81. 'tmin', 'tmax', 'tstd', 'tsem', 'moment',
  82. 'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',
  83. 'normaltest', 'jarque_bera',
  84. 'scoreatpercentile', 'percentileofscore',
  85. 'cumfreq', 'relfreq', 'obrientransform',
  86. 'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd',
  87. 'median_abs_deviation',
  88. 'sigmaclip', 'trimboth', 'trim1', 'trim_mean',
  89. 'f_oneway', 'pearsonr', 'fisher_exact',
  90. 'spearmanr', 'pointbiserialr',
  91. 'kendalltau', 'weightedtau',
  92. 'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',
  93. 'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',
  94. 'kstest', 'ks_1samp', 'ks_2samp',
  95. 'chisquare', 'power_divergence',
  96. 'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',
  97. 'rankdata', 'combine_pvalues', 'quantile_test',
  98. 'wasserstein_distance', 'wasserstein_distance_nd', 'energy_distance',
  99. 'brunnermunzel', 'alexandergovern',
  100. 'expectile', 'lmoment']
  101. def _chk_asarray(a, axis, *, xp=None):
  102. if xp is None:
  103. xp = array_namespace(a)
  104. if axis is None:
  105. a = xp.reshape(a, (-1,))
  106. outaxis = 0
  107. else:
  108. a = xp.asarray(a)
  109. outaxis = axis
  110. if a.ndim == 0:
  111. a = xp.reshape(a, (-1,))
  112. return a, outaxis
  113. SignificanceResult = _make_tuple_bunch('SignificanceResult',
  114. ['statistic', 'pvalue'], [])
  115. # Let's call a SignificanceResult with legacy :correlation" attribute a
  116. # "CorrelationResult". Don't add to `extra_field_names`- shouldn't be in repr.
  117. def _pack_CorrelationResult(statistic, pvalue, correlation):
  118. res = SignificanceResult(statistic, pvalue)
  119. res.correlation = correlation
  120. return res
  121. def _unpack_CorrelationResult(res, _):
  122. return res.statistic, res.pvalue, res.correlation
  123. # note that `weights` are paired with `x`
  124. @xp_capabilities()
  125. @_axis_nan_policy_factory(
  126. lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
  127. result_to_tuple=lambda x, _: (x,), kwd_samples=['weights'])
  128. def gmean(a, axis=0, dtype=None, weights=None):
  129. r"""Compute the weighted geometric mean along the specified axis.
  130. The weighted geometric mean of the array :math:`a_i` associated to weights
  131. :math:`w_i` is:
  132. .. math::
  133. \exp \left( \frac{ \sum_{i=1}^n w_i \ln a_i }{ \sum_{i=1}^n w_i }
  134. \right) \, ,
  135. and, with equal weights, it gives:
  136. .. math::
  137. \sqrt[n]{ \prod_{i=1}^n a_i } \, .
  138. Parameters
  139. ----------
  140. a : array_like
  141. Input array or object that can be converted to an array.
  142. axis : int or None, optional
  143. Axis along which the geometric mean is computed. Default is 0.
  144. If None, compute over the whole array `a`.
  145. dtype : dtype, optional
  146. Type to which the input arrays are cast before the calculation is
  147. performed.
  148. weights : array_like, optional
  149. The `weights` array must be broadcastable to the same shape as `a`.
  150. Default is None, which gives each value a weight of 1.0.
  151. Returns
  152. -------
  153. gmean : ndarray
  154. See `dtype` parameter above.
  155. See Also
  156. --------
  157. numpy.mean : Arithmetic average
  158. numpy.average : Weighted average
  159. hmean : Harmonic mean
  160. Notes
  161. -----
  162. The sample geometric mean is the exponential of the mean of the natural
  163. logarithms of the observations.
  164. Negative observations will produce NaNs in the output because the *natural*
  165. logarithm (as opposed to the *complex* logarithm) is defined only for
  166. non-negative reals.
  167. References
  168. ----------
  169. .. [1] "Weighted Geometric Mean", *Wikipedia*,
  170. https://en.wikipedia.org/wiki/Weighted_geometric_mean.
  171. .. [2] Grossman, J., Grossman, M., Katz, R., "Averages: A New Approach",
  172. Archimedes Foundation, 1983
  173. Examples
  174. --------
  175. >>> from scipy.stats import gmean
  176. >>> gmean([1, 4])
  177. 2.0
  178. >>> gmean([1, 2, 3, 4, 5, 6, 7])
  179. 3.3800151591412964
  180. >>> gmean([1, 4, 7], weights=[3, 1, 3])
  181. 2.80668351922014
  182. """
  183. xp = array_namespace(a, weights)
  184. a = xp.asarray(a, dtype=dtype)
  185. if weights is not None:
  186. weights = xp.asarray(weights, dtype=dtype)
  187. with np.errstate(divide='ignore'):
  188. log_a = xp.log(a)
  189. return xp.exp(_xp_mean(log_a, axis=axis, weights=weights))
  190. @xp_capabilities(jax_jit=False, allow_dask_compute=1)
  191. @_axis_nan_policy_factory(
  192. lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
  193. result_to_tuple=lambda x, _: (x,), kwd_samples=['weights'])
  194. def hmean(a, axis=0, dtype=None, *, weights=None):
  195. r"""Calculate the weighted harmonic mean along the specified axis.
  196. The weighted harmonic mean of the array :math:`a_i` associated to weights
  197. :math:`w_i` is:
  198. .. math::
  199. \frac{ \sum_{i=1}^n w_i }{ \sum_{i=1}^n \frac{w_i}{a_i} } \, ,
  200. and, with equal weights, it gives:
  201. .. math::
  202. \frac{ n }{ \sum_{i=1}^n \frac{1}{a_i} } \, .
  203. Parameters
  204. ----------
  205. a : array_like
  206. Input array, masked array or object that can be converted to an array.
  207. axis : int or None, optional
  208. Axis along which the harmonic mean is computed. Default is 0.
  209. If None, compute over the whole array `a`.
  210. dtype : dtype, optional
  211. Type of the returned array and of the accumulator in which the
  212. elements are summed. If `dtype` is not specified, it defaults to the
  213. dtype of `a`, unless `a` has an integer `dtype` with a precision less
  214. than that of the default platform integer. In that case, the default
  215. platform integer is used.
  216. weights : array_like, optional
  217. The weights array can either be 1-D (in which case its length must be
  218. the size of `a` along the given `axis`) or of the same shape as `a`.
  219. Default is None, which gives each value a weight of 1.0.
  220. .. versionadded:: 1.9
  221. Returns
  222. -------
  223. hmean : ndarray
  224. See `dtype` parameter above.
  225. See Also
  226. --------
  227. numpy.mean : Arithmetic average
  228. numpy.average : Weighted average
  229. gmean : Geometric mean
  230. Notes
  231. -----
  232. The sample harmonic mean is the reciprocal of the mean of the reciprocals
  233. of the observations.
  234. The harmonic mean is computed over a single dimension of the input
  235. array, axis=0 by default, or all values in the array if axis=None.
  236. float64 intermediate and return values are used for integer inputs.
  237. The harmonic mean is only defined if all observations are non-negative;
  238. otherwise, the result is NaN.
  239. References
  240. ----------
  241. .. [1] "Weighted Harmonic Mean", *Wikipedia*,
  242. https://en.wikipedia.org/wiki/Harmonic_mean#Weighted_harmonic_mean
  243. .. [2] Ferger, F., "The nature and use of the harmonic mean", Journal of
  244. the American Statistical Association, vol. 26, pp. 36-40, 1931
  245. Examples
  246. --------
  247. >>> from scipy.stats import hmean
  248. >>> hmean([1, 4])
  249. 1.6000000000000001
  250. >>> hmean([1, 2, 3, 4, 5, 6, 7])
  251. 2.6997245179063363
  252. >>> hmean([1, 4, 7], weights=[3, 1, 3])
  253. 1.9029126213592233
  254. """
  255. xp = array_namespace(a, weights)
  256. a = xp.asarray(a, dtype=dtype)
  257. if weights is not None:
  258. weights = xp.asarray(weights, dtype=dtype)
  259. negative_mask = a < 0
  260. if xp.any(negative_mask):
  261. # `where` avoids having to be careful about dtypes and will work with
  262. # JAX. This is the exceptional case, so it's OK to be a little slower.
  263. # Won't work for array_api_strict for now, but see data-apis/array-api#807
  264. a = xp.where(negative_mask, xp.nan, a)
  265. message = ("The harmonic mean is only defined if all elements are "
  266. "non-negative; otherwise, the result is NaN.")
  267. warnings.warn(message, RuntimeWarning, stacklevel=2)
  268. with np.errstate(divide='ignore'):
  269. return 1.0 / _xp_mean(1.0 / a, axis=axis, weights=weights)
  270. @xp_capabilities(jax_jit=False, allow_dask_compute=1)
  271. @_axis_nan_policy_factory(
  272. lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
  273. result_to_tuple=lambda x, _: (x,), kwd_samples=['weights'])
  274. def pmean(a, p, *, axis=0, dtype=None, weights=None):
  275. r"""Calculate the weighted power mean along the specified axis.
  276. The weighted power mean of the array :math:`a_i` associated to weights
  277. :math:`w_i` is:
  278. .. math::
  279. \left( \frac{ \sum_{i=1}^n w_i a_i^p }{ \sum_{i=1}^n w_i }
  280. \right)^{ 1 / p } \, ,
  281. and, with equal weights, it gives:
  282. .. math::
  283. \left( \frac{ 1 }{ n } \sum_{i=1}^n a_i^p \right)^{ 1 / p } \, .
  284. When ``p=0``, it returns the geometric mean.
  285. This mean is also called generalized mean or Hölder mean, and must not be
  286. confused with the Kolmogorov generalized mean, also called
  287. quasi-arithmetic mean or generalized f-mean [3]_.
  288. Parameters
  289. ----------
  290. a : array_like
  291. Input array, masked array or object that can be converted to an array.
  292. p : int or float
  293. Exponent. Must be finite.
  294. axis : int or None, optional
  295. Axis along which the power mean is computed. Default is 0.
  296. If None, compute over the whole array `a`.
  297. dtype : dtype, optional
  298. Type of the returned array and of the accumulator in which the
  299. elements are summed. If `dtype` is not specified, it defaults to the
  300. dtype of `a`, unless `a` has an integer `dtype` with a precision less
  301. than that of the default platform integer. In that case, the default
  302. platform integer is used.
  303. weights : array_like, optional
  304. The weights array can either be 1-D (in which case its length must be
  305. the size of `a` along the given `axis`) or of the same shape as `a`.
  306. Default is None, which gives each value a weight of 1.0.
  307. Returns
  308. -------
  309. pmean : ndarray, see `dtype` parameter above.
  310. Output array containing the power mean values.
  311. See Also
  312. --------
  313. numpy.average : Weighted average
  314. gmean : Geometric mean
  315. hmean : Harmonic mean
  316. Notes
  317. -----
  318. The power mean is computed over a single dimension of the input
  319. array, ``axis=0`` by default, or all values in the array if ``axis=None``.
  320. float64 intermediate and return values are used for integer inputs.
  321. The power mean is only defined if all observations are non-negative;
  322. otherwise, the result is NaN.
  323. .. versionadded:: 1.9
  324. References
  325. ----------
  326. .. [1] "Generalized Mean", *Wikipedia*,
  327. https://en.wikipedia.org/wiki/Generalized_mean
  328. .. [2] Norris, N., "Convexity properties of generalized mean value
  329. functions", The Annals of Mathematical Statistics, vol. 8,
  330. pp. 118-120, 1937
  331. .. [3] Bullen, P.S., Handbook of Means and Their Inequalities, 2003
  332. Examples
  333. --------
  334. >>> from scipy.stats import pmean, hmean, gmean
  335. >>> pmean([1, 4], 1.3)
  336. 2.639372938300652
  337. >>> pmean([1, 2, 3, 4, 5, 6, 7], 1.3)
  338. 4.157111214492084
  339. >>> pmean([1, 4, 7], -2, weights=[3, 1, 3])
  340. 1.4969684896631954
  341. For p=-1, power mean is equal to harmonic mean:
  342. >>> pmean([1, 4, 7], -1, weights=[3, 1, 3])
  343. 1.9029126213592233
  344. >>> hmean([1, 4, 7], weights=[3, 1, 3])
  345. 1.9029126213592233
  346. For p=0, power mean is defined as the geometric mean:
  347. >>> pmean([1, 4, 7], 0, weights=[3, 1, 3])
  348. 2.80668351922014
  349. >>> gmean([1, 4, 7], weights=[3, 1, 3])
  350. 2.80668351922014
  351. """
  352. if not isinstance(p, int | float):
  353. raise ValueError("Power mean only defined for exponent of type int or "
  354. "float.")
  355. if p == 0:
  356. return gmean(a, axis=axis, dtype=dtype, weights=weights)
  357. elif math.isinf(p):
  358. message = "Power mean only implemented for finite `p`"
  359. raise NotImplementedError(message)
  360. xp = array_namespace(a, weights)
  361. a = xp.asarray(a, dtype=dtype)
  362. if weights is not None:
  363. weights = xp.asarray(weights, dtype=dtype)
  364. negative_mask = a < 0
  365. if xp.any(negative_mask):
  366. # `where` avoids having to be careful about dtypes and will work with
  367. # JAX. This is the exceptional case, so it's OK to be a little slower.
  368. # Won't work for array_api_strict for now, but see data-apis/array-api#807
  369. a = xp.where(negative_mask, np.nan, a)
  370. message = ("The power mean is only defined if all elements are "
  371. "non-negative; otherwise, the result is NaN.")
  372. warnings.warn(message, RuntimeWarning, stacklevel=2)
  373. with np.errstate(divide='ignore', invalid='ignore'):
  374. return _xp_mean(a**float(p), axis=axis, weights=weights)**(1/p)
  375. ModeResult = namedtuple('ModeResult', ('mode', 'count'))
  376. def _mode_result(mode, count):
  377. # When a slice is empty, `_axis_nan_policy` automatically produces
  378. # NaN for `mode` and `count`. This is a reasonable convention for `mode`,
  379. # but `count` should not be NaN; it should be zero.
  380. xp = array_namespace(mode, count)
  381. i = xp.isnan(count)
  382. if i.shape == ():
  383. count = xp.asarray(0, dtype=count.dtype)[()] if i else count
  384. else:
  385. count = xpx.at(count)[i].set(0)
  386. return ModeResult(mode, count)
  387. @xp_capabilities(skip_backends=[('dask.array', "can't compute chunk size"),
  388. ('jax.numpy', "relies on _axis_nan_policy"),
  389. ('cupy', "data-apis/array-api-compat#312")])
  390. @_axis_nan_policy_factory(_mode_result, override={'nan_propagation': False})
  391. def mode(a, axis=0, nan_policy='propagate', keepdims=False):
  392. r"""Return an array of the modal (most common) value in the passed array.
  393. If there is more than one such value, only one is returned.
  394. The bin-count for the modal bins is also returned.
  395. Parameters
  396. ----------
  397. a : array_like
  398. Numeric, n-dimensional array of which to find mode(s).
  399. axis : int or None, optional
  400. Axis along which to operate. Default is 0. If None, compute over
  401. the whole array `a`.
  402. nan_policy : {'propagate', 'raise', 'omit'}, optional
  403. Defines how to handle when input contains nan.
  404. The following options are available (default is 'propagate'):
  405. * 'propagate': treats nan as it would treat any other value
  406. * 'raise': throws an error
  407. * 'omit': performs the calculations ignoring nan values
  408. keepdims : bool, optional
  409. If set to ``False``, the `axis` over which the statistic is taken
  410. is consumed (eliminated from the output array). If set to ``True``,
  411. the `axis` is retained with size one, and the result will broadcast
  412. correctly against the input array.
  413. Returns
  414. -------
  415. mode : ndarray
  416. Array of modal values.
  417. count : ndarray
  418. Array of counts for each mode.
  419. Notes
  420. -----
  421. The mode is calculated using `numpy.unique`.
  422. In NumPy versions 1.21 and after, all NaNs - even those with different
  423. binary representations - are treated as equivalent and counted as separate
  424. instances of the same value.
  425. By convention, the mode of an empty array is NaN, and the associated count
  426. is zero.
  427. Examples
  428. --------
  429. >>> import numpy as np
  430. >>> a = np.array([[3, 0, 3, 7],
  431. ... [3, 2, 6, 2],
  432. ... [1, 7, 2, 8],
  433. ... [3, 0, 6, 1],
  434. ... [3, 2, 5, 5]])
  435. >>> from scipy import stats
  436. >>> stats.mode(a, keepdims=True)
  437. ModeResult(mode=array([[3, 0, 6, 1]]), count=array([[4, 2, 2, 1]]))
  438. To get mode of whole array, specify ``axis=None``:
  439. >>> stats.mode(a, axis=None, keepdims=True)
  440. ModeResult(mode=[[3]], count=[[5]])
  441. >>> stats.mode(a, axis=None, keepdims=False)
  442. ModeResult(mode=3, count=5)
  443. """
  444. xp = array_namespace(a)
  445. # `axis`, `nan_policy`, and `keepdims` are handled by `_axis_nan_policy`
  446. if not xp.isdtype(a.dtype, 'numeric'):
  447. message = ("Argument `a` is not recognized as numeric. "
  448. "Support for input that cannot be coerced to a numeric "
  449. "array was deprecated in SciPy 1.9.0 and removed in SciPy "
  450. "1.11.0. Please consider `np.unique`.")
  451. raise TypeError(message)
  452. if xp_size(a) == 0:
  453. NaN = _get_nan(a, xp=xp)
  454. return ModeResult(*xp.asarray([NaN, 0], dtype=NaN.dtype))
  455. if a.ndim == 1:
  456. vals, cnts = xp.unique_counts(a)
  457. # in contrast with np.unique, `unique_counts` treats all NaNs as distinct,
  458. # but we have always grouped them. Replace `cnts` corresponding with NaNs
  459. # with the number of NaNs.
  460. mask = xp.isnan(vals)
  461. cnts = xpx.at(cnts)[mask].set(xp.count_nonzero(mask))
  462. modes, counts = vals[xp.argmax(cnts)], xp.max(cnts)
  463. default_int = xp.asarray(1).dtype # fail slow CI job failed - incorrect dtype
  464. counts = xp.astype(counts, default_int, copy=False)
  465. modes = modes[()] if modes.ndim == 0 else modes
  466. counts = counts[()] if counts.ndim == 0 else counts
  467. return ModeResult(modes, counts)
  468. # `axis` is always -1 after the `_axis_nan_policy` decorator
  469. y = xp.sort(a, axis=-1)
  470. # Get boolean array of elements that are different from the previous element
  471. i = xp.concat([xp.ones(y.shape[:-1] + (1,), dtype=xp.bool),
  472. (y[..., :-1] != y[..., 1:]) & ~xp.isnan(y[..., :-1])], axis=-1)
  473. # Get linear integer indices of these elements in a raveled array
  474. indices = xp.arange(xp_size(y), device=xp_device(y))[xp_ravel(i)]
  475. # The difference between integer indices is the number of repeats
  476. append = xp.full(indices.shape[:-1] + (1,), xp_size(y), dtype=indices.dtype)
  477. counts = xp.diff(indices, append=append)
  478. # Now we form an array of `counts` corresponding with each element of `y`...
  479. counts = xp.reshape(xp.repeat(counts, counts), y.shape)
  480. # ... so we can get the argmax of *each slice* separately.
  481. k = xp.argmax(counts, axis=-1, keepdims=True)
  482. # Extract the corresponding element/count, and eliminate the reduced dimension
  483. modes = xp.take_along_axis(y, k, axis=-1)[..., 0]
  484. counts = xp.take_along_axis(counts, k, axis=-1)[..., 0]
  485. modes = modes[()] if modes.ndim == 0 else modes
  486. counts = counts[()] if counts.ndim == 0 else counts
  487. return ModeResult(modes, counts)
  488. def _put_val_to_limits(a, limits, inclusive, val=np.nan, xp=None):
  489. """Replace elements outside limits with a value.
  490. This is primarily a utility function.
  491. Parameters
  492. ----------
  493. a : array
  494. limits : (float or None, float or None)
  495. A tuple consisting of the (lower limit, upper limit). Elements in the
  496. input array less than the lower limit or greater than the upper limit
  497. will be replaced with `val`. None implies no limit.
  498. inclusive : (bool, bool)
  499. A tuple consisting of the (lower flag, upper flag). These flags
  500. determine whether values exactly equal to lower or upper are allowed.
  501. val : float, default: NaN
  502. The value with which extreme elements of the array are replaced.
  503. """
  504. xp = array_namespace(a) if xp is None else xp
  505. mask = xp.zeros_like(a, dtype=xp.bool)
  506. if limits is None:
  507. return a, mask
  508. lower_limit, upper_limit = limits
  509. lower_include, upper_include = inclusive
  510. if lower_limit is not None:
  511. mask = mask | ((a < lower_limit) if lower_include else a <= lower_limit)
  512. if upper_limit is not None:
  513. mask = mask | ((a > upper_limit) if upper_include else a >= upper_limit)
  514. lazy = is_lazy_array(mask)
  515. if not lazy and xp.all(mask):
  516. raise ValueError("No array values within given limits")
  517. if lazy or xp.any(mask):
  518. a = xp.where(mask, val, a)
  519. return a, mask
  520. @xp_capabilities()
  521. @_axis_nan_policy_factory(
  522. lambda x: x, n_outputs=1, default_axis=None,
  523. result_to_tuple=lambda x, _: (x,)
  524. )
  525. def tmean(a, limits=None, inclusive=(True, True), axis=None):
  526. """Compute the trimmed mean.
  527. This function finds the arithmetic mean of given values, ignoring values
  528. outside the given `limits`.
  529. Parameters
  530. ----------
  531. a : array_like
  532. Array of values.
  533. limits : None or (lower limit, upper limit), optional
  534. Values in the input array less than the lower limit or greater than the
  535. upper limit will be ignored. When limits is None (default), then all
  536. values are used. Either of the limit values in the tuple can also be
  537. None representing a half-open interval.
  538. inclusive : (bool, bool), optional
  539. A tuple consisting of the (lower flag, upper flag). These flags
  540. determine whether values exactly equal to the lower or upper limits
  541. are included. The default value is (True, True).
  542. axis : int or None, optional
  543. Axis along which to compute test. Default is None.
  544. Returns
  545. -------
  546. tmean : ndarray
  547. Trimmed mean.
  548. See Also
  549. --------
  550. trim_mean : Returns mean after trimming a proportion from both tails.
  551. Examples
  552. --------
  553. >>> import numpy as np
  554. >>> from scipy import stats
  555. >>> x = np.arange(20)
  556. >>> stats.tmean(x)
  557. 9.5
  558. >>> stats.tmean(x, (3,17))
  559. 10.0
  560. """
  561. xp = array_namespace(a)
  562. a, mask = _put_val_to_limits(a, limits, inclusive, val=0., xp=xp)
  563. # explicit dtype specification required due to data-apis/array-api-compat#152
  564. sum = xp.sum(a, axis=axis, dtype=a.dtype)
  565. n = xp.sum(xp.asarray(~mask, dtype=a.dtype, device=xp_device(a)), axis=axis,
  566. dtype=a.dtype)
  567. mean = xpx.apply_where(n != 0, (sum, n), operator.truediv, fill_value=xp.nan)
  568. return mean[()] if mean.ndim == 0 else mean
  569. @xp_capabilities()
  570. @_axis_nan_policy_factory(
  571. lambda x: x, n_outputs=1, result_to_tuple=lambda x, _: (x,)
  572. )
  573. def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
  574. """Compute the trimmed variance.
  575. This function computes the sample variance of an array of values,
  576. while ignoring values which are outside of given `limits`.
  577. Parameters
  578. ----------
  579. a : array_like
  580. Array of values.
  581. limits : None or (lower limit, upper limit), optional
  582. Values in the input array less than the lower limit or greater than the
  583. upper limit will be ignored. When limits is None, then all values are
  584. used. Either of the limit values in the tuple can also be None
  585. representing a half-open interval. The default value is None.
  586. inclusive : (bool, bool), optional
  587. A tuple consisting of the (lower flag, upper flag). These flags
  588. determine whether values exactly equal to the lower or upper limits
  589. are included. The default value is (True, True).
  590. axis : int or None, optional
  591. Axis along which to operate. Default is 0. If None, compute over the
  592. whole array `a`.
  593. ddof : int, optional
  594. Delta degrees of freedom. Default is 1.
  595. Returns
  596. -------
  597. tvar : float
  598. Trimmed variance.
  599. Notes
  600. -----
  601. `tvar` computes the unbiased sample variance, i.e. it uses a correction
  602. factor ``n / (n - 1)``.
  603. Examples
  604. --------
  605. >>> import numpy as np
  606. >>> from scipy import stats
  607. >>> x = np.arange(20)
  608. >>> stats.tvar(x)
  609. 35.0
  610. >>> stats.tvar(x, (3,17))
  611. 20.0
  612. """
  613. xp = array_namespace(a)
  614. a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp)
  615. with warnings.catch_warnings():
  616. warnings.simplefilter("ignore", SmallSampleWarning)
  617. # Currently, this behaves like nan_policy='omit' for alternative array
  618. # backends, but nan_policy='propagate' will be handled for other backends
  619. # by the axis_nan_policy decorator shortly.
  620. return _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp)
  621. @xp_capabilities()
  622. @_axis_nan_policy_factory(
  623. lambda x: x, n_outputs=1, result_to_tuple=lambda x, _: (x,)
  624. )
  625. def tmin(a, lowerlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
  626. """Compute the trimmed minimum.
  627. This function finds the minimum value of an array `a` along the
  628. specified axis, but only considering values greater than a specified
  629. lower limit.
  630. Parameters
  631. ----------
  632. a : array_like
  633. Array of values.
  634. lowerlimit : None or float, optional
  635. Values in the input array less than the given limit will be ignored.
  636. When lowerlimit is None, then all values are used. The default value
  637. is None.
  638. axis : int or None, optional
  639. Axis along which to operate. Default is 0. If None, compute over the
  640. whole array `a`.
  641. inclusive : {True, False}, optional
  642. This flag determines whether values exactly equal to the lower limit
  643. are included. The default value is True.
  644. Returns
  645. -------
  646. tmin : float, int or ndarray
  647. Trimmed minimum.
  648. Examples
  649. --------
  650. >>> import numpy as np
  651. >>> from scipy import stats
  652. >>> x = np.arange(20)
  653. >>> stats.tmin(x)
  654. 0
  655. >>> stats.tmin(x, 13)
  656. 13
  657. >>> stats.tmin(x, 13, inclusive=False)
  658. 14
  659. """
  660. xp = array_namespace(a)
  661. max_ = xp.iinfo(a.dtype).max if xp.isdtype(a.dtype, 'integral') else xp.inf
  662. a, mask = _put_val_to_limits(a, (lowerlimit, None), (inclusive, None),
  663. val=max_, xp=xp)
  664. res = xp.min(a, axis=axis)
  665. invalid = xp.all(mask, axis=axis) # All elements are below lowerlimit
  666. # For eager backends, output dtype is data-dependent
  667. if is_lazy_array(invalid) or xp.any(invalid):
  668. # Possible loss of precision for int types
  669. res = xp_promote(res, force_floating=True, xp=xp)
  670. res = xp.where(invalid, xp.nan, res)
  671. return res[()] if res.ndim == 0 else res
  672. @xp_capabilities()
  673. @_axis_nan_policy_factory(
  674. lambda x: x, n_outputs=1, result_to_tuple=lambda x, _: (x,)
  675. )
  676. def tmax(a, upperlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
  677. """Compute the trimmed maximum.
  678. This function computes the maximum value of an array along a given axis,
  679. while ignoring values larger than a specified upper limit.
  680. Parameters
  681. ----------
  682. a : array_like
  683. Array of values.
  684. upperlimit : None or float, optional
  685. Values in the input array greater than the given limit will be ignored.
  686. When upperlimit is None, then all values are used. The default value
  687. is None.
  688. axis : int or None, optional
  689. Axis along which to operate. Default is 0. If None, compute over the
  690. whole array `a`.
  691. inclusive : {True, False}, optional
  692. This flag determines whether values exactly equal to the upper limit
  693. are included. The default value is True.
  694. Returns
  695. -------
  696. tmax : float, int or ndarray
  697. Trimmed maximum.
  698. Examples
  699. --------
  700. >>> import numpy as np
  701. >>> from scipy import stats
  702. >>> x = np.arange(20)
  703. >>> stats.tmax(x)
  704. 19
  705. >>> stats.tmax(x, 13)
  706. 13
  707. >>> stats.tmax(x, 13, inclusive=False)
  708. 12
  709. """
  710. xp = array_namespace(a)
  711. min_ = xp.iinfo(a.dtype).min if xp.isdtype(a.dtype, 'integral') else -xp.inf
  712. a, mask = _put_val_to_limits(a, (None, upperlimit), (None, inclusive),
  713. val=min_, xp=xp)
  714. res = xp.max(a, axis=axis)
  715. invalid = xp.all(mask, axis=axis) # All elements are above upperlimit
  716. # For eager backends, output dtype is data-dependent
  717. if is_lazy_array(invalid) or xp.any(invalid):
  718. # Possible loss of precision for int types
  719. res = xp_promote(res, force_floating=True, xp=xp)
  720. res = xp.where(invalid, xp.nan, res)
  721. return res[()] if res.ndim == 0 else res
  722. @xp_capabilities()
  723. @_axis_nan_policy_factory(
  724. lambda x: x, n_outputs=1, result_to_tuple=lambda x, _: (x,)
  725. )
  726. def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
  727. """Compute the trimmed sample standard deviation.
  728. This function finds the sample standard deviation of given values,
  729. ignoring values outside the given `limits`.
  730. Parameters
  731. ----------
  732. a : array_like
  733. Array of values.
  734. limits : None or (lower limit, upper limit), optional
  735. Values in the input array less than the lower limit or greater than the
  736. upper limit will be ignored. When limits is None, then all values are
  737. used. Either of the limit values in the tuple can also be None
  738. representing a half-open interval. The default value is None.
  739. inclusive : (bool, bool), optional
  740. A tuple consisting of the (lower flag, upper flag). These flags
  741. determine whether values exactly equal to the lower or upper limits
  742. are included. The default value is (True, True).
  743. axis : int or None, optional
  744. Axis along which to operate. Default is 0. If None, compute over the
  745. whole array `a`.
  746. ddof : int, optional
  747. Delta degrees of freedom. Default is 1.
  748. Returns
  749. -------
  750. tstd : float
  751. Trimmed sample standard deviation.
  752. Notes
  753. -----
  754. `tstd` computes the unbiased sample standard deviation, i.e. it uses a
  755. correction factor ``n / (n - 1)``.
  756. Examples
  757. --------
  758. >>> import numpy as np
  759. >>> from scipy import stats
  760. >>> x = np.arange(20)
  761. >>> stats.tstd(x)
  762. 5.9160797830996161
  763. >>> stats.tstd(x, (3,17))
  764. 4.4721359549995796
  765. """
  766. return tvar(a, limits, inclusive, axis, ddof, _no_deco=True)**0.5
  767. @xp_capabilities()
  768. @_axis_nan_policy_factory(
  769. lambda x: x, n_outputs=1, result_to_tuple=lambda x, _: (x,)
  770. )
  771. def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
  772. """Compute the trimmed standard error of the mean.
  773. This function finds the standard error of the mean for given
  774. values, ignoring values outside the given `limits`.
  775. Parameters
  776. ----------
  777. a : array_like
  778. Array of values.
  779. limits : None or (lower limit, upper limit), optional
  780. Values in the input array less than the lower limit or greater than the
  781. upper limit will be ignored. When limits is None, then all values are
  782. used. Either of the limit values in the tuple can also be None
  783. representing a half-open interval. The default value is None.
  784. inclusive : (bool, bool), optional
  785. A tuple consisting of the (lower flag, upper flag). These flags
  786. determine whether values exactly equal to the lower or upper limits
  787. are included. The default value is (True, True).
  788. axis : int or None, optional
  789. Axis along which to operate. Default is 0. If None, compute over the
  790. whole array `a`.
  791. ddof : int, optional
  792. Delta degrees of freedom. Default is 1.
  793. Returns
  794. -------
  795. tsem : float
  796. Trimmed standard error of the mean.
  797. Notes
  798. -----
  799. `tsem` uses unbiased sample standard deviation, i.e. it uses a
  800. correction factor ``n / (n - 1)``.
  801. Examples
  802. --------
  803. >>> import numpy as np
  804. >>> from scipy import stats
  805. >>> x = np.arange(20)
  806. >>> stats.tsem(x)
  807. 1.3228756555322954
  808. >>> stats.tsem(x, (3,17))
  809. 1.1547005383792515
  810. """
  811. xp = array_namespace(a)
  812. a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp)
  813. with warnings.catch_warnings():
  814. warnings.simplefilter("ignore", SmallSampleWarning)
  815. # Currently, this behaves like nan_policy='omit' for alternative array
  816. # backends, but nan_policy='propagate' will be handled for other backends
  817. # by the axis_nan_policy decorator shortly.
  818. sd = _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp)**0.5
  819. not_nan = xp.astype(~xp.isnan(a), a.dtype)
  820. n_obs = xp.sum(not_nan, axis=axis, dtype=sd.dtype)
  821. return sd / n_obs**0.5
  822. #####################################
  823. # MOMENTS #
  824. #####################################
  825. def _moment_outputs(kwds, default_order=1):
  826. order = np.atleast_1d(kwds.get('order', default_order))
  827. message = "`order` must be a scalar or a non-empty 1D array."
  828. if order.size == 0 or order.ndim > 1:
  829. raise ValueError(message)
  830. return len(order)
  831. def _moment_result_object(*args):
  832. if len(args) == 1:
  833. return args[0]
  834. xp = array_namespace(*args)
  835. return xp.stack(args)
  836. # When `order` is array-like with size > 1, moment produces an *array*
  837. # rather than a tuple, but the zeroth dimension is to be treated like
  838. # separate outputs. It is important to make the distinction between
  839. # separate outputs when adding the reduced axes back (`keepdims=True`).
  840. def _moment_tuple(x, n_out):
  841. return tuple(x[i, ...] for i in range(x.shape[0])) if n_out > 1 else (x,)
  842. # `moment` fits into the `_axis_nan_policy` pattern, but it is a bit unusual
  843. # because the number of outputs is variable. Specifically,
  844. # `result_to_tuple=lambda x: (x,)` may be surprising for a function that
  845. # can produce more than one output, but it is intended here.
  846. # When `moment is called to produce the output:
  847. # - `result_to_tuple` packs the returned array into a single-element tuple,
  848. # - `_moment_result_object` extracts and returns that single element.
  849. # However, when the input array is empty, `moment` is never called. Instead,
  850. # - `_check_empty_inputs` is used to produce an empty array with the
  851. # appropriate dimensions.
  852. # - A list comprehension creates the appropriate number of copies of this
  853. # array, depending on `n_outputs`.
  854. # - This list - which may have multiple elements - is passed into
  855. # `_moment_result_object`.
  856. # - If there is a single output, `_moment_result_object` extracts and returns
  857. # the single output from the list.
  858. # - If there are multiple outputs, and therefore multiple elements in the list,
  859. # `_moment_result_object` converts the list of arrays to a single array and
  860. # returns it.
  861. # Currently, this leads to a slight inconsistency: when the input array is
  862. # empty, there is no distinction between the `moment` function being called
  863. # with parameter `order=1` and `order=[1]`; the latter *should* produce
  864. # the same as the former but with a singleton zeroth dimension.
  865. @xp_capabilities(jax_jit=False, allow_dask_compute=True)
  866. @_rename_parameter('moment', 'order')
  867. @_axis_nan_policy_factory( # noqa: E302
  868. _moment_result_object, n_samples=1, result_to_tuple=_moment_tuple,
  869. n_outputs=_moment_outputs
  870. )
  871. def moment(a, order=1, axis=0, nan_policy='propagate', *, center=None):
  872. r"""Calculate the nth moment about the mean for a sample.
  873. A moment is a specific quantitative measure of the shape of a set of
  874. points. It is often used to calculate coefficients of skewness and kurtosis
  875. due to its close relationship with them.
  876. Parameters
  877. ----------
  878. a : array_like
  879. Input array.
  880. order : int or 1-D array_like of ints, optional
  881. Order of central moment that is returned. Default is 1.
  882. axis : int or None, optional
  883. Axis along which the central moment is computed. Default is 0.
  884. If None, compute over the whole array `a`.
  885. nan_policy : {'propagate', 'raise', 'omit'}, optional
  886. Defines how to handle when input contains nan.
  887. The following options are available (default is 'propagate'):
  888. * 'propagate': returns nan
  889. * 'raise': throws an error
  890. * 'omit': performs the calculations ignoring nan values
  891. center : float or None, optional
  892. The point about which moments are taken. This can be the sample mean,
  893. the origin, or any other be point. If `None` (default) compute the
  894. center as the sample mean.
  895. Returns
  896. -------
  897. n-th moment about the `center` : ndarray or float
  898. The appropriate moment along the given axis or over all values if axis
  899. is None. The denominator for the moment calculation is the number of
  900. observations, no degrees of freedom correction is done.
  901. See Also
  902. --------
  903. kurtosis, skew, describe
  904. Notes
  905. -----
  906. The k-th moment of a data sample is:
  907. .. math::
  908. m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - c)^k
  909. Where `n` is the number of samples, and `c` is the center around which the
  910. moment is calculated. This function uses exponentiation by squares [1]_ for
  911. efficiency.
  912. Note that, if `a` is an empty array (``a.size == 0``), array `moment` with
  913. one element (`moment.size == 1`) is treated the same as scalar `moment`
  914. (``np.isscalar(moment)``). This might produce arrays of unexpected shape.
  915. References
  916. ----------
  917. .. [1] https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
  918. Examples
  919. --------
  920. >>> from scipy.stats import moment
  921. >>> moment([1, 2, 3, 4, 5], order=1)
  922. 0.0
  923. >>> moment([1, 2, 3, 4, 5], order=2)
  924. 2.0
  925. """
  926. xp = array_namespace(a)
  927. a, axis = _chk_asarray(a, axis, xp=xp)
  928. a = xp_promote(a, force_floating=True, xp=xp)
  929. order = xp.asarray(order, dtype=a.dtype, device=xp_device(a))
  930. if xp_size(order) == 0:
  931. # This is tested by `_moment_outputs`, which is run by the `_axis_nan_policy`
  932. # decorator. Currently, the `_axis_nan_policy` decorator is skipped when `a`
  933. # is a non-NumPy array, so we need to check again. When the decorator is
  934. # updated for array API compatibility, we can remove this second check.
  935. raise ValueError("`order` must be a scalar or a non-empty 1D array.")
  936. if xp.any(order != xp.round(order)):
  937. raise ValueError("All elements of `order` must be integral.")
  938. order = order[()] if order.ndim == 0 else order
  939. # for array_like order input, return a value for each.
  940. if order.ndim > 0:
  941. # Calculated the mean once at most, and only if it will be used
  942. calculate_mean = center is None and xp.any(order > 1)
  943. mean = xp.mean(a, axis=axis, keepdims=True) if calculate_mean else None
  944. mmnt = []
  945. for i in range(order.shape[0]):
  946. order_i = order[i]
  947. if center is None and order_i > 1:
  948. mmnt.append(_moment(a, order_i, axis, mean=mean)[np.newaxis, ...])
  949. else:
  950. mmnt.append(_moment(a, order_i, axis, mean=center)[np.newaxis, ...])
  951. return xp.concat(mmnt, axis=0)
  952. else:
  953. return _moment(a, order, axis, mean=center)
  954. def _demean(a, mean, axis, *, xp, precision_warning=True):
  955. # subtracts `mean` from `a` and returns the result,
  956. # warning if there is catastrophic cancellation. `mean`
  957. # must be the mean of `a` along axis with `keepdims=True`.
  958. # Used in e.g. `_moment`, `_zscore`, `_xp_var`. See gh-15905.
  959. a_zero_mean = a - mean
  960. if (xp_size(a_zero_mean) == 0 or not precision_warning
  961. or is_lazy_array(a_zero_mean)):
  962. return a_zero_mean
  963. eps = xp.finfo(mean.dtype).eps * 10
  964. with np.errstate(divide='ignore', invalid='ignore'):
  965. rel_diff = xp.max(xp.abs(a_zero_mean), axis=axis,
  966. keepdims=True) / xp.abs(mean)
  967. n = _length_nonmasked(a, axis, xp=xp)
  968. with np.errstate(invalid='ignore'):
  969. # Old NumPy doesn't accept `device` arg
  970. device = {} if xp is np and np.__version__ < '2.0' else {'device': xp_device(a)}
  971. precision_loss = xp.any(xp.asarray(rel_diff < eps, **device)
  972. & xp.asarray(n > 1, **device))
  973. if precision_loss:
  974. message = ("Precision loss occurred in moment calculation due to "
  975. "catastrophic cancellation. This occurs when the data "
  976. "are nearly identical. Results may be unreliable.")
  977. warnings.warn(message, RuntimeWarning, stacklevel=5)
  978. return a_zero_mean
  979. def _moment(a, order, axis, *, mean=None, xp=None):
  980. """Vectorized calculation of raw moment about specified center
  981. When `mean` is None, the mean is computed and used as the center;
  982. otherwise, the provided value is used as the center.
  983. """
  984. xp = array_namespace(a) if xp is None else xp
  985. a = xp_promote(a, force_floating=True, xp=xp)
  986. dtype = a.dtype
  987. # moment of empty array is the same regardless of order
  988. if xp_size(a) == 0:
  989. return xp.mean(a, axis=axis)
  990. if order == 0 or (order == 1 and mean is None):
  991. # By definition the zeroth moment is always 1, and the first *central*
  992. # moment is 0.
  993. shape = list(a.shape)
  994. del shape[axis]
  995. temp = (xp.ones(shape, dtype=dtype, device=xp_device(a)) if order == 0
  996. else xp.zeros(shape, dtype=dtype, device=xp_device(a)))
  997. return temp[()] if temp.ndim == 0 else temp
  998. # Exponentiation by squares: form exponent sequence
  999. n_list = [order]
  1000. current_n = order
  1001. while current_n > 2:
  1002. if current_n % 2:
  1003. current_n = (current_n - 1) / 2
  1004. else:
  1005. current_n /= 2
  1006. n_list.append(current_n)
  1007. # Starting point for exponentiation by squares
  1008. mean = (xp.mean(a, axis=axis, keepdims=True) if mean is None
  1009. else xp.asarray(mean, dtype=dtype))
  1010. mean = mean[()] if mean.ndim == 0 else mean
  1011. a_zero_mean = _demean(a, mean, axis, xp=xp)
  1012. if n_list[-1] == 1:
  1013. s = xp.asarray(a_zero_mean, copy=True)
  1014. else:
  1015. s = a_zero_mean**2
  1016. # Perform multiplications
  1017. for n in n_list[-2::-1]:
  1018. s = s**2
  1019. if n % 2:
  1020. s *= a_zero_mean
  1021. return xp.mean(s, axis=axis)
  1022. def _var(x, axis=0, ddof=0, mean=None, xp=None):
  1023. # Calculate variance of sample, warning if precision is lost
  1024. xp = array_namespace(x) if xp is None else xp
  1025. var = _moment(x, 2, axis, mean=mean, xp=xp)
  1026. if ddof != 0:
  1027. n = _length_nonmasked(x, axis, xp=xp)
  1028. n = xp.asarray(n, dtype=x.dtype, device=xp_device(x))
  1029. var *= (n / (n-ddof)) # to avoid error on division by zero
  1030. return var
  1031. @xp_capabilities(jax_jit=False, allow_dask_compute=2)
  1032. @_axis_nan_policy_factory(
  1033. lambda x: x, result_to_tuple=lambda x, _: (x,), n_outputs=1
  1034. )
  1035. # nan_policy handled by `_axis_nan_policy`, but needs to be left
  1036. # in signature to preserve use as a positional argument
  1037. def skew(a, axis=0, bias=True, nan_policy='propagate'):
  1038. r"""Compute the sample skewness of a data set.
  1039. For normally distributed data, the skewness should be about zero. For
  1040. unimodal continuous distributions, a skewness value greater than zero means
  1041. that there is more weight in the right tail of the distribution. The
  1042. function `skewtest` can be used to determine if the skewness value
  1043. is close enough to zero, statistically speaking.
  1044. Parameters
  1045. ----------
  1046. a : ndarray
  1047. Input array.
  1048. axis : int or None, optional
  1049. Axis along which skewness is calculated. Default is 0.
  1050. If None, compute over the whole array `a`.
  1051. bias : bool, optional
  1052. If False, then the calculations are corrected for statistical bias.
  1053. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1054. Defines how to handle when input contains nan.
  1055. The following options are available (default is 'propagate'):
  1056. * 'propagate': returns nan
  1057. * 'raise': throws an error
  1058. * 'omit': performs the calculations ignoring nan values
  1059. Returns
  1060. -------
  1061. skewness : ndarray
  1062. The skewness of values along an axis, returning NaN where all values
  1063. are equal.
  1064. Notes
  1065. -----
  1066. The sample skewness is computed as the Fisher-Pearson coefficient
  1067. of skewness, i.e.
  1068. .. math::
  1069. g_1=\frac{m_3}{m_2^{3/2}}
  1070. where
  1071. .. math::
  1072. m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i
  1073. is the biased sample :math:`i\texttt{th}` central moment, and
  1074. :math:`\bar{x}` is
  1075. the sample mean. If ``bias`` is False, the calculations are
  1076. corrected for bias and the value computed is the adjusted
  1077. Fisher-Pearson standardized moment coefficient, i.e.
  1078. .. math::
  1079. G_1=\frac{k_3}{k_2^{3/2}}=
  1080. \frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}.
  1081. References
  1082. ----------
  1083. .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
  1084. Probability and Statistics Tables and Formulae. Chapman & Hall: New
  1085. York. 2000.
  1086. Section 2.2.24.1
  1087. Examples
  1088. --------
  1089. >>> from scipy.stats import skew
  1090. >>> skew([1, 2, 3, 4, 5])
  1091. 0.0
  1092. >>> skew([2, 8, 0, 4, 1, 9, 9, 0])
  1093. 0.2650554122698573
  1094. """
  1095. xp = array_namespace(a)
  1096. a, axis = _chk_asarray(a, axis, xp=xp)
  1097. n = _length_nonmasked(a, axis, xp=xp)
  1098. mean = xp.mean(a, axis=axis, keepdims=True)
  1099. mean_reduced = xp.squeeze(mean, axis=axis) # needed later
  1100. m2 = _moment(a, 2, axis, mean=mean, xp=xp)
  1101. m3 = _moment(a, 3, axis, mean=mean, xp=xp)
  1102. with np.errstate(all='ignore'):
  1103. eps = xp.finfo(m2.dtype).eps
  1104. zero = m2 <= (eps * mean_reduced)**2
  1105. vals = xp.where(zero, xp.nan, m3 / m2**1.5)
  1106. if not bias:
  1107. can_correct = ~zero & (n > 2)
  1108. if is_lazy_array(can_correct) or xp.any(can_correct):
  1109. nval = ((n - 1.0) * n)**0.5 / (n - 2.0) * m3 / m2**1.5
  1110. vals = xp.where(can_correct, nval, vals)
  1111. return vals[()] if vals.ndim == 0 else vals
  1112. @xp_capabilities(jax_jit=False, allow_dask_compute=2)
  1113. @_axis_nan_policy_factory(
  1114. lambda x: x, result_to_tuple=lambda x, _: (x,), n_outputs=1
  1115. )
  1116. # nan_policy handled by `_axis_nan_policy`, but needs to be left
  1117. # in signature to preserve use as a positional argument
  1118. def kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate'):
  1119. """Compute the kurtosis (Fisher or Pearson) of a dataset.
  1120. Kurtosis is the fourth central moment divided by the square of the
  1121. variance. If Fisher's definition is used, then 3.0 is subtracted from
  1122. the result to give 0.0 for a normal distribution.
  1123. If bias is False then the kurtosis is calculated using k statistics to
  1124. eliminate bias coming from biased moment estimators
  1125. Use `kurtosistest` to see if result is close enough to normal.
  1126. Parameters
  1127. ----------
  1128. a : array
  1129. Data for which the kurtosis is calculated.
  1130. axis : int or None, optional
  1131. Axis along which the kurtosis is calculated. Default is 0.
  1132. If None, compute over the whole array `a`.
  1133. fisher : bool, optional
  1134. If True, Fisher's definition is used (normal ==> 0.0). If False,
  1135. Pearson's definition is used (normal ==> 3.0).
  1136. bias : bool, optional
  1137. If False, then the calculations are corrected for statistical bias.
  1138. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1139. Defines how to handle when input contains nan. 'propagate' returns nan,
  1140. 'raise' throws an error, 'omit' performs the calculations ignoring nan
  1141. values. Default is 'propagate'.
  1142. Returns
  1143. -------
  1144. kurtosis : array
  1145. The kurtosis of values along an axis, returning NaN where all values
  1146. are equal.
  1147. References
  1148. ----------
  1149. .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
  1150. Probability and Statistics Tables and Formulae. Chapman & Hall: New
  1151. York. 2000.
  1152. Examples
  1153. --------
  1154. In Fisher's definition, the kurtosis of the normal distribution is zero.
  1155. In the following example, the kurtosis is close to zero, because it was
  1156. calculated from the dataset, not from the continuous distribution.
  1157. >>> import numpy as np
  1158. >>> from scipy.stats import norm, kurtosis
  1159. >>> data = norm.rvs(size=1000, random_state=3)
  1160. >>> kurtosis(data)
  1161. -0.06928694200380558
  1162. The distribution with a higher kurtosis has a heavier tail.
  1163. The zero valued kurtosis of the normal distribution in Fisher's definition
  1164. can serve as a reference point.
  1165. >>> import matplotlib.pyplot as plt
  1166. >>> import scipy.stats as stats
  1167. >>> from scipy.stats import kurtosis
  1168. >>> x = np.linspace(-5, 5, 100)
  1169. >>> ax = plt.subplot()
  1170. >>> distnames = ['laplace', 'norm', 'uniform']
  1171. >>> for distname in distnames:
  1172. ... if distname == 'uniform':
  1173. ... dist = getattr(stats, distname)(loc=-2, scale=4)
  1174. ... else:
  1175. ... dist = getattr(stats, distname)
  1176. ... data = dist.rvs(size=1000)
  1177. ... kur = kurtosis(data, fisher=True)
  1178. ... y = dist.pdf(x)
  1179. ... ax.plot(x, y, label="{}, {}".format(distname, round(kur, 3)))
  1180. ... ax.legend()
  1181. The Laplace distribution has a heavier tail than the normal distribution.
  1182. The uniform distribution (which has negative kurtosis) has the thinnest
  1183. tail.
  1184. """
  1185. xp = array_namespace(a)
  1186. a, axis = _chk_asarray(a, axis, xp=xp)
  1187. n = _length_nonmasked(a, axis, xp=xp)
  1188. mean = xp.mean(a, axis=axis, keepdims=True)
  1189. mean_reduced = xp.squeeze(mean, axis=axis) # needed later
  1190. m2 = _moment(a, 2, axis, mean=mean, xp=xp)
  1191. m4 = _moment(a, 4, axis, mean=mean, xp=xp)
  1192. with np.errstate(all='ignore'):
  1193. zero = m2 <= (xp.finfo(m2.dtype).eps * mean_reduced)**2
  1194. vals = xp.where(zero, xp.nan, m4 / m2**2.0)
  1195. if not bias:
  1196. can_correct = ~zero & (n > 3)
  1197. if is_lazy_array(can_correct) or xp.any(can_correct):
  1198. nval = 1.0/(n-2)/(n-3) * ((n**2-1.0)*m4/m2**2.0 - 3*(n-1)**2.0)
  1199. vals = xp.where(can_correct, nval + 3.0, vals)
  1200. vals = vals - 3 if fisher else vals
  1201. return vals[()] if vals.ndim == 0 else vals
  1202. DescribeResult = namedtuple('DescribeResult',
  1203. ('nobs', 'minmax', 'mean', 'variance', 'skewness',
  1204. 'kurtosis'))
  1205. @xp_capabilities(jax_jit=False, allow_dask_compute=True)
  1206. def describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate'):
  1207. """Compute several descriptive statistics of the passed array.
  1208. Parameters
  1209. ----------
  1210. a : array_like
  1211. Input data.
  1212. axis : int or None, optional
  1213. Axis along which statistics are calculated. Default is 0.
  1214. If None, compute over the whole array `a`.
  1215. ddof : int, optional
  1216. Delta degrees of freedom (only for variance). Default is 1.
  1217. bias : bool, optional
  1218. If False, then the skewness and kurtosis calculations are corrected
  1219. for statistical bias.
  1220. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1221. Defines how to handle when input contains nan.
  1222. The following options are available (default is 'propagate'):
  1223. * 'propagate': returns nan
  1224. * 'raise': throws an error
  1225. * 'omit': performs the calculations ignoring nan values
  1226. Returns
  1227. -------
  1228. nobs : int or ndarray of ints
  1229. Number of observations (length of data along `axis`).
  1230. When 'omit' is chosen as nan_policy, the length along each axis
  1231. slice is counted separately.
  1232. minmax: tuple of ndarrays or floats
  1233. Minimum and maximum value of `a` along the given axis.
  1234. mean : ndarray or float
  1235. Arithmetic mean of `a` along the given axis.
  1236. variance : ndarray or float
  1237. Unbiased variance of `a` along the given axis; denominator is number
  1238. of observations minus one.
  1239. skewness : ndarray or float
  1240. Skewness of `a` along the given axis, based on moment calculations
  1241. with denominator equal to the number of observations, i.e. no degrees
  1242. of freedom correction.
  1243. kurtosis : ndarray or float
  1244. Kurtosis (Fisher) of `a` along the given axis. The kurtosis is
  1245. normalized so that it is zero for the normal distribution. No
  1246. degrees of freedom are used.
  1247. Raises
  1248. ------
  1249. ValueError
  1250. If size of `a` is 0.
  1251. See Also
  1252. --------
  1253. skew, kurtosis
  1254. Examples
  1255. --------
  1256. >>> import numpy as np
  1257. >>> from scipy import stats
  1258. >>> a = np.arange(10)
  1259. >>> stats.describe(a)
  1260. DescribeResult(nobs=10, minmax=(0, 9), mean=4.5,
  1261. variance=9.166666666666666, skewness=0.0,
  1262. kurtosis=-1.2242424242424244)
  1263. >>> b = [[1, 2], [3, 4]]
  1264. >>> stats.describe(b)
  1265. DescribeResult(nobs=2, minmax=(array([1, 2]), array([3, 4])),
  1266. mean=array([2., 3.]), variance=array([2., 2.]),
  1267. skewness=array([0., 0.]), kurtosis=array([-2., -2.]))
  1268. """
  1269. xp = array_namespace(a)
  1270. a, axis = _chk_asarray(a, axis, xp=xp)
  1271. contains_nan = _contains_nan(a, nan_policy)
  1272. # Test nan_policy before the implicit call to bool(contains_nan)
  1273. # to avoid raising on lazy xps on the default nan_policy='propagate'
  1274. if nan_policy == 'omit' and contains_nan:
  1275. # only NumPy gets here; `_contains_nan` raises error for the rest
  1276. a = ma.masked_invalid(a)
  1277. return mstats_basic.describe(a, axis, ddof, bias)
  1278. if xp_size(a) == 0:
  1279. raise ValueError("The input must not be empty.")
  1280. # use xp.astype when data-apis/array-api-compat#226 is resolved
  1281. n = xp.asarray(_length_nonmasked(a, axis, xp=xp), dtype=xp.int64,
  1282. device=xp_device(a))
  1283. n = n[()] if n.ndim == 0 else n
  1284. mm = (xp.min(a, axis=axis), xp.max(a, axis=axis))
  1285. m = xp.mean(a, axis=axis)
  1286. v = _var(a, axis=axis, ddof=ddof, xp=xp)
  1287. sk = skew(a, axis, bias=bias)
  1288. kurt = kurtosis(a, axis, bias=bias)
  1289. return DescribeResult(n, mm, m, v, sk, kurt)
  1290. #####################################
  1291. # NORMALITY TESTS #
  1292. #####################################
  1293. def _get_pvalue(statistic, distribution, alternative, symmetric=True, xp=None):
  1294. """Get p-value given the statistic, (continuous) distribution, and alternative"""
  1295. xp = array_namespace(statistic) if xp is None else xp
  1296. if alternative == 'less':
  1297. pvalue = distribution.cdf(statistic)
  1298. elif alternative == 'greater':
  1299. pvalue = distribution.sf(statistic)
  1300. elif alternative == 'two-sided':
  1301. pvalue = 2 * (distribution.sf(xp.abs(statistic)) if symmetric
  1302. else xp.minimum(distribution.cdf(statistic),
  1303. distribution.sf(statistic)))
  1304. else:
  1305. message = "`alternative` must be 'less', 'greater', or 'two-sided'."
  1306. raise ValueError(message)
  1307. return pvalue
  1308. SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue'))
  1309. @xp_capabilities()
  1310. @_axis_nan_policy_factory(SkewtestResult, n_samples=1, too_small=7)
  1311. # nan_policy handled by `_axis_nan_policy`, but needs to be left
  1312. # in signature to preserve use as a positional argument
  1313. def skewtest(a, axis=0, nan_policy='propagate', alternative='two-sided'):
  1314. r"""Test whether the skew is different from the normal distribution.
  1315. This function tests the null hypothesis that the skewness of
  1316. the population that the sample was drawn from is the same
  1317. as that of a corresponding normal distribution.
  1318. Parameters
  1319. ----------
  1320. a : array
  1321. The data to be tested. Must contain at least eight observations.
  1322. axis : int or None, optional
  1323. Axis along which statistics are calculated. Default is 0.
  1324. If None, compute over the whole array `a`.
  1325. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1326. Defines how to handle when input contains nan.
  1327. The following options are available (default is 'propagate'):
  1328. * 'propagate': returns nan
  1329. * 'raise': throws an error
  1330. * 'omit': performs the calculations ignoring nan values
  1331. alternative : {'two-sided', 'less', 'greater'}, optional
  1332. Defines the alternative hypothesis. Default is 'two-sided'.
  1333. The following options are available:
  1334. * 'two-sided': the skewness of the distribution underlying the sample
  1335. is different from that of the normal distribution (i.e. 0)
  1336. * 'less': the skewness of the distribution underlying the sample
  1337. is less than that of the normal distribution
  1338. * 'greater': the skewness of the distribution underlying the sample
  1339. is greater than that of the normal distribution
  1340. .. versionadded:: 1.7.0
  1341. Returns
  1342. -------
  1343. statistic : float
  1344. The computed z-score for this test.
  1345. pvalue : float
  1346. The p-value for the hypothesis test.
  1347. See Also
  1348. --------
  1349. :ref:`hypothesis_skewtest` : Extended example
  1350. Notes
  1351. -----
  1352. The sample size must be at least 8.
  1353. References
  1354. ----------
  1355. .. [1] R. B. D'Agostino, A. J. Belanger and R. B. D'Agostino Jr.,
  1356. "A suggestion for using powerful and informative tests of
  1357. normality", American Statistician 44, pp. 316-321, 1990.
  1358. Examples
  1359. --------
  1360. >>> from scipy.stats import skewtest
  1361. >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8])
  1362. SkewtestResult(statistic=1.0108048609177787, pvalue=0.3121098361421897)
  1363. >>> skewtest([2, 8, 0, 4, 1, 9, 9, 0])
  1364. SkewtestResult(statistic=0.44626385374196975, pvalue=0.6554066631275459)
  1365. >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8000])
  1366. SkewtestResult(statistic=3.571773510360407, pvalue=0.0003545719905823133)
  1367. >>> skewtest([100, 100, 100, 100, 100, 100, 100, 101])
  1368. SkewtestResult(statistic=3.5717766638478072, pvalue=0.000354567720281634)
  1369. >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='less')
  1370. SkewtestResult(statistic=1.0108048609177787, pvalue=0.8439450819289052)
  1371. >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='greater')
  1372. SkewtestResult(statistic=1.0108048609177787, pvalue=0.15605491807109484)
  1373. For a more detailed example, see :ref:`hypothesis_skewtest`.
  1374. """
  1375. xp = array_namespace(a)
  1376. a, axis = _chk_asarray(a, axis, xp=xp)
  1377. b2 = skew(a, axis, _no_deco=True)
  1378. n = xp.asarray(_length_nonmasked(a, axis), dtype=b2.dtype, device=xp_device(a))
  1379. n = xpx.at(n, n < 8).set(xp.nan)
  1380. with np.errstate(divide='ignore', invalid='ignore'):
  1381. y = b2 * xp.sqrt(((n + 1) * (n + 3)) / (6.0 * (n - 2)))
  1382. beta2 = (3.0 * (n**2 + 27*n - 70) * (n+1) * (n+3) /
  1383. ((n-2.0) * (n+5) * (n+7) * (n+9)))
  1384. W2 = -1 + xp.sqrt(2 * (beta2 - 1))
  1385. delta = 1 / xp.sqrt(0.5 * xp.log(W2))
  1386. alpha = xp.sqrt(2.0 / (W2 - 1))
  1387. y = xp.where(y == 0, 1., y)
  1388. Z = delta * xp.log(y / alpha + xp.sqrt((y / alpha)**2 + 1))
  1389. pvalue = _get_pvalue(Z, _SimpleNormal(), alternative, xp=xp)
  1390. Z = Z[()] if Z.ndim == 0 else Z
  1391. pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
  1392. return SkewtestResult(Z, pvalue)
  1393. KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue'))
  1394. @xp_capabilities()
  1395. @_axis_nan_policy_factory(KurtosistestResult, n_samples=1, too_small=4)
  1396. def kurtosistest(a, axis=0, nan_policy='propagate', alternative='two-sided'):
  1397. r"""Test whether a dataset has normal kurtosis.
  1398. This function tests the null hypothesis that the kurtosis
  1399. of the population from which the sample was drawn is that
  1400. of the normal distribution.
  1401. Parameters
  1402. ----------
  1403. a : array
  1404. Array of the sample data. Must contain at least five observations.
  1405. axis : int or None, optional
  1406. Axis along which to compute test. Default is 0. If None,
  1407. compute over the whole array `a`.
  1408. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1409. Defines how to handle when input contains nan.
  1410. The following options are available (default is 'propagate'):
  1411. * 'propagate': returns nan
  1412. * 'raise': throws an error
  1413. * 'omit': performs the calculations ignoring nan values
  1414. alternative : {'two-sided', 'less', 'greater'}, optional
  1415. Defines the alternative hypothesis.
  1416. The following options are available (default is 'two-sided'):
  1417. * 'two-sided': the kurtosis of the distribution underlying the sample
  1418. is different from that of the normal distribution
  1419. * 'less': the kurtosis of the distribution underlying the sample
  1420. is less than that of the normal distribution
  1421. * 'greater': the kurtosis of the distribution underlying the sample
  1422. is greater than that of the normal distribution
  1423. .. versionadded:: 1.7.0
  1424. Returns
  1425. -------
  1426. statistic : float
  1427. The computed z-score for this test.
  1428. pvalue : float
  1429. The p-value for the hypothesis test.
  1430. See Also
  1431. --------
  1432. :ref:`hypothesis_kurtosistest` : Extended example
  1433. Notes
  1434. -----
  1435. Valid only for n>20. This function uses the method described in [1]_.
  1436. References
  1437. ----------
  1438. .. [1] F. J. Anscombe, W. J. Glynn, "Distribution of the kurtosis
  1439. statistic b2 for normal samples", Biometrika, vol. 70, pp. 227-234, 1983.
  1440. Examples
  1441. --------
  1442. >>> import numpy as np
  1443. >>> from scipy.stats import kurtosistest
  1444. >>> kurtosistest(list(range(20)))
  1445. KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.08804338332528348)
  1446. >>> kurtosistest(list(range(20)), alternative='less')
  1447. KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.04402169166264174)
  1448. >>> kurtosistest(list(range(20)), alternative='greater')
  1449. KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.9559783083373583)
  1450. >>> rng = np.random.default_rng()
  1451. >>> s = rng.normal(0, 1, 1000)
  1452. >>> kurtosistest(s)
  1453. KurtosistestResult(statistic=-1.475047944490622, pvalue=0.14019965402996987)
  1454. For a more detailed example, see :ref:`hypothesis_kurtosistest`.
  1455. """
  1456. xp = array_namespace(a)
  1457. a, axis = _chk_asarray(a, axis, xp=xp)
  1458. b2 = kurtosis(a, axis, fisher=False, _no_deco=True)
  1459. n = xp.asarray(_length_nonmasked(a, axis), dtype=b2.dtype, device=xp_device(a))
  1460. n = xpx.at(n, n < 5).set(xp.nan)
  1461. E = 3.0*(n-1) / (n+1)
  1462. varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5)) # [1]_ Eq. 1
  1463. x = (b2-E) / varb2**0.5 # [1]_ Eq. 4
  1464. # [1]_ Eq. 2:
  1465. sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * ((6.0*(n+3)*(n+5))
  1466. / (n*(n-2)*(n-3)))**0.5
  1467. # [1]_ Eq. 3:
  1468. A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + (1+4.0/(sqrtbeta1**2))**0.5)
  1469. term1 = 1 - 2/(9.0*A)
  1470. denom = 1 + x * (2/(A-4.0))**0.5
  1471. term2 = xp.sign(denom) * xp.where(denom == 0.0, xp.nan,
  1472. ((1-2.0/A)/xp.abs(denom))**(1/3))
  1473. if not is_lazy_array(denom) and xp.any(denom == 0):
  1474. msg = ("Test statistic not defined in some cases due to division by "
  1475. "zero. Return nan in that case...")
  1476. warnings.warn(msg, RuntimeWarning, stacklevel=2)
  1477. Z = (term1 - term2) / (2/(9.0*A))**0.5 # [1]_ Eq. 5
  1478. pvalue = _get_pvalue(Z, _SimpleNormal(), alternative, xp=xp)
  1479. Z = Z[()] if Z.ndim == 0 else Z
  1480. pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
  1481. return KurtosistestResult(Z, pvalue)
  1482. NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue'))
  1483. @xp_capabilities()
  1484. @_axis_nan_policy_factory(NormaltestResult, n_samples=1, too_small=7)
  1485. def normaltest(a, axis=0, nan_policy='propagate'):
  1486. r"""Test whether a sample differs from a normal distribution.
  1487. This function tests the null hypothesis that a sample comes
  1488. from a normal distribution. It is based on D'Agostino and
  1489. Pearson's [1]_, [2]_ test that combines skew and kurtosis to
  1490. produce an omnibus test of normality.
  1491. Parameters
  1492. ----------
  1493. a : array_like
  1494. The array containing the sample to be tested. Must contain
  1495. at least eight observations.
  1496. axis : int or None, optional
  1497. Axis along which to compute test. Default is 0. If None,
  1498. compute over the whole array `a`.
  1499. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1500. Defines how to handle when input contains nan.
  1501. The following options are available (default is 'propagate'):
  1502. * 'propagate': returns nan
  1503. * 'raise': throws an error
  1504. * 'omit': performs the calculations ignoring nan values
  1505. Returns
  1506. -------
  1507. statistic : float or array
  1508. ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and
  1509. ``k`` is the z-score returned by `kurtosistest`.
  1510. pvalue : float or array
  1511. A 2-sided chi squared probability for the hypothesis test.
  1512. See Also
  1513. --------
  1514. :ref:`hypothesis_normaltest` : Extended example
  1515. References
  1516. ----------
  1517. .. [1] D'Agostino, R. B. (1971), "An omnibus test of normality for
  1518. moderate and large sample size", Biometrika, 58, 341-348
  1519. .. [2] D'Agostino, R. and Pearson, E. S. (1973), "Tests for departure from
  1520. normality", Biometrika, 60, 613-622
  1521. Examples
  1522. --------
  1523. >>> import numpy as np
  1524. >>> from scipy import stats
  1525. >>> rng = np.random.default_rng()
  1526. >>> pts = 1000
  1527. >>> a = rng.normal(0, 1, size=pts)
  1528. >>> b = rng.normal(2, 1, size=pts)
  1529. >>> x = np.concatenate((a, b))
  1530. >>> res = stats.normaltest(x)
  1531. >>> res.statistic
  1532. 53.619... # random
  1533. >>> res.pvalue
  1534. 2.273917413209226e-12 # random
  1535. For a more detailed example, see :ref:`hypothesis_normaltest`.
  1536. """
  1537. xp = array_namespace(a)
  1538. s, _ = skewtest(a, axis, _no_deco=True)
  1539. k, _ = kurtosistest(a, axis, _no_deco=True)
  1540. statistic = s*s + k*k
  1541. chi2 = _SimpleChi2(xp.asarray(2., dtype=statistic.dtype, device=xp_device(a)))
  1542. pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp)
  1543. statistic = statistic[()] if statistic.ndim == 0 else statistic
  1544. pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
  1545. return NormaltestResult(statistic, pvalue)
  1546. @xp_capabilities(jax_jit=False, allow_dask_compute=True)
  1547. @_axis_nan_policy_factory(SignificanceResult, default_axis=None)
  1548. def jarque_bera(x, *, axis=None):
  1549. r"""Perform the Jarque-Bera goodness of fit test on sample data.
  1550. The Jarque-Bera test tests whether the sample data has the skewness and
  1551. kurtosis matching a normal distribution.
  1552. Note that this test only works for a large enough number of data samples
  1553. (>2000) as the test statistic asymptotically has a Chi-squared distribution
  1554. with 2 degrees of freedom.
  1555. Parameters
  1556. ----------
  1557. x : array_like
  1558. Observations of a random variable.
  1559. axis : int or None, default: 0
  1560. If an int, the axis of the input along which to compute the statistic.
  1561. The statistic of each axis-slice (e.g. row) of the input will appear in
  1562. a corresponding element of the output.
  1563. If ``None``, the input will be raveled before computing the statistic.
  1564. Returns
  1565. -------
  1566. result : SignificanceResult
  1567. An object with the following attributes:
  1568. statistic : float
  1569. The test statistic.
  1570. pvalue : float
  1571. The p-value for the hypothesis test.
  1572. See Also
  1573. --------
  1574. :ref:`hypothesis_jarque_bera` : Extended example
  1575. References
  1576. ----------
  1577. .. [1] Jarque, C. and Bera, A. (1980) "Efficient tests for normality,
  1578. homoscedasticity and serial independence of regression residuals",
  1579. 6 Econometric Letters 255-259.
  1580. Examples
  1581. --------
  1582. >>> import numpy as np
  1583. >>> from scipy import stats
  1584. >>> rng = np.random.default_rng()
  1585. >>> x = rng.normal(0, 1, 100000)
  1586. >>> jarque_bera_test = stats.jarque_bera(x)
  1587. >>> jarque_bera_test
  1588. Jarque_beraResult(statistic=3.3415184718131554, pvalue=0.18810419594996775)
  1589. >>> jarque_bera_test.statistic
  1590. 3.3415184718131554
  1591. >>> jarque_bera_test.pvalue
  1592. 0.18810419594996775
  1593. For a more detailed example, see :ref:`hypothesis_jarque_bera`.
  1594. """
  1595. xp = array_namespace(x)
  1596. x, axis = _chk_asarray(x, axis, xp=xp)
  1597. mu = _xp_mean(x, axis=axis, keepdims=True)
  1598. diffx = x - mu
  1599. s = skew(diffx, axis=axis, _no_deco=True)
  1600. k = kurtosis(diffx, axis=axis, _no_deco=True)
  1601. n = xp.asarray(_length_nonmasked(x, axis), dtype=mu.dtype, device=xp_device(x))
  1602. statistic = n / 6 * (s**2 + k**2 / 4)
  1603. chi2 = _SimpleChi2(xp.asarray(2., dtype=mu.dtype, device=xp_device(x)))
  1604. pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp)
  1605. statistic = statistic[()] if statistic.ndim == 0 else statistic
  1606. pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
  1607. return SignificanceResult(statistic, pvalue)
  1608. #####################################
  1609. # FREQUENCY FUNCTIONS #
  1610. #####################################
  1611. @xp_capabilities(np_only=True)
  1612. def scoreatpercentile(a, per, limit=(), interpolation_method='fraction',
  1613. axis=None):
  1614. """Calculate the score at a given percentile of the input sequence.
  1615. For example, the score at ``per=50`` is the median. If the desired quantile
  1616. lies between two data points, we interpolate between them, according to
  1617. the value of `interpolation`. If the parameter `limit` is provided, it
  1618. should be a tuple (lower, upper) of two values.
  1619. Parameters
  1620. ----------
  1621. a : array_like
  1622. A 1-D array of values from which to extract score.
  1623. per : array_like
  1624. Percentile(s) at which to extract score. Values should be in range
  1625. [0,100].
  1626. limit : tuple, optional
  1627. Tuple of two scalars, the lower and upper limits within which to
  1628. compute the percentile. Values of `a` outside
  1629. this (closed) interval will be ignored.
  1630. interpolation_method : {'fraction', 'lower', 'higher'}, optional
  1631. Specifies the interpolation method to use,
  1632. when the desired quantile lies between two data points `i` and `j`
  1633. The following options are available (default is 'fraction'):
  1634. * 'fraction': ``i + (j - i) * fraction`` where ``fraction`` is the
  1635. fractional part of the index surrounded by ``i`` and ``j``
  1636. * 'lower': ``i``
  1637. * 'higher': ``j``
  1638. axis : int, optional
  1639. Axis along which the percentiles are computed. Default is None. If
  1640. None, compute over the whole array `a`.
  1641. Returns
  1642. -------
  1643. score : float or ndarray
  1644. Score at percentile(s).
  1645. See Also
  1646. --------
  1647. percentileofscore, numpy.percentile
  1648. Notes
  1649. -----
  1650. This function will become obsolete in the future.
  1651. For NumPy 1.9 and higher, `numpy.percentile` provides all the functionality
  1652. that `scoreatpercentile` provides. And it's significantly faster.
  1653. Therefore it's recommended to use `numpy.percentile` for users that have
  1654. numpy >= 1.9.
  1655. Examples
  1656. --------
  1657. >>> import numpy as np
  1658. >>> from scipy import stats
  1659. >>> a = np.arange(100)
  1660. >>> stats.scoreatpercentile(a, 50)
  1661. 49.5
  1662. """
  1663. # adapted from NumPy's percentile function. When we require numpy >= 1.8,
  1664. # the implementation of this function can be replaced by np.percentile.
  1665. a = np.asarray(a)
  1666. if a.size == 0:
  1667. # empty array, return nan(s) with shape matching `per`
  1668. if np.isscalar(per):
  1669. return np.nan
  1670. else:
  1671. return np.full(np.asarray(per).shape, np.nan, dtype=np.float64)
  1672. if limit:
  1673. a = a[(limit[0] <= a) & (a <= limit[1])]
  1674. sorted_ = np.sort(a, axis=axis)
  1675. if axis is None:
  1676. axis = 0
  1677. return _compute_qth_percentile(sorted_, per, interpolation_method, axis)
  1678. # handle sequence of per's without calling sort multiple times
  1679. def _compute_qth_percentile(sorted_, per, interpolation_method, axis):
  1680. if not np.isscalar(per):
  1681. score = [_compute_qth_percentile(sorted_, i,
  1682. interpolation_method, axis)
  1683. for i in per]
  1684. return np.array(score)
  1685. if not (0 <= per <= 100):
  1686. raise ValueError("percentile must be in the range [0, 100]")
  1687. indexer = [slice(None)] * sorted_.ndim
  1688. idx = per / 100. * (sorted_.shape[axis] - 1)
  1689. if int(idx) != idx:
  1690. # round fractional indices according to interpolation method
  1691. if interpolation_method == 'lower':
  1692. idx = int(np.floor(idx))
  1693. elif interpolation_method == 'higher':
  1694. idx = int(np.ceil(idx))
  1695. elif interpolation_method == 'fraction':
  1696. pass # keep idx as fraction and interpolate
  1697. else:
  1698. raise ValueError("interpolation_method can only be 'fraction', "
  1699. "'lower' or 'higher'")
  1700. i = int(idx)
  1701. if i == idx:
  1702. indexer[axis] = slice(i, i + 1)
  1703. weights = array(1)
  1704. sumval = 1.0
  1705. else:
  1706. indexer[axis] = slice(i, i + 2)
  1707. j = i + 1
  1708. weights = array([(j - idx), (idx - i)], float)
  1709. wshape = [1] * sorted_.ndim
  1710. wshape[axis] = 2
  1711. weights = weights.reshape(wshape)
  1712. sumval = weights.sum()
  1713. # Use np.add.reduce (== np.sum but a little faster) to coerce data type
  1714. return np.add.reduce(sorted_[tuple(indexer)] * weights, axis=axis) / sumval
  1715. @xp_capabilities(np_only=True)
  1716. def percentileofscore(a, score, kind='rank', nan_policy='propagate'):
  1717. """Compute the percentile rank of a score relative to a list of scores.
  1718. A `percentileofscore` of, for example, 80% means that 80% of the
  1719. scores in `a` are below the given score. In the case of gaps or
  1720. ties, the exact definition depends on the optional keyword, `kind`.
  1721. Parameters
  1722. ----------
  1723. a : array_like
  1724. A 1-D array to which `score` is compared.
  1725. score : float or array_like
  1726. A float score or array of scores for which to compute the percentile(s).
  1727. kind : {'rank', 'weak', 'strict', 'mean'}, optional
  1728. Specifies the interpretation of the resulting score.
  1729. The following options are available (default is 'rank'):
  1730. * 'rank': Average percentage ranking of score. In case of multiple
  1731. matches, average the percentage rankings of all matching scores.
  1732. * 'weak': This kind corresponds to the definition of a cumulative
  1733. distribution function. A percentileofscore of 80% means that 80%
  1734. of values are less than or equal to the provided score.
  1735. * 'strict': Similar to "weak", except that only values that are
  1736. strictly less than the given score are counted.
  1737. * 'mean': The average of the "weak" and "strict" scores, often used
  1738. in testing. See https://en.wikipedia.org/wiki/Percentile_rank
  1739. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1740. Specifies how to treat `nan` values in `a`.
  1741. The following options are available (default is 'propagate'):
  1742. * 'propagate': returns nan (for each value in `score`).
  1743. * 'raise': throws an error
  1744. * 'omit': performs the calculations ignoring nan values
  1745. Returns
  1746. -------
  1747. pcos : float or array-like
  1748. Percentile-position(s) of `score` (0-100) relative to `a`.
  1749. See Also
  1750. --------
  1751. numpy.percentile
  1752. scipy.stats.scoreatpercentile, scipy.stats.rankdata
  1753. Examples
  1754. --------
  1755. Three-quarters of the given values lie below a given score:
  1756. >>> import numpy as np
  1757. >>> from scipy import stats
  1758. >>> stats.percentileofscore([1, 2, 3, 4], 3)
  1759. 75.0
  1760. With multiple matches, note how the scores of the two matches, 0.6
  1761. and 0.8 respectively, are averaged:
  1762. >>> stats.percentileofscore([1, 2, 3, 3, 4], 3)
  1763. 70.0
  1764. Only 2/5 values are strictly less than 3:
  1765. >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='strict')
  1766. 40.0
  1767. But 4/5 values are less than or equal to 3:
  1768. >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='weak')
  1769. 80.0
  1770. The average between the weak and the strict scores is:
  1771. >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='mean')
  1772. 60.0
  1773. Score arrays (of any dimensionality) are supported:
  1774. >>> stats.percentileofscore([1, 2, 3, 3, 4], [2, 3])
  1775. array([40., 70.])
  1776. The inputs can be infinite:
  1777. >>> stats.percentileofscore([-np.inf, 0, 1, np.inf], [1, 2, np.inf])
  1778. array([75., 75., 100.])
  1779. If `a` is empty, then the resulting percentiles are all `nan`:
  1780. >>> stats.percentileofscore([], [1, 2])
  1781. array([nan, nan])
  1782. """
  1783. a = np.asarray(a)
  1784. score = np.asarray(score)
  1785. if a.ndim != 1:
  1786. raise ValueError("`a` must be 1-dimensional.")
  1787. n = len(a)
  1788. # Nan treatment
  1789. cna = _contains_nan(a, nan_policy)
  1790. cns = _contains_nan(score, nan_policy)
  1791. if cns:
  1792. # If a score is nan, then the output should be nan
  1793. # (also if nan_policy is "omit", because it only applies to `a`)
  1794. score = ma.masked_where(np.isnan(score), score)
  1795. if cna:
  1796. if nan_policy == "omit":
  1797. # Don't count nans
  1798. a = ma.masked_where(np.isnan(a), a)
  1799. n = a.count()
  1800. if nan_policy == "propagate":
  1801. # All outputs should be nans
  1802. n = 0
  1803. # Cannot compare to empty list ==> nan
  1804. if n == 0:
  1805. perct = np.full_like(score, np.nan, dtype=np.float64)
  1806. else:
  1807. # Prepare broadcasting
  1808. score = score[..., None]
  1809. def count(x):
  1810. return np.count_nonzero(x, -1)
  1811. # Main computations/logic
  1812. if kind == 'rank':
  1813. left = count(a < score)
  1814. right = count(a <= score)
  1815. plus1 = left < right
  1816. perct = (left + right + plus1) * (50.0 / n)
  1817. elif kind == 'strict':
  1818. perct = count(a < score) * (100.0 / n)
  1819. elif kind == 'weak':
  1820. perct = count(a <= score) * (100.0 / n)
  1821. elif kind == 'mean':
  1822. left = count(a < score)
  1823. right = count(a <= score)
  1824. perct = (left + right) * (50.0 / n)
  1825. else:
  1826. raise ValueError(
  1827. "kind can only be 'rank', 'strict', 'weak' or 'mean'")
  1828. # Re-insert nan values
  1829. perct = ma.filled(perct, np.nan)
  1830. if perct.ndim == 0:
  1831. return perct[()]
  1832. return perct
  1833. HistogramResult = namedtuple('HistogramResult',
  1834. ('count', 'lowerlimit', 'binsize', 'extrapoints'))
  1835. def _histogram(a, numbins=10, defaultlimits=None, weights=None,
  1836. printextras=False):
  1837. """Create a histogram.
  1838. Separate the range into several bins and return the number of instances
  1839. in each bin.
  1840. Parameters
  1841. ----------
  1842. a : array_like
  1843. Array of scores which will be put into bins.
  1844. numbins : int, optional
  1845. The number of bins to use for the histogram. Default is 10.
  1846. defaultlimits : tuple (lower, upper), optional
  1847. The lower and upper values for the range of the histogram.
  1848. If no value is given, a range slightly larger than the range of the
  1849. values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
  1850. where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
  1851. weights : array_like, optional
  1852. The weights for each value in `a`. Default is None, which gives each
  1853. value a weight of 1.0
  1854. printextras : bool, optional
  1855. If True, if there are extra points (i.e. the points that fall outside
  1856. the bin limits) a warning is raised saying how many of those points
  1857. there are. Default is False.
  1858. Returns
  1859. -------
  1860. count : ndarray
  1861. Number of points (or sum of weights) in each bin.
  1862. lowerlimit : float
  1863. Lowest value of histogram, the lower limit of the first bin.
  1864. binsize : float
  1865. The size of the bins (all bins have the same size).
  1866. extrapoints : int
  1867. The number of points outside the range of the histogram.
  1868. See Also
  1869. --------
  1870. numpy.histogram
  1871. Notes
  1872. -----
  1873. This histogram is based on numpy's histogram but has a larger range by
  1874. default if default limits is not set.
  1875. """
  1876. a = np.ravel(a)
  1877. if defaultlimits is None:
  1878. if a.size == 0:
  1879. # handle empty arrays. Undetermined range, so use 0-1.
  1880. defaultlimits = (0, 1)
  1881. else:
  1882. # no range given, so use values in `a`
  1883. data_min = a.min()
  1884. data_max = a.max()
  1885. # Have bins extend past min and max values slightly
  1886. s = (data_max - data_min) / (2. * (numbins - 1.))
  1887. defaultlimits = (data_min - s, data_max + s)
  1888. # use numpy's histogram method to compute bins
  1889. hist, bin_edges = np.histogram(a, bins=numbins, range=defaultlimits,
  1890. weights=weights)
  1891. # hist are not always floats, convert to keep with old output
  1892. hist = np.array(hist, dtype=float)
  1893. # fixed width for bins is assumed, as numpy's histogram gives
  1894. # fixed width bins for int values for 'bins'
  1895. binsize = bin_edges[1] - bin_edges[0]
  1896. # calculate number of extra points
  1897. extrapoints = len([v for v in a
  1898. if defaultlimits[0] > v or v > defaultlimits[1]])
  1899. if extrapoints > 0 and printextras:
  1900. warnings.warn(f"Points outside given histogram range = {extrapoints}",
  1901. stacklevel=3,)
  1902. return HistogramResult(hist, defaultlimits[0], binsize, extrapoints)
  1903. CumfreqResult = namedtuple('CumfreqResult',
  1904. ('cumcount', 'lowerlimit', 'binsize',
  1905. 'extrapoints'))
  1906. @xp_capabilities(np_only=True)
  1907. def cumfreq(a, numbins=10, defaultreallimits=None, weights=None):
  1908. """Return a cumulative frequency histogram, using the histogram function.
  1909. A cumulative histogram is a mapping that counts the cumulative number of
  1910. observations in all of the bins up to the specified bin.
  1911. Parameters
  1912. ----------
  1913. a : array_like
  1914. Input array.
  1915. numbins : int, optional
  1916. The number of bins to use for the histogram. Default is 10.
  1917. defaultreallimits : tuple (lower, upper), optional
  1918. The lower and upper values for the range of the histogram.
  1919. If no value is given, a range slightly larger than the range of the
  1920. values in `a` is used. Specifically ``(a.min() - s, a.max() + s)``,
  1921. where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
  1922. weights : array_like, optional
  1923. The weights for each value in `a`. Default is None, which gives each
  1924. value a weight of 1.0
  1925. Returns
  1926. -------
  1927. cumcount : ndarray
  1928. Binned values of cumulative frequency.
  1929. lowerlimit : float
  1930. Lower real limit
  1931. binsize : float
  1932. Width of each bin.
  1933. extrapoints : int
  1934. Extra points.
  1935. Examples
  1936. --------
  1937. >>> import numpy as np
  1938. >>> import matplotlib.pyplot as plt
  1939. >>> from scipy import stats
  1940. >>> rng = np.random.default_rng()
  1941. >>> x = [1, 4, 2, 1, 3, 1]
  1942. >>> res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5))
  1943. >>> res.cumcount
  1944. array([ 1., 2., 3., 3.])
  1945. >>> res.extrapoints
  1946. 3
  1947. Create a normal distribution with 1000 random values
  1948. >>> samples = stats.norm.rvs(size=1000, random_state=rng)
  1949. Calculate cumulative frequencies
  1950. >>> res = stats.cumfreq(samples, numbins=25)
  1951. Calculate space of values for x
  1952. >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.cumcount.size,
  1953. ... res.cumcount.size + 1)
  1954. Plot histogram and cumulative histogram
  1955. >>> fig = plt.figure(figsize=(10, 4))
  1956. >>> ax1 = fig.add_subplot(1, 2, 1)
  1957. >>> ax2 = fig.add_subplot(1, 2, 2)
  1958. >>> ax1.hist(samples, bins=25)
  1959. >>> ax1.set_title('Histogram')
  1960. >>> ax2.bar(x[:-1], res.cumcount, width=res.binsize, align='edge')
  1961. >>> ax2.set_title('Cumulative histogram')
  1962. >>> ax2.set_xlim([x.min(), x.max()])
  1963. >>> plt.show()
  1964. """
  1965. h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
  1966. cumhist = np.cumsum(h * 1, axis=0)
  1967. return CumfreqResult(cumhist, l, b, e)
  1968. RelfreqResult = namedtuple('RelfreqResult',
  1969. ('frequency', 'lowerlimit', 'binsize',
  1970. 'extrapoints'))
  1971. @xp_capabilities(np_only=True)
  1972. def relfreq(a, numbins=10, defaultreallimits=None, weights=None):
  1973. """Return a relative frequency histogram, using the histogram function.
  1974. A relative frequency histogram is a mapping of the number of
  1975. observations in each of the bins relative to the total of observations.
  1976. Parameters
  1977. ----------
  1978. a : array_like
  1979. Input array.
  1980. numbins : int, optional
  1981. The number of bins to use for the histogram. Default is 10.
  1982. defaultreallimits : tuple (lower, upper), optional
  1983. The lower and upper values for the range of the histogram.
  1984. If no value is given, a range slightly larger than the range of the
  1985. values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
  1986. where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
  1987. weights : array_like, optional
  1988. The weights for each value in `a`. Default is None, which gives each
  1989. value a weight of 1.0
  1990. Returns
  1991. -------
  1992. frequency : ndarray
  1993. Binned values of relative frequency.
  1994. lowerlimit : float
  1995. Lower real limit.
  1996. binsize : float
  1997. Width of each bin.
  1998. extrapoints : int
  1999. Extra points.
  2000. Examples
  2001. --------
  2002. >>> import numpy as np
  2003. >>> import matplotlib.pyplot as plt
  2004. >>> from scipy import stats
  2005. >>> rng = np.random.default_rng()
  2006. >>> a = np.array([2, 4, 1, 2, 3, 2])
  2007. >>> res = stats.relfreq(a, numbins=4)
  2008. >>> res.frequency
  2009. array([ 0.16666667, 0.5 , 0.16666667, 0.16666667])
  2010. >>> np.sum(res.frequency) # relative frequencies should add up to 1
  2011. 1.0
  2012. Create a normal distribution with 1000 random values
  2013. >>> samples = stats.norm.rvs(size=1000, random_state=rng)
  2014. Calculate relative frequencies
  2015. >>> res = stats.relfreq(samples, numbins=25)
  2016. Calculate space of values for x
  2017. >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size,
  2018. ... res.frequency.size)
  2019. Plot relative frequency histogram
  2020. >>> fig = plt.figure(figsize=(5, 4))
  2021. >>> ax = fig.add_subplot(1, 1, 1)
  2022. >>> ax.bar(x, res.frequency, width=res.binsize)
  2023. >>> ax.set_title('Relative frequency histogram')
  2024. >>> ax.set_xlim([x.min(), x.max()])
  2025. >>> plt.show()
  2026. """
  2027. a = np.asanyarray(a)
  2028. h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
  2029. h = h / a.shape[0]
  2030. return RelfreqResult(h, l, b, e)
  2031. #####################################
  2032. # VARIABILITY FUNCTIONS #
  2033. #####################################
  2034. @xp_capabilities(np_only=True)
  2035. def obrientransform(*samples):
  2036. """Compute the O'Brien transform on input data (any number of arrays).
  2037. Used to test for homogeneity of variance prior to running one-way stats.
  2038. Each array in ``*samples`` is one level of a factor.
  2039. If `f_oneway` is run on the transformed data and found significant,
  2040. the variances are unequal. From Maxwell and Delaney [1]_, p.112.
  2041. Parameters
  2042. ----------
  2043. sample1, sample2, ... : array_like
  2044. Any number of arrays.
  2045. Returns
  2046. -------
  2047. obrientransform : ndarray
  2048. Transformed data for use in an ANOVA. The first dimension
  2049. of the result corresponds to the sequence of transformed
  2050. arrays. If the arrays given are all 1-D of the same length,
  2051. the return value is a 2-D array; otherwise it is a 1-D array
  2052. of type object, with each element being an ndarray.
  2053. Raises
  2054. ------
  2055. ValueError
  2056. If the mean of the transformed data is not equal to the original
  2057. variance, indicating a lack of convergence in the O'Brien transform.
  2058. References
  2059. ----------
  2060. .. [1] S. E. Maxwell and H. D. Delaney, "Designing Experiments and
  2061. Analyzing Data: A Model Comparison Perspective", Wadsworth, 1990.
  2062. Examples
  2063. --------
  2064. We'll test the following data sets for differences in their variance.
  2065. >>> x = [10, 11, 13, 9, 7, 12, 12, 9, 10]
  2066. >>> y = [13, 21, 5, 10, 8, 14, 10, 12, 7, 15]
  2067. Apply the O'Brien transform to the data.
  2068. >>> from scipy.stats import obrientransform
  2069. >>> tx, ty = obrientransform(x, y)
  2070. Use `scipy.stats.f_oneway` to apply a one-way ANOVA test to the
  2071. transformed data.
  2072. >>> from scipy.stats import f_oneway
  2073. >>> F, p = f_oneway(tx, ty)
  2074. >>> p
  2075. 0.1314139477040335
  2076. If we require that ``p < 0.05`` for significance, we cannot conclude
  2077. that the variances are different.
  2078. """
  2079. TINY = np.sqrt(np.finfo(float).eps)
  2080. # `arrays` will hold the transformed arguments.
  2081. arrays = []
  2082. sLast = None
  2083. for sample in samples:
  2084. a = np.asarray(sample)
  2085. n = len(a)
  2086. mu = np.mean(a)
  2087. sq = (a - mu)**2
  2088. sumsq = sq.sum()
  2089. # The O'Brien transform.
  2090. t = ((n - 1.5) * n * sq - 0.5 * sumsq) / ((n - 1) * (n - 2))
  2091. # Check that the mean of the transformed data is equal to the
  2092. # original variance.
  2093. var = sumsq / (n - 1)
  2094. if abs(var - np.mean(t)) > TINY:
  2095. raise ValueError('Lack of convergence in obrientransform.')
  2096. arrays.append(t)
  2097. sLast = a.shape
  2098. if sLast:
  2099. for arr in arrays[:-1]:
  2100. if sLast != arr.shape:
  2101. return np.array(arrays, dtype=object)
  2102. return np.array(arrays)
  2103. @xp_capabilities(jax_jit=False, allow_dask_compute=True)
  2104. @_axis_nan_policy_factory(
  2105. lambda x: x, result_to_tuple=lambda x, _: (x,), n_outputs=1, too_small=1
  2106. )
  2107. def sem(a, axis=0, ddof=1, nan_policy='propagate'):
  2108. """Compute standard error of the mean.
  2109. Calculate the standard error of the mean (or standard error of
  2110. measurement) of the values in the input array.
  2111. Parameters
  2112. ----------
  2113. a : array_like
  2114. An array containing the values for which the standard error is
  2115. returned. Must contain at least two observations.
  2116. axis : int or None, optional
  2117. Axis along which to operate. Default is 0. If None, compute over
  2118. the whole array `a`.
  2119. ddof : int, optional
  2120. Delta degrees-of-freedom. How many degrees of freedom to adjust
  2121. for bias in limited samples relative to the population estimate
  2122. of variance. Defaults to 1.
  2123. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2124. Defines how to handle when input contains nan.
  2125. The following options are available (default is 'propagate'):
  2126. * 'propagate': returns nan
  2127. * 'raise': throws an error
  2128. * 'omit': performs the calculations ignoring nan values
  2129. Returns
  2130. -------
  2131. s : ndarray or float
  2132. The standard error of the mean in the sample(s), along the input axis.
  2133. Notes
  2134. -----
  2135. The default value for `ddof` is different to the default (0) used by other
  2136. ddof containing routines, such as np.std and np.nanstd.
  2137. Examples
  2138. --------
  2139. Find standard error along the first axis:
  2140. >>> import numpy as np
  2141. >>> from scipy import stats
  2142. >>> a = np.arange(20).reshape(5,4)
  2143. >>> stats.sem(a)
  2144. array([ 2.8284, 2.8284, 2.8284, 2.8284])
  2145. Find standard error across the whole array, using n degrees of freedom:
  2146. >>> stats.sem(a, axis=None, ddof=0)
  2147. 1.2893796958227628
  2148. """
  2149. xp = array_namespace(a)
  2150. if axis is None:
  2151. a = xp.reshape(a, (-1,))
  2152. axis = 0
  2153. a = xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp)
  2154. n = _length_nonmasked(a, axis, xp=xp)
  2155. s = xp.std(a, axis=axis, correction=ddof) / n**0.5
  2156. return s
  2157. def _isconst(x):
  2158. """
  2159. Check if all values in x are the same. nans are ignored.
  2160. x must be a 1d array.
  2161. The return value is a 1d array with length 1, so it can be used
  2162. in np.apply_along_axis.
  2163. """
  2164. y = x[~np.isnan(x)]
  2165. if y.size == 0:
  2166. return np.array([True])
  2167. else:
  2168. return (y[0] == y).all(keepdims=True)
  2169. @xp_capabilities()
  2170. def zscore(a, axis=0, ddof=0, nan_policy='propagate'):
  2171. """
  2172. Compute the z score.
  2173. Compute the z score of each value in the sample, relative to the
  2174. sample mean and standard deviation.
  2175. Parameters
  2176. ----------
  2177. a : array_like
  2178. An array like object containing the sample data.
  2179. axis : int or None, optional
  2180. Axis along which to operate. Default is 0. If None, compute over
  2181. the whole array `a`.
  2182. ddof : int, optional
  2183. Degrees of freedom correction in the calculation of the
  2184. standard deviation. Default is 0.
  2185. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2186. Defines how to handle when input contains nan. 'propagate' returns nan,
  2187. 'raise' throws an error, 'omit' performs the calculations ignoring nan
  2188. values. Default is 'propagate'. Note that when the value is 'omit',
  2189. nans in the input also propagate to the output, but they do not affect
  2190. the z-scores computed for the non-nan values.
  2191. Returns
  2192. -------
  2193. zscore : array_like
  2194. The z-scores, standardized by mean and standard deviation of
  2195. input array `a`.
  2196. See Also
  2197. --------
  2198. numpy.mean : Arithmetic average
  2199. numpy.std : Arithmetic standard deviation
  2200. scipy.stats.gzscore : Geometric standard score
  2201. Notes
  2202. -----
  2203. This function preserves ndarray subclasses, and works also with
  2204. matrices and masked arrays (it uses `asanyarray` instead of
  2205. `asarray` for parameters).
  2206. References
  2207. ----------
  2208. .. [1] "Standard score", *Wikipedia*,
  2209. https://en.wikipedia.org/wiki/Standard_score.
  2210. .. [2] Huck, S. W., Cross, T. L., Clark, S. B, "Overcoming misconceptions
  2211. about Z-scores", Teaching Statistics, vol. 8, pp. 38-40, 1986
  2212. Examples
  2213. --------
  2214. >>> import numpy as np
  2215. >>> a = np.array([ 0.7972, 0.0767, 0.4383, 0.7866, 0.8091,
  2216. ... 0.1954, 0.6307, 0.6599, 0.1065, 0.0508])
  2217. >>> from scipy import stats
  2218. >>> stats.zscore(a)
  2219. array([ 1.1273, -1.247 , -0.0552, 1.0923, 1.1664, -0.8559, 0.5786,
  2220. 0.6748, -1.1488, -1.3324])
  2221. Computing along a specified axis, using n-1 degrees of freedom
  2222. (``ddof=1``) to calculate the standard deviation:
  2223. >>> b = np.array([[ 0.3148, 0.0478, 0.6243, 0.4608],
  2224. ... [ 0.7149, 0.0775, 0.6072, 0.9656],
  2225. ... [ 0.6341, 0.1403, 0.9759, 0.4064],
  2226. ... [ 0.5918, 0.6948, 0.904 , 0.3721],
  2227. ... [ 0.0921, 0.2481, 0.1188, 0.1366]])
  2228. >>> stats.zscore(b, axis=1, ddof=1)
  2229. array([[-0.19264823, -1.28415119, 1.07259584, 0.40420358],
  2230. [ 0.33048416, -1.37380874, 0.04251374, 1.00081084],
  2231. [ 0.26796377, -1.12598418, 1.23283094, -0.37481053],
  2232. [-0.22095197, 0.24468594, 1.19042819, -1.21416216],
  2233. [-0.82780366, 1.4457416 , -0.43867764, -0.1792603 ]])
  2234. An example with ``nan_policy='omit'``:
  2235. >>> x = np.array([[25.11, 30.10, np.nan, 32.02, 43.15],
  2236. ... [14.95, 16.06, 121.25, 94.35, 29.81]])
  2237. >>> stats.zscore(x, axis=1, nan_policy='omit')
  2238. array([[-1.13490897, -0.37830299, nan, -0.08718406, 1.60039602],
  2239. [-0.91611681, -0.89090508, 1.4983032 , 0.88731639, -0.5785977 ]])
  2240. """
  2241. return zmap(a, a, axis=axis, ddof=ddof, nan_policy=nan_policy)
  2242. @xp_capabilities()
  2243. def gzscore(a, *, axis=0, ddof=0, nan_policy='propagate'):
  2244. """
  2245. Compute the geometric standard score.
  2246. Compute the geometric z score of each strictly positive value in the
  2247. sample, relative to the geometric mean and standard deviation.
  2248. Mathematically the geometric z score can be evaluated as::
  2249. gzscore = log(a/gmu) / log(gsigma)
  2250. where ``gmu`` (resp. ``gsigma``) is the geometric mean (resp. standard
  2251. deviation).
  2252. Parameters
  2253. ----------
  2254. a : array_like
  2255. Sample data.
  2256. axis : int or None, optional
  2257. Axis along which to operate. Default is 0. If None, compute over
  2258. the whole array `a`.
  2259. ddof : int, optional
  2260. Degrees of freedom correction in the calculation of the
  2261. standard deviation. Default is 0.
  2262. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2263. Defines how to handle when input contains nan. 'propagate' returns nan,
  2264. 'raise' throws an error, 'omit' performs the calculations ignoring nan
  2265. values. Default is 'propagate'. Note that when the value is 'omit',
  2266. nans in the input also propagate to the output, but they do not affect
  2267. the geometric z scores computed for the non-nan values.
  2268. Returns
  2269. -------
  2270. gzscore : array_like
  2271. The geometric z scores, standardized by geometric mean and geometric
  2272. standard deviation of input array `a`.
  2273. See Also
  2274. --------
  2275. gmean : Geometric mean
  2276. gstd : Geometric standard deviation
  2277. zscore : Standard score
  2278. Notes
  2279. -----
  2280. This function preserves ndarray subclasses, and works also with
  2281. matrices and masked arrays (it uses ``asanyarray`` instead of
  2282. ``asarray`` for parameters).
  2283. .. versionadded:: 1.8
  2284. References
  2285. ----------
  2286. .. [1] "Geometric standard score", *Wikipedia*,
  2287. https://en.wikipedia.org/wiki/Geometric_standard_deviation#Geometric_standard_score.
  2288. Examples
  2289. --------
  2290. Draw samples from a log-normal distribution:
  2291. >>> import numpy as np
  2292. >>> from scipy.stats import zscore, gzscore
  2293. >>> import matplotlib.pyplot as plt
  2294. >>> rng = np.random.default_rng()
  2295. >>> mu, sigma = 3., 1. # mean and standard deviation
  2296. >>> x = rng.lognormal(mu, sigma, size=500)
  2297. Display the histogram of the samples:
  2298. >>> fig, ax = plt.subplots()
  2299. >>> ax.hist(x, 50)
  2300. >>> plt.show()
  2301. Display the histogram of the samples standardized by the classical zscore.
  2302. Distribution is rescaled but its shape is unchanged.
  2303. >>> fig, ax = plt.subplots()
  2304. >>> ax.hist(zscore(x), 50)
  2305. >>> plt.show()
  2306. Demonstrate that the distribution of geometric zscores is rescaled and
  2307. quasinormal:
  2308. >>> fig, ax = plt.subplots()
  2309. >>> ax.hist(gzscore(x), 50)
  2310. >>> plt.show()
  2311. """
  2312. xp = array_namespace(a)
  2313. a = xp_promote(a, force_floating=True, xp=xp)
  2314. log = ma.log if isinstance(a, ma.MaskedArray) else xp.log
  2315. return zscore(log(a), axis=axis, ddof=ddof, nan_policy=nan_policy)
  2316. @xp_capabilities()
  2317. def zmap(scores, compare, axis=0, ddof=0, nan_policy='propagate'):
  2318. """
  2319. Calculate the relative z-scores.
  2320. Return an array of z-scores, i.e., scores that are standardized to
  2321. zero mean and unit variance, where mean and variance are calculated
  2322. from the comparison array.
  2323. Parameters
  2324. ----------
  2325. scores : array_like
  2326. The input for which z-scores are calculated.
  2327. compare : array_like
  2328. The input from which the mean and standard deviation of the
  2329. normalization are taken; assumed to have the same dimension as
  2330. `scores`.
  2331. axis : int or None, optional
  2332. Axis over which mean and variance of `compare` are calculated.
  2333. Default is 0. If None, compute over the whole array `scores`.
  2334. ddof : int, optional
  2335. Degrees of freedom correction in the calculation of the
  2336. standard deviation. Default is 0.
  2337. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2338. Defines how to handle the occurrence of nans in `compare`.
  2339. 'propagate' returns nan, 'raise' raises an exception, 'omit'
  2340. performs the calculations ignoring nan values. Default is
  2341. 'propagate'. Note that when the value is 'omit', nans in `scores`
  2342. also propagate to the output, but they do not affect the z-scores
  2343. computed for the non-nan values.
  2344. Returns
  2345. -------
  2346. zscore : array_like
  2347. Z-scores, in the same shape as `scores`.
  2348. Notes
  2349. -----
  2350. This function preserves ndarray subclasses, and works also with
  2351. matrices and masked arrays (it uses `asanyarray` instead of
  2352. `asarray` for parameters).
  2353. Examples
  2354. --------
  2355. >>> from scipy.stats import zmap
  2356. >>> a = [0.5, 2.0, 2.5, 3]
  2357. >>> b = [0, 1, 2, 3, 4]
  2358. >>> zmap(a, b)
  2359. array([-1.06066017, 0. , 0.35355339, 0.70710678])
  2360. """
  2361. # The docstring explicitly states that it preserves subclasses.
  2362. # Let's table deprecating that and just get the array API version
  2363. # working.
  2364. like_zscore = (scores is compare)
  2365. xp = array_namespace(scores, compare)
  2366. scores, compare = xp_promote(scores, compare, force_floating=True, xp=xp)
  2367. with warnings.catch_warnings():
  2368. if like_zscore: # zscore should not emit SmallSampleWarning
  2369. warnings.simplefilter('ignore', SmallSampleWarning)
  2370. mn = _xp_mean(compare, axis=axis, keepdims=True, nan_policy=nan_policy)
  2371. std = _xp_var(compare, axis=axis, correction=ddof,
  2372. keepdims=True, nan_policy=nan_policy)**0.5
  2373. with np.errstate(invalid='ignore', divide='ignore'):
  2374. z = _demean(scores, mn, axis, xp=xp, precision_warning=False) / std
  2375. # If we know that scores and compare are identical, we can infer that
  2376. # some slices should have NaNs.
  2377. if like_zscore:
  2378. eps = xp.finfo(z.dtype).eps
  2379. zero = std <= xp.abs(eps * mn)
  2380. zero = xp.broadcast_to(zero, z.shape)
  2381. z = xpx.at(z, zero).set(xp.nan)
  2382. return z
  2383. @xp_capabilities()
  2384. def gstd(a, axis=0, ddof=1, *, keepdims=False, nan_policy='propagate'):
  2385. r"""
  2386. Calculate the geometric standard deviation of an array.
  2387. The geometric standard deviation describes the spread of a set of numbers
  2388. where the geometric mean is preferred. It is a multiplicative factor, and
  2389. so a dimensionless quantity.
  2390. It is defined as the exponential of the standard deviation of the
  2391. natural logarithms of the observations.
  2392. Parameters
  2393. ----------
  2394. a : array_like
  2395. An array containing finite, strictly positive, real numbers.
  2396. axis : int, tuple or None, optional
  2397. Axis along which to operate. Default is 0. If None, compute over
  2398. the whole array `a`.
  2399. ddof : int, optional
  2400. Degree of freedom correction in the calculation of the
  2401. geometric standard deviation. Default is 1.
  2402. keepdims : boolean, optional
  2403. If this is set to ``True``, the axes which are reduced are left
  2404. in the result as dimensions with length one. With this option,
  2405. the result will broadcast correctly against the input array.
  2406. nan_policy : {'propagate', 'omit', 'raise'}, default: 'propagate'
  2407. Defines how to handle input NaNs.
  2408. - ``propagate``: if a NaN is present in the axis slice (e.g. row) along
  2409. which the statistic is computed, the corresponding entry of the output
  2410. will be NaN.
  2411. - ``omit``: NaNs will be omitted when performing the calculation.
  2412. If insufficient data remains in the axis slice along which the
  2413. statistic is computed, the corresponding entry of the output will be
  2414. NaN.
  2415. - ``raise``: if a NaN is present, a ``ValueError`` will be raised.
  2416. Returns
  2417. -------
  2418. gstd : ndarray or float
  2419. An array of the geometric standard deviation. If `axis` is None or `a`
  2420. is a 1d array a float is returned.
  2421. See Also
  2422. --------
  2423. gmean : Geometric mean
  2424. numpy.std : Standard deviation
  2425. gzscore : Geometric standard score
  2426. Notes
  2427. -----
  2428. Mathematically, the sample geometric standard deviation :math:`s_G` can be
  2429. defined in terms of the natural logarithms of the observations
  2430. :math:`y_i = \log(x_i)`:
  2431. .. math::
  2432. s_G = \exp(s), \quad s = \sqrt{\frac{1}{n - d} \sum_{i=1}^n (y_i - \bar y)^2}
  2433. where :math:`n` is the number of observations, :math:`d` is the adjustment `ddof`
  2434. to the degrees of freedom, and :math:`\bar y` denotes the mean of the natural
  2435. logarithms of the observations. Note that the default ``ddof=1`` is different from
  2436. the default value used by similar functions, such as `numpy.std` and `numpy.var`.
  2437. When an observation is infinite, the geometric standard deviation is
  2438. NaN (undefined). Non-positive observations will also produce NaNs in the
  2439. output because the *natural* logarithm (as opposed to the *complex*
  2440. logarithm) is defined and finite only for positive reals.
  2441. The geometric standard deviation is sometimes confused with the exponential
  2442. of the standard deviation, ``exp(std(a))``. Instead, the geometric standard
  2443. deviation is ``exp(std(log(a)))``.
  2444. References
  2445. ----------
  2446. .. [1] "Geometric standard deviation", *Wikipedia*,
  2447. https://en.wikipedia.org/wiki/Geometric_standard_deviation.
  2448. .. [2] Kirkwood, T. B., "Geometric means and measures of dispersion",
  2449. Biometrics, vol. 35, pp. 908-909, 1979
  2450. Examples
  2451. --------
  2452. Find the geometric standard deviation of a log-normally distributed sample.
  2453. Note that the standard deviation of the distribution is one; on a
  2454. log scale this evaluates to approximately ``exp(1)``.
  2455. >>> import numpy as np
  2456. >>> from scipy.stats import gstd
  2457. >>> rng = np.random.default_rng()
  2458. >>> sample = rng.lognormal(mean=0, sigma=1, size=1000)
  2459. >>> gstd(sample)
  2460. 2.810010162475324
  2461. Compute the geometric standard deviation of a multidimensional array and
  2462. of a given axis.
  2463. >>> a = np.arange(1, 25).reshape(2, 3, 4)
  2464. >>> gstd(a, axis=None)
  2465. 2.2944076136018947
  2466. >>> gstd(a, axis=2)
  2467. array([[1.82424757, 1.22436866, 1.13183117],
  2468. [1.09348306, 1.07244798, 1.05914985]])
  2469. >>> gstd(a, axis=(1,2))
  2470. array([2.12939215, 1.22120169])
  2471. """
  2472. xp = array_namespace(a)
  2473. a = xp_promote(a, force_floating=True, xp=xp)
  2474. kwargs = dict(axis=axis, correction=ddof, keepdims=keepdims, nan_policy=nan_policy)
  2475. with np.errstate(invalid='ignore', divide='ignore'):
  2476. res = xp.exp(_xp_var(xp.log(a), **kwargs)**0.5)
  2477. if not is_lazy_array(a) and xp.any(a <= 0):
  2478. message = ("The geometric standard deviation is only defined if all elements "
  2479. "are greater than or equal to zero; otherwise, the result is NaN.")
  2480. warnings.warn(message, RuntimeWarning, stacklevel=2)
  2481. return res
  2482. # Private dictionary initialized only once at module level
  2483. # See https://en.wikipedia.org/wiki/Robust_measures_of_scale
  2484. _scale_conversions = {'normal': float(special.erfinv(0.5) * 2.0 * math.sqrt(2.0))}
  2485. @xp_capabilities(skip_backends=[('dask.array', 'no quantile (take_along_axis)'),
  2486. ('jax.numpy', 'lazy -> no _axis_nan_policy)')])
  2487. @_axis_nan_policy_factory(
  2488. lambda x: x, result_to_tuple=lambda x, _: (x,), n_outputs=1,
  2489. default_axis=None, override={'nan_propagation': False}
  2490. )
  2491. def iqr(x, axis=None, rng=(25, 75), scale=1.0, nan_policy='propagate',
  2492. interpolation='linear', keepdims=False):
  2493. r"""
  2494. Compute the interquartile range of the data along the specified axis.
  2495. The interquartile range (IQR) is the difference between the 75th and
  2496. 25th percentile of the data. It is a measure of the dispersion
  2497. similar to standard deviation or variance, but is much more robust
  2498. against outliers [2]_.
  2499. The ``rng`` parameter allows this function to compute other
  2500. percentile ranges than the actual IQR. For example, setting
  2501. ``rng=(0, 100)`` is equivalent to `numpy.ptp`.
  2502. The IQR of an empty array is `np.nan`.
  2503. .. versionadded:: 0.18.0
  2504. Parameters
  2505. ----------
  2506. x : array_like
  2507. Input array or object that can be converted to an array.
  2508. axis : int or sequence of int, optional
  2509. Axis along which the range is computed. The default is to
  2510. compute the IQR for the entire array.
  2511. rng : Two-element sequence containing floats in range of [0,100] optional
  2512. Percentiles over which to compute the range. Each must be
  2513. between 0 and 100, inclusive. The default is the true IQR:
  2514. ``(25, 75)``. The order of the elements is not important.
  2515. scale : scalar or str or array_like of reals, optional
  2516. The numerical value of scale will be divided out of the final
  2517. result. The following string value is also recognized:
  2518. * 'normal' : Scale by
  2519. :math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`.
  2520. The default is 1.0.
  2521. Array-like `scale` of real dtype is also allowed, as long
  2522. as it broadcasts correctly to the output such that
  2523. ``out / scale`` is a valid operation. The output dimensions
  2524. depend on the input array, `x`, the `axis` argument, and the
  2525. `keepdims` flag.
  2526. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2527. Defines how to handle when input contains nan.
  2528. The following options are available (default is 'propagate'):
  2529. * 'propagate': returns nan
  2530. * 'raise': throws an error
  2531. * 'omit': performs the calculations ignoring nan values
  2532. interpolation : str, optional
  2533. Specifies the interpolation method to use when the percentile
  2534. boundaries lie between two data points ``i`` and ``j``.
  2535. The following options are available (default is 'linear'):
  2536. * 'linear': ``i + (j - i)*fraction``, where ``fraction`` is the
  2537. fractional part of the index surrounded by ``i`` and ``j``.
  2538. * 'lower': ``i``.
  2539. * 'higher': ``j``.
  2540. * 'nearest': ``i`` or ``j`` whichever is nearest.
  2541. * 'midpoint': ``(i + j)/2``.
  2542. For NumPy >= 1.22.0, the additional options provided by the ``method``
  2543. keyword of `numpy.percentile` are also valid.
  2544. keepdims : bool, optional
  2545. If this is set to True, the reduced axes are left in the
  2546. result as dimensions with size one. With this option, the result
  2547. will broadcast correctly against the original array `x`.
  2548. Returns
  2549. -------
  2550. iqr : scalar or ndarray
  2551. If ``axis=None``, a scalar is returned. If the input contains
  2552. integers or floats of smaller precision than ``np.float64``, then the
  2553. output data-type is ``np.float64``. Otherwise, the output data-type is
  2554. the same as that of the input.
  2555. See Also
  2556. --------
  2557. numpy.std, numpy.var
  2558. References
  2559. ----------
  2560. .. [1] "Interquartile range" https://en.wikipedia.org/wiki/Interquartile_range
  2561. .. [2] "Robust measures of scale" https://en.wikipedia.org/wiki/Robust_measures_of_scale
  2562. .. [3] "Quantile" https://en.wikipedia.org/wiki/Quantile
  2563. Examples
  2564. --------
  2565. >>> import numpy as np
  2566. >>> from scipy.stats import iqr
  2567. >>> x = np.array([[10, 7, 4], [3, 2, 1]])
  2568. >>> x
  2569. array([[10, 7, 4],
  2570. [ 3, 2, 1]])
  2571. >>> iqr(x)
  2572. 4.0
  2573. >>> iqr(x, axis=0)
  2574. array([ 3.5, 2.5, 1.5])
  2575. >>> iqr(x, axis=1)
  2576. array([ 3., 1.])
  2577. >>> iqr(x, axis=1, keepdims=True)
  2578. array([[ 3.],
  2579. [ 1.]])
  2580. """
  2581. xp = array_namespace(x)
  2582. # An error may be raised here, so fail-fast, before doing lengthy
  2583. # computations, even though `scale` is not used until later
  2584. if isinstance(scale, str):
  2585. scale_key = scale.lower()
  2586. if scale_key not in _scale_conversions:
  2587. raise ValueError(f"{scale} not a valid scale for `iqr`")
  2588. scale = _scale_conversions[scale_key]
  2589. if len(rng) != 2:
  2590. raise TypeError("`rng` must be a two element sequence.")
  2591. if np.isnan(rng).any(): # OK to use NumPy; this shouldn't be an array
  2592. raise ValueError("`rng` must not contain NaNs.")
  2593. rng = (rng[0]/100, rng[1]/100) if rng[0] < rng[1] else (rng[1]/100, rng[0]/100)
  2594. if rng[0] < 0 or rng[1] > 1:
  2595. raise ValueError("Elements of `rng` must be in the range [0, 100].")
  2596. if interpolation in {'lower', 'midpoint', 'higher', 'nearest'}:
  2597. interpolation = '_' + interpolation
  2598. rng = xp.asarray(rng, dtype=xp_result_type(x, force_floating=True, xp=xp))
  2599. pct = stats.quantile(x, rng, axis=-1, method=interpolation, keepdims=True)
  2600. out = pct[..., 1:2] - pct[..., 0:1]
  2601. if scale != 1.0:
  2602. out /= scale
  2603. out = out if keepdims else xp.squeeze(out, axis=-1)
  2604. return out[()] if out.ndim == 0 else out
  2605. def _mad_1d(x, center, nan_policy):
  2606. # Median absolute deviation for 1-d array x.
  2607. # This is a helper function for `median_abs_deviation`; it assumes its
  2608. # arguments have been validated already. In particular, x must be a
  2609. # 1-d numpy array, center must be callable, and if nan_policy is not
  2610. # 'propagate', it is assumed to be 'omit', because 'raise' is handled
  2611. # in `median_abs_deviation`.
  2612. # No warning is generated if x is empty or all nan.
  2613. isnan = np.isnan(x)
  2614. if isnan.any():
  2615. if nan_policy == 'propagate':
  2616. return np.nan
  2617. x = x[~isnan]
  2618. if x.size == 0:
  2619. # MAD of an empty array is nan.
  2620. return np.nan
  2621. # Edge cases have been handled, so do the basic MAD calculation.
  2622. med = center(x)
  2623. mad = np.median(np.abs(x - med))
  2624. return mad
  2625. @xp_capabilities(skip_backends=[('jax.numpy', 'not supported by `quantile`'),
  2626. ('dask.array', 'not supported by `quantile`')])
  2627. @_axis_nan_policy_factory(
  2628. lambda x: x, result_to_tuple=lambda x, _: (x,), n_outputs=1, default_axis=0
  2629. )
  2630. def median_abs_deviation(x, axis=0, center=None, scale=1.0,
  2631. nan_policy='propagate'):
  2632. r"""
  2633. Compute the median absolute deviation of the data along the given axis.
  2634. The median absolute deviation (MAD, [1]_) computes the median over the
  2635. absolute deviations from the median. It is a measure of dispersion
  2636. similar to the standard deviation but more robust to outliers [2]_.
  2637. The MAD of an empty array is ``np.nan``.
  2638. .. versionadded:: 1.5.0
  2639. Parameters
  2640. ----------
  2641. x : array_like
  2642. Input array or object that can be converted to an array.
  2643. axis : int or None, optional
  2644. Axis along which the range is computed. Default is 0. If None, compute
  2645. the MAD over the entire array.
  2646. center : callable, optional
  2647. A function that will return the central value. The default is to use
  2648. np.median. Any user defined function used will need to have the
  2649. function signature ``func(arr, axis)``.
  2650. scale : scalar or str, optional
  2651. The numerical value of scale will be divided out of the final
  2652. result. The default is 1.0. The string "normal" is also accepted,
  2653. and results in `scale` being the inverse of the standard normal
  2654. quantile function at 0.75, which is approximately 0.67449.
  2655. Array-like scale is also allowed, as long as it broadcasts correctly
  2656. to the output such that ``out / scale`` is a valid operation. The
  2657. output dimensions depend on the input array, `x`, and the `axis`
  2658. argument.
  2659. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2660. Defines how to handle when input contains nan.
  2661. The following options are available (default is 'propagate'):
  2662. * 'propagate': returns nan
  2663. * 'raise': throws an error
  2664. * 'omit': performs the calculations ignoring nan values
  2665. Returns
  2666. -------
  2667. mad : scalar or ndarray
  2668. If ``axis=None``, a scalar is returned. If the input contains
  2669. integers or floats of smaller precision than ``np.float64``, then the
  2670. output data-type is ``np.float64``. Otherwise, the output data-type is
  2671. the same as that of the input.
  2672. See Also
  2673. --------
  2674. numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean,
  2675. scipy.stats.tstd, scipy.stats.tvar
  2676. Notes
  2677. -----
  2678. The `center` argument only affects the calculation of the central value
  2679. around which the MAD is calculated. That is, passing in ``center=np.mean``
  2680. will calculate the MAD around the mean - it will not calculate the *mean*
  2681. absolute deviation.
  2682. The input array may contain `inf`, but if `center` returns `inf`, the
  2683. corresponding MAD for that data will be `nan`.
  2684. References
  2685. ----------
  2686. .. [1] "Median absolute deviation",
  2687. https://en.wikipedia.org/wiki/Median_absolute_deviation
  2688. .. [2] "Robust measures of scale",
  2689. https://en.wikipedia.org/wiki/Robust_measures_of_scale
  2690. Examples
  2691. --------
  2692. When comparing the behavior of `median_abs_deviation` with ``np.std``,
  2693. the latter is affected when we change a single value of an array to have an
  2694. outlier value while the MAD hardly changes:
  2695. >>> import numpy as np
  2696. >>> from scipy import stats
  2697. >>> x = stats.norm.rvs(size=100, scale=1, random_state=123456)
  2698. >>> x.std()
  2699. 0.9973906394005013
  2700. >>> stats.median_abs_deviation(x)
  2701. 0.82832610097857
  2702. >>> x[0] = 345.6
  2703. >>> x.std()
  2704. 34.42304872314415
  2705. >>> stats.median_abs_deviation(x)
  2706. 0.8323442311590675
  2707. Axis handling example:
  2708. >>> x = np.array([[10, 7, 4], [3, 2, 1]])
  2709. >>> x
  2710. array([[10, 7, 4],
  2711. [ 3, 2, 1]])
  2712. >>> stats.median_abs_deviation(x)
  2713. array([3.5, 2.5, 1.5])
  2714. >>> stats.median_abs_deviation(x, axis=None)
  2715. 2.0
  2716. Scale normal example:
  2717. >>> x = stats.norm.rvs(size=1000000, scale=2, random_state=123456)
  2718. >>> stats.median_abs_deviation(x)
  2719. 1.3487398527041636
  2720. >>> stats.median_abs_deviation(x, scale='normal')
  2721. 1.9996446978061115
  2722. """
  2723. xp = array_namespace(x)
  2724. xp_median = (xp.median if is_numpy(xp)
  2725. else lambda x, axis: stats.quantile(x, 0.5, axis=axis))
  2726. center = (xp_median if center is None else center)
  2727. if not callable(center):
  2728. raise TypeError("The argument 'center' must be callable. The given "
  2729. f"value {repr(center)} is not callable.")
  2730. # An error may be raised here, so fail-fast, before doing lengthy
  2731. # computations, even though `scale` is not used until later
  2732. if isinstance(scale, str):
  2733. if scale.lower() == 'normal':
  2734. scale = 0.6744897501960817 # special.ndtri(0.75)
  2735. else:
  2736. raise ValueError(f"{scale} is not a valid scale value.")
  2737. # Wrap the call to center() in expand_dims() so it acts like
  2738. # keepdims=True was used.
  2739. med = xp.expand_dims(center(x, axis=axis), axis=axis)
  2740. mad = xp_median(xp.abs(x - med), axis=axis)
  2741. return mad / scale
  2742. #####################################
  2743. # TRIMMING FUNCTIONS #
  2744. #####################################
  2745. SigmaclipResult = namedtuple('SigmaclipResult', ('clipped', 'lower', 'upper'))
  2746. @xp_capabilities(skip_backends=[('dask.array', "doesn't know array size")],
  2747. jax_jit=False)
  2748. def sigmaclip(a, low=4., high=4.):
  2749. """Perform iterative sigma-clipping of array elements.
  2750. Starting from the full sample, all elements outside the critical range are
  2751. removed, i.e. all elements of the input array `c` that satisfy either of
  2752. the following conditions::
  2753. c < mean(c) - std(c)*low
  2754. c > mean(c) + std(c)*high
  2755. The iteration continues with the updated sample until no
  2756. elements are outside the (updated) range.
  2757. Parameters
  2758. ----------
  2759. a : array_like
  2760. Data array, will be raveled if not 1-D.
  2761. low : float, optional
  2762. Lower bound factor of sigma clipping. Default is 4.
  2763. high : float, optional
  2764. Upper bound factor of sigma clipping. Default is 4.
  2765. Returns
  2766. -------
  2767. clipped : ndarray
  2768. Input array with clipped elements removed.
  2769. lower : float
  2770. Lower threshold value use for clipping.
  2771. upper : float
  2772. Upper threshold value use for clipping.
  2773. Notes
  2774. -----
  2775. This function iteratively *removes* observations. Once observations are
  2776. removed, they are not re-added in subsequent iterations. Consequently,
  2777. although it is often the case that ``clipped`` is identical to
  2778. ``a[(a >= lower) & (a <= upper)]``, this property is not guaranteed to be
  2779. satisfied; ``clipped`` may have fewer elements.
  2780. Examples
  2781. --------
  2782. >>> import numpy as np
  2783. >>> from scipy.stats import sigmaclip
  2784. >>> a = np.concatenate((np.linspace(9.5, 10.5, 31),
  2785. ... np.linspace(0, 20, 5)))
  2786. >>> fact = 1.5
  2787. >>> c, low, upp = sigmaclip(a, fact, fact)
  2788. >>> c
  2789. array([ 9.96666667, 10. , 10.03333333, 10. ])
  2790. >>> c.var(), c.std()
  2791. (0.00055555555555555165, 0.023570226039551501)
  2792. >>> low, c.mean() - fact*c.std(), c.min()
  2793. (9.9646446609406727, 9.9646446609406727, 9.9666666666666668)
  2794. >>> upp, c.mean() + fact*c.std(), c.max()
  2795. (10.035355339059327, 10.035355339059327, 10.033333333333333)
  2796. >>> a = np.concatenate((np.linspace(9.5, 10.5, 11),
  2797. ... np.linspace(-100, -50, 3)))
  2798. >>> c, low, upp = sigmaclip(a, 1.8, 1.8)
  2799. >>> (c == np.linspace(9.5, 10.5, 11)).all()
  2800. True
  2801. """
  2802. xp = array_namespace(a)
  2803. c = xp_ravel(xp.asarray(a))
  2804. delta = 1
  2805. while delta:
  2806. c_std = xp.std(c)
  2807. c_mean = xp.mean(c)
  2808. size = xp_size(c)
  2809. critlower = c_mean - c_std * low
  2810. critupper = c_mean + c_std * high
  2811. c = c[(c >= critlower) & (c <= critupper)]
  2812. delta = size - xp_size(c)
  2813. return SigmaclipResult(c, critlower, critupper)
  2814. @xp_capabilities(np_only=True)
  2815. def trimboth(a, proportiontocut, axis=0):
  2816. """Slice off a proportion of items from both ends of an array.
  2817. Slice off the passed proportion of items from both ends of the passed
  2818. array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
  2819. rightmost 10% of scores). The trimmed values are the lowest and
  2820. highest ones.
  2821. Slice off less if proportion results in a non-integer slice index (i.e.
  2822. conservatively slices off `proportiontocut`).
  2823. Parameters
  2824. ----------
  2825. a : array_like
  2826. Data to trim.
  2827. proportiontocut : float
  2828. Proportion (in range 0-1) of total data set to trim of each end.
  2829. axis : int or None, optional
  2830. Axis along which to trim data. Default is 0. If None, compute over
  2831. the whole array `a`.
  2832. Returns
  2833. -------
  2834. out : ndarray
  2835. Trimmed version of array `a`. The order of the trimmed content
  2836. is undefined.
  2837. See Also
  2838. --------
  2839. trim_mean
  2840. Examples
  2841. --------
  2842. Create an array of 10 values and trim 10% of those values from each end:
  2843. >>> import numpy as np
  2844. >>> from scipy import stats
  2845. >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  2846. >>> stats.trimboth(a, 0.1)
  2847. array([1, 3, 2, 4, 5, 6, 7, 8])
  2848. Note that the elements of the input array are trimmed by value, but the
  2849. output array is not necessarily sorted.
  2850. The proportion to trim is rounded down to the nearest integer. For
  2851. instance, trimming 25% of the values from each end of an array of 10
  2852. values will return an array of 6 values:
  2853. >>> b = np.arange(10)
  2854. >>> stats.trimboth(b, 1/4).shape
  2855. (6,)
  2856. Multidimensional arrays can be trimmed along any axis or across the entire
  2857. array:
  2858. >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9]
  2859. >>> d = np.array([a, b, c])
  2860. >>> stats.trimboth(d, 0.4, axis=0).shape
  2861. (1, 10)
  2862. >>> stats.trimboth(d, 0.4, axis=1).shape
  2863. (3, 2)
  2864. >>> stats.trimboth(d, 0.4, axis=None).shape
  2865. (6,)
  2866. """
  2867. a = np.asarray(a)
  2868. if a.size == 0:
  2869. return a
  2870. if axis is None:
  2871. a = a.ravel()
  2872. axis = 0
  2873. nobs = a.shape[axis]
  2874. lowercut = int(proportiontocut * nobs)
  2875. uppercut = nobs - lowercut
  2876. if (lowercut >= uppercut):
  2877. raise ValueError("Proportion too big.")
  2878. atmp = np.partition(a, (lowercut, uppercut - 1), axis)
  2879. sl = [slice(None)] * atmp.ndim
  2880. sl[axis] = slice(lowercut, uppercut)
  2881. return atmp[tuple(sl)]
  2882. @xp_capabilities(np_only=True)
  2883. def trim1(a, proportiontocut, tail='right', axis=0):
  2884. """Slice off a proportion from ONE end of the passed array distribution.
  2885. If `proportiontocut` = 0.1, slices off 'leftmost' or 'rightmost'
  2886. 10% of scores. The lowest or highest values are trimmed (depending on
  2887. the tail).
  2888. Slice off less if proportion results in a non-integer slice index
  2889. (i.e. conservatively slices off `proportiontocut` ).
  2890. Parameters
  2891. ----------
  2892. a : array_like
  2893. Input array.
  2894. proportiontocut : float
  2895. Fraction to cut off of 'left' or 'right' of distribution.
  2896. tail : {'left', 'right'}, optional
  2897. Defaults to 'right'.
  2898. axis : int or None, optional
  2899. Axis along which to trim data. Default is 0. If None, compute over
  2900. the whole array `a`.
  2901. Returns
  2902. -------
  2903. trim1 : ndarray
  2904. Trimmed version of array `a`. The order of the trimmed content is
  2905. undefined.
  2906. Examples
  2907. --------
  2908. Create an array of 10 values and trim 20% of its lowest values:
  2909. >>> import numpy as np
  2910. >>> from scipy import stats
  2911. >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  2912. >>> stats.trim1(a, 0.2, 'left')
  2913. array([2, 4, 3, 5, 6, 7, 8, 9])
  2914. Note that the elements of the input array are trimmed by value, but the
  2915. output array is not necessarily sorted.
  2916. The proportion to trim is rounded down to the nearest integer. For
  2917. instance, trimming 25% of the values from an array of 10 values will
  2918. return an array of 8 values:
  2919. >>> b = np.arange(10)
  2920. >>> stats.trim1(b, 1/4).shape
  2921. (8,)
  2922. Multidimensional arrays can be trimmed along any axis or across the entire
  2923. array:
  2924. >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9]
  2925. >>> d = np.array([a, b, c])
  2926. >>> stats.trim1(d, 0.8, axis=0).shape
  2927. (1, 10)
  2928. >>> stats.trim1(d, 0.8, axis=1).shape
  2929. (3, 2)
  2930. >>> stats.trim1(d, 0.8, axis=None).shape
  2931. (6,)
  2932. """
  2933. a = np.asarray(a)
  2934. if axis is None:
  2935. a = a.ravel()
  2936. axis = 0
  2937. nobs = a.shape[axis]
  2938. # avoid possible corner case
  2939. if proportiontocut >= 1:
  2940. return []
  2941. if tail.lower() == 'right':
  2942. lowercut = 0
  2943. uppercut = nobs - int(proportiontocut * nobs)
  2944. elif tail.lower() == 'left':
  2945. lowercut = int(proportiontocut * nobs)
  2946. uppercut = nobs
  2947. atmp = np.partition(a, (lowercut, uppercut - 1), axis)
  2948. sl = [slice(None)] * atmp.ndim
  2949. sl[axis] = slice(lowercut, uppercut)
  2950. return atmp[tuple(sl)]
  2951. @xp_capabilities()
  2952. @_axis_nan_policy_factory(lambda x: x, result_to_tuple=lambda x, _: (x,), n_outputs=1)
  2953. def trim_mean(a, proportiontocut, axis=0):
  2954. """Return mean of array after trimming a specified fraction of extreme values
  2955. Removes the specified proportion of elements from *each* end of the
  2956. sorted array, then computes the mean of the remaining elements.
  2957. Parameters
  2958. ----------
  2959. a : array_like
  2960. Input array.
  2961. proportiontocut : float
  2962. Fraction of the most positive and most negative elements to remove.
  2963. When the specified proportion does not result in an integer number of
  2964. elements, the number of elements to trim is rounded down.
  2965. axis : int or None, default: 0
  2966. Axis along which the trimmed means are computed.
  2967. If None, compute over the raveled array.
  2968. Returns
  2969. -------
  2970. trim_mean : ndarray
  2971. Mean of trimmed array.
  2972. See Also
  2973. --------
  2974. trimboth : Remove a proportion of elements from each end of an array.
  2975. tmean : Compute the mean after trimming values outside specified limits.
  2976. Notes
  2977. -----
  2978. For 1-D array `a`, `trim_mean` is approximately equivalent to the following
  2979. calculation::
  2980. import numpy as np
  2981. a = np.sort(a)
  2982. m = int(proportiontocut * len(a))
  2983. np.mean(a[m: len(a) - m])
  2984. Examples
  2985. --------
  2986. >>> import numpy as np
  2987. >>> from scipy import stats
  2988. >>> x = [1, 2, 3, 5]
  2989. >>> stats.trim_mean(x, 0.25)
  2990. 2.5
  2991. When the specified proportion does not result in an integer number of
  2992. elements, the number of elements to trim is rounded down.
  2993. >>> stats.trim_mean(x, 0.24999) == np.mean(x)
  2994. True
  2995. Use `axis` to specify the axis along which the calculation is performed.
  2996. >>> x2 = [[1, 2, 3, 5],
  2997. ... [10, 20, 30, 50]]
  2998. >>> stats.trim_mean(x2, 0.25)
  2999. array([ 5.5, 11. , 16.5, 27.5])
  3000. >>> stats.trim_mean(x2, 0.25, axis=1)
  3001. array([ 2.5, 25. ])
  3002. """
  3003. xp = array_namespace(a)
  3004. a = xp.asarray(a)
  3005. if xp_size(a) == 0:
  3006. return _get_nan(a, xp=xp)
  3007. if axis is None:
  3008. a = xp_ravel(a)
  3009. axis = 0
  3010. nobs = a.shape[axis]
  3011. lowercut = int(proportiontocut * nobs)
  3012. uppercut = nobs - lowercut
  3013. if (lowercut > uppercut):
  3014. raise ValueError("Proportion too big.")
  3015. atmp = (np.partition(a, (lowercut, uppercut - 1), axis) if is_numpy(xp)
  3016. else xp.sort(a, axis=axis))
  3017. sl = [slice(None)] * atmp.ndim
  3018. sl[axis] = slice(lowercut, uppercut)
  3019. trimmed = xp_promote(atmp[tuple(sl)], force_floating=True, xp=xp)
  3020. return xp.mean(trimmed, axis=axis)
  3021. F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue'))
  3022. def _f_oneway_is_too_small(samples, kwargs=None, axis=-1):
  3023. message = f"At least two samples are required; got {len(samples)}."
  3024. if len(samples) < 2:
  3025. raise TypeError(message)
  3026. # Check this after forming alldata, so shape errors are detected
  3027. # and reported before checking for 0 length inputs.
  3028. if any(sample.shape[axis] == 0 for sample in samples):
  3029. return True
  3030. # Must have at least one group with length greater than 1.
  3031. if all(sample.shape[axis] == 1 for sample in samples):
  3032. msg = ('all input arrays have length 1. f_oneway requires that at '
  3033. 'least one input has length greater than 1.')
  3034. warnings.warn(SmallSampleWarning(msg), stacklevel=2)
  3035. return True
  3036. return False
  3037. @xp_capabilities(jax_jit=False, cpu_only=True, exceptions=['cupy'])
  3038. @_axis_nan_policy_factory(
  3039. F_onewayResult, n_samples=None, too_small=_f_oneway_is_too_small)
  3040. def f_oneway(*samples, axis=0, equal_var=True):
  3041. """Perform one-way ANOVA.
  3042. The one-way ANOVA tests the null hypothesis that two or more groups have
  3043. the same population mean. The test is applied to samples from two or
  3044. more groups, possibly with differing sizes.
  3045. Parameters
  3046. ----------
  3047. sample1, sample2, ... : array_like
  3048. The sample measurements for each group. There must be at least
  3049. two arguments. If the arrays are multidimensional, then all the
  3050. dimensions of the array must be the same except for `axis`.
  3051. axis : int, optional
  3052. Axis of the input arrays along which the test is applied.
  3053. Default is 0.
  3054. equal_var: bool, optional
  3055. If True (default), perform a standard one-way ANOVA test that
  3056. assumes equal population variances [2]_.
  3057. If False, perform Welch's ANOVA test, which does not assume
  3058. equal population variances [4]_.
  3059. .. versionadded:: 1.16.0
  3060. Returns
  3061. -------
  3062. statistic : float
  3063. The computed F statistic of the test.
  3064. pvalue : float
  3065. The associated p-value from the F distribution.
  3066. Warns
  3067. -----
  3068. `~scipy.stats.ConstantInputWarning`
  3069. Emitted if all values within each of the input arrays are identical.
  3070. In this case the F statistic is either infinite or isn't defined,
  3071. so ``np.inf`` or ``np.nan`` is returned.
  3072. RuntimeWarning
  3073. Emitted if the length of any input array is 0, or if all the input
  3074. arrays have length 1. ``np.nan`` is returned for the F statistic
  3075. and the p-value in these cases.
  3076. Notes
  3077. -----
  3078. The ANOVA test has important assumptions that must be satisfied in order
  3079. for the associated p-value to be valid.
  3080. 1. The samples are independent.
  3081. 2. Each sample is from a normally distributed population.
  3082. 3. The population standard deviations of the groups are all equal. This
  3083. property is known as homoscedasticity.
  3084. If these assumptions are not true for a given set of data, it may still
  3085. be possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`) or
  3086. the Alexander-Govern test (`scipy.stats.alexandergovern`) although with
  3087. some loss of power.
  3088. The length of each group must be at least one, and there must be at
  3089. least one group with length greater than one. If these conditions
  3090. are not satisfied, a warning is generated and (``np.nan``, ``np.nan``)
  3091. is returned.
  3092. If all values in each group are identical, and there exist at least two
  3093. groups with different values, the function generates a warning and
  3094. returns (``np.inf``, 0).
  3095. If all values in all groups are the same, function generates a warning
  3096. and returns (``np.nan``, ``np.nan``).
  3097. The algorithm is from Heiman [2]_, pp.394-7.
  3098. References
  3099. ----------
  3100. .. [1] R. Lowry, "Concepts and Applications of Inferential Statistics",
  3101. Chapter 14, 2014, http://vassarstats.net/textbook/
  3102. .. [2] G.W. Heiman, "Understanding research methods and statistics: An
  3103. integrated introduction for psychology", Houghton, Mifflin and
  3104. Company, 2001.
  3105. .. [3] G.H. McDonald, "Handbook of Biological Statistics", One-way ANOVA.
  3106. http://www.biostathandbook.com/onewayanova.html
  3107. .. [4] B. L. Welch, "On the Comparison of Several Mean Values:
  3108. An Alternative Approach", Biometrika, vol. 38, no. 3/4,
  3109. pp. 330-336, 1951, doi: 10.2307/2332579.
  3110. Examples
  3111. --------
  3112. >>> import numpy as np
  3113. >>> from scipy.stats import f_oneway
  3114. Here are some data [3]_ on a shell measurement (the length of the anterior
  3115. adductor muscle scar, standardized by dividing by length) in the mussel
  3116. Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon;
  3117. Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland, taken from a
  3118. much larger data set used in McDonald et al. (1991).
  3119. >>> tillamook = [0.0571, 0.0813, 0.0831, 0.0976, 0.0817, 0.0859, 0.0735,
  3120. ... 0.0659, 0.0923, 0.0836]
  3121. >>> newport = [0.0873, 0.0662, 0.0672, 0.0819, 0.0749, 0.0649, 0.0835,
  3122. ... 0.0725]
  3123. >>> petersburg = [0.0974, 0.1352, 0.0817, 0.1016, 0.0968, 0.1064, 0.105]
  3124. >>> magadan = [0.1033, 0.0915, 0.0781, 0.0685, 0.0677, 0.0697, 0.0764,
  3125. ... 0.0689]
  3126. >>> tvarminne = [0.0703, 0.1026, 0.0956, 0.0973, 0.1039, 0.1045]
  3127. >>> f_oneway(tillamook, newport, petersburg, magadan, tvarminne)
  3128. F_onewayResult(statistic=7.121019471642447, pvalue=0.0002812242314534544)
  3129. `f_oneway` accepts multidimensional input arrays. When the inputs
  3130. are multidimensional and `axis` is not given, the test is performed
  3131. along the first axis of the input arrays. For the following data, the
  3132. test is performed three times, once for each column.
  3133. >>> a = np.array([[9.87, 9.03, 6.81],
  3134. ... [7.18, 8.35, 7.00],
  3135. ... [8.39, 7.58, 7.68],
  3136. ... [7.45, 6.33, 9.35],
  3137. ... [6.41, 7.10, 9.33],
  3138. ... [8.00, 8.24, 8.44]])
  3139. >>> b = np.array([[6.35, 7.30, 7.16],
  3140. ... [6.65, 6.68, 7.63],
  3141. ... [5.72, 7.73, 6.72],
  3142. ... [7.01, 9.19, 7.41],
  3143. ... [7.75, 7.87, 8.30],
  3144. ... [6.90, 7.97, 6.97]])
  3145. >>> c = np.array([[3.31, 8.77, 1.01],
  3146. ... [8.25, 3.24, 3.62],
  3147. ... [6.32, 8.81, 5.19],
  3148. ... [7.48, 8.83, 8.91],
  3149. ... [8.59, 6.01, 6.07],
  3150. ... [3.07, 9.72, 7.48]])
  3151. >>> F = f_oneway(a, b, c)
  3152. >>> F.statistic
  3153. array([1.75676344, 0.03701228, 3.76439349])
  3154. >>> F.pvalue
  3155. array([0.20630784, 0.96375203, 0.04733157])
  3156. Welch ANOVA will be performed if `equal_var` is False.
  3157. """
  3158. xp = array_namespace(*samples)
  3159. samples = xp_promote(*samples, force_floating=True, xp=xp)
  3160. if len(samples) < 2:
  3161. raise TypeError('at least two inputs are required;'
  3162. f' got {len(samples)}.')
  3163. # ANOVA on N groups, each in its own array
  3164. num_groups = len(samples)
  3165. # axis is guaranteed to be -1 by the _axis_nan_policy decorator
  3166. alldata = xp.concat(samples, axis=-1)
  3167. bign = _length_nonmasked(alldata, axis=-1, xp=xp)
  3168. # Check if the inputs are too small (for testing _axis_nan_policy decorator)
  3169. if _f_oneway_is_too_small(samples):
  3170. NaN = _get_nan(*samples, xp=xp)
  3171. return F_onewayResult(NaN, NaN)
  3172. # Check if all values within each group are identical, and if the common
  3173. # value in at least one group is different from that in another group.
  3174. # Based on https://github.com/scipy/scipy/issues/11669
  3175. # If axis=0, say, and the groups have shape (n0, ...), (n1, ...), ...,
  3176. # then is_const is a boolean array with shape (num_groups, ...).
  3177. # It is True if the values within the groups along the axis slice are
  3178. # identical. In the typical case where each input array is 1-d, is_const is
  3179. # a 1-d array with length num_groups.
  3180. is_const = xp.concat([xp.all(xp.diff(sample, axis=-1) == 0, axis=-1, keepdims=True)
  3181. for sample in samples], axis=-1)
  3182. # all_const is a boolean array with shape (...) (see previous comment).
  3183. # It is True if the values within each group along the axis slice are
  3184. # the same (e.g. [[3, 3, 3], [5, 5, 5, 5], [4, 4, 4]]).
  3185. all_const = xp.all(is_const, axis=-1)
  3186. # all_same_const is True if all the values in the groups along the axis=0
  3187. # slice are the same (e.g. [[3, 3, 3], [3, 3, 3, 3], [3, 3, 3]]).
  3188. all_same_const = xp.all(xp.diff(alldata, axis=-1) == 0, axis=-1)
  3189. if not isinstance(equal_var, bool):
  3190. raise TypeError("Expected a boolean value for 'equal_var'")
  3191. if equal_var:
  3192. # Determine the mean of the data, and subtract that from all inputs to a
  3193. # variance (via sum_of_sq / sq_of_sum) calculation. Variance is invariant
  3194. # to a shift in location, and centering all data around zero vastly
  3195. # improves numerical stability.
  3196. offset = xp.mean(alldata, axis=-1, keepdims=True)
  3197. alldata = alldata - offset
  3198. normalized_ss = xp.sum(alldata, axis=-1)**2. / bign
  3199. sstot = xp.vecdot(alldata, alldata, axis=-1) - normalized_ss
  3200. ssbn = 0
  3201. for sample in samples:
  3202. smo_ss = xp.sum(sample - offset, axis=-1)**2.
  3203. ssbn = ssbn + smo_ss / _length_nonmasked(sample, axis=-1, xp=xp)
  3204. # Naming: variables ending in bn/b are for "between treatments", wn/w are
  3205. # for "within treatments"
  3206. ssbn = ssbn - normalized_ss
  3207. sswn = sstot - ssbn
  3208. dfbn = num_groups - 1
  3209. dfwn = bign - num_groups
  3210. msb = ssbn / dfbn
  3211. msw = sswn / dfwn
  3212. with np.errstate(divide='ignore', invalid='ignore'):
  3213. f = msb / msw
  3214. dfn, dfd = dfbn, dfwn
  3215. else:
  3216. # calculate basic statistics for each sample
  3217. # Beginning of second paragraph [4] page 1:
  3218. # "As a particular case $y_t$ may be the means ... of samples
  3219. y_t = xp.stack([xp.mean(sample, axis=-1) for sample in samples])
  3220. # "... of $n_t$ observations..."
  3221. if is_marray(xp):
  3222. n_t = xp.stack([_length_nonmasked(sample, axis=-1, xp=xp)
  3223. for sample in samples])
  3224. n_t = xp.asarray(n_t, dtype=n_t.dtype)
  3225. else:
  3226. n_t = xp.asarray([sample.shape[-1] for sample in samples], dtype=y_t.dtype)
  3227. n_t = xp.reshape(n_t, (-1,) + (1,) * (y_t.ndim - 1))
  3228. # "... from $k$ different normal populations..."
  3229. k = len(samples)
  3230. # "The separate samples provide estimates $s_t^2$ of the $\sigma_t^2$."
  3231. s_t2 = xp.stack([xp.var(sample, axis=-1, correction=1) for sample in samples])
  3232. # calculate weight by number of data and variance
  3233. # "we have $\lambda_t = 1 / n_t$ ... where w_t = 1 / {\lambda_t s_t^2}$"
  3234. w_t = n_t / s_t2
  3235. # sum of w_t
  3236. s_w_t = xp.sum(w_t, axis=0)
  3237. # calculate adjusted grand mean
  3238. # "... and $\hat{y} = \sum w_t y_t / \sum w_t$. When all..."
  3239. axis_zero = -w_t.ndim
  3240. y_hat = xp.vecdot(w_t, y_t, axis=axis_zero) / xp.sum(w_t, axis=0)
  3241. # adjust f statistic
  3242. # ref.[4] p.334 eq.29
  3243. numerator = xp.vecdot(w_t, (y_t - y_hat)**2, axis=axis_zero) / (k - 1)
  3244. denominator = (
  3245. 1 + 2 * (k - 2) / (k**2 - 1) *
  3246. xp.vecdot(1 / (n_t - 1), (1 - w_t / s_w_t)**2, axis=axis_zero)
  3247. )
  3248. f = numerator / denominator
  3249. # degree of freedom 1
  3250. # ref.[4] p.334 eq.30
  3251. hat_f1 = k - 1
  3252. # adjusted degree of freedom 2
  3253. # ref.[4] p.334 eq.30
  3254. hat_f2 = (
  3255. (k**2 - 1) /
  3256. (3 * xp.vecdot(1 / (n_t - 1), (1 - w_t / s_w_t)**2, axis=axis_zero))
  3257. )
  3258. dfn, dfd = hat_f1, hat_f2
  3259. # Fix any f values that should be inf or nan because the corresponding
  3260. # inputs were constant.
  3261. f = xpx.at(f)[all_const].set(xp.inf)
  3262. f = xpx.at(f)[all_same_const].set(xp.nan)
  3263. # calculate p value
  3264. # ref.[4] p.334 eq.28
  3265. prob = special.fdtrc(dfn, dfd, f)
  3266. prob = xp.asarray(prob, dtype=f.dtype)
  3267. f, prob = (f[()], prob[()]) if f.ndim == 0 else (f, prob)
  3268. return F_onewayResult(f, prob)
  3269. @dataclass
  3270. class AlexanderGovernResult:
  3271. statistic: float
  3272. pvalue: float
  3273. @xp_capabilities()
  3274. @_axis_nan_policy_factory(
  3275. AlexanderGovernResult, n_samples=None,
  3276. result_to_tuple=lambda x, _: (x.statistic, x.pvalue),
  3277. too_small=1
  3278. )
  3279. def alexandergovern(*samples, nan_policy='propagate', axis=0):
  3280. """Performs the Alexander Govern test.
  3281. The Alexander-Govern approximation tests the equality of k independent
  3282. means in the face of heterogeneity of variance. The test is applied to
  3283. samples from two or more groups, possibly with differing sizes.
  3284. Parameters
  3285. ----------
  3286. sample1, sample2, ... : array_like
  3287. The sample measurements for each group. There must be at least
  3288. two samples, and each sample must contain at least two observations.
  3289. nan_policy : {'propagate', 'raise', 'omit'}, optional
  3290. Defines how to handle when input contains nan.
  3291. The following options are available (default is 'propagate'):
  3292. * 'propagate': returns nan
  3293. * 'raise': throws an error
  3294. * 'omit': performs the calculations ignoring nan values
  3295. Returns
  3296. -------
  3297. res : AlexanderGovernResult
  3298. An object with attributes:
  3299. statistic : float
  3300. The computed A statistic of the test.
  3301. pvalue : float
  3302. The associated p-value from the chi-squared distribution.
  3303. Warns
  3304. -----
  3305. `~scipy.stats.ConstantInputWarning`
  3306. Raised if an input is a constant array. The statistic is not defined
  3307. in this case, so ``np.nan`` is returned.
  3308. See Also
  3309. --------
  3310. f_oneway : one-way ANOVA
  3311. Notes
  3312. -----
  3313. The use of this test relies on several assumptions.
  3314. 1. The samples are independent.
  3315. 2. Each sample is from a normally distributed population.
  3316. 3. Unlike `f_oneway`, this test does not assume on homoscedasticity,
  3317. instead relaxing the assumption of equal variances.
  3318. Input samples must be finite, one dimensional, and with size greater than
  3319. one.
  3320. References
  3321. ----------
  3322. .. [1] Alexander, Ralph A., and Diane M. Govern. "A New and Simpler
  3323. Approximation for ANOVA under Variance Heterogeneity." Journal
  3324. of Educational Statistics, vol. 19, no. 2, 1994, pp. 91-101.
  3325. JSTOR, www.jstor.org/stable/1165140. Accessed 12 Sept. 2020.
  3326. Examples
  3327. --------
  3328. >>> from scipy.stats import alexandergovern
  3329. Here are some data on annual percentage rate of interest charged on
  3330. new car loans at nine of the largest banks in four American cities
  3331. taken from the National Institute of Standards and Technology's
  3332. ANOVA dataset.
  3333. We use `alexandergovern` to test the null hypothesis that all cities
  3334. have the same mean APR against the alternative that the cities do not
  3335. all have the same mean APR. We decide that a significance level of 5%
  3336. is required to reject the null hypothesis in favor of the alternative.
  3337. >>> atlanta = [13.75, 13.75, 13.5, 13.5, 13.0, 13.0, 13.0, 12.75, 12.5]
  3338. >>> chicago = [14.25, 13.0, 12.75, 12.5, 12.5, 12.4, 12.3, 11.9, 11.9]
  3339. >>> houston = [14.0, 14.0, 13.51, 13.5, 13.5, 13.25, 13.0, 12.5, 12.5]
  3340. >>> memphis = [15.0, 14.0, 13.75, 13.59, 13.25, 12.97, 12.5, 12.25,
  3341. ... 11.89]
  3342. >>> alexandergovern(atlanta, chicago, houston, memphis)
  3343. AlexanderGovernResult(statistic=4.65087071883494,
  3344. pvalue=0.19922132490385214)
  3345. The p-value is 0.1992, indicating a nearly 20% chance of observing
  3346. such an extreme value of the test statistic under the null hypothesis.
  3347. This exceeds 5%, so we do not reject the null hypothesis in favor of
  3348. the alternative.
  3349. """
  3350. xp = array_namespace(*samples)
  3351. samples = _alexandergovern_input_validation(samples, nan_policy, axis, xp=xp)
  3352. # The following formula numbers reference the equation described on
  3353. # page 92 by Alexander, Govern. Formulas 5, 6, and 7 describe other
  3354. # tests that serve as the basis for equation (8) but are not needed
  3355. # to perform the test.
  3356. # precalculate mean and length of each sample
  3357. lengths = [sample.shape[-1] for sample in samples]
  3358. means = xp.stack([_xp_mean(sample, axis=-1) for sample in samples])
  3359. # (1) determine standard error of the mean for each sample
  3360. se2 = [(_xp_var(sample, correction=1, axis=-1) / length)
  3361. for sample, length in zip(samples, lengths)]
  3362. standard_errors_squared = xp.stack(se2)
  3363. standard_errors = standard_errors_squared**0.5
  3364. # Special case: statistic is NaN when variance is zero
  3365. eps = xp.finfo(standard_errors.dtype).eps
  3366. zero = standard_errors <= xp.abs(eps * means)
  3367. NaN = xp.asarray(xp.nan, dtype=standard_errors.dtype)
  3368. standard_errors = xp.where(zero, NaN, standard_errors)
  3369. # (2) define a weight for each sample
  3370. inv_sq_se = 1 / standard_errors_squared
  3371. weights = inv_sq_se / xp.sum(inv_sq_se, axis=0, keepdims=True)
  3372. # (3) determine variance-weighted estimate of the common mean
  3373. # Consider replacing with vecdot when data-apis/array-api#910 is resolved
  3374. var_w = xp.sum(weights * means, axis=0, keepdims=True)
  3375. # (4) determine one-sample t statistic for each group
  3376. t_stats = _demean(means, var_w, axis=0, xp=xp) / standard_errors
  3377. # calculate parameters to be used in transformation
  3378. v = xp.asarray(lengths, dtype=t_stats.dtype) - 1
  3379. # align along 0th axis, which corresponds with separate samples
  3380. v = xp.reshape(v, (-1,) + (1,)*(t_stats.ndim-1))
  3381. a = v - .5
  3382. b = 48 * a**2
  3383. c = (a * xp.log(1 + (t_stats ** 2)/v))**.5
  3384. # (8) perform a normalizing transformation on t statistic
  3385. z = (c + ((c**3 + 3*c)/b) -
  3386. ((4*c**7 + 33*c**5 + 240*c**3 + 855*c) /
  3387. (b**2*10 + 8*b*c**4 + 1000*b)))
  3388. # (9) calculate statistic
  3389. A = xp.vecdot(z, z, axis=-z.ndim)
  3390. A = A[()] if A.ndim == 0 else A # data-apis/array-api-compat#355
  3391. # "[the p value is determined from] central chi-square random deviates
  3392. # with k - 1 degrees of freedom". Alexander, Govern (94)
  3393. df = xp.asarray(len(samples) - 1, dtype=A.dtype)
  3394. chi2 = _SimpleChi2(df)
  3395. p = _get_pvalue(A, chi2, alternative='greater', symmetric=False, xp=xp)
  3396. return AlexanderGovernResult(A, p)
  3397. def _alexandergovern_input_validation(samples, nan_policy, axis, xp):
  3398. if len(samples) < 2:
  3399. raise TypeError(f"2 or more inputs required, got {len(samples)}")
  3400. for sample in samples:
  3401. if sample.shape[axis] <= 1:
  3402. raise ValueError("Input sample size must be greater than one.")
  3403. samples = [xp.moveaxis(sample, axis, -1) for sample in samples]
  3404. return samples
  3405. def _pearsonr_fisher_ci(r, n, confidence_level, alternative):
  3406. """
  3407. Compute the confidence interval for Pearson's R.
  3408. Fisher's transformation is used to compute the confidence interval
  3409. (https://en.wikipedia.org/wiki/Fisher_transformation).
  3410. """
  3411. xp = array_namespace(r)
  3412. ones = xp.ones_like(r)
  3413. n = xp.asarray(n, dtype=r.dtype, device=xp_device(r))
  3414. confidence_level = xp.asarray(confidence_level, dtype=r.dtype, device=xp_device(r))
  3415. with np.errstate(divide='ignore', invalid='ignore'):
  3416. zr = xp.atanh(r)
  3417. se = xp.sqrt(1 / (n - 3))
  3418. if alternative == "two-sided":
  3419. h = special.ndtri(0.5 + confidence_level/2)
  3420. zlo = zr - h*se
  3421. zhi = zr + h*se
  3422. rlo = xp.tanh(zlo)
  3423. rhi = xp.tanh(zhi)
  3424. elif alternative == "less":
  3425. h = special.ndtri(confidence_level)
  3426. zhi = zr + h*se
  3427. rhi = xp.tanh(zhi)
  3428. rlo = -ones
  3429. else:
  3430. # alternative == "greater":
  3431. h = special.ndtri(confidence_level)
  3432. zlo = zr - h*se
  3433. rlo = xp.tanh(zlo)
  3434. rhi = ones
  3435. mask = (n <= 3)
  3436. if mask.ndim == 0:
  3437. # This is Array API legal, but Dask doesn't like it.
  3438. mask = xp.broadcast_to(mask, rlo.shape)
  3439. rlo = xpx.at(rlo)[mask].set(-1)
  3440. rhi = xpx.at(rhi)[mask].set(1)
  3441. rlo = rlo[()] if rlo.ndim == 0 else rlo
  3442. rhi = rhi[()] if rhi.ndim == 0 else rhi
  3443. return ConfidenceInterval(low=rlo, high=rhi)
  3444. def _pearsonr_bootstrap_ci(confidence_level, method, x, y, alternative, axis):
  3445. """
  3446. Compute the confidence interval for Pearson's R using the bootstrap.
  3447. """
  3448. def statistic(x, y, axis):
  3449. statistic, _ = pearsonr(x, y, axis=axis)
  3450. return statistic
  3451. res = bootstrap((x, y), statistic, confidence_level=confidence_level, axis=axis,
  3452. paired=True, alternative=alternative, **method._asdict())
  3453. # for one-sided confidence intervals, bootstrap gives +/- inf on one side
  3454. res.confidence_interval = np.clip(res.confidence_interval, -1, 1)
  3455. return ConfidenceInterval(*res.confidence_interval)
  3456. ConfidenceInterval = namedtuple('ConfidenceInterval', ['low', 'high'])
  3457. PearsonRResultBase = _make_tuple_bunch('PearsonRResultBase',
  3458. ['statistic', 'pvalue'], [])
  3459. class PearsonRResult(PearsonRResultBase):
  3460. """
  3461. Result of `scipy.stats.pearsonr`
  3462. Attributes
  3463. ----------
  3464. statistic : float
  3465. Pearson product-moment correlation coefficient.
  3466. pvalue : float
  3467. The p-value associated with the chosen alternative.
  3468. Methods
  3469. -------
  3470. confidence_interval
  3471. Computes the confidence interval of the correlation
  3472. coefficient `statistic` for the given confidence level.
  3473. """
  3474. def __init__(self, statistic, pvalue, alternative, n, x, y, axis):
  3475. super().__init__(statistic, pvalue)
  3476. self._alternative = alternative
  3477. self._n = n
  3478. self._x = x
  3479. self._y = y
  3480. self._axis = axis
  3481. # add alias for consistency with other correlation functions
  3482. self.correlation = statistic
  3483. def confidence_interval(self, confidence_level=0.95, method=None):
  3484. """
  3485. The confidence interval for the correlation coefficient.
  3486. Compute the confidence interval for the correlation coefficient
  3487. ``statistic`` with the given confidence level.
  3488. If `method` is not provided,
  3489. The confidence interval is computed using the Fisher transformation
  3490. F(r) = arctanh(r) [1]_. When the sample pairs are drawn from a
  3491. bivariate normal distribution, F(r) approximately follows a normal
  3492. distribution with standard error ``1/sqrt(n - 3)``, where ``n`` is the
  3493. length of the original samples along the calculation axis. When
  3494. ``n <= 3``, this approximation does not yield a finite, real standard
  3495. error, so we define the confidence interval to be -1 to 1.
  3496. If `method` is an instance of `BootstrapMethod`, the confidence
  3497. interval is computed using `scipy.stats.bootstrap` with the provided
  3498. configuration options and other appropriate settings. In some cases,
  3499. confidence limits may be NaN due to a degenerate resample, and this is
  3500. typical for very small samples (~6 observations).
  3501. Parameters
  3502. ----------
  3503. confidence_level : float
  3504. The confidence level for the calculation of the correlation
  3505. coefficient confidence interval. Default is 0.95.
  3506. method : BootstrapMethod, optional
  3507. Defines the method used to compute the confidence interval. See
  3508. method description for details.
  3509. .. versionadded:: 1.11.0
  3510. Returns
  3511. -------
  3512. ci : namedtuple
  3513. The confidence interval is returned in a ``namedtuple`` with
  3514. fields `low` and `high`.
  3515. References
  3516. ----------
  3517. .. [1] "Pearson correlation coefficient", Wikipedia,
  3518. https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
  3519. """
  3520. if isinstance(method, BootstrapMethod):
  3521. xp = array_namespace(self._x)
  3522. message = ('`method` must be `None` if `pearsonr` '
  3523. 'arguments were not NumPy arrays.')
  3524. if not is_numpy(xp):
  3525. raise ValueError(message)
  3526. ci = _pearsonr_bootstrap_ci(confidence_level, method, self._x, self._y,
  3527. self._alternative, self._axis)
  3528. elif method is None:
  3529. ci = _pearsonr_fisher_ci(self.statistic, self._n, confidence_level,
  3530. self._alternative)
  3531. else:
  3532. message = ('`method` must be an instance of `BootstrapMethod` '
  3533. 'or None.')
  3534. raise ValueError(message)
  3535. return ci
  3536. # Missing special.betainc on torch
  3537. @xp_capabilities(cpu_only=True, exceptions=['cupy', 'jax.numpy'])
  3538. def pearsonr(x, y, *, alternative='two-sided', method=None, axis=0):
  3539. r"""
  3540. Pearson correlation coefficient and p-value for testing non-correlation.
  3541. The Pearson correlation coefficient [1]_ measures the linear relationship
  3542. between two datasets. Like other correlation
  3543. coefficients, this one varies between -1 and +1 with 0 implying no
  3544. correlation. Correlations of -1 or +1 imply an exact linear relationship.
  3545. Positive correlations imply that as x increases, so does y. Negative
  3546. correlations imply that as x increases, y decreases.
  3547. This function also performs a test of the null hypothesis that the
  3548. distributions underlying the samples are uncorrelated and normally
  3549. distributed. (See Kowalski [3]_
  3550. for a discussion of the effects of non-normality of the input on the
  3551. distribution of the correlation coefficient.)
  3552. The p-value roughly indicates the probability of an uncorrelated system
  3553. producing datasets that have a Pearson correlation at least as extreme
  3554. as the one computed from these datasets.
  3555. Parameters
  3556. ----------
  3557. x : array_like
  3558. Input array.
  3559. y : array_like
  3560. Input array.
  3561. axis : int or None, default
  3562. Axis along which to perform the calculation. Default is 0.
  3563. If None, ravel both arrays before performing the calculation.
  3564. .. versionadded:: 1.14.0
  3565. alternative : {'two-sided', 'greater', 'less'}, optional
  3566. Defines the alternative hypothesis. Default is 'two-sided'.
  3567. The following options are available:
  3568. * 'two-sided': the correlation is nonzero
  3569. * 'less': the correlation is negative (less than zero)
  3570. * 'greater': the correlation is positive (greater than zero)
  3571. .. versionadded:: 1.9.0
  3572. method : ResamplingMethod, optional
  3573. Defines the method used to compute the p-value. If `method` is an
  3574. instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is
  3575. computed using
  3576. `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
  3577. provided configuration options and other appropriate settings.
  3578. Otherwise, the p-value is computed as documented in the notes.
  3579. .. versionadded:: 1.11.0
  3580. Returns
  3581. -------
  3582. result : `~scipy.stats._result_classes.PearsonRResult`
  3583. An object with the following attributes:
  3584. statistic : float
  3585. Pearson product-moment correlation coefficient.
  3586. pvalue : float
  3587. The p-value associated with the chosen alternative.
  3588. The object has the following method:
  3589. confidence_interval(confidence_level, method)
  3590. This computes the confidence interval of the correlation
  3591. coefficient `statistic` for the given confidence level.
  3592. The confidence interval is returned in a ``namedtuple`` with
  3593. fields `low` and `high`. If `method` is not provided, the
  3594. confidence interval is computed using the Fisher transformation
  3595. [1]_. If `method` is an instance of `BootstrapMethod`, the
  3596. confidence interval is computed using `scipy.stats.bootstrap` with
  3597. the provided configuration options and other appropriate settings.
  3598. In some cases, confidence limits may be NaN due to a degenerate
  3599. resample, and this is typical for very small samples (~6
  3600. observations).
  3601. Raises
  3602. ------
  3603. ValueError
  3604. If `x` and `y` do not have length at least 2.
  3605. Warns
  3606. -----
  3607. `~scipy.stats.ConstantInputWarning`
  3608. Raised if an input is a constant array. The correlation coefficient
  3609. is not defined in this case, so ``np.nan`` is returned.
  3610. `~scipy.stats.NearConstantInputWarning`
  3611. Raised if an input is "nearly" constant. The array ``x`` is considered
  3612. nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``.
  3613. Numerical errors in the calculation ``x - mean(x)`` in this case might
  3614. result in an inaccurate calculation of r.
  3615. See Also
  3616. --------
  3617. spearmanr : Spearman rank-order correlation coefficient.
  3618. kendalltau : Kendall's tau, a correlation measure for ordinal data.
  3619. :ref:`hypothesis_pearsonr` : Extended example
  3620. Notes
  3621. -----
  3622. The correlation coefficient is calculated as follows:
  3623. .. math::
  3624. r = \frac{\sum (x - m_x) (y - m_y)}
  3625. {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}}
  3626. where :math:`m_x` is the mean of the vector x and :math:`m_y` is
  3627. the mean of the vector y.
  3628. Under the assumption that x and y are drawn from
  3629. independent normal distributions (so the population correlation coefficient
  3630. is 0), the probability density function of the sample correlation
  3631. coefficient r is ([1]_, [2]_):
  3632. .. math::
  3633. f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)}
  3634. where n is the number of samples, and B is the beta function. This
  3635. is sometimes referred to as the exact distribution of r. This is
  3636. the distribution that is used in `pearsonr` to compute the p-value when
  3637. the `method` parameter is left at its default value (None).
  3638. The distribution is a beta distribution on the interval [-1, 1],
  3639. with equal shape parameters a = b = n/2 - 1. In terms of SciPy's
  3640. implementation of the beta distribution, the distribution of r is::
  3641. dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2)
  3642. The default p-value returned by `pearsonr` is a two-sided p-value. For a
  3643. given sample with correlation coefficient r, the p-value is
  3644. the probability that abs(r') of a random sample x' and y' drawn from
  3645. the population with zero correlation would be greater than or equal
  3646. to abs(r). In terms of the object ``dist`` shown above, the p-value
  3647. for a given r and length n can be computed as::
  3648. p = 2*dist.cdf(-abs(r))
  3649. When n is 2, the above continuous distribution is not well-defined.
  3650. One can interpret the limit of the beta distribution as the shape
  3651. parameters a and b approach a = b = 0 as a discrete distribution with
  3652. equal probability masses at r = 1 and r = -1. More directly, one
  3653. can observe that, given the data x = [x1, x2] and y = [y1, y2], and
  3654. assuming x1 != x2 and y1 != y2, the only possible values for r are 1
  3655. and -1. Because abs(r') for any sample x' and y' with length 2 will
  3656. be 1, the two-sided p-value for a sample of length 2 is always 1.
  3657. For backwards compatibility, the object that is returned also behaves
  3658. like a tuple of length two that holds the statistic and the p-value.
  3659. References
  3660. ----------
  3661. .. [1] "Pearson correlation coefficient", Wikipedia,
  3662. https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
  3663. .. [2] Student, "Probable error of a correlation coefficient",
  3664. Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310.
  3665. .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution
  3666. of the Sample Product-Moment Correlation Coefficient"
  3667. Journal of the Royal Statistical Society. Series C (Applied
  3668. Statistics), Vol. 21, No. 1 (1972), pp. 1-12.
  3669. Examples
  3670. --------
  3671. >>> import numpy as np
  3672. >>> from scipy import stats
  3673. >>> x, y = [1, 2, 3, 4, 5, 6, 7], [10, 9, 2.5, 6, 4, 3, 2]
  3674. >>> res = stats.pearsonr(x, y)
  3675. >>> res
  3676. PearsonRResult(statistic=-0.828503883588428, pvalue=0.021280260007523286)
  3677. To perform an exact permutation version of the test:
  3678. >>> rng = np.random.default_rng(7796654889291491997)
  3679. >>> method = stats.PermutationMethod(n_resamples=np.inf, random_state=rng)
  3680. >>> stats.pearsonr(x, y, method=method)
  3681. PearsonRResult(statistic=-0.828503883588428, pvalue=0.028174603174603175)
  3682. To perform the test under the null hypothesis that the data were drawn from
  3683. *uniform* distributions:
  3684. >>> method = stats.MonteCarloMethod(rvs=(rng.uniform, rng.uniform))
  3685. >>> stats.pearsonr(x, y, method=method)
  3686. PearsonRResult(statistic=-0.828503883588428, pvalue=0.0188)
  3687. To produce an asymptotic 90% confidence interval:
  3688. >>> res.confidence_interval(confidence_level=0.9)
  3689. ConfidenceInterval(low=-0.9644331982722841, high=-0.3460237473272273)
  3690. And for a bootstrap confidence interval:
  3691. >>> method = stats.BootstrapMethod(method='BCa', rng=rng)
  3692. >>> res.confidence_interval(confidence_level=0.9, method=method)
  3693. ConfidenceInterval(low=-0.9983163756488651, high=-0.22771001702132443) # may vary
  3694. If N-dimensional arrays are provided, multiple tests are performed in a
  3695. single call according to the same conventions as most `scipy.stats` functions:
  3696. >>> rng = np.random.default_rng(2348246935601934321)
  3697. >>> x = rng.standard_normal((8, 15))
  3698. >>> y = rng.standard_normal((8, 15))
  3699. >>> stats.pearsonr(x, y, axis=0).statistic.shape # between corresponding columns
  3700. (15,)
  3701. >>> stats.pearsonr(x, y, axis=1).statistic.shape # between corresponding rows
  3702. (8,)
  3703. To perform all pairwise comparisons between slices of the arrays,
  3704. use standard NumPy broadcasting techniques. For instance, to compute the
  3705. correlation between all pairs of rows:
  3706. >>> stats.pearsonr(x[:, np.newaxis, :], y, axis=-1).statistic.shape
  3707. (8, 8)
  3708. There is a linear dependence between x and y if y = a + b*x + e, where
  3709. a,b are constants and e is a random error term, assumed to be independent
  3710. of x. For simplicity, assume that x is standard normal, a=0, b=1 and let
  3711. e follow a normal distribution with mean zero and standard deviation s>0.
  3712. >>> rng = np.random.default_rng()
  3713. >>> s = 0.5
  3714. >>> x = stats.norm.rvs(size=500, random_state=rng)
  3715. >>> e = stats.norm.rvs(scale=s, size=500, random_state=rng)
  3716. >>> y = x + e
  3717. >>> stats.pearsonr(x, y).statistic
  3718. 0.9001942438244763
  3719. This should be close to the exact value given by
  3720. >>> 1/np.sqrt(1 + s**2)
  3721. 0.8944271909999159
  3722. For s=0.5, we observe a high level of correlation. In general, a large
  3723. variance of the noise reduces the correlation, while the correlation
  3724. approaches one as the variance of the error goes to zero.
  3725. It is important to keep in mind that no correlation does not imply
  3726. independence unless (x, y) is jointly normal. Correlation can even be zero
  3727. when there is a very simple dependence structure: if X follows a
  3728. standard normal distribution, let y = abs(x). Note that the correlation
  3729. between x and y is zero. Indeed, since the expectation of x is zero,
  3730. cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero
  3731. by symmetry. The following lines of code illustrate this observation:
  3732. >>> y = np.abs(x)
  3733. >>> stats.pearsonr(x, y)
  3734. PearsonRResult(statistic=-0.05444919272687482, pvalue=0.22422294836207743)
  3735. A non-zero correlation coefficient can be misleading. For example, if X has
  3736. a standard normal distribution, define y = x if x < 0 and y = 0 otherwise.
  3737. A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797...,
  3738. implying a high level of correlation:
  3739. >>> y = np.where(x < 0, x, 0)
  3740. >>> stats.pearsonr(x, y)
  3741. PearsonRResult(statistic=0.861985781588, pvalue=4.813432002751103e-149)
  3742. This is unintuitive since there is no dependence of x and y if x is larger
  3743. than zero which happens in about half of the cases if we sample x and y.
  3744. For a more detailed example, see :ref:`hypothesis_pearsonr`.
  3745. """
  3746. xp = array_namespace(x, y)
  3747. x, y = xp_promote(x, y, force_floating=True, xp=xp)
  3748. dtype = x.dtype
  3749. if not is_numpy(xp) and method is not None:
  3750. method = 'invalid'
  3751. if axis is None:
  3752. x = xp.reshape(x, (-1,))
  3753. y = xp.reshape(y, (-1,))
  3754. axis = -1
  3755. axis_int = int(axis)
  3756. if axis_int != axis:
  3757. raise ValueError('`axis` must be an integer.')
  3758. axis = axis_int
  3759. try:
  3760. np.broadcast_shapes(x.shape, y.shape)
  3761. # For consistency with other `stats` functions, we need to
  3762. # match the dimensionalities before looking at `axis`.
  3763. # (Note: this is not the NEP 5 / gufunc order of operations;
  3764. # see TestPearsonr::test_different_dimensionality for more information.)
  3765. ndim = max(x.ndim, y.ndim)
  3766. x = xp.reshape(x, (1,) * (ndim - x.ndim) + x.shape)
  3767. y = xp.reshape(y, (1,) * (ndim - y.ndim) + y.shape)
  3768. except (ValueError, RuntimeError) as e:
  3769. message = '`x` and `y` must be broadcastable.'
  3770. raise ValueError(message) from e
  3771. if x.shape[axis] != y.shape[axis]:
  3772. raise ValueError('`x` and `y` must have the same length along `axis`.')
  3773. if x.shape[axis] < 2:
  3774. raise ValueError('`x` and `y` must have length at least 2.')
  3775. x, y = _share_masks(x, y, xp=xp)
  3776. n = xp.asarray(_length_nonmasked(x, axis=axis), dtype=x.dtype)
  3777. x = xp.moveaxis(x, axis, -1)
  3778. y = xp.moveaxis(y, axis, -1)
  3779. axis = -1
  3780. if xp.isdtype(dtype, "complex floating"):
  3781. raise ValueError('This function does not support complex data')
  3782. x = xp.astype(x, dtype, copy=False)
  3783. y = xp.astype(y, dtype, copy=False)
  3784. threshold = xp.finfo(dtype).eps ** 0.75
  3785. # If an input is constant, the correlation coefficient is not defined.
  3786. const_x = xp.all(x == x[..., 0:1], axis=-1)
  3787. const_y = xp.all(y == y[..., 0:1], axis=-1)
  3788. const_xy = const_x | const_y
  3789. any_const_xy = xp.any(const_xy)
  3790. lazy = is_lazy_array(const_xy)
  3791. if not lazy and any_const_xy:
  3792. msg = ("An input array is constant; the correlation coefficient "
  3793. "is not defined.")
  3794. warnings.warn(stats.ConstantInputWarning(msg), stacklevel=2)
  3795. if lazy or any_const_xy:
  3796. x = xp.where(const_x[..., xp.newaxis], xp.nan, x)
  3797. y = xp.where(const_y[..., xp.newaxis], xp.nan, y)
  3798. if isinstance(method, PermutationMethod):
  3799. def statistic(y, axis):
  3800. statistic, _ = pearsonr(x, y, axis=axis, alternative=alternative)
  3801. return statistic
  3802. res = permutation_test((y,), statistic, permutation_type='pairings',
  3803. axis=axis, alternative=alternative, **method._asdict())
  3804. return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n,
  3805. alternative=alternative, x=x, y=y, axis=axis)
  3806. elif isinstance(method, MonteCarloMethod):
  3807. def statistic(x, y, axis):
  3808. statistic, _ = pearsonr(x, y, axis=axis, alternative=alternative)
  3809. return statistic
  3810. # `monte_carlo_test` accepts an `rvs` tuple of callables, not an `rng`
  3811. # If the user specified an `rng`, replace it with the appropriate callables
  3812. method = method._asdict()
  3813. if (rng := method.pop('rng', None)) is not None: # goo-goo g'joob
  3814. rng = np.random.default_rng(rng)
  3815. method['rvs'] = rng.normal, rng.normal
  3816. res = monte_carlo_test((x, y,), statistic=statistic, axis=axis,
  3817. alternative=alternative, **method)
  3818. return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n,
  3819. alternative=alternative, x=x, y=y, axis=axis)
  3820. elif method == 'invalid':
  3821. message = '`method` must be `None` if arguments are not NumPy arrays.'
  3822. raise ValueError(message)
  3823. elif method is not None:
  3824. message = ('`method` must be an instance of `PermutationMethod`, '
  3825. '`MonteCarloMethod`, or None.')
  3826. raise ValueError(message)
  3827. xmean = xp.mean(x, axis=axis, keepdims=True)
  3828. ymean = xp.mean(y, axis=axis, keepdims=True)
  3829. xm = x - xmean
  3830. ym = y - ymean
  3831. # scipy.linalg.norm(xm) avoids premature overflow when xm is e.g.
  3832. # [-5e210, 5e210, 3e200, -3e200]
  3833. # but not when `axis` is provided, so scale manually. scipy.linalg.norm
  3834. # also raises an error with NaN input rather than returning NaN, so
  3835. # use np.linalg.norm.
  3836. xmax = xp.max(xp.abs(xm), axis=axis, keepdims=True)
  3837. ymax = xp.max(xp.abs(ym), axis=axis, keepdims=True)
  3838. with np.errstate(invalid='ignore', divide='ignore'):
  3839. normxm = xmax * xp_vector_norm(xm/xmax, axis=axis, keepdims=True)
  3840. normym = ymax * xp_vector_norm(ym/ymax, axis=axis, keepdims=True)
  3841. if not lazy:
  3842. nconst_x = xp.any(normxm < threshold*xp.abs(xmean), axis=axis)
  3843. nconst_y = xp.any(normym < threshold*xp.abs(ymean), axis=axis)
  3844. nconst_xy = nconst_x | nconst_y
  3845. if xp.any(nconst_xy & (~const_xy)):
  3846. # If all the values in x (likewise y) are very close to the mean,
  3847. # the loss of precision that occurs in the subtraction xm = x - xmean
  3848. # might result in large errors in r.
  3849. msg = ("An input array is nearly constant; the computed "
  3850. "correlation coefficient may be inaccurate.")
  3851. warnings.warn(stats.NearConstantInputWarning(msg), stacklevel=2)
  3852. with np.errstate(invalid='ignore', divide='ignore'):
  3853. r = xp.vecdot(xm / normxm, ym / normym, axis=axis)
  3854. # Presumably, if abs(r) > 1, then it is only some small artifact of
  3855. # floating point arithmetic.
  3856. r = xp.clip(r, -1., 1.)
  3857. r = xpx.at(r, const_xy).set(xp.nan)
  3858. # As explained in the docstring, the distribution of `r` under the null
  3859. # hypothesis is the beta distribution on (-1, 1) with a = b = n/2 - 1.
  3860. ab = xp.asarray(n/2 - 1, dtype=dtype, device=xp_device(x))
  3861. dist = _SimpleBeta(ab, ab, loc=-1, scale=2)
  3862. pvalue = _get_pvalue(r, dist, alternative, xp=xp)
  3863. mask = (n == 2) # return exactly 1.0 or -1.0 values for n == 2 case as promised
  3864. # data-apis/array-api-extra#196
  3865. mxp = array_namespace(r._meta) if is_dask(xp) else xp
  3866. def special_case(r):
  3867. return mxp.where(mxp.isnan(r), mxp.nan, mxp.ones_like(r))
  3868. r = xpx.apply_where(mask, r, mxp.round, fill_value=r)
  3869. pvalue = xpx.apply_where(mask, (r,), special_case, fill_value=pvalue)
  3870. r = r[()] if r.ndim == 0 else r
  3871. pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
  3872. return PearsonRResult(statistic=r, pvalue=pvalue, n=n,
  3873. alternative=alternative, x=x, y=y, axis=axis)
  3874. @xp_capabilities(np_only=True)
  3875. def fisher_exact(table, alternative=None, *, method=None):
  3876. """Perform a Fisher exact test on a contingency table.
  3877. For a 2x2 table,
  3878. the null hypothesis is that the true odds ratio of the populations
  3879. underlying the observations is one, and the observations were sampled
  3880. from these populations under a condition: the marginals of the
  3881. resulting table must equal those of the observed table.
  3882. The statistic is the unconditional maximum likelihood estimate of the odds
  3883. ratio, and the p-value is the probability under the null hypothesis of
  3884. obtaining a table at least as extreme as the one that was actually
  3885. observed.
  3886. For other table sizes, or if `method` is provided, the null hypothesis
  3887. is that the rows and columns of the tables have fixed sums and are
  3888. independent; i.e., the table was sampled from a `scipy.stats.random_table`
  3889. distribution with the observed marginals. The statistic is the
  3890. probability mass of this distribution evaluated at `table`, and the
  3891. p-value is the percentage of the population of tables with statistic at
  3892. least as extreme (small) as that of `table`. There is only one alternative
  3893. hypothesis available: the rows and columns are not independent.
  3894. There are other possible choices of statistic and two-sided
  3895. p-value definition associated with Fisher's exact test; please see the
  3896. Notes for more information.
  3897. Parameters
  3898. ----------
  3899. table : array_like of ints
  3900. A contingency table. Elements must be non-negative integers.
  3901. alternative : {'two-sided', 'less', 'greater'}, optional
  3902. Defines the alternative hypothesis for 2x2 tables; unused for other
  3903. table sizes.
  3904. The following options are available (default is 'two-sided'):
  3905. * 'two-sided': the odds ratio of the underlying population is not one
  3906. * 'less': the odds ratio of the underlying population is less than one
  3907. * 'greater': the odds ratio of the underlying population is greater
  3908. than one
  3909. See the Notes for more details.
  3910. method : ResamplingMethod, optional
  3911. Defines the method used to compute the p-value.
  3912. If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`,
  3913. the p-value is computed using
  3914. `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
  3915. provided configuration options and other appropriate settings.
  3916. Note that if `method` is an instance of `MonteCarloMethod`, the ``rvs``
  3917. attribute must be left unspecified; Monte Carlo samples are always drawn
  3918. using the ``rvs`` method of `scipy.stats.random_table`.
  3919. Otherwise, the p-value is computed as documented in the notes.
  3920. .. versionadded:: 1.15.0
  3921. Returns
  3922. -------
  3923. res : SignificanceResult
  3924. An object containing attributes:
  3925. statistic : float
  3926. For a 2x2 table with default `method`, this is the odds ratio - the
  3927. prior odds ratio not a posterior estimate. In all other cases, this
  3928. is the probability density of obtaining the observed table under the
  3929. null hypothesis of independence with marginals fixed.
  3930. pvalue : float
  3931. The probability under the null hypothesis of obtaining a
  3932. table at least as extreme as the one that was actually observed.
  3933. Raises
  3934. ------
  3935. ValueError
  3936. If `table` is not two-dimensional or has negative entries.
  3937. See Also
  3938. --------
  3939. chi2_contingency : Chi-square test of independence of variables in a
  3940. contingency table. This can be used as an alternative to
  3941. `fisher_exact` when the numbers in the table are large.
  3942. contingency.odds_ratio : Compute the odds ratio (sample or conditional
  3943. MLE) for a 2x2 contingency table.
  3944. barnard_exact : Barnard's exact test, which is a more powerful alternative
  3945. than Fisher's exact test for 2x2 contingency tables.
  3946. boschloo_exact : Boschloo's exact test, which is a more powerful
  3947. alternative than Fisher's exact test for 2x2 contingency tables.
  3948. :ref:`hypothesis_fisher_exact` : Extended example
  3949. Notes
  3950. -----
  3951. *Null hypothesis and p-values*
  3952. The null hypothesis is that the true odds ratio of the populations
  3953. underlying the observations is one, and the observations were sampled at
  3954. random from these populations under a condition: the marginals of the
  3955. resulting table must equal those of the observed table. Equivalently,
  3956. the null hypothesis is that the input table is from the hypergeometric
  3957. distribution with parameters (as used in `hypergeom`)
  3958. ``M = a + b + c + d``, ``n = a + b`` and ``N = a + c``, where the
  3959. input table is ``[[a, b], [c, d]]``. This distribution has support
  3960. ``max(0, N + n - M) <= x <= min(N, n)``, or, in terms of the values
  3961. in the input table, ``min(0, a - d) <= x <= a + min(b, c)``. ``x``
  3962. can be interpreted as the upper-left element of a 2x2 table, so the
  3963. tables in the distribution have form::
  3964. [ x n - x ]
  3965. [N - x M - (n + N) + x]
  3966. For example, if::
  3967. table = [6 2]
  3968. [1 4]
  3969. then the support is ``2 <= x <= 7``, and the tables in the distribution
  3970. are::
  3971. [2 6] [3 5] [4 4] [5 3] [6 2] [7 1]
  3972. [5 0] [4 1] [3 2] [2 3] [1 4] [0 5]
  3973. The probability of each table is given by the hypergeometric distribution
  3974. ``hypergeom.pmf(x, M, n, N)``. For this example, these are (rounded to
  3975. three significant digits)::
  3976. x 2 3 4 5 6 7
  3977. p 0.0163 0.163 0.408 0.326 0.0816 0.00466
  3978. These can be computed with::
  3979. >>> import numpy as np
  3980. >>> from scipy.stats import hypergeom
  3981. >>> table = np.array([[6, 2], [1, 4]])
  3982. >>> M = table.sum()
  3983. >>> n = table[0].sum()
  3984. >>> N = table[:, 0].sum()
  3985. >>> start, end = hypergeom.support(M, n, N)
  3986. >>> hypergeom.pmf(np.arange(start, end+1), M, n, N)
  3987. array([0.01631702, 0.16317016, 0.40792541, 0.32634033, 0.08158508,
  3988. 0.004662 ])
  3989. The two-sided p-value is the probability that, under the null hypothesis,
  3990. a random table would have a probability equal to or less than the
  3991. probability of the input table. For our example, the probability of
  3992. the input table (where ``x = 6``) is 0.0816. The x values where the
  3993. probability does not exceed this are 2, 6 and 7, so the two-sided p-value
  3994. is ``0.0163 + 0.0816 + 0.00466 ~= 0.10256``::
  3995. >>> from scipy.stats import fisher_exact
  3996. >>> res = fisher_exact(table, alternative='two-sided')
  3997. >>> res.pvalue
  3998. 0.10256410256410257
  3999. The one-sided p-value for ``alternative='greater'`` is the probability
  4000. that a random table has ``x >= a``, which in our example is ``x >= 6``,
  4001. or ``0.0816 + 0.00466 ~= 0.08626``::
  4002. >>> res = fisher_exact(table, alternative='greater')
  4003. >>> res.pvalue
  4004. 0.08624708624708627
  4005. This is equivalent to computing the survival function of the
  4006. distribution at ``x = 5`` (one less than ``x`` from the input table,
  4007. because we want to include the probability of ``x = 6`` in the sum)::
  4008. >>> hypergeom.sf(5, M, n, N)
  4009. 0.08624708624708627
  4010. For ``alternative='less'``, the one-sided p-value is the probability
  4011. that a random table has ``x <= a``, (i.e. ``x <= 6`` in our example),
  4012. or ``0.0163 + 0.163 + 0.408 + 0.326 + 0.0816 ~= 0.9949``::
  4013. >>> res = fisher_exact(table, alternative='less')
  4014. >>> res.pvalue
  4015. 0.9953379953379957
  4016. This is equivalent to computing the cumulative distribution function
  4017. of the distribution at ``x = 6``:
  4018. >>> hypergeom.cdf(6, M, n, N)
  4019. 0.9953379953379957
  4020. *Odds ratio*
  4021. The calculated odds ratio is different from the value computed by the
  4022. R function ``fisher.test``. This implementation returns the "sample"
  4023. or "unconditional" maximum likelihood estimate, while ``fisher.test``
  4024. in R uses the conditional maximum likelihood estimate. To compute the
  4025. conditional maximum likelihood estimate of the odds ratio, use
  4026. `scipy.stats.contingency.odds_ratio`.
  4027. References
  4028. ----------
  4029. .. [1] Fisher, Sir Ronald A, "The Design of Experiments:
  4030. Mathematics of a Lady Tasting Tea." ISBN 978-0-486-41151-4, 1935.
  4031. .. [2] "Fisher's exact test",
  4032. https://en.wikipedia.org/wiki/Fisher's_exact_test
  4033. Examples
  4034. --------
  4035. >>> from scipy.stats import fisher_exact
  4036. >>> res = fisher_exact([[8, 2], [1, 5]])
  4037. >>> res.statistic
  4038. 20.0
  4039. >>> res.pvalue
  4040. 0.034965034965034975
  4041. For tables with shape other than ``(2, 2)``, provide an instance of
  4042. `scipy.stats.MonteCarloMethod` or `scipy.stats.PermutationMethod` for the
  4043. `method` parameter:
  4044. >>> import numpy as np
  4045. >>> from scipy.stats import MonteCarloMethod
  4046. >>> rng = np.random.default_rng(4507195762371367)
  4047. >>> method = MonteCarloMethod(rng=rng)
  4048. >>> fisher_exact([[8, 2, 3], [1, 5, 4]], method=method)
  4049. SignificanceResult(statistic=np.float64(0.005782), pvalue=np.float64(0.0603))
  4050. For a more detailed example, see :ref:`hypothesis_fisher_exact`.
  4051. """
  4052. hypergeom = distributions.hypergeom
  4053. # int32 is not enough for the algorithm
  4054. c = np.asarray(table, dtype=np.int64)
  4055. if not c.ndim == 2:
  4056. raise ValueError("The input `table` must have two dimensions.")
  4057. if np.any(c < 0):
  4058. raise ValueError("All values in `table` must be nonnegative.")
  4059. if not c.shape == (2, 2) or method is not None:
  4060. return _fisher_exact_rxc(c, alternative, method)
  4061. alternative = 'two-sided' if alternative is None else alternative
  4062. if 0 in c.sum(axis=0) or 0 in c.sum(axis=1):
  4063. # If both values in a row or column are zero, the p-value is 1 and
  4064. # the odds ratio is NaN.
  4065. return SignificanceResult(np.nan, 1.0)
  4066. if c[1, 0] > 0 and c[0, 1] > 0:
  4067. oddsratio = c[0, 0] * c[1, 1] / (c[1, 0] * c[0, 1])
  4068. else:
  4069. oddsratio = np.inf
  4070. n1 = c[0, 0] + c[0, 1]
  4071. n2 = c[1, 0] + c[1, 1]
  4072. n = c[0, 0] + c[1, 0]
  4073. def pmf(x):
  4074. return hypergeom.pmf(x, n1 + n2, n1, n)
  4075. if alternative == 'less':
  4076. pvalue = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
  4077. elif alternative == 'greater':
  4078. # Same formula as the 'less' case, but with the second column.
  4079. pvalue = hypergeom.cdf(c[0, 1], n1 + n2, n1, c[0, 1] + c[1, 1])
  4080. elif alternative == 'two-sided':
  4081. mode = int((n + 1) * (n1 + 1) / (n1 + n2 + 2))
  4082. pexact = hypergeom.pmf(c[0, 0], n1 + n2, n1, n)
  4083. pmode = hypergeom.pmf(mode, n1 + n2, n1, n)
  4084. epsilon = 1e-14
  4085. gamma = 1 + epsilon
  4086. if np.abs(pexact - pmode) / np.maximum(pexact, pmode) <= epsilon:
  4087. return SignificanceResult(oddsratio, 1.)
  4088. elif c[0, 0] < mode:
  4089. plower = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
  4090. if hypergeom.pmf(n, n1 + n2, n1, n) > pexact * gamma:
  4091. return SignificanceResult(oddsratio, plower)
  4092. guess = _binary_search(lambda x: -pmf(x), -pexact * gamma, mode, n)
  4093. pvalue = plower + hypergeom.sf(guess, n1 + n2, n1, n)
  4094. else:
  4095. pupper = hypergeom.sf(c[0, 0] - 1, n1 + n2, n1, n)
  4096. if hypergeom.pmf(0, n1 + n2, n1, n) > pexact * gamma:
  4097. return SignificanceResult(oddsratio, pupper)
  4098. guess = _binary_search(pmf, pexact * gamma, 0, mode)
  4099. pvalue = pupper + hypergeom.cdf(guess, n1 + n2, n1, n)
  4100. else:
  4101. msg = "`alternative` should be one of {'two-sided', 'less', 'greater'}"
  4102. raise ValueError(msg)
  4103. pvalue = min(pvalue, 1.0)
  4104. return SignificanceResult(oddsratio, pvalue)
  4105. def _fisher_exact_rxc(table, alternative, method):
  4106. if alternative is not None:
  4107. message = ('`alternative` must be the default (None) unless '
  4108. '`table` has shape `(2, 2)` and `method is None`.')
  4109. raise ValueError(message)
  4110. if table.size == 0:
  4111. raise ValueError("`table` must have at least one row and one column.")
  4112. if table.shape[0] == 1 or table.shape[1] == 1 or np.all(table == 0):
  4113. # Only one such table with those marginals
  4114. return SignificanceResult(1.0, 1.0)
  4115. if method is None:
  4116. method = stats.MonteCarloMethod()
  4117. if isinstance(method, stats.PermutationMethod):
  4118. res = _fisher_exact_permutation_method(table, method)
  4119. elif isinstance(method, stats.MonteCarloMethod):
  4120. res = _fisher_exact_monte_carlo_method(table, method)
  4121. else:
  4122. message = (f'`{method=}` not recognized; if provided, `method` must be an '
  4123. 'instance of `PermutationMethod` or `MonteCarloMethod`.')
  4124. raise ValueError(message)
  4125. return SignificanceResult(np.clip(res.statistic, None, 1.0), res.pvalue)
  4126. def _fisher_exact_permutation_method(table, method):
  4127. x, y = _untabulate(table)
  4128. colsums = np.sum(table, axis=0)
  4129. rowsums = np.sum(table, axis=1)
  4130. X = stats.random_table(rowsums, colsums)
  4131. # `permutation_test` with `permutation_type='pairings' permutes the order of `x`,
  4132. # which pairs observations in `x` with different observations in `y`.
  4133. def statistic(x):
  4134. # crosstab the resample and compute the statistic
  4135. table = stats.contingency.crosstab(x, y)[1]
  4136. return X.pmf(table)
  4137. # tables with *smaller* probability mass are considered to be more extreme
  4138. return stats.permutation_test((x,), statistic, permutation_type='pairings',
  4139. alternative='less', **method._asdict())
  4140. def _fisher_exact_monte_carlo_method(table, method):
  4141. method = method._asdict()
  4142. if method.pop('rvs', None) is not None:
  4143. message = ('If the `method` argument of `fisher_exact` is an '
  4144. 'instance of `MonteCarloMethod`, its `rvs` attribute '
  4145. 'must be unspecified. Use the `MonteCarloMethod` `rng` argument '
  4146. 'to control the random state.')
  4147. raise ValueError(message)
  4148. rng = np.random.default_rng(method.pop('rng', None))
  4149. # `random_table.rvs` produces random contingency tables with the given marginals
  4150. # under the null hypothesis of independence
  4151. shape = table.shape
  4152. colsums = np.sum(table, axis=0)
  4153. rowsums = np.sum(table, axis=1)
  4154. totsum = np.sum(table)
  4155. X = stats.random_table(rowsums, colsums, seed=rng)
  4156. def rvs(size):
  4157. n_resamples = size[0]
  4158. return X.rvs(size=n_resamples).reshape(size)
  4159. # axis signals to `monte_carlo_test` that statistic is vectorized, but we know
  4160. # how it will pass the table(s), so we don't need to use `axis` explicitly.
  4161. def statistic(table, axis):
  4162. shape_ = (-1,) + shape if table.size > totsum else shape
  4163. return X.pmf(table.reshape(shape_))
  4164. # tables with *smaller* probability mass are considered to be more extreme
  4165. return stats.monte_carlo_test(table.ravel(), rvs, statistic,
  4166. alternative='less', **method)
  4167. def _untabulate(table):
  4168. # converts a contingency table to paired samples indicating the
  4169. # correspondence between row and column indices
  4170. r, c = table.shape
  4171. x, y = [], []
  4172. for i in range(r):
  4173. for j in range(c):
  4174. x.append([i] * table[i, j])
  4175. y.append([j] * table[i, j])
  4176. return np.concatenate(x), np.concatenate(y)
  4177. @xp_capabilities(np_only=True)
  4178. def spearmanr(a, b=None, axis=0, nan_policy='propagate',
  4179. alternative='two-sided'):
  4180. r"""Calculate a Spearman correlation coefficient with associated p-value.
  4181. The Spearman rank-order correlation coefficient is a nonparametric measure
  4182. of the monotonicity of the relationship between two datasets.
  4183. Like other correlation coefficients,
  4184. this one varies between -1 and +1 with 0 implying no correlation.
  4185. Correlations of -1 or +1 imply an exact monotonic relationship. Positive
  4186. correlations imply that as x increases, so does y. Negative correlations
  4187. imply that as x increases, y decreases.
  4188. The p-value roughly indicates the probability of an uncorrelated system
  4189. producing datasets that have a Spearman correlation at least as extreme
  4190. as the one computed from these datasets. Although calculation of the
  4191. p-value does not make strong assumptions about the distributions underlying
  4192. the samples, it is only accurate for very large samples (>500
  4193. observations). For smaller sample sizes, consider a permutation test (see
  4194. Examples section below).
  4195. Parameters
  4196. ----------
  4197. a, b : 1D or 2D array_like, b is optional
  4198. One or two 1-D or 2-D arrays containing multiple variables and
  4199. observations. When these are 1-D, each represents a vector of
  4200. observations of a single variable. For the behavior in the 2-D case,
  4201. see under ``axis``, below.
  4202. Both arrays need to have the same length in the ``axis`` dimension.
  4203. axis : int or None, optional
  4204. If axis=0 (default), then each column represents a variable, with
  4205. observations in the rows. If axis=1, the relationship is transposed:
  4206. each row represents a variable, while the columns contain observations.
  4207. If axis=None, then both arrays will be raveled.
  4208. nan_policy : {'propagate', 'raise', 'omit'}, optional
  4209. Defines how to handle when input contains nan.
  4210. The following options are available (default is 'propagate'):
  4211. * 'propagate': returns nan
  4212. * 'raise': throws an error
  4213. * 'omit': performs the calculations ignoring nan values
  4214. alternative : {'two-sided', 'less', 'greater'}, optional
  4215. Defines the alternative hypothesis. Default is 'two-sided'.
  4216. The following options are available:
  4217. * 'two-sided': the correlation is nonzero
  4218. * 'less': the correlation is negative (less than zero)
  4219. * 'greater': the correlation is positive (greater than zero)
  4220. .. versionadded:: 1.7.0
  4221. Returns
  4222. -------
  4223. res : SignificanceResult
  4224. An object containing attributes:
  4225. statistic : float or ndarray (2-D square)
  4226. Spearman correlation matrix or correlation coefficient (if only 2
  4227. variables are given as parameters). Correlation matrix is square
  4228. with length equal to total number of variables (columns or rows) in
  4229. ``a`` and ``b`` combined.
  4230. pvalue : float
  4231. The p-value for a hypothesis test whose null hypothesis
  4232. is that two samples have no ordinal correlation. See
  4233. `alternative` above for alternative hypotheses. `pvalue` has the
  4234. same shape as `statistic`.
  4235. Raises
  4236. ------
  4237. ValueError
  4238. If `axis` is not 0, 1 or None, or if the number of dimensions of `a`
  4239. is greater than 2, or if `b` is None and the number of dimensions of
  4240. `a` is less than 2.
  4241. Warns
  4242. -----
  4243. `~scipy.stats.ConstantInputWarning`
  4244. Raised if an input is a constant array. The correlation coefficient
  4245. is not defined in this case, so ``np.nan`` is returned.
  4246. See Also
  4247. --------
  4248. :ref:`hypothesis_spearmanr` : Extended example
  4249. References
  4250. ----------
  4251. .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
  4252. Probability and Statistics Tables and Formulae. Chapman & Hall: New
  4253. York. 2000.
  4254. Section 14.7
  4255. .. [2] Kendall, M. G. and Stuart, A. (1973).
  4256. The Advanced Theory of Statistics, Volume 2: Inference and Relationship.
  4257. Griffin. 1973.
  4258. Section 31.18
  4259. Examples
  4260. --------
  4261. >>> import numpy as np
  4262. >>> from scipy import stats
  4263. >>> res = stats.spearmanr([1, 2, 3, 4, 5], [5, 6, 7, 8, 7])
  4264. >>> res.statistic
  4265. 0.8207826816681233
  4266. >>> res.pvalue
  4267. 0.08858700531354381
  4268. >>> rng = np.random.default_rng()
  4269. >>> x2n = rng.standard_normal((100, 2))
  4270. >>> y2n = rng.standard_normal((100, 2))
  4271. >>> res = stats.spearmanr(x2n)
  4272. >>> res.statistic, res.pvalue
  4273. (-0.07960396039603959, 0.4311168705769747)
  4274. >>> res = stats.spearmanr(x2n[:, 0], x2n[:, 1])
  4275. >>> res.statistic, res.pvalue
  4276. (-0.07960396039603959, 0.4311168705769747)
  4277. >>> res = stats.spearmanr(x2n, y2n)
  4278. >>> res.statistic
  4279. array([[ 1. , -0.07960396, -0.08314431, 0.09662166],
  4280. [-0.07960396, 1. , -0.14448245, 0.16738074],
  4281. [-0.08314431, -0.14448245, 1. , 0.03234323],
  4282. [ 0.09662166, 0.16738074, 0.03234323, 1. ]])
  4283. >>> res.pvalue
  4284. array([[0. , 0.43111687, 0.41084066, 0.33891628],
  4285. [0.43111687, 0. , 0.15151618, 0.09600687],
  4286. [0.41084066, 0.15151618, 0. , 0.74938561],
  4287. [0.33891628, 0.09600687, 0.74938561, 0. ]])
  4288. >>> res = stats.spearmanr(x2n.T, y2n.T, axis=1)
  4289. >>> res.statistic
  4290. array([[ 1. , -0.07960396, -0.08314431, 0.09662166],
  4291. [-0.07960396, 1. , -0.14448245, 0.16738074],
  4292. [-0.08314431, -0.14448245, 1. , 0.03234323],
  4293. [ 0.09662166, 0.16738074, 0.03234323, 1. ]])
  4294. >>> res = stats.spearmanr(x2n, y2n, axis=None)
  4295. >>> res.statistic, res.pvalue
  4296. (0.044981624540613524, 0.5270803651336189)
  4297. >>> res = stats.spearmanr(x2n.ravel(), y2n.ravel())
  4298. >>> res.statistic, res.pvalue
  4299. (0.044981624540613524, 0.5270803651336189)
  4300. >>> rng = np.random.default_rng()
  4301. >>> xint = rng.integers(10, size=(100, 2))
  4302. >>> res = stats.spearmanr(xint)
  4303. >>> res.statistic, res.pvalue
  4304. (0.09800224850707953, 0.3320271757932076)
  4305. For small samples, consider performing a permutation test instead of
  4306. relying on the asymptotic p-value. Note that to calculate the null
  4307. distribution of the statistic (for all possibly pairings between
  4308. observations in sample ``x`` and ``y``), only one of the two inputs needs
  4309. to be permuted.
  4310. >>> x = [1.76405235, 0.40015721, 0.97873798,
  4311. ... 2.2408932, 1.86755799, -0.97727788]
  4312. >>> y = [2.71414076, 0.2488, 0.87551913,
  4313. ... 2.6514917, 2.01160156, 0.47699563]
  4314. >>> def statistic(x): # permute only `x`
  4315. ... return stats.spearmanr(x, y).statistic
  4316. >>> res_exact = stats.permutation_test((x,), statistic,
  4317. ... permutation_type='pairings')
  4318. >>> res_asymptotic = stats.spearmanr(x, y)
  4319. >>> res_exact.pvalue, res_asymptotic.pvalue # asymptotic pvalue is too low
  4320. (0.10277777777777777, 0.07239650145772594)
  4321. For a more detailed example, see :ref:`hypothesis_spearmanr`.
  4322. """
  4323. if axis is not None and axis > 1:
  4324. raise ValueError("spearmanr only handles 1-D or 2-D arrays, "
  4325. f"supplied axis argument {axis}, please use only "
  4326. "values 0, 1 or None for axis")
  4327. a, axisout = _chk_asarray(a, axis)
  4328. if a.ndim > 2:
  4329. raise ValueError("spearmanr only handles 1-D or 2-D arrays")
  4330. if b is None:
  4331. if a.ndim < 2:
  4332. raise ValueError("`spearmanr` needs at least 2 "
  4333. "variables to compare")
  4334. else:
  4335. # Concatenate a and b, so that we now only have to handle the case
  4336. # of a 2-D `a`.
  4337. b, _ = _chk_asarray(b, axis)
  4338. if axisout == 0:
  4339. a = np.column_stack((a, b))
  4340. else:
  4341. a = np.vstack((a, b))
  4342. n_vars = a.shape[1 - axisout]
  4343. n_obs = a.shape[axisout]
  4344. if n_obs <= 1:
  4345. # Handle empty arrays or single observations.
  4346. res = SignificanceResult(np.nan, np.nan)
  4347. res.correlation = np.nan
  4348. return res
  4349. warn_msg = ("An input array is constant; the correlation coefficient "
  4350. "is not defined.")
  4351. if axisout == 0:
  4352. if (a[:, 0][0] == a[:, 0]).all() or (a[:, 1][0] == a[:, 1]).all():
  4353. # If an input is constant, the correlation coefficient
  4354. # is not defined.
  4355. warnings.warn(stats.ConstantInputWarning(warn_msg), stacklevel=2)
  4356. res = SignificanceResult(np.nan, np.nan)
  4357. res.correlation = np.nan
  4358. return res
  4359. else: # case when axisout == 1 b/c a is 2 dim only
  4360. if (a[0, :][0] == a[0, :]).all() or (a[1, :][0] == a[1, :]).all():
  4361. # If an input is constant, the correlation coefficient
  4362. # is not defined.
  4363. warnings.warn(stats.ConstantInputWarning(warn_msg), stacklevel=2)
  4364. res = SignificanceResult(np.nan, np.nan)
  4365. res.correlation = np.nan
  4366. return res
  4367. a_contains_nan = _contains_nan(a, nan_policy)
  4368. variable_has_nan = np.zeros(n_vars, dtype=bool)
  4369. if a_contains_nan:
  4370. if nan_policy == 'omit':
  4371. return mstats_basic.spearmanr(a, axis=axis, nan_policy=nan_policy,
  4372. alternative=alternative)
  4373. elif nan_policy == 'propagate':
  4374. if a.ndim == 1 or n_vars <= 2:
  4375. res = SignificanceResult(np.nan, np.nan)
  4376. res.correlation = np.nan
  4377. return res
  4378. else:
  4379. # Keep track of variables with NaNs, set the outputs to NaN
  4380. # only for those variables
  4381. variable_has_nan = np.isnan(a).any(axis=axisout)
  4382. a_ranked = np.apply_along_axis(rankdata, axisout, a)
  4383. rs = np.corrcoef(a_ranked, rowvar=axisout)
  4384. dof = n_obs - 2 # degrees of freedom
  4385. # rs can have elements equal to 1, so avoid zero division warnings
  4386. with np.errstate(divide='ignore'):
  4387. # clip the small negative values possibly caused by rounding
  4388. # errors before taking the square root
  4389. t = rs * np.sqrt((dof/((rs+1.0)*(1.0-rs))).clip(0))
  4390. dist = _SimpleStudentT(dof)
  4391. prob = _get_pvalue(t, dist, alternative, xp=np)
  4392. # For backwards compatibility, return scalars when comparing 2 columns
  4393. if rs.shape == (2, 2):
  4394. res = SignificanceResult(rs[1, 0], prob[1, 0])
  4395. res.correlation = rs[1, 0]
  4396. return res
  4397. else:
  4398. rs[variable_has_nan, :] = np.nan
  4399. rs[:, variable_has_nan] = np.nan
  4400. res = SignificanceResult(rs[()], prob[()])
  4401. res.correlation = rs
  4402. return res
  4403. @xp_capabilities(np_only=True)
  4404. @_axis_nan_policy_factory(_pack_CorrelationResult, n_samples=2,
  4405. result_to_tuple=_unpack_CorrelationResult, paired=True,
  4406. too_small=1, n_outputs=3)
  4407. def pointbiserialr(x, y):
  4408. r"""Calculate a point biserial correlation coefficient and its p-value.
  4409. The point biserial correlation is used to measure the relationship
  4410. between a binary variable, x, and a continuous variable, y. Like other
  4411. correlation coefficients, this one varies between -1 and +1 with 0
  4412. implying no correlation. Correlations of -1 or +1 imply a determinative
  4413. relationship.
  4414. This function may be computed using a shortcut formula but produces the
  4415. same result as `pearsonr`.
  4416. Parameters
  4417. ----------
  4418. x : array_like of bools
  4419. Input array.
  4420. y : array_like
  4421. Input array.
  4422. Returns
  4423. -------
  4424. res: SignificanceResult
  4425. An object containing attributes:
  4426. statistic : float
  4427. The R value.
  4428. pvalue : float
  4429. The two-sided p-value.
  4430. Notes
  4431. -----
  4432. `pointbiserialr` uses a t-test with ``n-1`` degrees of freedom.
  4433. It is equivalent to `pearsonr`.
  4434. The value of the point-biserial correlation can be calculated from:
  4435. .. math::
  4436. r_{pb} = \frac{\overline{Y_1} - \overline{Y_0}}
  4437. {s_y}
  4438. \sqrt{\frac{N_0 N_1}
  4439. {N (N - 1)}}
  4440. Where :math:`\overline{Y_{0}}` and :math:`\overline{Y_{1}}` are means
  4441. of the metric observations coded 0 and 1 respectively; :math:`N_{0}` and
  4442. :math:`N_{1}` are number of observations coded 0 and 1 respectively;
  4443. :math:`N` is the total number of observations and :math:`s_{y}` is the
  4444. standard deviation of all the metric observations.
  4445. A value of :math:`r_{pb}` that is significantly different from zero is
  4446. completely equivalent to a significant difference in means between the two
  4447. groups. Thus, an independent groups t Test with :math:`N-2` degrees of
  4448. freedom may be used to test whether :math:`r_{pb}` is nonzero. The
  4449. relation between the t-statistic for comparing two independent groups and
  4450. :math:`r_{pb}` is given by:
  4451. .. math::
  4452. t = \sqrt{N - 2}\frac{r_{pb}}{\sqrt{1 - r^{2}_{pb}}}
  4453. References
  4454. ----------
  4455. .. [1] J. Lev, "The Point Biserial Coefficient of Correlation", Ann. Math.
  4456. Statist., Vol. 20, no.1, pp. 125-126, 1949.
  4457. .. [2] R.F. Tate, "Correlation Between a Discrete and a Continuous
  4458. Variable. Point-Biserial Correlation.", Ann. Math. Statist., Vol. 25,
  4459. np. 3, pp. 603-607, 1954.
  4460. .. [3] D. Kornbrot "Point Biserial Correlation", In Wiley StatsRef:
  4461. Statistics Reference Online (eds N. Balakrishnan, et al.), 2014.
  4462. :doi:`10.1002/9781118445112.stat06227`
  4463. Examples
  4464. --------
  4465. >>> import numpy as np
  4466. >>> from scipy import stats
  4467. >>> a = np.array([0, 0, 0, 1, 1, 1, 1])
  4468. >>> b = np.arange(7)
  4469. >>> stats.pointbiserialr(a, b)
  4470. (0.8660254037844386, 0.011724811003954652)
  4471. >>> stats.pearsonr(a, b)
  4472. (0.86602540378443871, 0.011724811003954626)
  4473. >>> np.corrcoef(a, b)
  4474. array([[ 1. , 0.8660254],
  4475. [ 0.8660254, 1. ]])
  4476. """
  4477. rpb, prob = pearsonr(x, y)
  4478. # create result object with alias for backward compatibility
  4479. res = SignificanceResult(rpb, prob)
  4480. res.correlation = rpb
  4481. return res
  4482. @xp_capabilities(np_only=True)
  4483. @_axis_nan_policy_factory(_pack_CorrelationResult, default_axis=None, n_samples=2,
  4484. result_to_tuple=_unpack_CorrelationResult, paired=True,
  4485. too_small=1, n_outputs=3)
  4486. def kendalltau(x, y, *, nan_policy='propagate',
  4487. method='auto', variant='b', alternative='two-sided'):
  4488. r"""Calculate Kendall's tau, a correlation measure for ordinal data.
  4489. Kendall's tau is a measure of the correspondence between two rankings.
  4490. Values close to 1 indicate strong agreement, and values close to -1
  4491. indicate strong disagreement. This implements two variants of Kendall's
  4492. tau: tau-b (the default) and tau-c (also known as Stuart's tau-c). These
  4493. differ only in how they are normalized to lie within the range -1 to 1;
  4494. the hypothesis tests (their p-values) are identical. Kendall's original
  4495. tau-a is not implemented separately because both tau-b and tau-c reduce
  4496. to tau-a in the absence of ties.
  4497. Although a naive implementation has O(n^2) complexity, this implementation
  4498. uses a Fenwick tree to do the computation in O(n log(n)) complexity.
  4499. Parameters
  4500. ----------
  4501. x, y : array_like
  4502. Arrays of rankings, of the same shape. If arrays are not 1-D, they
  4503. will be flattened to 1-D.
  4504. nan_policy : {'propagate', 'raise', 'omit'}, optional
  4505. Defines how to handle when input contains nan.
  4506. The following options are available (default is 'propagate'):
  4507. * 'propagate': returns nan
  4508. * 'raise': throws an error
  4509. * 'omit': performs the calculations ignoring nan values
  4510. method : {'auto', 'asymptotic', 'exact'}, optional
  4511. Defines which method is used to calculate the p-value [5]_.
  4512. The following options are available (default is 'auto'):
  4513. * 'auto': selects the appropriate method based on a trade-off
  4514. between speed and accuracy
  4515. * 'asymptotic': uses a normal approximation valid for large samples
  4516. * 'exact': computes the exact p-value, but can only be used if no ties
  4517. are present. As the sample size increases, the 'exact' computation
  4518. time may grow and the result may lose some precision.
  4519. variant : {'b', 'c'}, optional
  4520. Defines which variant of Kendall's tau is returned. Default is 'b'.
  4521. alternative : {'two-sided', 'less', 'greater'}, optional
  4522. Defines the alternative hypothesis. Default is 'two-sided'.
  4523. The following options are available:
  4524. * 'two-sided': the rank correlation is nonzero
  4525. * 'less': the rank correlation is negative (less than zero)
  4526. * 'greater': the rank correlation is positive (greater than zero)
  4527. Returns
  4528. -------
  4529. res : SignificanceResult
  4530. An object containing attributes:
  4531. statistic : float
  4532. The tau statistic.
  4533. pvalue : float
  4534. The p-value for a hypothesis test whose null hypothesis is
  4535. an absence of association, tau = 0.
  4536. Raises
  4537. ------
  4538. ValueError
  4539. If `nan_policy` is 'omit' and `variant` is not 'b' or
  4540. if `method` is 'exact' and there are ties between `x` and `y`.
  4541. See Also
  4542. --------
  4543. spearmanr : Calculates a Spearman rank-order correlation coefficient.
  4544. theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
  4545. weightedtau : Computes a weighted version of Kendall's tau.
  4546. :ref:`hypothesis_kendalltau` : Extended example
  4547. Notes
  4548. -----
  4549. The definition of Kendall's tau that is used is [2]_::
  4550. tau_b = (P - Q) / sqrt((P + Q + T) * (P + Q + U))
  4551. tau_c = 2 (P - Q) / (n**2 * (m - 1) / m)
  4552. where P is the number of concordant pairs, Q the number of discordant
  4553. pairs, T the number of tied pairs only in `x`, and U the number of tied pairs only
  4554. in `y`. If a tie occurs for the same pair in both `x` and `y`, it is not
  4555. added to either T or U. n is the total number of samples, and m is the
  4556. number of unique values in either `x` or `y`, whichever is smaller.
  4557. References
  4558. ----------
  4559. .. [1] Maurice G. Kendall, "A New Measure of Rank Correlation", Biometrika
  4560. Vol. 30, No. 1/2, pp. 81-93, 1938.
  4561. .. [2] Maurice G. Kendall, "The treatment of ties in ranking problems",
  4562. Biometrika Vol. 33, No. 3, pp. 239-251. 1945.
  4563. .. [3] Gottfried E. Noether, "Elements of Nonparametric Statistics", John
  4564. Wiley & Sons, 1967.
  4565. .. [4] Peter M. Fenwick, "A new data structure for cumulative frequency
  4566. tables", Software: Practice and Experience, Vol. 24, No. 3,
  4567. pp. 327-336, 1994.
  4568. .. [5] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
  4569. Charles Griffin & Co., 1970.
  4570. Examples
  4571. --------
  4572. >>> from scipy import stats
  4573. >>> x1 = [12, 2, 1, 12, 2]
  4574. >>> x2 = [1, 4, 7, 1, 0]
  4575. >>> res = stats.kendalltau(x1, x2)
  4576. >>> res.statistic
  4577. -0.47140452079103173
  4578. >>> res.pvalue
  4579. 0.2827454599327748
  4580. For a more detailed example, see :ref:`hypothesis_kendalltau`.
  4581. """
  4582. x = np.asarray(x).ravel()
  4583. y = np.asarray(y).ravel()
  4584. if x.size != y.size:
  4585. raise ValueError("Array shapes are incompatible for broadcasting.")
  4586. elif not x.size or not y.size:
  4587. # Return NaN if arrays are empty
  4588. NaN = _get_nan(x, y)
  4589. res = SignificanceResult(NaN, NaN)
  4590. res.correlation = NaN
  4591. return res
  4592. def count_rank_tie(ranks):
  4593. cnt = np.bincount(ranks).astype('int64', copy=False)
  4594. cnt = cnt[cnt > 1]
  4595. # Python ints to avoid overflow down the line
  4596. return (int((cnt * (cnt - 1) // 2).sum()),
  4597. int((cnt * (cnt - 1.) * (cnt - 2)).sum()),
  4598. int((cnt * (cnt - 1.) * (2*cnt + 5)).sum()))
  4599. size = x.size
  4600. perm = np.argsort(y) # sort on y and convert y to dense ranks
  4601. x, y = x[perm], y[perm]
  4602. y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp)
  4603. # stable sort on x and convert x to dense ranks
  4604. perm = np.argsort(x, kind='mergesort')
  4605. x, y = x[perm], y[perm]
  4606. x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp)
  4607. dis = _kendall_dis(x, y) # discordant pairs
  4608. obs = np.r_[True, (x[1:] != x[:-1]) | (y[1:] != y[:-1]), True]
  4609. cnt = np.diff(np.nonzero(obs)[0]).astype('int64', copy=False)
  4610. ntie = int((cnt * (cnt - 1) // 2).sum()) # joint ties
  4611. xtie, x0, x1 = count_rank_tie(x) # ties in x, stats
  4612. ytie, y0, y1 = count_rank_tie(y) # ties in y, stats
  4613. tot = (size * (size - 1)) // 2
  4614. if xtie == tot or ytie == tot:
  4615. NaN = _get_nan(x, y)
  4616. res = SignificanceResult(NaN, NaN)
  4617. res.correlation = NaN
  4618. return res
  4619. # Note that tot = con + dis + (xtie - ntie) + (ytie - ntie) + ntie
  4620. # = con + dis + xtie + ytie - ntie
  4621. con_minus_dis = tot - xtie - ytie + ntie - 2 * dis
  4622. if variant == 'b':
  4623. tau = con_minus_dis / np.sqrt(tot - xtie) / np.sqrt(tot - ytie)
  4624. elif variant == 'c':
  4625. minclasses = min(len(set(x)), len(set(y)))
  4626. tau = 2*con_minus_dis / (size**2 * (minclasses-1)/minclasses)
  4627. else:
  4628. raise ValueError(f"Unknown variant of the method chosen: {variant}. "
  4629. "variant must be 'b' or 'c'.")
  4630. # Limit range to fix computational errors
  4631. tau = np.minimum(1., max(-1., tau))
  4632. # The p-value calculation is the same for all variants since the p-value
  4633. # depends only on con_minus_dis.
  4634. if method == 'exact' and (xtie != 0 or ytie != 0):
  4635. raise ValueError("Ties found, exact method cannot be used.")
  4636. if method == 'auto':
  4637. if (xtie == 0 and ytie == 0) and (size <= 33 or
  4638. min(dis, tot-dis) <= 1):
  4639. method = 'exact'
  4640. else:
  4641. method = 'asymptotic'
  4642. if xtie == 0 and ytie == 0 and method == 'exact':
  4643. pvalue = mstats_basic._kendall_p_exact(size, tot-dis, alternative)
  4644. elif method == 'asymptotic':
  4645. # con_minus_dis is approx normally distributed with this variance [3]_
  4646. m = size * (size - 1.)
  4647. var = ((m * (2*size + 5) - x1 - y1) / 18 +
  4648. (2 * xtie * ytie) / m + x0 * y0 / (9 * m * (size - 2)))
  4649. z = con_minus_dis / np.sqrt(var)
  4650. pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
  4651. else:
  4652. raise ValueError(f"Unknown method {method} specified. Use 'auto', "
  4653. "'exact' or 'asymptotic'.")
  4654. # create result object with alias for backward compatibility
  4655. res = SignificanceResult(tau[()], pvalue[()])
  4656. res.correlation = tau[()]
  4657. return res
  4658. def _weightedtau_n_samples(kwargs):
  4659. rank = kwargs.get('rank', False)
  4660. return 2 if (isinstance(rank, bool) or rank is None) else 3
  4661. @xp_capabilities(np_only=True)
  4662. @_axis_nan_policy_factory(_pack_CorrelationResult, default_axis=None,
  4663. n_samples=_weightedtau_n_samples,
  4664. result_to_tuple=_unpack_CorrelationResult, paired=True,
  4665. too_small=1, n_outputs=3, override={'nan_propagation': False})
  4666. def weightedtau(x, y, rank=True, weigher=None, additive=True):
  4667. r"""Compute a weighted version of Kendall's :math:`\tau`.
  4668. The weighted :math:`\tau` is a weighted version of Kendall's
  4669. :math:`\tau` in which exchanges of high weight are more influential than
  4670. exchanges of low weight. The default parameters compute the additive
  4671. hyperbolic version of the index, :math:`\tau_\mathrm h`, which has
  4672. been shown to provide the best balance between important and
  4673. unimportant elements [1]_.
  4674. The weighting is defined by means of a rank array, which assigns a
  4675. nonnegative rank to each element (higher importance ranks being
  4676. associated with smaller values, e.g., 0 is the highest possible rank),
  4677. and a weigher function, which assigns a weight based on the rank to
  4678. each element. The weight of an exchange is then the sum or the product
  4679. of the weights of the ranks of the exchanged elements. The default
  4680. parameters compute :math:`\tau_\mathrm h`: an exchange between
  4681. elements with rank :math:`r` and :math:`s` (starting from zero) has
  4682. weight :math:`1/(r+1) + 1/(s+1)`.
  4683. Specifying a rank array is meaningful only if you have in mind an
  4684. external criterion of importance. If, as it usually happens, you do
  4685. not have in mind a specific rank, the weighted :math:`\tau` is
  4686. defined by averaging the values obtained using the decreasing
  4687. lexicographical rank by (`x`, `y`) and by (`y`, `x`). This is the
  4688. behavior with default parameters. Note that the convention used
  4689. here for ranking (lower values imply higher importance) is opposite
  4690. to that used by other SciPy statistical functions.
  4691. Parameters
  4692. ----------
  4693. x, y : array_like
  4694. Arrays of scores, of the same shape. If arrays are not 1-D, they will
  4695. be flattened to 1-D.
  4696. rank : array_like of ints or bool, optional
  4697. A nonnegative rank assigned to each element. If it is None, the
  4698. decreasing lexicographical rank by (`x`, `y`) will be used: elements of
  4699. higher rank will be those with larger `x`-values, using `y`-values to
  4700. break ties (in particular, swapping `x` and `y` will give a different
  4701. result). If it is False, the element indices will be used
  4702. directly as ranks. The default is True, in which case this
  4703. function returns the average of the values obtained using the
  4704. decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`).
  4705. weigher : callable, optional
  4706. The weigher function. Must map nonnegative integers (zero
  4707. representing the most important element) to a nonnegative weight.
  4708. The default, None, provides hyperbolic weighing, that is,
  4709. rank :math:`r` is mapped to weight :math:`1/(r+1)`.
  4710. additive : bool, optional
  4711. If True, the weight of an exchange is computed by adding the
  4712. weights of the ranks of the exchanged elements; otherwise, the weights
  4713. are multiplied. The default is True.
  4714. Returns
  4715. -------
  4716. res: SignificanceResult
  4717. An object containing attributes:
  4718. statistic : float
  4719. The weighted :math:`\tau` correlation index.
  4720. pvalue : float
  4721. Presently ``np.nan``, as the null distribution of the statistic is
  4722. unknown (even in the additive hyperbolic case).
  4723. See Also
  4724. --------
  4725. kendalltau : Calculates Kendall's tau.
  4726. spearmanr : Calculates a Spearman rank-order correlation coefficient.
  4727. theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
  4728. Notes
  4729. -----
  4730. This function uses an :math:`O(n \log n)`, mergesort-based algorithm
  4731. [1]_ that is a weighted extension of Knight's algorithm for Kendall's
  4732. :math:`\tau` [2]_. It can compute Shieh's weighted :math:`\tau` [3]_
  4733. between rankings without ties (i.e., permutations) by setting
  4734. `additive` and `rank` to False, as the definition given in [1]_ is a
  4735. generalization of Shieh's.
  4736. NaNs are considered the smallest possible score.
  4737. .. versionadded:: 0.19.0
  4738. References
  4739. ----------
  4740. .. [1] Sebastiano Vigna, "A weighted correlation index for rankings with
  4741. ties", Proceedings of the 24th international conference on World
  4742. Wide Web, pp. 1166-1176, ACM, 2015.
  4743. .. [2] W.R. Knight, "A Computer Method for Calculating Kendall's Tau with
  4744. Ungrouped Data", Journal of the American Statistical Association,
  4745. Vol. 61, No. 314, Part 1, pp. 436-439, 1966.
  4746. .. [3] Grace S. Shieh. "A weighted Kendall's tau statistic", Statistics &
  4747. Probability Letters, Vol. 39, No. 1, pp. 17-24, 1998.
  4748. Examples
  4749. --------
  4750. >>> import numpy as np
  4751. >>> from scipy import stats
  4752. >>> x = [12, 2, 1, 12, 2]
  4753. >>> y = [1, 4, 7, 1, 0]
  4754. >>> res = stats.weightedtau(x, y)
  4755. >>> res.statistic
  4756. -0.56694968153682723
  4757. >>> res.pvalue
  4758. nan
  4759. >>> res = stats.weightedtau(x, y, additive=False)
  4760. >>> res.statistic
  4761. -0.62205716951801038
  4762. NaNs are considered the smallest possible score:
  4763. >>> x = [12, 2, 1, 12, 2]
  4764. >>> y = [1, 4, 7, 1, np.nan]
  4765. >>> res = stats.weightedtau(x, y)
  4766. >>> res.statistic
  4767. -0.56694968153682723
  4768. This is exactly Kendall's tau:
  4769. >>> x = [12, 2, 1, 12, 2]
  4770. >>> y = [1, 4, 7, 1, 0]
  4771. >>> res = stats.weightedtau(x, y, weigher=lambda x: 1)
  4772. >>> res.statistic
  4773. -0.47140452079103173
  4774. >>> x = [12, 2, 1, 12, 2]
  4775. >>> y = [1, 4, 7, 1, 0]
  4776. >>> stats.weightedtau(x, y, rank=None)
  4777. SignificanceResult(statistic=-0.4157652301037516, pvalue=nan)
  4778. >>> stats.weightedtau(y, x, rank=None)
  4779. SignificanceResult(statistic=-0.7181341329699028, pvalue=nan)
  4780. """
  4781. x = np.asarray(x).ravel()
  4782. y = np.asarray(y).ravel()
  4783. NaN = _get_nan(x, y)
  4784. if x.size != y.size:
  4785. raise ValueError("Array shapes are incompatible for broadcasting.")
  4786. if not x.size:
  4787. # Return NaN if arrays are empty
  4788. res = SignificanceResult(NaN, NaN)
  4789. res.correlation = NaN
  4790. return res
  4791. # If there are NaNs we apply _toint64()
  4792. if np.isnan(np.sum(x)):
  4793. x = _toint64(x)
  4794. if np.isnan(np.sum(y)):
  4795. y = _toint64(y)
  4796. # Reduce to ranks unsupported types
  4797. if x.dtype != y.dtype:
  4798. if x.dtype != np.int64:
  4799. x = _toint64(x)
  4800. if y.dtype != np.int64:
  4801. y = _toint64(y)
  4802. else:
  4803. if x.dtype not in (np.int32, np.int64, np.float32, np.float64):
  4804. x = _toint64(x)
  4805. y = _toint64(y)
  4806. if rank is True:
  4807. tau = np.asarray(
  4808. _weightedrankedtau(x, y, None, weigher, additive) +
  4809. _weightedrankedtau(y, x, None, weigher, additive)
  4810. )[()] / 2
  4811. res = SignificanceResult(tau, NaN)
  4812. res.correlation = tau
  4813. return res
  4814. if rank is False:
  4815. rank = np.arange(x.size, dtype=np.intp)
  4816. elif rank is not None:
  4817. rank = np.asarray(rank).ravel()
  4818. rank = _toint64(rank).astype(np.intp)
  4819. if rank.size != x.size:
  4820. raise ValueError(
  4821. "All inputs to `weightedtau` must be of the same size, "
  4822. f"found x-size {x.size} and rank-size {rank.size}"
  4823. )
  4824. tau = np.asarray(_weightedrankedtau(x, y, rank, weigher, additive))[()]
  4825. res = SignificanceResult(tau, NaN)
  4826. res.correlation = tau
  4827. return res
  4828. #####################################
  4829. # INFERENTIAL STATISTICS #
  4830. #####################################
  4831. TtestResultBase = _make_tuple_bunch('TtestResultBase',
  4832. ['statistic', 'pvalue'], ['df'])
  4833. class TtestResult(TtestResultBase):
  4834. """
  4835. Result of a t-test.
  4836. See the documentation of the particular t-test function for more
  4837. information about the definition of the statistic and meaning of
  4838. the confidence interval.
  4839. Attributes
  4840. ----------
  4841. statistic : float or array
  4842. The t-statistic of the sample.
  4843. pvalue : float or array
  4844. The p-value associated with the given alternative.
  4845. df : float or array
  4846. The number of degrees of freedom used in calculation of the
  4847. t-statistic; this is one less than the size of the sample
  4848. (``a.shape[axis]-1`` if there are no masked elements or omitted NaNs).
  4849. Methods
  4850. -------
  4851. confidence_interval
  4852. Computes a confidence interval around the population statistic
  4853. for the given confidence level.
  4854. The confidence interval is returned in a ``namedtuple`` with
  4855. fields `low` and `high`.
  4856. """
  4857. def __init__(self, statistic, pvalue, df, # public
  4858. alternative, standard_error, estimate, # private
  4859. statistic_np=None, xp=None): # private
  4860. super().__init__(statistic, pvalue, df=df)
  4861. self._alternative = alternative
  4862. self._standard_error = standard_error # denominator of t-statistic
  4863. self._estimate = estimate # point estimate of sample mean
  4864. self._statistic_np = statistic if statistic_np is None else statistic_np
  4865. self._dtype = statistic.dtype
  4866. self._xp = array_namespace(statistic, pvalue) if xp is None else xp
  4867. def confidence_interval(self, confidence_level=0.95):
  4868. """
  4869. Parameters
  4870. ----------
  4871. confidence_level : float
  4872. The confidence level for the calculation of the population mean
  4873. confidence interval. Default is 0.95.
  4874. Returns
  4875. -------
  4876. ci : namedtuple
  4877. The confidence interval is returned in a ``namedtuple`` with
  4878. fields `low` and `high`.
  4879. """
  4880. low, high = _t_confidence_interval(self.df, self._statistic_np,
  4881. confidence_level, self._alternative,
  4882. self._dtype, self._xp)
  4883. low = low * self._standard_error + self._estimate
  4884. high = high * self._standard_error + self._estimate
  4885. return ConfidenceInterval(low=low, high=high)
  4886. def pack_TtestResult(statistic, pvalue, df, alternative, standard_error,
  4887. estimate):
  4888. # this could be any number of dimensions (including 0d), but there is
  4889. # at most one unique non-NaN value
  4890. xp = array_namespace(statistic, pvalue)
  4891. alternative = xpx.atleast_nd(xp.asarray(alternative), ndim=1, xp=xp)
  4892. alternative = alternative[xp.isfinite(alternative)]
  4893. alternative = alternative[0] if xp_size(alternative) != 0 else xp.nan
  4894. return TtestResult(statistic, pvalue, df=df, alternative=alternative,
  4895. standard_error=standard_error, estimate=estimate)
  4896. def unpack_TtestResult(res, _):
  4897. return (res.statistic, res.pvalue, res.df, res._alternative,
  4898. res._standard_error, res._estimate)
  4899. @xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"],
  4900. jax_jit=False, allow_dask_compute=True)
  4901. @_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
  4902. result_to_tuple=unpack_TtestResult, n_outputs=6)
  4903. # nan_policy handled by `_axis_nan_policy`, but needs to be left
  4904. # in signature to preserve use as a positional argument
  4905. def ttest_1samp(a, popmean, axis=0, nan_policy="propagate", alternative="two-sided"):
  4906. """Calculate the T-test for the mean of ONE group of scores.
  4907. This is a test for the null hypothesis that the expected value
  4908. (mean) of a sample of independent observations `a` is equal to the given
  4909. population mean, `popmean`.
  4910. Parameters
  4911. ----------
  4912. a : array_like
  4913. Sample observations.
  4914. popmean : float or array_like
  4915. Expected value in null hypothesis. If array_like, then its length along
  4916. `axis` must equal 1, and it must otherwise be broadcastable with `a`.
  4917. axis : int or None, optional
  4918. Axis along which to compute test; default is 0. If None, compute over
  4919. the whole array `a`.
  4920. nan_policy : {'propagate', 'raise', 'omit'}, optional
  4921. Defines how to handle when input contains nan.
  4922. The following options are available (default is 'propagate'):
  4923. * 'propagate': returns nan
  4924. * 'raise': throws an error
  4925. * 'omit': performs the calculations ignoring nan values
  4926. alternative : {'two-sided', 'less', 'greater'}, optional
  4927. Defines the alternative hypothesis.
  4928. The following options are available (default is 'two-sided'):
  4929. * 'two-sided': the mean of the underlying distribution of the sample
  4930. is different than the given population mean (`popmean`)
  4931. * 'less': the mean of the underlying distribution of the sample is
  4932. less than the given population mean (`popmean`)
  4933. * 'greater': the mean of the underlying distribution of the sample is
  4934. greater than the given population mean (`popmean`)
  4935. Returns
  4936. -------
  4937. result : `~scipy.stats._result_classes.TtestResult`
  4938. An object with the following attributes:
  4939. statistic : float or array
  4940. The t-statistic.
  4941. pvalue : float or array
  4942. The p-value associated with the given alternative.
  4943. df : float or array
  4944. The number of degrees of freedom used in calculation of the
  4945. t-statistic; this is one less than the size of the sample
  4946. (``a.shape[axis]``).
  4947. .. versionadded:: 1.10.0
  4948. The object also has the following method:
  4949. confidence_interval(confidence_level=0.95)
  4950. Computes a confidence interval around the population
  4951. mean for the given confidence level.
  4952. The confidence interval is returned in a ``namedtuple`` with
  4953. fields `low` and `high`.
  4954. .. versionadded:: 1.10.0
  4955. Notes
  4956. -----
  4957. The statistic is calculated as ``(np.mean(a) - popmean)/se``, where
  4958. ``se`` is the standard error. Therefore, the statistic will be positive
  4959. when the sample mean is greater than the population mean and negative when
  4960. the sample mean is less than the population mean.
  4961. Examples
  4962. --------
  4963. Suppose we wish to test the null hypothesis that the mean of a population
  4964. is equal to 0.5. We choose a confidence level of 99%; that is, we will
  4965. reject the null hypothesis in favor of the alternative if the p-value is
  4966. less than 0.01.
  4967. When testing random variates from the standard uniform distribution, which
  4968. has a mean of 0.5, we expect the data to be consistent with the null
  4969. hypothesis most of the time.
  4970. >>> import numpy as np
  4971. >>> from scipy import stats
  4972. >>> rng = np.random.default_rng()
  4973. >>> rvs = stats.uniform.rvs(size=50, random_state=rng)
  4974. >>> stats.ttest_1samp(rvs, popmean=0.5)
  4975. TtestResult(statistic=2.456308468440, pvalue=0.017628209047638, df=49)
  4976. As expected, the p-value of 0.017 is not below our threshold of 0.01, so
  4977. we cannot reject the null hypothesis.
  4978. When testing data from the standard *normal* distribution, which has a mean
  4979. of 0, we would expect the null hypothesis to be rejected.
  4980. >>> rvs = stats.norm.rvs(size=50, random_state=rng)
  4981. >>> stats.ttest_1samp(rvs, popmean=0.5)
  4982. TtestResult(statistic=-7.433605518875, pvalue=1.416760157221e-09, df=49)
  4983. Indeed, the p-value is lower than our threshold of 0.01, so we reject the
  4984. null hypothesis in favor of the default "two-sided" alternative: the mean
  4985. of the population is *not* equal to 0.5.
  4986. However, suppose we were to test the null hypothesis against the
  4987. one-sided alternative that the mean of the population is *greater* than
  4988. 0.5. Since the mean of the standard normal is less than 0.5, we would not
  4989. expect the null hypothesis to be rejected.
  4990. >>> stats.ttest_1samp(rvs, popmean=0.5, alternative='greater')
  4991. TtestResult(statistic=-7.433605518875, pvalue=0.99999999929, df=49)
  4992. Unsurprisingly, with a p-value greater than our threshold, we would not
  4993. reject the null hypothesis.
  4994. Note that when working with a confidence level of 99%, a true null
  4995. hypothesis will be rejected approximately 1% of the time.
  4996. >>> rvs = stats.uniform.rvs(size=(100, 50), random_state=rng)
  4997. >>> res = stats.ttest_1samp(rvs, popmean=0.5, axis=1)
  4998. >>> np.sum(res.pvalue < 0.01)
  4999. 1
  5000. Indeed, even though all 100 samples above were drawn from the standard
  5001. uniform distribution, which *does* have a population mean of 0.5, we would
  5002. mistakenly reject the null hypothesis for one of them.
  5003. `ttest_1samp` can also compute a confidence interval around the population
  5004. mean.
  5005. >>> rvs = stats.norm.rvs(size=50, random_state=rng)
  5006. >>> res = stats.ttest_1samp(rvs, popmean=0)
  5007. >>> ci = res.confidence_interval(confidence_level=0.95)
  5008. >>> ci
  5009. ConfidenceInterval(low=-0.3193887540880017, high=0.2898583388980972)
  5010. The bounds of the 95% confidence interval are the
  5011. minimum and maximum values of the parameter `popmean` for which the
  5012. p-value of the test would be 0.05.
  5013. >>> res = stats.ttest_1samp(rvs, popmean=ci.low)
  5014. >>> np.testing.assert_allclose(res.pvalue, 0.05)
  5015. >>> res = stats.ttest_1samp(rvs, popmean=ci.high)
  5016. >>> np.testing.assert_allclose(res.pvalue, 0.05)
  5017. Under certain assumptions about the population from which a sample
  5018. is drawn, the confidence interval with confidence level 95% is expected
  5019. to contain the true population mean in 95% of sample replications.
  5020. >>> rvs = stats.norm.rvs(size=(50, 1000), loc=1, random_state=rng)
  5021. >>> res = stats.ttest_1samp(rvs, popmean=0)
  5022. >>> ci = res.confidence_interval()
  5023. >>> contains_pop_mean = (ci.low < 1) & (ci.high > 1)
  5024. >>> contains_pop_mean.sum()
  5025. 953
  5026. """
  5027. xp = array_namespace(a)
  5028. a, popmean = xp_promote(a, popmean, force_floating=True, xp=xp)
  5029. a, axis = _chk_asarray(a, axis, xp=xp)
  5030. n = _length_nonmasked(a, axis)
  5031. df = n - 1
  5032. if a.shape[axis] == 0:
  5033. # This is really only needed for *testing* _axis_nan_policy decorator
  5034. # It won't happen when the decorator is used.
  5035. NaN = _get_nan(a)
  5036. return TtestResult(NaN, NaN, df=NaN, alternative=NaN,
  5037. standard_error=NaN, estimate=NaN)
  5038. mean = xp.mean(a, axis=axis)
  5039. try:
  5040. popmean = xp.asarray(popmean)
  5041. popmean = xp.squeeze(popmean, axis=axis) if popmean.ndim > 0 else popmean
  5042. except ValueError as e:
  5043. raise ValueError("`popmean.shape[axis]` must equal 1.") from e
  5044. d = mean - popmean
  5045. v = _var(a, axis=axis, ddof=1)
  5046. denom = xp.sqrt(v / n)
  5047. with np.errstate(divide='ignore', invalid='ignore'):
  5048. t = xp.divide(d, denom)
  5049. t = t[()] if t.ndim == 0 else t
  5050. dist = _SimpleStudentT(xp.asarray(df, dtype=t.dtype, device=xp_device(a)))
  5051. prob = _get_pvalue(t, dist, alternative, xp=xp)
  5052. prob = prob[()] if prob.ndim == 0 else prob
  5053. # when nan_policy='omit', `df` can be different for different axis-slices
  5054. df = xp.broadcast_to(xp.asarray(df, device=xp_device(a)), t.shape)
  5055. df = df[()] if df.ndim == 0 else df
  5056. # _axis_nan_policy decorator doesn't play well with strings
  5057. alternative_num = {"less": -1, "two-sided": 0, "greater": 1}[alternative]
  5058. return TtestResult(t, prob, df=df, alternative=alternative_num,
  5059. standard_error=denom, estimate=mean,
  5060. statistic_np=xp.asarray(t), xp=xp)
  5061. def _t_confidence_interval(df, t, confidence_level, alternative, dtype=None, xp=None):
  5062. # Input validation on `alternative` is already done
  5063. # We just need IV on confidence_level
  5064. dtype = t.dtype if dtype is None else dtype
  5065. xp = array_namespace(t) if xp is None else xp
  5066. if confidence_level < 0 or confidence_level > 1:
  5067. message = "`confidence_level` must be a number between 0 and 1."
  5068. raise ValueError(message)
  5069. confidence_level = xp.asarray(confidence_level, dtype=dtype, device=xp_device(t))
  5070. inf = xp.asarray(xp.inf, dtype=dtype)
  5071. if alternative < 0: # 'less'
  5072. p = confidence_level
  5073. low, high = xp.broadcast_arrays(-inf, special.stdtrit(df, p))
  5074. elif alternative > 0: # 'greater'
  5075. p = 1 - confidence_level
  5076. low, high = xp.broadcast_arrays(special.stdtrit(df, p), inf)
  5077. elif alternative == 0: # 'two-sided'
  5078. tail_probability = (1 - confidence_level)/2
  5079. p = xp.stack((tail_probability, 1-tail_probability))
  5080. # axis of p must be the zeroth and orthogonal to all the rest
  5081. p = xp.reshape(p, tuple([2] + [1]*xp.asarray(df, device=xp_device(t)).ndim))
  5082. ci = special.stdtrit(df, p)
  5083. low, high = ci[0, ...], ci[1, ...]
  5084. else: # alternative is NaN when input is empty (see _axis_nan_policy)
  5085. nan = xp.asarray(xp.nan, device=xp_device(t))
  5086. p, nans = xp.broadcast_arrays(t, nan)
  5087. low, high = nans, nans
  5088. low = xp.asarray(low, dtype=dtype)
  5089. low = low[()] if low.ndim == 0 else low
  5090. high = xp.asarray(high, dtype=dtype)
  5091. high = high[()] if high.ndim == 0 else high
  5092. return low, high
  5093. def _ttest_ind_from_stats(mean1, mean2, denom, df, alternative, xp=None):
  5094. xp = array_namespace(mean1, mean2, denom) if xp is None else xp
  5095. d = mean1 - mean2
  5096. with np.errstate(divide='ignore', invalid='ignore'):
  5097. t = xp.divide(d, denom)
  5098. dist = _SimpleStudentT(xp.asarray(df, dtype=t.dtype, device=xp_device(t)))
  5099. prob = _get_pvalue(t, dist, alternative, xp=xp)
  5100. prob = prob[()] if prob.ndim == 0 else prob
  5101. t = t[()] if t.ndim == 0 else t
  5102. prob = prob[()] if prob.ndim == 0 else prob
  5103. return t, prob
  5104. def _unequal_var_ttest_denom(v1, n1, v2, n2, xp=None):
  5105. xp = array_namespace(v1, v2) if xp is None else xp
  5106. vn1 = v1 / n1
  5107. vn2 = v2 / n2
  5108. with np.errstate(divide='ignore', invalid='ignore'):
  5109. df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1))
  5110. # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0).
  5111. # Hence it doesn't matter what df is as long as it's not NaN.
  5112. df = xp.where(xp.isnan(df), 1., df)
  5113. denom = xp.sqrt(vn1 + vn2)
  5114. return df, denom
  5115. def _equal_var_ttest_denom(v1, n1, v2, n2, xp=None):
  5116. xp = array_namespace(v1, v2) if xp is None else xp
  5117. # If there is a single observation in one sample, this formula for pooled
  5118. # variance breaks down because the variance of that sample is undefined.
  5119. # The pooled variance is still defined, though, because the (n-1) in the
  5120. # numerator should cancel with the (n-1) in the denominator, leaving only
  5121. # the sum of squared differences from the mean: zero.
  5122. v1 = xp.where(xp.asarray(n1 == 1), 0., v1)
  5123. v2 = xp.where(xp.asarray(n2 == 1), 0., v2)
  5124. df = n1 + n2 - 2.0
  5125. svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df
  5126. denom = xp.sqrt(svar * (1.0 / n1 + 1.0 / n2))
  5127. df = xp.asarray(df, dtype=denom.dtype)
  5128. return df, denom
  5129. Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue'))
  5130. @xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"])
  5131. def ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2,
  5132. equal_var=True, alternative="two-sided"):
  5133. r"""
  5134. T-test for means of two independent samples from descriptive statistics.
  5135. This is a test for the null hypothesis that two independent
  5136. samples have identical average (expected) values.
  5137. Parameters
  5138. ----------
  5139. mean1 : array_like
  5140. The mean(s) of sample 1.
  5141. std1 : array_like
  5142. The corrected sample standard deviation of sample 1 (i.e. ``ddof=1``).
  5143. nobs1 : array_like
  5144. The number(s) of observations of sample 1.
  5145. mean2 : array_like
  5146. The mean(s) of sample 2.
  5147. std2 : array_like
  5148. The corrected sample standard deviation of sample 2 (i.e. ``ddof=1``).
  5149. nobs2 : array_like
  5150. The number(s) of observations of sample 2.
  5151. equal_var : bool, optional
  5152. If True (default), perform a standard independent 2 sample test
  5153. that assumes equal population variances [1]_.
  5154. If False, perform Welch's t-test, which does not assume equal
  5155. population variance [2]_.
  5156. alternative : {'two-sided', 'less', 'greater'}, optional
  5157. Defines the alternative hypothesis.
  5158. The following options are available (default is 'two-sided'):
  5159. * 'two-sided': the means of the distributions are unequal.
  5160. * 'less': the mean of the first distribution is less than the
  5161. mean of the second distribution.
  5162. * 'greater': the mean of the first distribution is greater than the
  5163. mean of the second distribution.
  5164. .. versionadded:: 1.6.0
  5165. Returns
  5166. -------
  5167. statistic : float or array
  5168. The calculated t-statistics.
  5169. pvalue : float or array
  5170. The two-tailed p-value.
  5171. See Also
  5172. --------
  5173. scipy.stats.ttest_ind
  5174. Notes
  5175. -----
  5176. The statistic is calculated as ``(mean1 - mean2)/se``, where ``se`` is the
  5177. standard error. Therefore, the statistic will be positive when `mean1` is
  5178. greater than `mean2` and negative when `mean1` is less than `mean2`.
  5179. This method does not check whether any of the elements of `std1` or `std2`
  5180. are negative. If any elements of the `std1` or `std2` parameters are
  5181. negative in a call to this method, this method will return the same result
  5182. as if it were passed ``numpy.abs(std1)`` and ``numpy.abs(std2)``,
  5183. respectively, instead; no exceptions or warnings will be emitted.
  5184. References
  5185. ----------
  5186. .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
  5187. .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
  5188. Examples
  5189. --------
  5190. Suppose we have the summary data for two samples, as follows (with the
  5191. Sample Variance being the corrected sample variance)::
  5192. Sample Sample
  5193. Size Mean Variance
  5194. Sample 1 13 15.0 87.5
  5195. Sample 2 11 12.0 39.0
  5196. Apply the t-test to this data (with the assumption that the population
  5197. variances are equal):
  5198. >>> import numpy as np
  5199. >>> from scipy.stats import ttest_ind_from_stats
  5200. >>> ttest_ind_from_stats(mean1=15.0, std1=np.sqrt(87.5), nobs1=13,
  5201. ... mean2=12.0, std2=np.sqrt(39.0), nobs2=11)
  5202. Ttest_indResult(statistic=0.9051358093310269, pvalue=0.3751996797581487)
  5203. For comparison, here is the data from which those summary statistics
  5204. were taken. With this data, we can compute the same result using
  5205. `scipy.stats.ttest_ind`:
  5206. >>> a = np.array([1, 3, 4, 6, 11, 13, 15, 19, 22, 24, 25, 26, 26])
  5207. >>> b = np.array([2, 4, 6, 9, 11, 13, 14, 15, 18, 19, 21])
  5208. >>> from scipy.stats import ttest_ind
  5209. >>> ttest_ind(a, b)
  5210. TtestResult(statistic=0.905135809331027,
  5211. pvalue=0.3751996797581486,
  5212. df=22.0)
  5213. Suppose we instead have binary data and would like to apply a t-test to
  5214. compare the proportion of 1s in two independent groups::
  5215. Number of Sample Sample
  5216. Size ones Mean Variance
  5217. Sample 1 150 30 0.2 0.161073
  5218. Sample 2 200 45 0.225 0.175251
  5219. The sample mean :math:`\hat{p}` is the proportion of ones in the sample
  5220. and the variance for a binary observation is estimated by
  5221. :math:`\hat{p}(1-\hat{p})`.
  5222. >>> ttest_ind_from_stats(mean1=0.2, std1=np.sqrt(0.161073), nobs1=150,
  5223. ... mean2=0.225, std2=np.sqrt(0.175251), nobs2=200)
  5224. Ttest_indResult(statistic=-0.5627187905196761, pvalue=0.5739887114209541)
  5225. For comparison, we could compute the t statistic and p-value using
  5226. arrays of 0s and 1s and `scipy.stat.ttest_ind`, as above.
  5227. >>> group1 = np.array([1]*30 + [0]*(150-30))
  5228. >>> group2 = np.array([1]*45 + [0]*(200-45))
  5229. >>> ttest_ind(group1, group2)
  5230. TtestResult(statistic=-0.5627179589855622,
  5231. pvalue=0.573989277115258,
  5232. df=348.0)
  5233. """
  5234. xp = array_namespace(mean1, std1, mean2, std2)
  5235. mean1 = xp.asarray(mean1)
  5236. std1 = xp.asarray(std1)
  5237. mean2 = xp.asarray(mean2)
  5238. std2 = xp.asarray(std2)
  5239. if equal_var:
  5240. df, denom = _equal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2, xp=xp)
  5241. else:
  5242. df, denom = _unequal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2, xp=xp)
  5243. res = _ttest_ind_from_stats(mean1, mean2, denom, df, alternative)
  5244. return Ttest_indResult(*res)
  5245. @xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"])
  5246. @_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
  5247. result_to_tuple=unpack_TtestResult, n_outputs=6)
  5248. def ttest_ind(a, b, *, axis=0, equal_var=True, nan_policy='propagate',
  5249. alternative="two-sided", trim=0, method=None):
  5250. """
  5251. Calculate the T-test for the means of *two independent* samples of scores.
  5252. This is a test for the null hypothesis that 2 independent samples
  5253. have identical average (expected) values. This test assumes that the
  5254. populations have identical variances by default.
  5255. Parameters
  5256. ----------
  5257. a, b : array_like
  5258. The arrays must have the same shape, except in the dimension
  5259. corresponding to `axis` (the first, by default).
  5260. axis : int or None, optional
  5261. Axis along which to compute test. If None, compute over the whole
  5262. arrays, `a`, and `b`.
  5263. equal_var : bool, optional
  5264. If True (default), perform a standard independent 2 sample test
  5265. that assumes equal population variances [1]_.
  5266. If False, perform Welch's t-test, which does not assume equal
  5267. population variance [2]_.
  5268. .. versionadded:: 0.11.0
  5269. nan_policy : {'propagate', 'raise', 'omit'}, optional
  5270. Defines how to handle when input contains nan.
  5271. The following options are available (default is 'propagate'):
  5272. * 'propagate': returns nan
  5273. * 'raise': throws an error
  5274. * 'omit': performs the calculations ignoring nan values
  5275. The 'omit' option is not currently available for one-sided asymptotic tests.
  5276. alternative : {'two-sided', 'less', 'greater'}, optional
  5277. Defines the alternative hypothesis.
  5278. The following options are available (default is 'two-sided'):
  5279. * 'two-sided': the means of the distributions underlying the samples
  5280. are unequal.
  5281. * 'less': the mean of the distribution underlying the first sample
  5282. is less than the mean of the distribution underlying the second
  5283. sample.
  5284. * 'greater': the mean of the distribution underlying the first
  5285. sample is greater than the mean of the distribution underlying
  5286. the second sample.
  5287. trim : float, optional
  5288. If nonzero, performs a trimmed (Yuen's) t-test.
  5289. Defines the fraction of elements to be trimmed from each end of the
  5290. input samples. If 0 (default), no elements will be trimmed from either
  5291. side. The number of trimmed elements from each tail is the floor of the
  5292. trim times the number of elements. Valid range is [0, .5).
  5293. method : ResamplingMethod, optional
  5294. Defines the method used to compute the p-value. If `method` is an
  5295. instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is
  5296. computed using
  5297. `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
  5298. provided configuration options and other appropriate settings.
  5299. Otherwise, the p-value is computed by comparing the test statistic
  5300. against a theoretical t-distribution.
  5301. .. versionadded:: 1.15.0
  5302. Returns
  5303. -------
  5304. result : `~scipy.stats._result_classes.TtestResult`
  5305. An object with the following attributes:
  5306. statistic : float or ndarray
  5307. The t-statistic.
  5308. pvalue : float or ndarray
  5309. The p-value associated with the given alternative.
  5310. df : float or ndarray
  5311. The number of degrees of freedom used in calculation of the
  5312. t-statistic.
  5313. .. versionadded:: 1.11.0
  5314. The object also has the following method:
  5315. confidence_interval(confidence_level=0.95)
  5316. Computes a confidence interval around the difference in
  5317. population means for the given confidence level.
  5318. The confidence interval is returned in a ``namedtuple`` with
  5319. fields ``low`` and ``high``.
  5320. .. versionadded:: 1.11.0
  5321. Notes
  5322. -----
  5323. Suppose we observe two independent samples, e.g. flower petal lengths, and
  5324. we are considering whether the two samples were drawn from the same
  5325. population (e.g. the same species of flower or two species with similar
  5326. petal characteristics) or two different populations.
  5327. The t-test quantifies the difference between the arithmetic means
  5328. of the two samples. The p-value quantifies the probability of observing
  5329. as or more extreme values assuming the null hypothesis, that the
  5330. samples are drawn from populations with the same population means, is true.
  5331. A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that
  5332. our observation is not so unlikely to have occurred by chance. Therefore,
  5333. we do not reject the null hypothesis of equal population means.
  5334. If the p-value is smaller than our threshold, then we have evidence
  5335. against the null hypothesis of equal population means.
  5336. By default, the p-value is determined by comparing the t-statistic of the
  5337. observed data against a theoretical t-distribution.
  5338. It is also possible to compute the test statistic using a permutation test by
  5339. passing ``method=scipy.stats.PermutationMethod(n_resamples=permutations)``,
  5340. where ``permutations`` is the desired number of "permutations" to use in
  5341. forming the null distribution. When ``1 < permutations < binom(n, k)``, where
  5342. * ``k`` is the number of observations in `a`,
  5343. * ``n`` is the total number of observations in `a` and `b`, and
  5344. * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``),
  5345. the data are pooled (concatenated), randomly assigned to either group `a`
  5346. or `b`, and the t-statistic is calculated. This process is performed
  5347. repeatedly (``permutations`` times), generating a distribution of the
  5348. t-statistic under the null hypothesis, and the t-statistic of the observed
  5349. data is compared to this distribution to determine the p-value.
  5350. Specifically, the p-value reported is the "achieved significance level"
  5351. (ASL) as defined in 4.4 of [3]_. Note that there are other ways of
  5352. estimating p-values using randomized permutation tests; for other
  5353. options, see the more general `permutation_test`.
  5354. When ``permutations >= binom(n, k)``, an exact test is performed: the data
  5355. are partitioned between the groups in each distinct way exactly once.
  5356. The permutation test can be computationally expensive and not necessarily
  5357. more accurate than the analytical test, but it does not make strong
  5358. assumptions about the shape of the underlying distribution.
  5359. Use of trimming is commonly referred to as the trimmed t-test. At times
  5360. called Yuen's t-test, this is an extension of Welch's t-test, with the
  5361. difference being the use of winsorized means in calculation of the variance
  5362. and the trimmed sample size in calculation of the statistic. Trimming is
  5363. recommended if the underlying distribution is long-tailed or contaminated
  5364. with outliers [4]_.
  5365. The statistic is calculated as ``(np.mean(a) - np.mean(b))/se``, where
  5366. ``se`` is the standard error. Therefore, the statistic will be positive
  5367. when the sample mean of `a` is greater than the sample mean of `b` and
  5368. negative when the sample mean of `a` is less than the sample mean of
  5369. `b`.
  5370. References
  5371. ----------
  5372. .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
  5373. .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
  5374. .. [3] B. Efron and T. Hastie. Computer Age Statistical Inference. (2016).
  5375. .. [4] Yuen, Karen K. "The Two-Sample Trimmed t for Unequal Population
  5376. Variances." Biometrika, vol. 61, no. 1, 1974, pp. 165-170. JSTOR,
  5377. www.jstor.org/stable/2334299. Accessed 30 Mar. 2021.
  5378. .. [5] Yuen, Karen K., and W. J. Dixon. "The Approximate Behaviour and
  5379. Performance of the Two-Sample Trimmed t." Biometrika, vol. 60,
  5380. no. 2, 1973, pp. 369-374. JSTOR, www.jstor.org/stable/2334550.
  5381. Accessed 30 Mar. 2021.
  5382. Examples
  5383. --------
  5384. >>> import numpy as np
  5385. >>> from scipy import stats
  5386. >>> rng = np.random.default_rng()
  5387. Test with sample with identical means:
  5388. >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
  5389. >>> rvs2 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
  5390. >>> stats.ttest_ind(rvs1, rvs2)
  5391. TtestResult(statistic=-0.4390847099199348,
  5392. pvalue=0.6606952038870015,
  5393. df=998.0)
  5394. >>> stats.ttest_ind(rvs1, rvs2, equal_var=False)
  5395. TtestResult(statistic=-0.4390847099199348,
  5396. pvalue=0.6606952553131064,
  5397. df=997.4602304121448)
  5398. `ttest_ind` underestimates p for unequal variances:
  5399. >>> rvs3 = stats.norm.rvs(loc=5, scale=20, size=500, random_state=rng)
  5400. >>> stats.ttest_ind(rvs1, rvs3)
  5401. TtestResult(statistic=-1.6370984482905417,
  5402. pvalue=0.1019251574705033,
  5403. df=998.0)
  5404. >>> stats.ttest_ind(rvs1, rvs3, equal_var=False)
  5405. TtestResult(statistic=-1.637098448290542,
  5406. pvalue=0.10202110497954867,
  5407. df=765.1098655246868)
  5408. When ``n1 != n2``, the equal variance t-statistic is no longer equal to the
  5409. unequal variance t-statistic:
  5410. >>> rvs4 = stats.norm.rvs(loc=5, scale=20, size=100, random_state=rng)
  5411. >>> stats.ttest_ind(rvs1, rvs4)
  5412. TtestResult(statistic=-1.9481646859513422,
  5413. pvalue=0.05186270935842703,
  5414. df=598.0)
  5415. >>> stats.ttest_ind(rvs1, rvs4, equal_var=False)
  5416. TtestResult(statistic=-1.3146566100751664,
  5417. pvalue=0.1913495266513811,
  5418. df=110.41349083985212)
  5419. T-test with different means, variance, and n:
  5420. >>> rvs5 = stats.norm.rvs(loc=8, scale=20, size=100, random_state=rng)
  5421. >>> stats.ttest_ind(rvs1, rvs5)
  5422. TtestResult(statistic=-2.8415950600298774,
  5423. pvalue=0.0046418707568707885,
  5424. df=598.0)
  5425. >>> stats.ttest_ind(rvs1, rvs5, equal_var=False)
  5426. TtestResult(statistic=-1.8686598649188084,
  5427. pvalue=0.06434714193919686,
  5428. df=109.32167496550137)
  5429. Take these two samples, one of which has an extreme tail.
  5430. >>> a = (56, 128.6, 12, 123.8, 64.34, 78, 763.3)
  5431. >>> b = (1.1, 2.9, 4.2)
  5432. Use the `trim` keyword to perform a trimmed (Yuen) t-test. For example,
  5433. using 20% trimming, ``trim=.2``, the test will reduce the impact of one
  5434. (``np.floor(trim*len(a))``) element from each tail of sample `a`. It will
  5435. have no effect on sample `b` because ``np.floor(trim*len(b))`` is 0.
  5436. >>> stats.ttest_ind(a, b, trim=.2)
  5437. TtestResult(statistic=3.4463884028073513,
  5438. pvalue=0.01369338726499547,
  5439. df=6.0)
  5440. """
  5441. xp = array_namespace(a, b)
  5442. a, b = xp_promote(a, b, force_floating=True, xp=xp)
  5443. if axis is None:
  5444. a, b, axis = xp_ravel(a), xp_ravel(b), 0
  5445. if not (0 <= trim < .5):
  5446. raise ValueError("Trimming percentage should be 0 <= `trim` < .5.")
  5447. if not isinstance(method, PermutationMethod | MonteCarloMethod | None):
  5448. message = ("`method` must be an instance of `PermutationMethod`, an instance "
  5449. "of `MonteCarloMethod`, or None (default).")
  5450. raise ValueError(message)
  5451. if not is_numpy(xp) and method is not None:
  5452. message = "Use of resampling methods is compatible only with NumPy arrays."
  5453. raise NotImplementedError(message)
  5454. result_shape = _broadcast_array_shapes_remove_axis((a, b), axis=axis)
  5455. NaN = _get_nan(a, b, shape=result_shape, xp=xp)
  5456. if xp_size(a) == 0 or xp_size(b) == 0:
  5457. return TtestResult(NaN, NaN, df=NaN, alternative=NaN,
  5458. standard_error=NaN, estimate=NaN)
  5459. alternative_nums = {"less": -1, "two-sided": 0, "greater": 1}
  5460. n1 = _length_nonmasked(a, axis)
  5461. n2 = _length_nonmasked(b, axis)
  5462. if trim == 0:
  5463. with np.errstate(divide='ignore', invalid='ignore'):
  5464. v1 = _var(a, axis, ddof=1, xp=xp)
  5465. v2 = _var(b, axis, ddof=1, xp=xp)
  5466. m1 = xp.mean(a, axis=axis)
  5467. m2 = xp.mean(b, axis=axis)
  5468. else:
  5469. message = "Use of `trim` is compatible only with NumPy arrays."
  5470. if not is_numpy(xp):
  5471. raise NotImplementedError(message)
  5472. v1, m1, n1 = _ttest_trim_var_mean_len(a, trim, axis)
  5473. v2, m2, n2 = _ttest_trim_var_mean_len(b, trim, axis)
  5474. if equal_var:
  5475. df, denom = _equal_var_ttest_denom(v1, n1, v2, n2, xp=xp)
  5476. else:
  5477. df, denom = _unequal_var_ttest_denom(v1, n1, v2, n2, xp=xp)
  5478. if method is None:
  5479. t, prob = _ttest_ind_from_stats(m1, m2, denom, df, alternative)
  5480. else:
  5481. # nan_policy is taken care of by axis_nan_policy decorator
  5482. ttest_kwargs = dict(equal_var=equal_var, trim=trim)
  5483. t, prob = _ttest_resampling(a, b, axis, alternative, ttest_kwargs, method)
  5484. # when nan_policy='omit', `df` can be different for different axis-slices
  5485. df = xp.broadcast_to(df, t.shape)
  5486. df = df[()] if df.ndim ==0 else df
  5487. estimate = m1 - m2
  5488. return TtestResult(t, prob, df=df, alternative=alternative_nums[alternative],
  5489. standard_error=denom, estimate=estimate)
  5490. def _ttest_resampling(x, y, axis, alternative, ttest_kwargs, method):
  5491. def statistic(x, y, axis):
  5492. return ttest_ind(x, y, axis=axis, **ttest_kwargs).statistic
  5493. test = (permutation_test if isinstance(method, PermutationMethod)
  5494. else monte_carlo_test)
  5495. method = method._asdict()
  5496. if test is monte_carlo_test:
  5497. # `monte_carlo_test` accepts an `rvs` tuple of callables, not an `rng`
  5498. # If the user specified an `rng`, replace it with the default callables
  5499. if (rng := method.pop('rng', None)) is not None:
  5500. rng = np.random.default_rng(rng)
  5501. method['rvs'] = rng.normal, rng.normal
  5502. res = test((x, y,), statistic=statistic, axis=axis,
  5503. alternative=alternative, **method)
  5504. return res.statistic, res.pvalue
  5505. def _ttest_trim_var_mean_len(a, trim, axis):
  5506. """Variance, mean, and length of winsorized input along specified axis"""
  5507. # for use with `ttest_ind` when trimming.
  5508. # further calculations in this test assume that the inputs are sorted.
  5509. # From [4] Section 1 "Let x_1, ..., x_n be n ordered observations..."
  5510. a = np.sort(a, axis=axis)
  5511. # `g` is the number of elements to be replaced on each tail, converted
  5512. # from a percentage amount of trimming
  5513. n = a.shape[axis]
  5514. g = int(n * trim)
  5515. # Calculate the Winsorized variance of the input samples according to
  5516. # specified `g`
  5517. v = _calculate_winsorized_variance(a, g, axis)
  5518. # the total number of elements in the trimmed samples
  5519. n -= 2 * g
  5520. # calculate the g-times trimmed mean, as defined in [4] (1-1)
  5521. m = trim_mean(a, trim, axis=axis)
  5522. return v, m, n
  5523. def _calculate_winsorized_variance(a, g, axis):
  5524. """Calculates g-times winsorized variance along specified axis"""
  5525. # it is expected that the input `a` is sorted along the correct axis
  5526. if g == 0:
  5527. return _var(a, ddof=1, axis=axis)
  5528. # move the intended axis to the end that way it is easier to manipulate
  5529. a_win = np.moveaxis(a, axis, -1)
  5530. # save where NaNs are for later use.
  5531. nans_indices = np.any(np.isnan(a_win), axis=-1)
  5532. # Winsorization and variance calculation are done in one step in [4]
  5533. # (1-3), but here winsorization is done first; replace the left and
  5534. # right sides with the repeating value. This can be see in effect in (
  5535. # 1-3) in [4], where the leftmost and rightmost tails are replaced with
  5536. # `(g + 1) * x_{g + 1}` on the left and `(g + 1) * x_{n - g}` on the
  5537. # right. Zero-indexing turns `g + 1` to `g`, and `n - g` to `- g - 1` in
  5538. # array indexing.
  5539. a_win[..., :g] = a_win[..., [g]]
  5540. a_win[..., -g:] = a_win[..., [-g - 1]]
  5541. # Determine the variance. In [4], the degrees of freedom is expressed as
  5542. # `h - 1`, where `h = n - 2g` (unnumbered equations in Section 1, end of
  5543. # page 369, beginning of page 370). This is converted to NumPy's format,
  5544. # `n - ddof` for use with `np.var`. The result is converted to an
  5545. # array to accommodate indexing later.
  5546. var_win = np.asarray(_var(a_win, ddof=(2 * g + 1), axis=-1))
  5547. # with `nan_policy='propagate'`, NaNs may be completely trimmed out
  5548. # because they were sorted into the tail of the array. In these cases,
  5549. # replace computed variances with `np.nan`.
  5550. var_win[nans_indices] = np.nan
  5551. return var_win
  5552. @xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"],
  5553. jax_jit=False, allow_dask_compute=True)
  5554. @_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
  5555. result_to_tuple=unpack_TtestResult, n_outputs=6,
  5556. paired=True)
  5557. def ttest_rel(a, b, axis=0, nan_policy='propagate', alternative="two-sided"):
  5558. """Calculate the t-test on TWO RELATED samples of scores, a and b.
  5559. This is a test for the null hypothesis that two related or
  5560. repeated samples have identical average (expected) values.
  5561. Parameters
  5562. ----------
  5563. a, b : array_like
  5564. The arrays must have the same shape.
  5565. axis : int or None, optional
  5566. Axis along which to compute test. If None, compute over the whole
  5567. arrays, `a`, and `b`.
  5568. nan_policy : {'propagate', 'raise', 'omit'}, optional
  5569. Defines how to handle when input contains nan.
  5570. The following options are available (default is 'propagate'):
  5571. * 'propagate': returns nan
  5572. * 'raise': throws an error
  5573. * 'omit': performs the calculations ignoring nan values
  5574. alternative : {'two-sided', 'less', 'greater'}, optional
  5575. Defines the alternative hypothesis.
  5576. The following options are available (default is 'two-sided'):
  5577. * 'two-sided': the means of the distributions underlying the samples
  5578. are unequal.
  5579. * 'less': the mean of the distribution underlying the first sample
  5580. is less than the mean of the distribution underlying the second
  5581. sample.
  5582. * 'greater': the mean of the distribution underlying the first
  5583. sample is greater than the mean of the distribution underlying
  5584. the second sample.
  5585. .. versionadded:: 1.6.0
  5586. Returns
  5587. -------
  5588. result : `~scipy.stats._result_classes.TtestResult`
  5589. An object with the following attributes:
  5590. statistic : float or array
  5591. The t-statistic.
  5592. pvalue : float or array
  5593. The p-value associated with the given alternative.
  5594. df : float or array
  5595. The number of degrees of freedom used in calculation of the
  5596. t-statistic; this is one less than the size of the sample
  5597. (``a.shape[axis]``).
  5598. .. versionadded:: 1.10.0
  5599. The object also has the following method:
  5600. confidence_interval(confidence_level=0.95)
  5601. Computes a confidence interval around the difference in
  5602. population means for the given confidence level.
  5603. The confidence interval is returned in a ``namedtuple`` with
  5604. fields `low` and `high`.
  5605. .. versionadded:: 1.10.0
  5606. Notes
  5607. -----
  5608. Examples for use are scores of the same set of student in
  5609. different exams, or repeated sampling from the same units. The
  5610. test measures whether the average score differs significantly
  5611. across samples (e.g. exams). If we observe a large p-value, for
  5612. example greater than 0.05 or 0.1 then we cannot reject the null
  5613. hypothesis of identical average scores. If the p-value is smaller
  5614. than the threshold, e.g. 1%, 5% or 10%, then we reject the null
  5615. hypothesis of equal averages. Small p-values are associated with
  5616. large t-statistics.
  5617. The t-statistic is calculated as ``np.mean(a - b)/se``, where ``se`` is the
  5618. standard error. Therefore, the t-statistic will be positive when the sample
  5619. mean of ``a - b`` is greater than zero and negative when the sample mean of
  5620. ``a - b`` is less than zero.
  5621. References
  5622. ----------
  5623. https://en.wikipedia.org/wiki/T-test#Dependent_t-test_for_paired_samples
  5624. Examples
  5625. --------
  5626. >>> import numpy as np
  5627. >>> from scipy import stats
  5628. >>> rng = np.random.default_rng()
  5629. >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
  5630. >>> rvs2 = (stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
  5631. ... + stats.norm.rvs(scale=0.2, size=500, random_state=rng))
  5632. >>> stats.ttest_rel(rvs1, rvs2)
  5633. TtestResult(statistic=-0.4549717054410304, pvalue=0.6493274702088672, df=499)
  5634. >>> rvs3 = (stats.norm.rvs(loc=8, scale=10, size=500, random_state=rng)
  5635. ... + stats.norm.rvs(scale=0.2, size=500, random_state=rng))
  5636. >>> stats.ttest_rel(rvs1, rvs3)
  5637. TtestResult(statistic=-5.879467544540889, pvalue=7.540777129099917e-09, df=499)
  5638. """
  5639. return ttest_1samp(a - b, popmean=0., axis=axis, alternative=alternative,
  5640. _no_deco=True)
  5641. # Map from names to lambda_ values used in power_divergence().
  5642. _power_div_lambda_names = {
  5643. "pearson": 1,
  5644. "log-likelihood": 0,
  5645. "freeman-tukey": -0.5,
  5646. "mod-log-likelihood": -1,
  5647. "neyman": -2,
  5648. "cressie-read": 2/3,
  5649. }
  5650. Power_divergenceResult = namedtuple('Power_divergenceResult',
  5651. ('statistic', 'pvalue'))
  5652. def _pd_nsamples(kwargs):
  5653. return 2 if kwargs.get('f_exp', None) is not None else 1
  5654. @xp_capabilities(jax_jit=False, allow_dask_compute=True)
  5655. @_axis_nan_policy_factory(Power_divergenceResult, paired=True, n_samples=_pd_nsamples,
  5656. too_small=-1)
  5657. def power_divergence(f_obs, f_exp=None, ddof=0, axis=0, lambda_=None):
  5658. """Cressie-Read power divergence statistic and goodness of fit test.
  5659. This function tests the null hypothesis that the categorical data
  5660. has the given frequencies, using the Cressie-Read power divergence
  5661. statistic.
  5662. Parameters
  5663. ----------
  5664. f_obs : array_like
  5665. Observed frequencies in each category.
  5666. f_exp : array_like, optional
  5667. Expected frequencies in each category. By default the categories are
  5668. assumed to be equally likely.
  5669. ddof : int, optional
  5670. "Delta degrees of freedom": adjustment to the degrees of freedom
  5671. for the p-value. The p-value is computed using a chi-squared
  5672. distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
  5673. is the number of observed frequencies. The default value of `ddof`
  5674. is 0.
  5675. axis : int or None, optional
  5676. The axis of the broadcast result of `f_obs` and `f_exp` along which to
  5677. apply the test. If axis is None, all values in `f_obs` are treated
  5678. as a single data set. Default is 0.
  5679. lambda_ : float or str, optional
  5680. The power in the Cressie-Read power divergence statistic. The default
  5681. is 1. For convenience, `lambda_` may be assigned one of the following
  5682. strings, in which case the corresponding numerical value is used:
  5683. * ``"pearson"`` (value 1)
  5684. Pearson's chi-squared statistic. In this case, the function is
  5685. equivalent to `chisquare`.
  5686. * ``"log-likelihood"`` (value 0)
  5687. Log-likelihood ratio. Also known as the G-test [3]_.
  5688. * ``"freeman-tukey"`` (value -1/2)
  5689. Freeman-Tukey statistic.
  5690. * ``"mod-log-likelihood"`` (value -1)
  5691. Modified log-likelihood ratio.
  5692. * ``"neyman"`` (value -2)
  5693. Neyman's statistic.
  5694. * ``"cressie-read"`` (value 2/3)
  5695. The power recommended in [5]_.
  5696. Returns
  5697. -------
  5698. res: Power_divergenceResult
  5699. An object containing attributes:
  5700. statistic : float or ndarray
  5701. The Cressie-Read power divergence test statistic. The value is
  5702. a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D.
  5703. pvalue : float or ndarray
  5704. The p-value of the test. The value is a float if `ddof` and the
  5705. return value `stat` are scalars.
  5706. See Also
  5707. --------
  5708. chisquare
  5709. Notes
  5710. -----
  5711. This test is invalid when the observed or expected frequencies in each
  5712. category are too small. A typical rule is that all of the observed
  5713. and expected frequencies should be at least 5.
  5714. Also, the sum of the observed and expected frequencies must be the same
  5715. for the test to be valid; `power_divergence` raises an error if the sums
  5716. do not agree within a relative tolerance of ``eps**0.5``, where ``eps``
  5717. is the precision of the input dtype.
  5718. When `lambda_` is less than zero, the formula for the statistic involves
  5719. dividing by `f_obs`, so a warning or error may be generated if any value
  5720. in `f_obs` is 0.
  5721. Similarly, a warning or error may be generated if any value in `f_exp` is
  5722. zero when `lambda_` >= 0.
  5723. The default degrees of freedom, k-1, are for the case when no parameters
  5724. of the distribution are estimated. If p parameters are estimated by
  5725. efficient maximum likelihood then the correct degrees of freedom are
  5726. k-1-p. If the parameters are estimated in a different way, then the
  5727. dof can be between k-1-p and k-1. However, it is also possible that
  5728. the asymptotic distribution is not a chisquare, in which case this
  5729. test is not appropriate.
  5730. References
  5731. ----------
  5732. .. [1] Lowry, Richard. "Concepts and Applications of Inferential
  5733. Statistics". Chapter 8.
  5734. https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html
  5735. .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
  5736. .. [3] "G-test", https://en.wikipedia.org/wiki/G-test
  5737. .. [4] Sokal, R. R. and Rohlf, F. J. "Biometry: the principles and
  5738. practice of statistics in biological research", New York: Freeman
  5739. (1981)
  5740. .. [5] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
  5741. Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
  5742. pp. 440-464.
  5743. Examples
  5744. --------
  5745. (See `chisquare` for more examples.)
  5746. When just `f_obs` is given, it is assumed that the expected frequencies
  5747. are uniform and given by the mean of the observed frequencies. Here we
  5748. perform a G-test (i.e. use the log-likelihood ratio statistic):
  5749. >>> import numpy as np
  5750. >>> from scipy.stats import power_divergence
  5751. >>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood')
  5752. (2.006573162632538, 0.84823476779463769)
  5753. The expected frequencies can be given with the `f_exp` argument:
  5754. >>> power_divergence([16, 18, 16, 14, 12, 12],
  5755. ... f_exp=[16, 16, 16, 16, 16, 8],
  5756. ... lambda_='log-likelihood')
  5757. (3.3281031458963746, 0.6495419288047497)
  5758. When `f_obs` is 2-D, by default the test is applied to each column.
  5759. >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
  5760. >>> obs.shape
  5761. (6, 2)
  5762. >>> power_divergence(obs, lambda_="log-likelihood")
  5763. (array([ 2.00657316, 6.77634498]), array([ 0.84823477, 0.23781225]))
  5764. By setting ``axis=None``, the test is applied to all data in the array,
  5765. which is equivalent to applying the test to the flattened array.
  5766. >>> power_divergence(obs, axis=None)
  5767. (23.31034482758621, 0.015975692534127565)
  5768. >>> power_divergence(obs.ravel())
  5769. (23.31034482758621, 0.015975692534127565)
  5770. `ddof` is the change to make to the default degrees of freedom.
  5771. >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1)
  5772. (2.0, 0.73575888234288467)
  5773. The calculation of the p-values is done by broadcasting the
  5774. test statistic with `ddof`.
  5775. >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
  5776. (2.0, array([ 0.84914504, 0.73575888, 0.5724067 ]))
  5777. `f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has
  5778. shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
  5779. `f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared
  5780. statistics, we must use ``axis=1``:
  5781. >>> power_divergence([16, 18, 16, 14, 12, 12],
  5782. ... f_exp=[[16, 16, 16, 16, 16, 8],
  5783. ... [8, 20, 20, 16, 12, 12]],
  5784. ... axis=1)
  5785. (array([ 3.5 , 9.25]), array([ 0.62338763, 0.09949846]))
  5786. """
  5787. return _power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis, lambda_=lambda_)
  5788. def _power_divergence(f_obs, f_exp, ddof, axis, lambda_, sum_check=True):
  5789. xp = array_namespace(f_obs, f_exp, ddof)
  5790. f_obs, f_exp, ddof = xp_promote(f_obs, f_exp, ddof,
  5791. force_floating=True, xp=xp)
  5792. # Convert the input argument `lambda_` to a numerical value.
  5793. if isinstance(lambda_, str):
  5794. if lambda_ not in _power_div_lambda_names:
  5795. names = repr(list(_power_div_lambda_names.keys()))[1:-1]
  5796. raise ValueError(f"invalid string for lambda_: {lambda_!r}. "
  5797. f"Valid strings are {names}")
  5798. lambda_ = _power_div_lambda_names[lambda_]
  5799. elif lambda_ is None:
  5800. lambda_ = 1
  5801. if f_exp is not None:
  5802. # not sure why we force to float64, but not going to touch it
  5803. f_obs_float = xp.asarray(f_obs, dtype=xp.float64)
  5804. bshape = _broadcast_shapes((f_obs_float.shape, f_exp.shape))
  5805. f_obs_float = xp.broadcast_to(f_obs_float, bshape)
  5806. f_exp = xp.broadcast_to(f_exp, bshape)
  5807. f_obs_float, f_exp = _share_masks(f_obs_float, f_exp, xp=xp)
  5808. if sum_check:
  5809. dtype_res = xp.result_type(f_obs.dtype, f_exp.dtype)
  5810. rtol = xp.finfo(dtype_res).eps**0.5 # to pass existing tests
  5811. with np.errstate(invalid='ignore'):
  5812. f_obs_sum = xp.sum(f_obs_float, axis=axis)
  5813. f_exp_sum = xp.sum(f_exp, axis=axis)
  5814. relative_diff = (xp.abs(f_obs_sum - f_exp_sum) /
  5815. xp.minimum(f_obs_sum, f_exp_sum))
  5816. diff_gt_tol = xp.any(relative_diff > rtol, axis=None)
  5817. if diff_gt_tol:
  5818. msg = (f"For each axis slice, the sum of the observed "
  5819. f"frequencies must agree with the sum of the "
  5820. f"expected frequencies to a relative tolerance "
  5821. f"of {rtol}, but the percent differences are:\n"
  5822. f"{relative_diff}")
  5823. raise ValueError(msg)
  5824. else:
  5825. # Avoid warnings with the edge case of a data set with length 0
  5826. with warnings.catch_warnings():
  5827. warnings.simplefilter("ignore")
  5828. f_exp = xp.mean(f_obs, axis=axis, keepdims=True)
  5829. # `terms` is the array of terms that are summed along `axis` to create
  5830. # the test statistic. We use some specialized code for a few special
  5831. # cases of lambda_.
  5832. if lambda_ == 1:
  5833. # Pearson's chi-squared statistic
  5834. terms = (f_obs - f_exp)**2 / f_exp
  5835. elif lambda_ == 0:
  5836. # Log-likelihood ratio (i.e. G-test)
  5837. terms = 2.0 * special.xlogy(f_obs, f_obs / f_exp)
  5838. elif lambda_ == -1:
  5839. # Modified log-likelihood ratio
  5840. terms = 2.0 * special.xlogy(f_exp, f_exp / f_obs)
  5841. else:
  5842. # General Cressie-Read power divergence.
  5843. terms = f_obs * ((f_obs / f_exp)**lambda_ - 1)
  5844. terms /= 0.5 * lambda_ * (lambda_ + 1)
  5845. stat = xp.sum(terms, axis=axis)
  5846. num_obs = xp.asarray(_length_nonmasked(terms, axis), device=xp_device(terms),
  5847. dtype=f_obs.dtype)
  5848. df = num_obs - 1 - ddof
  5849. chi2 = _SimpleChi2(df)
  5850. pvalue = _get_pvalue(stat, chi2 , alternative='greater', symmetric=False, xp=xp)
  5851. stat = stat[()] if stat.ndim == 0 else stat
  5852. pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
  5853. return Power_divergenceResult(stat, pvalue)
  5854. @xp_capabilities(jax_jit=False, allow_dask_compute=True)
  5855. @_axis_nan_policy_factory(Power_divergenceResult, paired=True, n_samples=_pd_nsamples,
  5856. too_small=-1)
  5857. def chisquare(f_obs, f_exp=None, ddof=0, axis=0, *, sum_check=True):
  5858. """Perform Pearson's chi-squared test.
  5859. Pearson's chi-squared test [1]_ is a goodness-of-fit test for a multinomial
  5860. distribution with given probabilities; that is, it assesses the null hypothesis
  5861. that the observed frequencies (counts) are obtained by independent
  5862. sampling of *N* observations from a categorical distribution with given
  5863. expected frequencies.
  5864. Parameters
  5865. ----------
  5866. f_obs : array_like
  5867. Observed frequencies in each category.
  5868. f_exp : array_like, optional
  5869. Expected frequencies in each category. By default, the categories are
  5870. assumed to be equally likely.
  5871. ddof : int, optional
  5872. "Delta degrees of freedom": adjustment to the degrees of freedom
  5873. for the p-value. The p-value is computed using a chi-squared
  5874. distribution with ``k - 1 - ddof`` degrees of freedom, where ``k``
  5875. is the number of categories. The default value of `ddof` is 0.
  5876. axis : int or None, optional
  5877. The axis of the broadcast result of `f_obs` and `f_exp` along which to
  5878. apply the test. If axis is None, all values in `f_obs` are treated
  5879. as a single data set. Default is 0.
  5880. sum_check : bool, optional
  5881. Whether to perform a check that ``sum(f_obs) - sum(f_exp) == 0``. If True,
  5882. (default) raise an error when the relative difference exceeds the square root
  5883. of the precision of the data type. See Notes for rationale and possible
  5884. exceptions.
  5885. Returns
  5886. -------
  5887. res: Power_divergenceResult
  5888. An object containing attributes:
  5889. statistic : float or ndarray
  5890. The chi-squared test statistic. The value is a float if `axis` is
  5891. None or `f_obs` and `f_exp` are 1-D.
  5892. pvalue : float or ndarray
  5893. The p-value of the test. The value is a float if `ddof` and the
  5894. result attribute `statistic` are scalars.
  5895. See Also
  5896. --------
  5897. scipy.stats.power_divergence
  5898. scipy.stats.fisher_exact : Fisher exact test on a 2x2 contingency table.
  5899. scipy.stats.barnard_exact : An unconditional exact test. An alternative
  5900. to chi-squared test for small sample sizes.
  5901. :ref:`hypothesis_chisquare` : Extended example
  5902. Notes
  5903. -----
  5904. This test is invalid when the observed or expected frequencies in each
  5905. category are too small. A typical rule is that all of the observed
  5906. and expected frequencies should be at least 5. According to [2]_, the
  5907. total number of observations is recommended to be greater than 13,
  5908. otherwise exact tests (such as Barnard's Exact test) should be used
  5909. because they do not overreject.
  5910. The default degrees of freedom, k-1, are for the case when no parameters
  5911. of the distribution are estimated. If p parameters are estimated by
  5912. efficient maximum likelihood then the correct degrees of freedom are
  5913. k-1-p. If the parameters are estimated in a different way, then the
  5914. dof can be between k-1-p and k-1. However, it is also possible that
  5915. the asymptotic distribution is not chi-square, in which case this test
  5916. is not appropriate.
  5917. For Pearson's chi-squared test, the total observed and expected counts must match
  5918. for the p-value to accurately reflect the probability of observing such an extreme
  5919. value of the statistic under the null hypothesis.
  5920. This function may be used to perform other statistical tests that do not require
  5921. the total counts to be equal. For instance, to test the null hypothesis that
  5922. ``f_obs[i]`` is Poisson-distributed with expectation ``f_exp[i]``, set ``ddof=-1``
  5923. and ``sum_check=False``. This test follows from the fact that a Poisson random
  5924. variable with mean and variance ``f_exp[i]`` is approximately normal with the
  5925. same mean and variance; the chi-squared statistic standardizes, squares, and sums
  5926. the observations; and the sum of ``n`` squared standard normal variables follows
  5927. the chi-squared distribution with ``n`` degrees of freedom.
  5928. References
  5929. ----------
  5930. .. [1] "Pearson's chi-squared test".
  5931. *Wikipedia*. https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test
  5932. .. [2] Pearson, Karl. "On the criterion that a given system of deviations from the probable
  5933. in the case of a correlated system of variables is such that it can be reasonably
  5934. supposed to have arisen from random sampling", Philosophical Magazine. Series 5. 50
  5935. (1900), pp. 157-175.
  5936. Examples
  5937. --------
  5938. When only the mandatory `f_obs` argument is given, it is assumed that the
  5939. expected frequencies are uniform and given by the mean of the observed
  5940. frequencies:
  5941. >>> import numpy as np
  5942. >>> from scipy.stats import chisquare
  5943. >>> chisquare([16, 18, 16, 14, 12, 12])
  5944. Power_divergenceResult(statistic=2.0, pvalue=0.84914503608460956)
  5945. The optional `f_exp` argument gives the expected frequencies.
  5946. >>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8])
  5947. Power_divergenceResult(statistic=3.5, pvalue=0.62338762774958223)
  5948. When `f_obs` is 2-D, by default the test is applied to each column.
  5949. >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
  5950. >>> obs.shape
  5951. (6, 2)
  5952. >>> chisquare(obs)
  5953. Power_divergenceResult(statistic=array([2. , 6.66666667]), pvalue=array([0.84914504, 0.24663415]))
  5954. By setting ``axis=None``, the test is applied to all data in the array,
  5955. which is equivalent to applying the test to the flattened array.
  5956. >>> chisquare(obs, axis=None)
  5957. Power_divergenceResult(statistic=23.31034482758621, pvalue=0.015975692534127565)
  5958. >>> chisquare(obs.ravel())
  5959. Power_divergenceResult(statistic=23.310344827586206, pvalue=0.01597569253412758)
  5960. `ddof` is the change to make to the default degrees of freedom.
  5961. >>> chisquare([16, 18, 16, 14, 12, 12], ddof=1)
  5962. Power_divergenceResult(statistic=2.0, pvalue=0.7357588823428847)
  5963. The calculation of the p-values is done by broadcasting the
  5964. chi-squared statistic with `ddof`.
  5965. >>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0, 1, 2])
  5966. Power_divergenceResult(statistic=2.0, pvalue=array([0.84914504, 0.73575888, 0.5724067 ]))
  5967. `f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has
  5968. shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
  5969. `f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared
  5970. statistics, we use ``axis=1``:
  5971. >>> chisquare([16, 18, 16, 14, 12, 12],
  5972. ... f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]],
  5973. ... axis=1)
  5974. Power_divergenceResult(statistic=array([3.5 , 9.25]), pvalue=array([0.62338763, 0.09949846]))
  5975. For a more detailed example, see :ref:`hypothesis_chisquare`.
  5976. """ # noqa: E501
  5977. return _power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis,
  5978. lambda_="pearson", sum_check=sum_check)
  5979. KstestResult = _make_tuple_bunch('KstestResult', ['statistic', 'pvalue'],
  5980. ['statistic_location', 'statistic_sign'])
  5981. def _compute_d(cdfvals, x, sign, xp=None):
  5982. """Computes D+/D- as used in the Kolmogorov-Smirnov test.
  5983. Vectorized along the last axis.
  5984. Parameters
  5985. ----------
  5986. cdfvals : array_like
  5987. Sorted array of CDF values between 0 and 1
  5988. x: array_like
  5989. Sorted array of the stochastic variable itself
  5990. sign: int
  5991. Indicates whether to compute D+ (+1) or D- (-1).
  5992. Returns
  5993. -------
  5994. res: Pair with the following elements:
  5995. - The maximum distance of the CDF values below/above (D+/D-) Uniform(0, 1).
  5996. - The location at which the maximum is reached.
  5997. """
  5998. xp = array_namespace(cdfvals, x) if xp is None else xp
  5999. n = cdfvals.shape[-1]
  6000. D = (xp.arange(1.0, n + 1, dtype=x.dtype) / n - cdfvals if sign == +1
  6001. else (cdfvals - xp.arange(0.0, n, dtype=x.dtype)/n))
  6002. amax = xp.argmax(D, axis=-1, keepdims=True)
  6003. loc_max = xp.squeeze(xp.take_along_axis(x, amax, axis=-1), axis=-1)
  6004. D = xp.squeeze(xp.take_along_axis(D, amax, axis=-1), axis=-1)
  6005. return D[()] if D.ndim == 0 else D, loc_max[()] if loc_max.ndim == 0 else loc_max
  6006. def _tuple_to_KstestResult(statistic, pvalue,
  6007. statistic_location, statistic_sign):
  6008. return KstestResult(statistic, pvalue,
  6009. statistic_location=statistic_location,
  6010. statistic_sign=statistic_sign)
  6011. def _KstestResult_to_tuple(res, _):
  6012. return *res, res.statistic_location, res.statistic_sign
  6013. @xp_capabilities(cpu_only=True, jax_jit=False,
  6014. skip_backends=[('dask.array', 'needs take_along_axis')])
  6015. @_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=1, n_outputs=4,
  6016. result_to_tuple=_KstestResult_to_tuple)
  6017. @_rename_parameter("mode", "method")
  6018. def ks_1samp(x, cdf, args=(), alternative='two-sided', method='auto', *, axis=0):
  6019. """
  6020. Performs the one-sample Kolmogorov-Smirnov test for goodness of fit.
  6021. This test compares the underlying distribution F(x) of a sample
  6022. against a given continuous distribution G(x). See Notes for a description
  6023. of the available null and alternative hypotheses.
  6024. Parameters
  6025. ----------
  6026. x : array_like
  6027. a 1-D array of observations of iid random variables.
  6028. cdf : callable
  6029. callable used to calculate the cdf.
  6030. args : tuple, sequence, optional
  6031. Distribution parameters, used with `cdf`.
  6032. alternative : {'two-sided', 'less', 'greater'}, optional
  6033. Defines the null and alternative hypotheses. Default is 'two-sided'.
  6034. Please see explanations in the Notes below.
  6035. method : {'auto', 'exact', 'approx', 'asymp'}, optional
  6036. Defines the distribution used for calculating the p-value.
  6037. The following options are available (default is 'auto'):
  6038. * 'auto' : selects one of the other options.
  6039. * 'exact' : uses the exact distribution of test statistic.
  6040. * 'approx' : approximates the two-sided probability with twice
  6041. the one-sided probability
  6042. * 'asymp': uses asymptotic distribution of test statistic
  6043. axis : int or tuple of ints, default: 0
  6044. If an int or tuple of ints, the axis or axes of the input along which
  6045. to compute the statistic. The statistic of each axis-slice (e.g. row)
  6046. of the input will appear in a corresponding element of the output.
  6047. If ``None``, the input will be raveled before computing the statistic.
  6048. Returns
  6049. -------
  6050. res: KstestResult
  6051. An object containing attributes:
  6052. statistic : float
  6053. KS test statistic, either D+, D-, or D (the maximum of the two)
  6054. pvalue : float
  6055. One-tailed or two-tailed p-value.
  6056. statistic_location : float
  6057. Value of `x` corresponding with the KS statistic; i.e., the
  6058. distance between the empirical distribution function and the
  6059. hypothesized cumulative distribution function is measured at this
  6060. observation.
  6061. statistic_sign : int
  6062. +1 if the KS statistic is the maximum positive difference between
  6063. the empirical distribution function and the hypothesized cumulative
  6064. distribution function (D+); -1 if the KS statistic is the maximum
  6065. negative difference (D-).
  6066. See Also
  6067. --------
  6068. ks_2samp, kstest
  6069. Notes
  6070. -----
  6071. There are three options for the null and corresponding alternative
  6072. hypothesis that can be selected using the `alternative` parameter.
  6073. - `two-sided`: The null hypothesis is that the two distributions are
  6074. identical, F(x)=G(x) for all x; the alternative is that they are not
  6075. identical.
  6076. - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
  6077. alternative is that F(x) < G(x) for at least one x.
  6078. - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
  6079. alternative is that F(x) > G(x) for at least one x.
  6080. Note that the alternative hypotheses describe the *CDFs* of the
  6081. underlying distributions, not the observed values. For example,
  6082. suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
  6083. x1 tend to be less than those in x2.
  6084. Examples
  6085. --------
  6086. Suppose we wish to test the null hypothesis that a sample is distributed
  6087. according to the standard normal.
  6088. We choose a confidence level of 95%; that is, we will reject the null
  6089. hypothesis in favor of the alternative if the p-value is less than 0.05.
  6090. When testing uniformly distributed data, we would expect the
  6091. null hypothesis to be rejected.
  6092. >>> import numpy as np
  6093. >>> from scipy import stats
  6094. >>> rng = np.random.default_rng()
  6095. >>> stats.ks_1samp(stats.uniform.rvs(size=100, random_state=rng),
  6096. ... stats.norm.cdf)
  6097. KstestResult(statistic=0.5001899973268688,
  6098. pvalue=1.1616392184763533e-23,
  6099. statistic_location=0.00047625268963724654,
  6100. statistic_sign=-1)
  6101. Indeed, the p-value is lower than our threshold of 0.05, so we reject the
  6102. null hypothesis in favor of the default "two-sided" alternative: the data
  6103. are *not* distributed according to the standard normal.
  6104. When testing random variates from the standard normal distribution, we
  6105. expect the data to be consistent with the null hypothesis most of the time.
  6106. >>> x = stats.norm.rvs(size=100, random_state=rng)
  6107. >>> stats.ks_1samp(x, stats.norm.cdf)
  6108. KstestResult(statistic=0.05345882212970396,
  6109. pvalue=0.9227159037744717,
  6110. statistic_location=-1.2451343873745018,
  6111. statistic_sign=1)
  6112. As expected, the p-value of 0.92 is not below our threshold of 0.05, so
  6113. we cannot reject the null hypothesis.
  6114. Suppose, however, that the random variates are distributed according to
  6115. a normal distribution that is shifted toward greater values. In this case,
  6116. the cumulative density function (CDF) of the underlying distribution tends
  6117. to be *less* than the CDF of the standard normal. Therefore, we would
  6118. expect the null hypothesis to be rejected with ``alternative='less'``:
  6119. >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng)
  6120. >>> stats.ks_1samp(x, stats.norm.cdf, alternative='less')
  6121. KstestResult(statistic=0.17482387821055168,
  6122. pvalue=0.001913921057766743,
  6123. statistic_location=0.3713830565352756,
  6124. statistic_sign=-1)
  6125. and indeed, with p-value smaller than our threshold, we reject the null
  6126. hypothesis in favor of the alternative.
  6127. """
  6128. # `_axis_nan_policy` decorator ensures `axis=-1`
  6129. xp = array_namespace(x)
  6130. mode = method
  6131. alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
  6132. alternative.lower()[0], alternative)
  6133. if alternative not in ['two-sided', 'greater', 'less']:
  6134. raise ValueError(f"Unexpected value {alternative=}")
  6135. N = x.shape[-1]
  6136. x = xp.sort(x, axis=-1)
  6137. x = xp_promote(x, force_floating=True, xp=xp)
  6138. cdfvals = cdf(x, *args)
  6139. ones = xp.ones(x.shape[:-1], dtype=xp.int8)
  6140. ones = ones[()] if ones.ndim == 0 else ones
  6141. if alternative == 'greater':
  6142. Dplus, d_location = _compute_d(cdfvals, x, +1)
  6143. pvalue = xp.asarray(distributions.ksone.sf(Dplus, N), dtype=x.dtype)
  6144. pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
  6145. return KstestResult(Dplus, pvalue,
  6146. statistic_location=d_location,
  6147. statistic_sign=ones)
  6148. if alternative == 'less':
  6149. Dminus, d_location = _compute_d(cdfvals, x, -1)
  6150. pvalue = xp.asarray(distributions.ksone.sf(Dminus, N), dtype=x.dtype)
  6151. pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
  6152. return KstestResult(Dminus, pvalue,
  6153. statistic_location=d_location,
  6154. statistic_sign=-ones)
  6155. # alternative == 'two-sided':
  6156. Dplus, dplus_location = _compute_d(cdfvals, x, +1)
  6157. Dminus, dminus_location = _compute_d(cdfvals, x, -1)
  6158. i_plus = Dplus > Dminus
  6159. D = xp.where(i_plus, Dplus, Dminus)
  6160. d_location = xp.where(i_plus, dplus_location, dminus_location)
  6161. d_sign = xp.where(i_plus, ones, -ones)
  6162. if D.ndim == 0:
  6163. D, d_location, d_sign = D[()], d_location[()], d_sign[()]
  6164. if mode == 'auto': # Always select exact
  6165. mode = 'exact'
  6166. if mode == 'exact':
  6167. prob = distributions.kstwo.sf(D, N)
  6168. elif mode == 'asymp':
  6169. prob = distributions.kstwobign.sf(D * math.sqrt(N))
  6170. else:
  6171. # mode == 'approx'
  6172. prob = 2 * distributions.ksone.sf(D, N)
  6173. prob = xp.clip(xp.asarray(prob, dtype=x.dtype), 0., 1.)
  6174. return KstestResult(D, prob,
  6175. statistic_location=d_location,
  6176. statistic_sign=d_sign)
  6177. Ks_2sampResult = KstestResult
  6178. def _compute_prob_outside_square(n, h):
  6179. """
  6180. Compute the proportion of paths that pass outside the two diagonal lines.
  6181. Parameters
  6182. ----------
  6183. n : integer
  6184. n > 0
  6185. h : integer
  6186. 0 <= h <= n
  6187. Returns
  6188. -------
  6189. p : float
  6190. The proportion of paths that pass outside the lines x-y = +/-h.
  6191. """
  6192. # Compute Pr(D_{n,n} >= h/n)
  6193. # Prob = 2 * ( binom(2n, n-h) - binom(2n, n-2a) + binom(2n, n-3a) - ... )
  6194. # / binom(2n, n)
  6195. # This formulation exhibits subtractive cancellation.
  6196. # Instead divide each term by binom(2n, n), then factor common terms
  6197. # and use a Horner-like algorithm
  6198. # P = 2 * A0 * (1 - A1*(1 - A2*(1 - A3*(1 - A4*(...)))))
  6199. P = 0.0
  6200. k = int(np.floor(n / h))
  6201. while k >= 0:
  6202. p1 = 1.0
  6203. # Each of the Ai terms has numerator and denominator with
  6204. # h simple terms.
  6205. for j in range(h):
  6206. p1 = (n - k * h - j) * p1 / (n + k * h + j + 1)
  6207. P = p1 * (1.0 - P)
  6208. k -= 1
  6209. return 2 * P
  6210. def _count_paths_outside_method(m, n, g, h):
  6211. """Count the number of paths that pass outside the specified diagonal.
  6212. Parameters
  6213. ----------
  6214. m : integer
  6215. m > 0
  6216. n : integer
  6217. n > 0
  6218. g : integer
  6219. g is greatest common divisor of m and n
  6220. h : integer
  6221. 0 <= h <= lcm(m,n)
  6222. Returns
  6223. -------
  6224. p : float
  6225. The number of paths that go low.
  6226. The calculation may overflow - check for a finite answer.
  6227. Notes
  6228. -----
  6229. Count the integer lattice paths from (0, 0) to (m, n), which at some
  6230. point (x, y) along the path, satisfy:
  6231. m*y <= n*x - h*g
  6232. The paths make steps of size +1 in either positive x or positive y
  6233. directions.
  6234. We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
  6235. Hodges, J.L. Jr.,
  6236. "The Significance Probability of the Smirnov Two-Sample Test,"
  6237. Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
  6238. """
  6239. # Compute #paths which stay lower than x/m-y/n = h/lcm(m,n)
  6240. # B(x, y) = #{paths from (0,0) to (x,y) without
  6241. # previously crossing the boundary}
  6242. # = binom(x, y) - #{paths which already reached the boundary}
  6243. # Multiply by the number of path extensions going from (x, y) to (m, n)
  6244. # Sum.
  6245. # Probability is symmetrical in m, n. Computation below assumes m >= n.
  6246. if m < n:
  6247. m, n = n, m
  6248. mg = m // g
  6249. ng = n // g
  6250. # Not every x needs to be considered.
  6251. # xj holds the list of x values to be checked.
  6252. # Wherever n*x/m + ng*h crosses an integer
  6253. lxj = n + (mg-h)//mg
  6254. xj = [(h + mg * j + ng-1)//ng for j in range(lxj)]
  6255. # B is an array just holding a few values of B(x,y), the ones needed.
  6256. # B[j] == B(x_j, j)
  6257. if lxj == 0:
  6258. return special.binom(m + n, n)
  6259. B = np.zeros(lxj)
  6260. B[0] = 1
  6261. # Compute the B(x, y) terms
  6262. for j in range(1, lxj):
  6263. Bj = special.binom(xj[j] + j, j)
  6264. for i in range(j):
  6265. bin = special.binom(xj[j] - xj[i] + j - i, j-i)
  6266. Bj -= bin * B[i]
  6267. B[j] = Bj
  6268. # Compute the number of path extensions...
  6269. num_paths = 0
  6270. for j in range(lxj):
  6271. bin = special.binom((m-xj[j]) + (n - j), n-j)
  6272. term = B[j] * bin
  6273. num_paths += term
  6274. return num_paths
  6275. def _attempt_exact_2kssamp(n1, n2, g, d, alternative):
  6276. """Attempts to compute the exact 2sample probability.
  6277. n1, n2 are the sample sizes
  6278. g is the gcd(n1, n2)
  6279. d is the computed max difference in ECDFs
  6280. Returns (success, d, probability)
  6281. """
  6282. lcm = (n1 // g) * n2
  6283. h = int(np.round(d * lcm))
  6284. d = h * 1.0 / lcm
  6285. if h == 0:
  6286. return True, d, 1.0
  6287. saw_fp_error, prob = False, np.nan
  6288. try:
  6289. with np.errstate(invalid="raise", over="raise"):
  6290. if alternative == 'two-sided':
  6291. if n1 == n2:
  6292. prob = _compute_prob_outside_square(n1, h)
  6293. else:
  6294. prob = _compute_outer_prob_inside_method(n1, n2, g, h)
  6295. else:
  6296. if n1 == n2:
  6297. # prob = binom(2n, n-h) / binom(2n, n)
  6298. # Evaluating in that form incurs roundoff errors
  6299. # from special.binom. Instead calculate directly
  6300. jrange = np.arange(h)
  6301. prob = np.prod((n1 - jrange) / (n1 + jrange + 1.0))
  6302. else:
  6303. with np.errstate(over='raise'):
  6304. num_paths = _count_paths_outside_method(n1, n2, g, h)
  6305. bin = special.binom(n1 + n2, n1)
  6306. if num_paths > bin or np.isinf(bin):
  6307. saw_fp_error = True
  6308. else:
  6309. prob = num_paths / bin
  6310. except (FloatingPointError, OverflowError):
  6311. saw_fp_error = True
  6312. if saw_fp_error:
  6313. return False, d, np.nan
  6314. if not (0 <= prob <= 1):
  6315. return False, d, prob
  6316. return True, d, prob
  6317. @xp_capabilities(np_only=True)
  6318. @_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=2, n_outputs=4,
  6319. result_to_tuple=_KstestResult_to_tuple)
  6320. @_rename_parameter("mode", "method")
  6321. def ks_2samp(data1, data2, alternative='two-sided', method='auto'):
  6322. """
  6323. Performs the two-sample Kolmogorov-Smirnov test for goodness of fit.
  6324. This test compares the underlying continuous distributions F(x) and G(x)
  6325. of two independent samples. See Notes for a description of the available
  6326. null and alternative hypotheses.
  6327. Parameters
  6328. ----------
  6329. data1, data2 : array_like, 1-Dimensional
  6330. Two arrays of sample observations assumed to be drawn from a continuous
  6331. distribution, sample sizes can be different.
  6332. alternative : {'two-sided', 'less', 'greater'}, optional
  6333. Defines the null and alternative hypotheses. Default is 'two-sided'.
  6334. Please see explanations in the Notes below.
  6335. method : {'auto', 'exact', 'asymp'}, optional
  6336. Defines the method used for calculating the p-value.
  6337. The following options are available (default is 'auto'):
  6338. * 'auto' : use 'exact' for small size arrays, 'asymp' for large
  6339. * 'exact' : use exact distribution of test statistic
  6340. * 'asymp' : use asymptotic distribution of test statistic
  6341. Returns
  6342. -------
  6343. res: KstestResult
  6344. An object containing attributes:
  6345. statistic : float
  6346. KS test statistic.
  6347. pvalue : float
  6348. One-tailed or two-tailed p-value.
  6349. statistic_location : float
  6350. Value from `data1` or `data2` corresponding with the KS statistic;
  6351. i.e., the distance between the empirical distribution functions is
  6352. measured at this observation.
  6353. statistic_sign : int
  6354. +1 if the empirical distribution function of `data1` exceeds
  6355. the empirical distribution function of `data2` at
  6356. `statistic_location`, otherwise -1.
  6357. See Also
  6358. --------
  6359. kstest, ks_1samp, epps_singleton_2samp, anderson_ksamp
  6360. Notes
  6361. -----
  6362. There are three options for the null and corresponding alternative
  6363. hypothesis that can be selected using the `alternative` parameter.
  6364. - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
  6365. alternative is that F(x) < G(x) for at least one x. The statistic
  6366. is the magnitude of the minimum (most negative) difference between the
  6367. empirical distribution functions of the samples.
  6368. - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
  6369. alternative is that F(x) > G(x) for at least one x. The statistic
  6370. is the maximum (most positive) difference between the empirical
  6371. distribution functions of the samples.
  6372. - `two-sided`: The null hypothesis is that the two distributions are
  6373. identical, F(x)=G(x) for all x; the alternative is that they are not
  6374. identical. The statistic is the maximum absolute difference between the
  6375. empirical distribution functions of the samples.
  6376. Note that the alternative hypotheses describe the *CDFs* of the
  6377. underlying distributions, not the observed values of the data. For example,
  6378. suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
  6379. x1 tend to be less than those in x2.
  6380. If the KS statistic is large, then the p-value will be small, and this may
  6381. be taken as evidence against the null hypothesis in favor of the
  6382. alternative.
  6383. If ``method='exact'``, `ks_2samp` attempts to compute an exact p-value,
  6384. that is, the probability under the null hypothesis of obtaining a test
  6385. statistic value as extreme as the value computed from the data.
  6386. If ``method='asymp'``, the asymptotic Kolmogorov-Smirnov distribution is
  6387. used to compute an approximate p-value.
  6388. If ``method='auto'``, an exact p-value computation is attempted if both
  6389. sample sizes are less than 10000; otherwise, the asymptotic method is used.
  6390. In any case, if an exact p-value calculation is attempted and fails, a
  6391. warning will be emitted, and the asymptotic p-value will be returned.
  6392. The 'two-sided' 'exact' computation computes the complementary probability
  6393. and then subtracts from 1. As such, the minimum probability it can return
  6394. is about 1e-16. While the algorithm itself is exact, numerical
  6395. errors may accumulate for large sample sizes. It is most suited to
  6396. situations in which one of the sample sizes is only a few thousand.
  6397. We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk [1]_.
  6398. References
  6399. ----------
  6400. .. [1] Hodges, J.L. Jr., "The Significance Probability of the Smirnov
  6401. Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-486.
  6402. Examples
  6403. --------
  6404. Suppose we wish to test the null hypothesis that two samples were drawn
  6405. from the same distribution.
  6406. We choose a confidence level of 95%; that is, we will reject the null
  6407. hypothesis in favor of the alternative if the p-value is less than 0.05.
  6408. If the first sample were drawn from a uniform distribution and the second
  6409. were drawn from the standard normal, we would expect the null hypothesis
  6410. to be rejected.
  6411. >>> import numpy as np
  6412. >>> from scipy import stats
  6413. >>> rng = np.random.default_rng()
  6414. >>> sample1 = stats.uniform.rvs(size=100, random_state=rng)
  6415. >>> sample2 = stats.norm.rvs(size=110, random_state=rng)
  6416. >>> stats.ks_2samp(sample1, sample2)
  6417. KstestResult(statistic=0.5454545454545454,
  6418. pvalue=7.37417839555191e-15,
  6419. statistic_location=-0.014071496412861274,
  6420. statistic_sign=-1)
  6421. Indeed, the p-value is lower than our threshold of 0.05, so we reject the
  6422. null hypothesis in favor of the default "two-sided" alternative: the data
  6423. were *not* drawn from the same distribution.
  6424. When both samples are drawn from the same distribution, we expect the data
  6425. to be consistent with the null hypothesis most of the time.
  6426. >>> sample1 = stats.norm.rvs(size=105, random_state=rng)
  6427. >>> sample2 = stats.norm.rvs(size=95, random_state=rng)
  6428. >>> stats.ks_2samp(sample1, sample2)
  6429. KstestResult(statistic=0.10927318295739348,
  6430. pvalue=0.5438289009927495,
  6431. statistic_location=-0.1670157701848795,
  6432. statistic_sign=-1)
  6433. As expected, the p-value of 0.54 is not below our threshold of 0.05, so
  6434. we cannot reject the null hypothesis.
  6435. Suppose, however, that the first sample were drawn from
  6436. a normal distribution shifted toward greater values. In this case,
  6437. the cumulative density function (CDF) of the underlying distribution tends
  6438. to be *less* than the CDF underlying the second sample. Therefore, we would
  6439. expect the null hypothesis to be rejected with ``alternative='less'``:
  6440. >>> sample1 = stats.norm.rvs(size=105, loc=0.5, random_state=rng)
  6441. >>> stats.ks_2samp(sample1, sample2, alternative='less')
  6442. KstestResult(statistic=0.4055137844611529,
  6443. pvalue=3.5474563068855554e-08,
  6444. statistic_location=-0.13249370614972575,
  6445. statistic_sign=-1)
  6446. and indeed, with p-value smaller than our threshold, we reject the null
  6447. hypothesis in favor of the alternative.
  6448. """
  6449. mode = method
  6450. if mode not in ['auto', 'exact', 'asymp']:
  6451. raise ValueError(f'Invalid value for mode: {mode}')
  6452. alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
  6453. alternative.lower()[0], alternative)
  6454. if alternative not in ['two-sided', 'less', 'greater']:
  6455. raise ValueError(f'Invalid value for alternative: {alternative}')
  6456. MAX_AUTO_N = 10000 # 'auto' will attempt to be exact if n1,n2 <= MAX_AUTO_N
  6457. if np.ma.is_masked(data1):
  6458. data1 = data1.compressed()
  6459. if np.ma.is_masked(data2):
  6460. data2 = data2.compressed()
  6461. data1 = np.sort(data1)
  6462. data2 = np.sort(data2)
  6463. n1 = data1.shape[0]
  6464. n2 = data2.shape[0]
  6465. if min(n1, n2) == 0:
  6466. raise ValueError('Data passed to ks_2samp must not be empty')
  6467. data_all = np.concatenate([data1, data2])
  6468. # using searchsorted solves equal data problem
  6469. cdf1 = np.searchsorted(data1, data_all, side='right') / n1
  6470. cdf2 = np.searchsorted(data2, data_all, side='right') / n2
  6471. cddiffs = cdf1 - cdf2
  6472. # Identify the location of the statistic
  6473. argminS = np.argmin(cddiffs)
  6474. argmaxS = np.argmax(cddiffs)
  6475. loc_minS = data_all[argminS]
  6476. loc_maxS = data_all[argmaxS]
  6477. # Ensure sign of minS is not negative.
  6478. minS = np.clip(-cddiffs[argminS], 0, 1)
  6479. maxS = cddiffs[argmaxS]
  6480. if alternative == 'less' or (alternative == 'two-sided' and minS > maxS):
  6481. d = minS
  6482. d_location = loc_minS
  6483. d_sign = -1
  6484. else:
  6485. d = maxS
  6486. d_location = loc_maxS
  6487. d_sign = 1
  6488. g = math.gcd(n1, n2)
  6489. n1g = n1 // g
  6490. n2g = n2 // g
  6491. prob = -np.inf
  6492. if mode == 'auto':
  6493. mode = 'exact' if max(n1, n2) <= MAX_AUTO_N else 'asymp'
  6494. elif mode == 'exact':
  6495. # If lcm(n1, n2) is too big, switch from exact to asymp
  6496. if n1g >= np.iinfo(np.int32).max / n2g:
  6497. mode = 'asymp'
  6498. warnings.warn(
  6499. f"Exact ks_2samp calculation not possible with samples sizes "
  6500. f"{n1} and {n2}. Switching to 'asymp'.", RuntimeWarning,
  6501. stacklevel=3)
  6502. if mode == 'exact':
  6503. success, d, prob = _attempt_exact_2kssamp(n1, n2, g, d, alternative)
  6504. if not success:
  6505. mode = 'asymp'
  6506. warnings.warn(f"ks_2samp: Exact calculation unsuccessful. "
  6507. f"Switching to method={mode}.", RuntimeWarning,
  6508. stacklevel=3)
  6509. if mode == 'asymp':
  6510. # The product n1*n2 is large. Use Smirnov's asymptotic formula.
  6511. # Ensure float to avoid overflow in multiplication
  6512. # sorted because the one-sided formula is not symmetric in n1, n2
  6513. m, n = sorted([float(n1), float(n2)], reverse=True)
  6514. en = m * n / (m + n)
  6515. if alternative == 'two-sided':
  6516. prob = distributions.kstwo.sf(d, np.round(en))
  6517. else:
  6518. z = np.sqrt(en) * d
  6519. # Use Hodges' suggested approximation Eqn 5.3
  6520. # Requires m to be the larger of (n1, n2)
  6521. expt = -2 * z**2 - 2 * z * (m + 2*n)/np.sqrt(m*n*(m+n))/3.0
  6522. prob = np.exp(expt)
  6523. prob = np.clip(prob, 0, 1)
  6524. # Currently, `d` is a Python float. We want it to be a NumPy type, so
  6525. # float64 is appropriate. An enhancement would be for `d` to respect the
  6526. # dtype of the input.
  6527. return KstestResult(np.float64(d), prob, statistic_location=d_location,
  6528. statistic_sign=np.int8(d_sign))
  6529. def _parse_kstest_args(data1, data2, args, N):
  6530. # kstest allows many different variations of arguments.
  6531. # Pull out the parsing into a separate function
  6532. # (xvals, yvals, ) # 2sample
  6533. # (xvals, cdf function,..)
  6534. # (xvals, name of distribution, ...)
  6535. # (name of distribution, name of distribution, ...)
  6536. # Returns xvals, yvals, cdf
  6537. # where cdf is a cdf function, or None
  6538. # and yvals is either an array_like of values, or None
  6539. # and xvals is array_like.
  6540. rvsfunc, cdf = None, None
  6541. if isinstance(data1, str):
  6542. rvsfunc = getattr(distributions, data1).rvs
  6543. elif callable(data1):
  6544. rvsfunc = data1
  6545. if isinstance(data2, str):
  6546. cdf = getattr(distributions, data2).cdf
  6547. data2 = None
  6548. elif callable(data2):
  6549. cdf = data2
  6550. data2 = None
  6551. xp = array_namespace(data1, data2, *args)
  6552. data1 = xp.sort(rvsfunc(*args, size=N) if rvsfunc else data1)
  6553. return data1, data2, cdf
  6554. def _kstest_n_samples(kwargs):
  6555. cdf = kwargs['cdf']
  6556. return 1 if (isinstance(cdf, str) or callable(cdf)) else 2
  6557. @xp_capabilities(out_of_scope=True)
  6558. @_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=_kstest_n_samples,
  6559. n_outputs=4, result_to_tuple=_KstestResult_to_tuple)
  6560. @_rename_parameter("mode", "method")
  6561. def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', method='auto'):
  6562. """
  6563. Performs the (one-sample or two-sample) Kolmogorov-Smirnov test for
  6564. goodness of fit.
  6565. The one-sample test compares the underlying distribution F(x) of a sample
  6566. against a given distribution G(x). The two-sample test compares the
  6567. underlying distributions of two independent samples. Both tests are valid
  6568. only for continuous distributions.
  6569. Parameters
  6570. ----------
  6571. rvs : str, array_like, or callable
  6572. If an array, it should be a 1-D array of observations of random
  6573. variables.
  6574. If a callable, it should be a function to generate random variables;
  6575. it is required to have a keyword argument `size`.
  6576. If a string, it should be the name of a distribution in `scipy.stats`,
  6577. which will be used to generate random variables.
  6578. cdf : str, array_like or callable
  6579. If array_like, it should be a 1-D array of observations of random
  6580. variables, and the two-sample test is performed
  6581. (and rvs must be array_like).
  6582. If a callable, that callable is used to calculate the cdf.
  6583. If a string, it should be the name of a distribution in `scipy.stats`,
  6584. which will be used as the cdf function.
  6585. args : tuple, sequence, optional
  6586. Distribution parameters, used if `rvs` or `cdf` are strings or
  6587. callables.
  6588. N : int, optional
  6589. Sample size if `rvs` is string or callable. Default is 20.
  6590. alternative : {'two-sided', 'less', 'greater'}, optional
  6591. Defines the null and alternative hypotheses. Default is 'two-sided'.
  6592. Please see explanations in the Notes below.
  6593. method : {'auto', 'exact', 'approx', 'asymp'}, optional
  6594. Defines the distribution used for calculating the p-value.
  6595. The following options are available (default is 'auto'):
  6596. * 'auto' : selects one of the other options.
  6597. * 'exact' : uses the exact distribution of test statistic.
  6598. * 'approx' : approximates the two-sided probability with twice the
  6599. one-sided probability
  6600. * 'asymp': uses asymptotic distribution of test statistic
  6601. Returns
  6602. -------
  6603. res: KstestResult
  6604. An object containing attributes:
  6605. statistic : float
  6606. KS test statistic, either D+, D-, or D (the maximum of the two)
  6607. pvalue : float
  6608. One-tailed or two-tailed p-value.
  6609. statistic_location : float
  6610. In a one-sample test, this is the value of `rvs`
  6611. corresponding with the KS statistic; i.e., the distance between
  6612. the empirical distribution function and the hypothesized cumulative
  6613. distribution function is measured at this observation.
  6614. In a two-sample test, this is the value from `rvs` or `cdf`
  6615. corresponding with the KS statistic; i.e., the distance between
  6616. the empirical distribution functions is measured at this
  6617. observation.
  6618. statistic_sign : int
  6619. In a one-sample test, this is +1 if the KS statistic is the
  6620. maximum positive difference between the empirical distribution
  6621. function and the hypothesized cumulative distribution function
  6622. (D+); it is -1 if the KS statistic is the maximum negative
  6623. difference (D-).
  6624. In a two-sample test, this is +1 if the empirical distribution
  6625. function of `rvs` exceeds the empirical distribution
  6626. function of `cdf` at `statistic_location`, otherwise -1.
  6627. See Also
  6628. --------
  6629. ks_1samp, ks_2samp
  6630. Notes
  6631. -----
  6632. There are three options for the null and corresponding alternative
  6633. hypothesis that can be selected using the `alternative` parameter.
  6634. - `two-sided`: The null hypothesis is that the two distributions are
  6635. identical, F(x)=G(x) for all x; the alternative is that they are not
  6636. identical.
  6637. - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
  6638. alternative is that F(x) < G(x) for at least one x.
  6639. - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
  6640. alternative is that F(x) > G(x) for at least one x.
  6641. Note that the alternative hypotheses describe the *CDFs* of the
  6642. underlying distributions, not the observed values. For example,
  6643. suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
  6644. x1 tend to be less than those in x2.
  6645. Examples
  6646. --------
  6647. Suppose we wish to test the null hypothesis that a sample is distributed
  6648. according to the standard normal.
  6649. We choose a confidence level of 95%; that is, we will reject the null
  6650. hypothesis in favor of the alternative if the p-value is less than 0.05.
  6651. When testing uniformly distributed data, we would expect the
  6652. null hypothesis to be rejected.
  6653. >>> import numpy as np
  6654. >>> from scipy import stats
  6655. >>> rng = np.random.default_rng()
  6656. >>> stats.kstest(stats.uniform.rvs(size=100, random_state=rng),
  6657. ... stats.norm.cdf)
  6658. KstestResult(statistic=0.5001899973268688,
  6659. pvalue=1.1616392184763533e-23,
  6660. statistic_location=0.00047625268963724654,
  6661. statistic_sign=-1)
  6662. Indeed, the p-value is lower than our threshold of 0.05, so we reject the
  6663. null hypothesis in favor of the default "two-sided" alternative: the data
  6664. are *not* distributed according to the standard normal.
  6665. When testing random variates from the standard normal distribution, we
  6666. expect the data to be consistent with the null hypothesis most of the time.
  6667. >>> x = stats.norm.rvs(size=100, random_state=rng)
  6668. >>> stats.kstest(x, stats.norm.cdf)
  6669. KstestResult(statistic=0.05345882212970396,
  6670. pvalue=0.9227159037744717,
  6671. statistic_location=-1.2451343873745018,
  6672. statistic_sign=1)
  6673. As expected, the p-value of 0.92 is not below our threshold of 0.05, so
  6674. we cannot reject the null hypothesis.
  6675. Suppose, however, that the random variates are distributed according to
  6676. a normal distribution that is shifted toward greater values. In this case,
  6677. the cumulative density function (CDF) of the underlying distribution tends
  6678. to be *less* than the CDF of the standard normal. Therefore, we would
  6679. expect the null hypothesis to be rejected with ``alternative='less'``:
  6680. >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng)
  6681. >>> stats.kstest(x, stats.norm.cdf, alternative='less')
  6682. KstestResult(statistic=0.17482387821055168,
  6683. pvalue=0.001913921057766743,
  6684. statistic_location=0.3713830565352756,
  6685. statistic_sign=-1)
  6686. and indeed, with p-value smaller than our threshold, we reject the null
  6687. hypothesis in favor of the alternative.
  6688. For convenience, the previous test can be performed using the name of the
  6689. distribution as the second argument.
  6690. >>> stats.kstest(x, "norm", alternative='less')
  6691. KstestResult(statistic=0.17482387821055168,
  6692. pvalue=0.001913921057766743,
  6693. statistic_location=0.3713830565352756,
  6694. statistic_sign=-1)
  6695. The examples above have all been one-sample tests identical to those
  6696. performed by `ks_1samp`. Note that `kstest` can also perform two-sample
  6697. tests identical to those performed by `ks_2samp`. For example, when two
  6698. samples are drawn from the same distribution, we expect the data to be
  6699. consistent with the null hypothesis most of the time.
  6700. >>> sample1 = stats.laplace.rvs(size=105, random_state=rng)
  6701. >>> sample2 = stats.laplace.rvs(size=95, random_state=rng)
  6702. >>> stats.kstest(sample1, sample2)
  6703. KstestResult(statistic=0.11779448621553884,
  6704. pvalue=0.4494256912629795,
  6705. statistic_location=0.6138814275424155,
  6706. statistic_sign=1)
  6707. As expected, the p-value of 0.45 is not below our threshold of 0.05, so
  6708. we cannot reject the null hypothesis.
  6709. """
  6710. # to not break compatibility with existing code
  6711. if alternative == 'two_sided':
  6712. alternative = 'two-sided'
  6713. if alternative not in ['two-sided', 'greater', 'less']:
  6714. raise ValueError(f"Unexpected alternative: {alternative}")
  6715. xvals, yvals, cdf = _parse_kstest_args(rvs, cdf, args, N)
  6716. if cdf:
  6717. return ks_1samp(xvals, cdf, args=args, alternative=alternative,
  6718. method=method, _no_deco=True)
  6719. return ks_2samp(xvals, yvals, alternative=alternative, method=method,
  6720. _no_deco=True)
  6721. @xp_capabilities(np_only=True)
  6722. def tiecorrect(rankvals):
  6723. """Tie correction factor for Mann-Whitney U and Kruskal-Wallis H tests.
  6724. Parameters
  6725. ----------
  6726. rankvals : array_like
  6727. A 1-D sequence of ranks. Typically this will be the array
  6728. returned by `~scipy.stats.rankdata`.
  6729. Returns
  6730. -------
  6731. factor : float
  6732. Correction factor for U or H.
  6733. See Also
  6734. --------
  6735. rankdata : Assign ranks to the data
  6736. mannwhitneyu : Mann-Whitney rank test
  6737. kruskal : Kruskal-Wallis H test
  6738. References
  6739. ----------
  6740. .. [1] Siegel, S. (1956) Nonparametric Statistics for the Behavioral
  6741. Sciences. New York: McGraw-Hill.
  6742. Examples
  6743. --------
  6744. >>> from scipy.stats import tiecorrect, rankdata
  6745. >>> tiecorrect([1, 2.5, 2.5, 4])
  6746. 0.9
  6747. >>> ranks = rankdata([1, 3, 2, 4, 5, 7, 2, 8, 4])
  6748. >>> ranks
  6749. array([ 1. , 4. , 2.5, 5.5, 7. , 8. , 2.5, 9. , 5.5])
  6750. >>> tiecorrect(ranks)
  6751. 0.9833333333333333
  6752. """
  6753. arr = np.sort(rankvals)
  6754. idx = np.nonzero(np.r_[True, arr[1:] != arr[:-1], True])[0]
  6755. cnt = np.diff(idx).astype(np.float64)
  6756. size = np.float64(arr.size)
  6757. return 1.0 if size < 2 else 1.0 - (cnt**3 - cnt).sum() / (size**3 - size)
  6758. RanksumsResult = namedtuple('RanksumsResult', ('statistic', 'pvalue'))
  6759. @xp_capabilities(np_only=True)
  6760. @_axis_nan_policy_factory(RanksumsResult, n_samples=2)
  6761. def ranksums(x, y, alternative='two-sided'):
  6762. """Compute the Wilcoxon rank-sum statistic for two samples.
  6763. The Wilcoxon rank-sum test tests the null hypothesis that two sets
  6764. of measurements are drawn from the same distribution. The alternative
  6765. hypothesis is that values in one sample are more likely to be
  6766. larger than the values in the other sample.
  6767. This test should be used to compare two samples from continuous
  6768. distributions. It does not handle ties between measurements
  6769. in x and y. For tie-handling and an optional continuity correction
  6770. see `scipy.stats.mannwhitneyu`.
  6771. Parameters
  6772. ----------
  6773. x,y : array_like
  6774. The data from the two samples.
  6775. alternative : {'two-sided', 'less', 'greater'}, optional
  6776. Defines the alternative hypothesis. Default is 'two-sided'.
  6777. The following options are available:
  6778. * 'two-sided': one of the distributions (underlying `x` or `y`) is
  6779. stochastically greater than the other.
  6780. * 'less': the distribution underlying `x` is stochastically less
  6781. than the distribution underlying `y`.
  6782. * 'greater': the distribution underlying `x` is stochastically greater
  6783. than the distribution underlying `y`.
  6784. .. versionadded:: 1.7.0
  6785. Returns
  6786. -------
  6787. statistic : float
  6788. The test statistic under the large-sample approximation that the
  6789. rank sum statistic is normally distributed.
  6790. pvalue : float
  6791. The p-value of the test.
  6792. References
  6793. ----------
  6794. .. [1] https://en.wikipedia.org/wiki/Wilcoxon_rank-sum_test
  6795. Examples
  6796. --------
  6797. We can test the hypothesis that two independent unequal-sized samples are
  6798. drawn from the same distribution with computing the Wilcoxon rank-sum
  6799. statistic.
  6800. >>> import numpy as np
  6801. >>> from scipy.stats import ranksums
  6802. >>> rng = np.random.default_rng()
  6803. >>> sample1 = rng.uniform(-1, 1, 200)
  6804. >>> sample2 = rng.uniform(-0.5, 1.5, 300) # a shifted distribution
  6805. >>> ranksums(sample1, sample2)
  6806. RanksumsResult(statistic=-7.887059,
  6807. pvalue=3.09390448e-15) # may vary
  6808. >>> ranksums(sample1, sample2, alternative='less')
  6809. RanksumsResult(statistic=-7.750585297581713,
  6810. pvalue=4.573497606342543e-15) # may vary
  6811. >>> ranksums(sample1, sample2, alternative='greater')
  6812. RanksumsResult(statistic=-7.750585297581713,
  6813. pvalue=0.9999999999999954) # may vary
  6814. The p-value of less than ``0.05`` indicates that this test rejects the
  6815. hypothesis at the 5% significance level.
  6816. """
  6817. x, y = map(np.asarray, (x, y))
  6818. n1 = len(x)
  6819. n2 = len(y)
  6820. alldata = np.concatenate((x, y))
  6821. ranked = rankdata(alldata)
  6822. x = ranked[:n1]
  6823. s = np.sum(x, axis=0)
  6824. expected = n1 * (n1+n2+1) / 2.0
  6825. z = (s - expected) / np.sqrt(n1*n2*(n1+n2+1)/12.0)
  6826. pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
  6827. return RanksumsResult(z[()], pvalue[()])
  6828. KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue'))
  6829. @xp_capabilities(skip_backends=[('cupy', 'no rankdata'), ('dask.array', 'no rankdata')],
  6830. jax_jit=False)
  6831. @_axis_nan_policy_factory(KruskalResult, n_samples=None)
  6832. def kruskal(*samples, nan_policy='propagate', axis=0):
  6833. """Compute the Kruskal-Wallis H-test for independent samples.
  6834. The Kruskal-Wallis H-test tests the null hypothesis that the population
  6835. median of all of the groups are equal. It is a non-parametric version of
  6836. ANOVA. The test works on 2 or more independent samples, which may have
  6837. different sizes. Note that rejecting the null hypothesis does not
  6838. indicate which of the groups differs. Post hoc comparisons between
  6839. groups are required to determine which groups are different.
  6840. Parameters
  6841. ----------
  6842. sample1, sample2, ... : array_like
  6843. Two or more arrays with the sample measurements can be given as
  6844. arguments. Samples must be one-dimensional.
  6845. nan_policy : {'propagate', 'raise', 'omit'}, optional
  6846. Defines how to handle when input contains nan.
  6847. The following options are available (default is 'propagate'):
  6848. * 'propagate': returns nan
  6849. * 'raise': throws an error
  6850. * 'omit': performs the calculations ignoring nan values
  6851. axis : int or tuple of ints, default: 0
  6852. If an int or tuple of ints, the axis or axes of the input along which
  6853. to compute the statistic. The statistic of each axis-slice (e.g. row)
  6854. of the input will appear in a corresponding element of the output.
  6855. If ``None``, the input will be raveled before computing the statistic.
  6856. Returns
  6857. -------
  6858. statistic : float
  6859. The Kruskal-Wallis H statistic, corrected for ties.
  6860. pvalue : float
  6861. The p-value for the test using the assumption that H has a chi
  6862. square distribution. The p-value returned is the survival function of
  6863. the chi square distribution evaluated at H.
  6864. See Also
  6865. --------
  6866. f_oneway : 1-way ANOVA.
  6867. mannwhitneyu : Mann-Whitney rank test on two samples.
  6868. friedmanchisquare : Friedman test for repeated measurements.
  6869. Notes
  6870. -----
  6871. Due to the assumption that H has a chi square distribution, the number
  6872. of samples in each group must not be too small. A typical rule is
  6873. that each sample must have at least 5 measurements.
  6874. References
  6875. ----------
  6876. .. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in
  6877. One-Criterion Variance Analysis", Journal of the American Statistical
  6878. Association, Vol. 47, Issue 260, pp. 583-621, 1952.
  6879. .. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance
  6880. Examples
  6881. --------
  6882. >>> from scipy import stats
  6883. >>> x = [1, 3, 5, 7, 9]
  6884. >>> y = [2, 4, 6, 8, 10]
  6885. >>> stats.kruskal(x, y)
  6886. KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895)
  6887. >>> x = [1, 1, 1]
  6888. >>> y = [2, 2, 2]
  6889. >>> z = [2, 2]
  6890. >>> stats.kruskal(x, y, z)
  6891. KruskalResult(statistic=7.0, pvalue=0.0301973834223185)
  6892. """
  6893. xp = array_namespace(*samples)
  6894. samples = xp_promote(*samples, force_floating=True, xp=xp)
  6895. num_groups = len(samples)
  6896. if num_groups < 2:
  6897. raise ValueError("Need at least two groups in stats.kruskal()")
  6898. n = [sample.shape[-1] for sample in samples]
  6899. totaln = sum(n)
  6900. if any(n) < 1: # Only needed for `test_axis_nan_policy`
  6901. raise ValueError("Inputs must not be empty.")
  6902. alldata = xp.concat(samples, axis=-1)
  6903. ranked, t = _rankdata(alldata, method='average', return_ties=True)
  6904. # should adjust output dtype of _rankdata
  6905. ranked = xp.astype(ranked, alldata.dtype, copy=False)
  6906. t = xp.astype(t, alldata.dtype, copy=False)
  6907. ties = 1 - xp.sum(t**3 - t, axis=-1) / (totaln**3 - totaln) # tiecorrect(ranked)
  6908. # Compute sum^2/n for each group and sum
  6909. j = list(itertools.accumulate(n, initial=0))
  6910. ssbn = sum(xp.sum(ranked[..., j[i]:j[i + 1]], axis=-1)**2 / n[i]
  6911. for i in range(num_groups))
  6912. h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3 * (totaln + 1)
  6913. df = xp.asarray(num_groups - 1, dtype=h.dtype)
  6914. h /= ties
  6915. chi2 = _SimpleChi2(df)
  6916. pvalue = _get_pvalue(h, chi2, alternative='greater', symmetric=False, xp=np)
  6917. return KruskalResult(h, pvalue)
  6918. FriedmanchisquareResult = namedtuple('FriedmanchisquareResult',
  6919. ('statistic', 'pvalue'))
  6920. @xp_capabilities(skip_backends=[("cupy", "no rankdata"), ("dask.array", "no rankdata")],
  6921. jax_jit=False)
  6922. @_axis_nan_policy_factory(FriedmanchisquareResult, n_samples=None, paired=True)
  6923. def friedmanchisquare(*samples, axis=0):
  6924. """Compute the Friedman test for repeated samples.
  6925. The Friedman test tests the null hypothesis that repeated samples of
  6926. the same individuals have the same distribution. It is often used
  6927. to test for consistency among samples obtained in different ways.
  6928. For example, if two sampling techniques are used on the same set of
  6929. individuals, the Friedman test can be used to determine if the two
  6930. sampling techniques are consistent.
  6931. Parameters
  6932. ----------
  6933. sample1, sample2, sample3... : array_like
  6934. Arrays of observations. All of the arrays must have the same number
  6935. of elements. At least three samples must be given.
  6936. axis : int or tuple of ints, default: 0
  6937. If an int or tuple of ints, the axis or axes of the input along which
  6938. to compute the statistic. The statistic of each axis-slice (e.g. row)
  6939. of the input will appear in a corresponding element of the output.
  6940. If ``None``, the input will be raveled before computing the statistic.
  6941. Returns
  6942. -------
  6943. statistic : float
  6944. The test statistic, correcting for ties.
  6945. pvalue : float
  6946. The associated p-value assuming that the test statistic has a chi
  6947. squared distribution.
  6948. See Also
  6949. --------
  6950. :ref:`hypothesis_friedmanchisquare` : Extended example
  6951. Notes
  6952. -----
  6953. Due to the assumption that the test statistic has a chi squared
  6954. distribution, the p-value is only reliable for n > 10 and more than
  6955. 6 repeated samples.
  6956. References
  6957. ----------
  6958. .. [1] https://en.wikipedia.org/wiki/Friedman_test
  6959. .. [2] Demsar, J. (2006). Statistical comparisons of classifiers over
  6960. multiple data sets. Journal of Machine Learning Research, 7, 1-30.
  6961. Examples
  6962. --------
  6963. >>> import numpy as np
  6964. >>> rng = np.random.default_rng(seed=18)
  6965. >>> x = rng.random((6, 10))
  6966. >>> from scipy.stats import friedmanchisquare
  6967. >>> res = friedmanchisquare(x[0], x[1], x[2], x[3], x[4], x[5])
  6968. >>> res.statistic, res.pvalue
  6969. (11.428571428571416, 0.043514520866727614)
  6970. The p-value is less than 0.05; however, as noted above, the results may not
  6971. be reliable since we have a small number of repeated samples.
  6972. For a more detailed example, see :ref:`hypothesis_friedmanchisquare`.
  6973. """
  6974. k = len(samples)
  6975. if k < 3:
  6976. raise ValueError('At least 3 samples must be given '
  6977. f'for Friedman test, got {k}.')
  6978. xp = array_namespace(*samples)
  6979. samples = xp_promote(*samples, force_floating=True, xp=xp)
  6980. dtype = samples[0].dtype
  6981. n = samples[0].shape[-1]
  6982. if n == 0: # only for `test_axis_nan_policy`; user doesn't see this
  6983. raise ValueError("One or more sample arguments is too small.")
  6984. # Rank data
  6985. # axis-slices are aligned with axis -1 by decorator; stack puts samples along axis 0
  6986. # The transpose flips this so we can work with axis-slices along -1. This is a
  6987. # reducing statistic, so both axes 0 and -1 are consumed.
  6988. data = xp_swapaxes(xp.stack(samples), 0, -1)
  6989. data, t = _rankdata(data, method='average', return_ties=True)
  6990. data, t = xp.asarray(data, dtype=dtype), xp.asarray(t, dtype=dtype)
  6991. # Handle ties
  6992. ties = xp.sum(t * (t*t - 1), axis=(0, -1))
  6993. c = 1 - ties / (k*(k*k - 1)*n)
  6994. ssbn = xp.sum(xp.sum(data, axis=0)**2, axis=-1)
  6995. statistic = (12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)) / c
  6996. chi2 = _SimpleChi2(xp.asarray(k - 1, dtype=dtype))
  6997. pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp)
  6998. return FriedmanchisquareResult(statistic, pvalue)
  6999. BrunnerMunzelResult = namedtuple('BrunnerMunzelResult',
  7000. ('statistic', 'pvalue'))
  7001. @xp_capabilities(cpu_only=True, # torch GPU can't use `stdtr`
  7002. skip_backends=[('dask.array', 'needs rankdata'),
  7003. ('cupy', 'needs rankdata'),
  7004. ('jax.numpy', 'needs _axis_nan_policy decorator')])
  7005. @_axis_nan_policy_factory(BrunnerMunzelResult, n_samples=2)
  7006. def brunnermunzel(x, y, alternative="two-sided", distribution="t",
  7007. nan_policy='propagate', *, axis=0):
  7008. """Compute the Brunner-Munzel test on samples x and y.
  7009. The Brunner-Munzel test is a nonparametric test of the null hypothesis that
  7010. when values are taken one by one from each group, the probabilities of
  7011. getting large values in both groups are equal.
  7012. Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the
  7013. assumption of equivariance of two groups. Note that this does not assume
  7014. the distributions are same. This test works on two independent samples,
  7015. which may have different sizes.
  7016. Parameters
  7017. ----------
  7018. x, y : array_like
  7019. Array of samples, should be one-dimensional.
  7020. alternative : {'two-sided', 'less', 'greater'}, optional
  7021. Defines the alternative hypothesis.
  7022. The following options are available (default is 'two-sided'):
  7023. * 'two-sided'
  7024. * 'less': one-sided
  7025. * 'greater': one-sided
  7026. distribution : {'t', 'normal'}, optional
  7027. Defines how to get the p-value.
  7028. The following options are available (default is 't'):
  7029. * 't': get the p-value by t-distribution
  7030. * 'normal': get the p-value by standard normal distribution.
  7031. nan_policy : {'propagate', 'raise', 'omit'}, optional
  7032. Defines how to handle when input contains nan.
  7033. The following options are available (default is 'propagate'):
  7034. * 'propagate': returns nan
  7035. * 'raise': throws an error
  7036. * 'omit': performs the calculations ignoring nan values
  7037. axis : int or None, default=0
  7038. If an int, the axis of the input along which to compute the statistic.
  7039. The statistic of each axis-slice (e.g. row) of the input will appear
  7040. in a corresponding element of the output. If None, the input will be
  7041. raveled before computing the statistic.
  7042. Returns
  7043. -------
  7044. statistic : float
  7045. The Brunner-Munzer W statistic.
  7046. pvalue : float
  7047. p-value assuming an t distribution. One-sided or
  7048. two-sided, depending on the choice of `alternative` and `distribution`.
  7049. See Also
  7050. --------
  7051. mannwhitneyu : Mann-Whitney rank test on two samples.
  7052. Notes
  7053. -----
  7054. Brunner and Munzel recommended to estimate the p-value by t-distribution
  7055. when the size of data is 50 or less. If the size is lower than 10, it would
  7056. be better to use permuted Brunner Munzel test (see [2]_).
  7057. References
  7058. ----------
  7059. .. [1] Brunner, E. and Munzel, U. "The nonparametric Benhrens-Fisher
  7060. problem: Asymptotic theory and a small-sample approximation".
  7061. Biometrical Journal. Vol. 42(2000): 17-25.
  7062. .. [2] Neubert, K. and Brunner, E. "A studentized permutation test for the
  7063. non-parametric Behrens-Fisher problem". Computational Statistics and
  7064. Data Analysis. Vol. 51(2007): 5192-5204.
  7065. Examples
  7066. --------
  7067. >>> from scipy import stats
  7068. >>> x1 = [1,2,1,1,1,1,1,1,1,1,2,4,1,1]
  7069. >>> x2 = [3,3,4,3,1,2,3,1,1,5,4]
  7070. >>> w, p_value = stats.brunnermunzel(x1, x2)
  7071. >>> w
  7072. 3.1374674823029505
  7073. >>> p_value
  7074. 0.0057862086661515377
  7075. """
  7076. xp = array_namespace(x, y)
  7077. nx = x.shape[-1]
  7078. ny = y.shape[-1]
  7079. # _axis_nan_policy decorator ensures we can work along the last axis
  7080. rankc = rankdata(xp.concat((x, y), axis=axis), axis=-1)
  7081. rankcx = rankc[..., 0:nx]
  7082. rankcy = rankc[..., nx:nx+ny]
  7083. rankcx_mean = xp.mean(rankcx, axis=-1, keepdims=True)
  7084. rankcy_mean = xp.mean(rankcy, axis=-1, keepdims=True)
  7085. rankx = rankdata(x, axis=-1)
  7086. ranky = rankdata(y, axis=-1)
  7087. rankx_mean = xp.mean(rankx, axis=-1, keepdims=True)
  7088. ranky_mean = xp.mean(ranky, axis=-1, keepdims=True)
  7089. temp_x = rankcx - rankx - rankcx_mean + rankx_mean
  7090. Sx = xp.vecdot(temp_x, temp_x, axis=-1)
  7091. Sx /= nx - 1
  7092. temp_y = rankcy - ranky - rankcy_mean + ranky_mean
  7093. Sy = xp.vecdot(temp_y, temp_y, axis=-1)
  7094. Sy /= ny - 1
  7095. rankcx_mean = xp.squeeze(rankcx_mean, axis=-1)
  7096. rankcy_mean = xp.squeeze(rankcy_mean, axis=-1)
  7097. wbfn = nx * ny * (rankcy_mean - rankcx_mean)
  7098. wbfn /= (nx + ny) * xp.sqrt(nx * Sx + ny * Sy)
  7099. if distribution == "t":
  7100. df_numer = xp.pow(nx * Sx + ny * Sy, 2.0)
  7101. df_denom = xp.pow(nx * Sx, 2.0) / (nx - 1)
  7102. df_denom += xp.pow(ny * Sy, 2.0) / (ny - 1)
  7103. df = df_numer / df_denom
  7104. if xp.any(df_numer == 0) and xp.any(df_denom == 0):
  7105. message = ("p-value cannot be estimated with `distribution='t' "
  7106. "because degrees of freedom parameter is undefined "
  7107. "(0/0). Try using `distribution='normal'")
  7108. warnings.warn(message, RuntimeWarning, stacklevel=2)
  7109. distribution = _SimpleStudentT(df)
  7110. elif distribution == "normal":
  7111. distribution = _SimpleNormal()
  7112. else:
  7113. raise ValueError(
  7114. "distribution should be 't' or 'normal'")
  7115. p = _get_pvalue(-wbfn, distribution, alternative, xp=xp)
  7116. return BrunnerMunzelResult(wbfn, p)
  7117. @xp_capabilities(cpu_only=True, exceptions=['cupy', 'jax.numpy'],
  7118. reason='Delegation for `special.stdtr` only implemented for CuPy and JAX.',
  7119. jax_jit=False, allow_dask_compute=True)
  7120. @_axis_nan_policy_factory(SignificanceResult, kwd_samples=['weights'], paired=True)
  7121. def combine_pvalues(pvalues, method='fisher', weights=None, *, axis=0):
  7122. """
  7123. Combine p-values from independent tests that bear upon the same hypothesis.
  7124. These methods are intended only for combining p-values from hypothesis
  7125. tests based upon continuous distributions.
  7126. Each method assumes that under the null hypothesis, the p-values are
  7127. sampled independently and uniformly from the interval [0, 1]. A test
  7128. statistic (different for each method) is computed and a combined
  7129. p-value is calculated based upon the distribution of this test statistic
  7130. under the null hypothesis.
  7131. Parameters
  7132. ----------
  7133. pvalues : array_like
  7134. Array of p-values assumed to come from independent tests based on
  7135. continuous distributions.
  7136. method : {'fisher', 'pearson', 'tippett', 'stouffer', 'mudholkar_george'}
  7137. Name of method to use to combine p-values.
  7138. The available methods are (see Notes for details):
  7139. * 'fisher': Fisher's method (Fisher's combined probability test)
  7140. * 'pearson': Pearson's method
  7141. * 'mudholkar_george': Mudholkar's and George's method
  7142. * 'tippett': Tippett's method
  7143. * 'stouffer': Stouffer's Z-score method
  7144. weights : array_like, optional
  7145. Optional array of weights used only for Stouffer's Z-score method.
  7146. Ignored by other methods.
  7147. Returns
  7148. -------
  7149. res : SignificanceResult
  7150. An object containing attributes:
  7151. statistic : float
  7152. The statistic calculated by the specified method.
  7153. pvalue : float
  7154. The combined p-value.
  7155. Examples
  7156. --------
  7157. Suppose we wish to combine p-values from four independent tests
  7158. of the same null hypothesis using Fisher's method (default).
  7159. >>> from scipy.stats import combine_pvalues
  7160. >>> pvalues = [0.1, 0.05, 0.02, 0.3]
  7161. >>> combine_pvalues(pvalues)
  7162. SignificanceResult(statistic=20.828626352604235, pvalue=0.007616871850449092)
  7163. When the individual p-values carry different weights, consider Stouffer's
  7164. method.
  7165. >>> weights = [1, 2, 3, 4]
  7166. >>> res = combine_pvalues(pvalues, method='stouffer', weights=weights)
  7167. >>> res.pvalue
  7168. 0.009578891494533616
  7169. Notes
  7170. -----
  7171. If this function is applied to tests with a discrete statistics such as
  7172. any rank test or contingency-table test, it will yield systematically
  7173. wrong results, e.g. Fisher's method will systematically overestimate the
  7174. p-value [1]_. This problem becomes less severe for large sample sizes
  7175. when the discrete distributions become approximately continuous.
  7176. The differences between the methods can be best illustrated by their
  7177. statistics and what aspects of a combination of p-values they emphasise
  7178. when considering significance [2]_. For example, methods emphasising large
  7179. p-values are more sensitive to strong false and true negatives; conversely
  7180. methods focussing on small p-values are sensitive to positives.
  7181. * The statistics of Fisher's method (also known as Fisher's combined
  7182. probability test) [3]_ is :math:`-2\\sum_i \\log(p_i)`, which is
  7183. equivalent (as a test statistics) to the product of individual p-values:
  7184. :math:`\\prod_i p_i`. Under the null hypothesis, this statistics follows
  7185. a :math:`\\chi^2` distribution. This method emphasises small p-values.
  7186. * Pearson's method uses :math:`-2\\sum_i\\log(1-p_i)`, which is equivalent
  7187. to :math:`\\prod_i \\frac{1}{1-p_i}` [2]_.
  7188. It thus emphasises large p-values.
  7189. * Mudholkar and George compromise between Fisher's and Pearson's method by
  7190. averaging their statistics [4]_. Their method emphasises extreme
  7191. p-values, both close to 1 and 0.
  7192. * Stouffer's method [5]_ uses Z-scores and the statistic:
  7193. :math:`\\sum_i \\Phi^{-1} (p_i)`, where :math:`\\Phi` is the CDF of the
  7194. standard normal distribution. The advantage of this method is that it is
  7195. straightforward to introduce weights, which can make Stouffer's method
  7196. more powerful than Fisher's method when the p-values are from studies
  7197. of different size [6]_ [7]_.
  7198. * Tippett's method uses the smallest p-value as a statistic.
  7199. (Mind that this minimum is not the combined p-value.)
  7200. Fisher's method may be extended to combine p-values from dependent tests
  7201. [8]_. Extensions such as Brown's method and Kost's method are not currently
  7202. implemented.
  7203. .. versionadded:: 0.15.0
  7204. References
  7205. ----------
  7206. .. [1] Kincaid, W. M., "The Combination of Tests Based on Discrete
  7207. Distributions." Journal of the American Statistical Association 57,
  7208. no. 297 (1962), 10-19.
  7209. .. [2] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of
  7210. combining p-values." Biometrika 105.1 (2018): 239-246.
  7211. .. [3] https://en.wikipedia.org/wiki/Fisher%27s_method
  7212. .. [4] George, E. O., and G. S. Mudholkar. "On the convolution of logistic
  7213. random variables." Metrika 30.1 (1983): 1-13.
  7214. .. [5] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method
  7215. .. [6] Whitlock, M. C. "Combining probability from independent tests: the
  7216. weighted Z-method is superior to Fisher's approach." Journal of
  7217. Evolutionary Biology 18, no. 5 (2005): 1368-1373.
  7218. .. [7] Zaykin, Dmitri V. "Optimally weighted Z-test is a powerful method
  7219. for combining probabilities in meta-analysis." Journal of
  7220. Evolutionary Biology 24, no. 8 (2011): 1836-1841.
  7221. .. [8] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method
  7222. """
  7223. xp = array_namespace(pvalues, weights)
  7224. pvalues, weights = xp_promote(pvalues, weights, broadcast=True,
  7225. force_floating=True, xp=xp)
  7226. if xp_size(pvalues) == 0:
  7227. # This is really only needed for *testing* _axis_nan_policy decorator
  7228. # It won't happen when the decorator is used.
  7229. NaN = _get_nan(pvalues)
  7230. return SignificanceResult(NaN, NaN)
  7231. n = _length_nonmasked(pvalues, axis)
  7232. n = xp.asarray(n, dtype=pvalues.dtype, device=xp_device(pvalues))
  7233. if method == 'fisher':
  7234. statistic = -2 * xp.sum(xp.log(pvalues), axis=axis)
  7235. chi2 = _SimpleChi2(2*n)
  7236. pval = _get_pvalue(statistic, chi2, alternative='greater',
  7237. symmetric=False, xp=xp)
  7238. elif method == 'pearson':
  7239. statistic = 2 * xp.sum(xp.log1p(-pvalues), axis=axis)
  7240. chi2 = _SimpleChi2(2*n)
  7241. pval = _get_pvalue(-statistic, chi2, alternative='less', symmetric=False, xp=xp)
  7242. elif method == 'mudholkar_george':
  7243. normalizing_factor = xp.sqrt(3/n)/xp.pi
  7244. statistic = (-xp.sum(xp.log(pvalues), axis=axis)
  7245. + xp.sum(xp.log1p(-pvalues), axis=axis))
  7246. nu = 5*n + 4
  7247. approx_factor = xp.sqrt(nu / (nu - 2))
  7248. t = _SimpleStudentT(nu)
  7249. pval = _get_pvalue(statistic * normalizing_factor * approx_factor, t,
  7250. alternative="greater", xp=xp)
  7251. elif method == 'tippett':
  7252. statistic = xp.min(pvalues, axis=axis)
  7253. beta = _SimpleBeta(xp.ones_like(n), n)
  7254. pval = _get_pvalue(statistic, beta, alternative='less', symmetric=False, xp=xp)
  7255. elif method == 'stouffer':
  7256. if weights is None:
  7257. weights = xp.ones_like(pvalues, dtype=pvalues.dtype)
  7258. pvalues, weights = _share_masks(pvalues, weights, xp=xp)
  7259. norm = _SimpleNormal()
  7260. Zi = norm.isf(pvalues)
  7261. # Consider `vecdot` when data-apis/array-api#910 is resolved
  7262. statistic = (xp.sum(weights * Zi, axis=axis)
  7263. / xp_vector_norm(weights, axis=axis))
  7264. pval = _get_pvalue(statistic, norm, alternative="greater", xp=xp)
  7265. else:
  7266. raise ValueError(
  7267. f"Invalid method {method!r}. Valid methods are 'fisher', "
  7268. "'pearson', 'mudholkar_george', 'tippett', and 'stouffer'"
  7269. )
  7270. return SignificanceResult(statistic, pval)
  7271. @dataclass
  7272. class QuantileTestResult:
  7273. r"""
  7274. Result of `scipy.stats.quantile_test`.
  7275. Attributes
  7276. ----------
  7277. statistic: float
  7278. The statistic used to calculate the p-value; either ``T1``, the
  7279. number of observations less than or equal to the hypothesized quantile,
  7280. or ``T2``, the number of observations strictly less than the
  7281. hypothesized quantile. Two test statistics are required to handle the
  7282. possibility the data was generated from a discrete or mixed
  7283. distribution.
  7284. statistic_type : int
  7285. ``1`` or ``2`` depending on which of ``T1`` or ``T2`` was used to
  7286. calculate the p-value respectively. ``T1`` corresponds to the
  7287. ``"greater"`` alternative hypothesis and ``T2`` to the ``"less"``. For
  7288. the ``"two-sided"`` case, the statistic type that leads to smallest
  7289. p-value is used. For significant tests, ``statistic_type = 1`` means
  7290. there is evidence that the population quantile is significantly greater
  7291. than the hypothesized value and ``statistic_type = 2`` means there is
  7292. evidence that it is significantly less than the hypothesized value.
  7293. pvalue : float
  7294. The p-value of the hypothesis test.
  7295. """
  7296. statistic: float
  7297. statistic_type: int
  7298. pvalue: float
  7299. _alternative: list[str] = field(repr=False)
  7300. _x : np.ndarray = field(repr=False)
  7301. _p : float = field(repr=False)
  7302. def confidence_interval(self, confidence_level=0.95):
  7303. """
  7304. Compute the confidence interval of the quantile.
  7305. Parameters
  7306. ----------
  7307. confidence_level : float, default: 0.95
  7308. Confidence level for the computed confidence interval
  7309. of the quantile. Default is 0.95.
  7310. Returns
  7311. -------
  7312. ci : ``ConfidenceInterval`` object
  7313. The object has attributes ``low`` and ``high`` that hold the
  7314. lower and upper bounds of the confidence interval.
  7315. Examples
  7316. --------
  7317. >>> import numpy as np
  7318. >>> import scipy.stats as stats
  7319. >>> p = 0.75 # quantile of interest
  7320. >>> q = 0 # hypothesized value of the quantile
  7321. >>> x = np.exp(np.arange(0, 1.01, 0.01))
  7322. >>> res = stats.quantile_test(x, q=q, p=p, alternative='less')
  7323. >>> lb, ub = res.confidence_interval()
  7324. >>> lb, ub
  7325. (-inf, 2.293318740264183)
  7326. >>> res = stats.quantile_test(x, q=q, p=p, alternative='two-sided')
  7327. >>> lb, ub = res.confidence_interval(0.9)
  7328. >>> lb, ub
  7329. (1.9542373206359396, 2.293318740264183)
  7330. """
  7331. alternative = self._alternative
  7332. p = self._p
  7333. x = np.sort(self._x)
  7334. n = len(x)
  7335. bd = stats.binom(n, p)
  7336. if confidence_level <= 0 or confidence_level >= 1:
  7337. message = "`confidence_level` must be a number between 0 and 1."
  7338. raise ValueError(message)
  7339. low_index = np.nan
  7340. high_index = np.nan
  7341. if alternative == 'less':
  7342. p = 1 - confidence_level
  7343. low = -np.inf
  7344. high_index = int(bd.isf(p))
  7345. high = x[high_index] if high_index < n else np.nan
  7346. elif alternative == 'greater':
  7347. p = 1 - confidence_level
  7348. low_index = int(bd.ppf(p)) - 1
  7349. low = x[low_index] if low_index >= 0 else np.nan
  7350. high = np.inf
  7351. elif alternative == 'two-sided':
  7352. p = (1 - confidence_level) / 2
  7353. low_index = int(bd.ppf(p)) - 1
  7354. low = x[low_index] if low_index >= 0 else np.nan
  7355. high_index = int(bd.isf(p))
  7356. high = x[high_index] if high_index < n else np.nan
  7357. return ConfidenceInterval(low, high)
  7358. def quantile_test_iv(x, q, p, alternative):
  7359. x = np.atleast_1d(x)
  7360. message = '`x` must be a one-dimensional array of numbers.'
  7361. if x.ndim != 1 or not np.issubdtype(x.dtype, np.number):
  7362. raise ValueError(message)
  7363. q = np.array(q)[()]
  7364. message = "`q` must be a scalar."
  7365. if q.ndim != 0 or not np.issubdtype(q.dtype, np.number):
  7366. raise ValueError(message)
  7367. p = np.array(p)[()]
  7368. message = "`p` must be a float strictly between 0 and 1."
  7369. if p.ndim != 0 or p >= 1 or p <= 0:
  7370. raise ValueError(message)
  7371. alternatives = {'two-sided', 'less', 'greater'}
  7372. message = f"`alternative` must be one of {alternatives}"
  7373. if alternative not in alternatives:
  7374. raise ValueError(message)
  7375. return x, q, p, alternative
  7376. @xp_capabilities(np_only=True)
  7377. def quantile_test(x, *, q=0, p=0.5, alternative='two-sided'):
  7378. r"""
  7379. Perform a quantile test and compute a confidence interval of the quantile.
  7380. This function tests the null hypothesis that `q` is the value of the
  7381. quantile associated with probability `p` of the population underlying
  7382. sample `x`. For example, with default parameters, it tests that the
  7383. median of the population underlying `x` is zero. The function returns an
  7384. object including the test statistic, a p-value, and a method for computing
  7385. the confidence interval around the quantile.
  7386. Parameters
  7387. ----------
  7388. x : array_like
  7389. A one-dimensional sample.
  7390. q : float, default: 0
  7391. The hypothesized value of the quantile.
  7392. p : float, default: 0.5
  7393. The probability associated with the quantile; i.e. the proportion of
  7394. the population less than `q` is `p`. Must be strictly between 0 and
  7395. 1.
  7396. alternative : {'two-sided', 'less', 'greater'}, optional
  7397. Defines the alternative hypothesis.
  7398. The following options are available (default is 'two-sided'):
  7399. * 'two-sided': the quantile associated with the probability `p`
  7400. is not `q`.
  7401. * 'less': the quantile associated with the probability `p` is less
  7402. than `q`.
  7403. * 'greater': the quantile associated with the probability `p` is
  7404. greater than `q`.
  7405. Returns
  7406. -------
  7407. result : QuantileTestResult
  7408. An object with the following attributes:
  7409. statistic : float
  7410. One of two test statistics that may be used in the quantile test.
  7411. The first test statistic, ``T1``, is the proportion of samples in
  7412. `x` that are less than or equal to the hypothesized quantile
  7413. `q`. The second test statistic, ``T2``, is the proportion of
  7414. samples in `x` that are strictly less than the hypothesized
  7415. quantile `q`.
  7416. When ``alternative = 'greater'``, ``T1`` is used to calculate the
  7417. p-value and ``statistic`` is set to ``T1``.
  7418. When ``alternative = 'less'``, ``T2`` is used to calculate the
  7419. p-value and ``statistic`` is set to ``T2``.
  7420. When ``alternative = 'two-sided'``, both ``T1`` and ``T2`` are
  7421. considered, and the one that leads to the smallest p-value is used.
  7422. statistic_type : int
  7423. Either `1` or `2` depending on which of ``T1`` or ``T2`` was
  7424. used to calculate the p-value.
  7425. pvalue : float
  7426. The p-value associated with the given alternative.
  7427. The object also has the following method:
  7428. confidence_interval(confidence_level=0.95)
  7429. Computes a confidence interval around the the
  7430. population quantile associated with the probability `p`. The
  7431. confidence interval is returned in a ``namedtuple`` with
  7432. fields `low` and `high`. Values are `nan` when there are
  7433. not enough observations to compute the confidence interval at
  7434. the desired confidence.
  7435. Notes
  7436. -----
  7437. This test and its method for computing confidence intervals are
  7438. non-parametric. They are valid if and only if the observations are i.i.d.
  7439. The implementation of the test follows Conover [1]_. Two test statistics
  7440. are considered.
  7441. ``T1``: The number of observations in `x` less than or equal to `q`.
  7442. ``T1 = (x <= q).sum()``
  7443. ``T2``: The number of observations in `x` strictly less than `q`.
  7444. ``T2 = (x < q).sum()``
  7445. The use of two test statistics is necessary to handle the possibility that
  7446. `x` was generated from a discrete or mixed distribution.
  7447. The null hypothesis for the test is:
  7448. H0: The :math:`p^{\mathrm{th}}` population quantile is `q`.
  7449. and the null distribution for each test statistic is
  7450. :math:`\mathrm{binom}\left(n, p\right)`. When ``alternative='less'``,
  7451. the alternative hypothesis is:
  7452. H1: The :math:`p^{\mathrm{th}}` population quantile is less than `q`.
  7453. and the p-value is the probability that the binomial random variable
  7454. .. math::
  7455. Y \sim \mathrm{binom}\left(n, p\right)
  7456. is greater than or equal to the observed value ``T2``.
  7457. When ``alternative='greater'``, the alternative hypothesis is:
  7458. H1: The :math:`p^{\mathrm{th}}` population quantile is greater than `q`
  7459. and the p-value is the probability that the binomial random variable Y
  7460. is less than or equal to the observed value ``T1``.
  7461. When ``alternative='two-sided'``, the alternative hypothesis is
  7462. H1: `q` is not the :math:`p^{\mathrm{th}}` population quantile.
  7463. and the p-value is twice the smaller of the p-values for the ``'less'``
  7464. and ``'greater'`` cases. Both of these p-values can exceed 0.5 for the same
  7465. data, so the value is clipped into the interval :math:`[0, 1]`.
  7466. The approach for confidence intervals is attributed to Thompson [2]_ and
  7467. later proven to be applicable to any set of i.i.d. samples [3]_. The
  7468. computation is based on the observation that the probability of a quantile
  7469. :math:`q` to be larger than any observations :math:`x_m (1\leq m \leq N)`
  7470. can be computed as
  7471. .. math::
  7472. \mathbb{P}(x_m \leq q) = 1 - \sum_{k=0}^{m-1} \binom{N}{k}
  7473. q^k(1-q)^{N-k}
  7474. By default, confidence intervals are computed for a 95% confidence level.
  7475. A common interpretation of a 95% confidence intervals is that if i.i.d.
  7476. samples are drawn repeatedly from the same population and confidence
  7477. intervals are formed each time, the confidence interval will contain the
  7478. true value of the specified quantile in approximately 95% of trials.
  7479. A similar function is available in the QuantileNPCI R package [4]_. The
  7480. foundation is the same, but it computes the confidence interval bounds by
  7481. doing interpolations between the sample values, whereas this function uses
  7482. only sample values as bounds. Thus, ``quantile_test.confidence_interval``
  7483. returns more conservative intervals (i.e., larger).
  7484. The same computation of confidence intervals for quantiles is included in
  7485. the confintr package [5]_.
  7486. Two-sided confidence intervals are not guaranteed to be optimal; i.e.,
  7487. there may exist a tighter interval that may contain the quantile of
  7488. interest with probability larger than the confidence level.
  7489. Without further assumption on the samples (e.g., the nature of the
  7490. underlying distribution), the one-sided intervals are optimally tight.
  7491. References
  7492. ----------
  7493. .. [1] W. J. Conover. Practical Nonparametric Statistics, 3rd Ed. 1999.
  7494. .. [2] W. R. Thompson, "On Confidence Ranges for the Median and Other
  7495. Expectation Distributions for Populations of Unknown Distribution
  7496. Form," The Annals of Mathematical Statistics, vol. 7, no. 3,
  7497. pp. 122-128, 1936, Accessed: Sep. 18, 2019. [Online]. Available:
  7498. https://www.jstor.org/stable/2957563.
  7499. .. [3] H. A. David and H. N. Nagaraja, "Order Statistics in Nonparametric
  7500. Inference" in Order Statistics, John Wiley & Sons, Ltd, 2005, pp.
  7501. 159-170. Available:
  7502. https://onlinelibrary.wiley.com/doi/10.1002/0471722162.ch7.
  7503. .. [4] N. Hutson, A. Hutson, L. Yan, "QuantileNPCI: Nonparametric
  7504. Confidence Intervals for Quantiles," R package,
  7505. https://cran.r-project.org/package=QuantileNPCI
  7506. .. [5] M. Mayer, "confintr: Confidence Intervals," R package,
  7507. https://cran.r-project.org/package=confintr
  7508. Examples
  7509. --------
  7510. Suppose we wish to test the null hypothesis that the median of a population
  7511. is equal to 0.5. We choose a confidence level of 99%; that is, we will
  7512. reject the null hypothesis in favor of the alternative if the p-value is
  7513. less than 0.01.
  7514. When testing random variates from the standard uniform distribution, which
  7515. has a median of 0.5, we expect the data to be consistent with the null
  7516. hypothesis most of the time.
  7517. >>> import numpy as np
  7518. >>> from scipy import stats
  7519. >>> rng = np.random.default_rng(6981396440634228121)
  7520. >>> rvs = stats.uniform.rvs(size=100, random_state=rng)
  7521. >>> stats.quantile_test(rvs, q=0.5, p=0.5)
  7522. QuantileTestResult(statistic=45, statistic_type=1, pvalue=0.36820161732669576)
  7523. As expected, the p-value is not below our threshold of 0.01, so
  7524. we cannot reject the null hypothesis.
  7525. When testing data from the standard *normal* distribution, which has a
  7526. median of 0, we would expect the null hypothesis to be rejected.
  7527. >>> rvs = stats.norm.rvs(size=100, random_state=rng)
  7528. >>> stats.quantile_test(rvs, q=0.5, p=0.5)
  7529. QuantileTestResult(statistic=67, statistic_type=2, pvalue=0.0008737198369123724)
  7530. Indeed, the p-value is lower than our threshold of 0.01, so we reject the
  7531. null hypothesis in favor of the default "two-sided" alternative: the median
  7532. of the population is *not* equal to 0.5.
  7533. However, suppose we were to test the null hypothesis against the
  7534. one-sided alternative that the median of the population is *greater* than
  7535. 0.5. Since the median of the standard normal is less than 0.5, we would not
  7536. expect the null hypothesis to be rejected.
  7537. >>> stats.quantile_test(rvs, q=0.5, p=0.5, alternative='greater')
  7538. QuantileTestResult(statistic=67, statistic_type=1, pvalue=0.9997956114162866)
  7539. Unsurprisingly, with a p-value greater than our threshold, we would not
  7540. reject the null hypothesis in favor of the chosen alternative.
  7541. The quantile test can be used for any quantile, not only the median. For
  7542. example, we can test whether the third quartile of the distribution
  7543. underlying the sample is greater than 0.6.
  7544. >>> rvs = stats.uniform.rvs(size=100, random_state=rng)
  7545. >>> stats.quantile_test(rvs, q=0.6, p=0.75, alternative='greater')
  7546. QuantileTestResult(statistic=64, statistic_type=1, pvalue=0.00940696592998271)
  7547. The p-value is lower than the threshold. We reject the null hypothesis in
  7548. favor of the alternative: the third quartile of the distribution underlying
  7549. our sample is greater than 0.6.
  7550. `quantile_test` can also compute confidence intervals for any quantile.
  7551. >>> rvs = stats.norm.rvs(size=100, random_state=rng)
  7552. >>> res = stats.quantile_test(rvs, q=0.6, p=0.75)
  7553. >>> ci = res.confidence_interval(confidence_level=0.95)
  7554. >>> ci
  7555. ConfidenceInterval(low=0.284491604437432, high=0.8912531024914844)
  7556. When testing a one-sided alternative, the confidence interval contains
  7557. all observations such that if passed as `q`, the p-value of the
  7558. test would be greater than 0.05, and therefore the null hypothesis
  7559. would not be rejected. For example:
  7560. >>> rvs.sort()
  7561. >>> q, p, alpha = 0.6, 0.75, 0.95
  7562. >>> res = stats.quantile_test(rvs, q=q, p=p, alternative='less')
  7563. >>> ci = res.confidence_interval(confidence_level=alpha)
  7564. >>> for x in rvs[rvs <= ci.high]:
  7565. ... res = stats.quantile_test(rvs, q=x, p=p, alternative='less')
  7566. ... assert res.pvalue > 1-alpha
  7567. >>> for x in rvs[rvs > ci.high]:
  7568. ... res = stats.quantile_test(rvs, q=x, p=p, alternative='less')
  7569. ... assert res.pvalue < 1-alpha
  7570. Also, if a 95% confidence interval is repeatedly generated for random
  7571. samples, the confidence interval will contain the true quantile value in
  7572. approximately 95% of replications.
  7573. >>> dist = stats.rayleigh() # our "unknown" distribution
  7574. >>> p = 0.2
  7575. >>> true_stat = dist.ppf(p) # the true value of the statistic
  7576. >>> n_trials = 1000
  7577. >>> quantile_ci_contains_true_stat = 0
  7578. >>> for i in range(n_trials):
  7579. ... data = dist.rvs(size=100, random_state=rng)
  7580. ... res = stats.quantile_test(data, p=p)
  7581. ... ci = res.confidence_interval(0.95)
  7582. ... if ci[0] < true_stat < ci[1]:
  7583. ... quantile_ci_contains_true_stat += 1
  7584. >>> quantile_ci_contains_true_stat >= 950
  7585. True
  7586. This works with any distribution and any quantile, as long as the samples
  7587. are i.i.d.
  7588. """
  7589. # Implementation carefully follows [1] 3.2
  7590. # "H0: the p*th quantile of X is x*"
  7591. # To facilitate comparison with [1], we'll use variable names that
  7592. # best match Conover's notation
  7593. X, x_star, p_star, H1 = quantile_test_iv(x, q, p, alternative)
  7594. # "We will use two test statistics in this test. Let T1 equal "
  7595. # "the number of observations less than or equal to x*, and "
  7596. # "let T2 equal the number of observations less than x*."
  7597. T1 = np.count_nonzero(X <= x_star)
  7598. T2 = np.count_nonzero(X < x_star)
  7599. # "The null distribution of the test statistics T1 and T2 is "
  7600. # "the binomial distribution, with parameters n = sample size, and "
  7601. # "p = p* as given in the null hypothesis.... Y has the binomial "
  7602. # "distribution with parameters n and p*."
  7603. n = len(X)
  7604. Y = stats.binom(n=n, p=p_star)
  7605. # "H1: the p* population quantile is less than x*"
  7606. if H1 == 'less':
  7607. # "The p-value is the probability that a binomial random variable Y "
  7608. # "is greater than *or equal to* the observed value of T2...using p=p*"
  7609. pvalue = Y.sf(T2-1) # Y.pmf(T2) + Y.sf(T2)
  7610. statistic = T2
  7611. statistic_type = 2
  7612. # "H1: the p* population quantile is greater than x*"
  7613. elif H1 == 'greater':
  7614. # "The p-value is the probability that a binomial random variable Y "
  7615. # "is less than or equal to the observed value of T1... using p = p*"
  7616. pvalue = Y.cdf(T1)
  7617. statistic = T1
  7618. statistic_type = 1
  7619. # "H1: x* is not the p*th population quantile"
  7620. elif H1 == 'two-sided':
  7621. # "The p-value is twice the smaller of the probabilities that a
  7622. # binomial random variable Y is less than or equal to the observed
  7623. # value of T1 or greater than or equal to the observed value of T2
  7624. # using p=p*."
  7625. # Note: both one-sided p-values can exceed 0.5 for the same data, so
  7626. # `clip`
  7627. pvalues = [Y.cdf(T1), Y.sf(T2 - 1)] # [greater, less]
  7628. sorted_idx = np.argsort(pvalues)
  7629. pvalue = np.clip(2*pvalues[sorted_idx[0]], 0, 1)
  7630. if sorted_idx[0]:
  7631. statistic, statistic_type = T2, 2
  7632. else:
  7633. statistic, statistic_type = T1, 1
  7634. return QuantileTestResult(
  7635. statistic=statistic,
  7636. statistic_type=statistic_type,
  7637. pvalue=pvalue,
  7638. _alternative=H1,
  7639. _x=X,
  7640. _p=p_star
  7641. )
  7642. #####################################
  7643. # STATISTICAL DISTANCES #
  7644. #####################################
  7645. @xp_capabilities(np_only=True)
  7646. def wasserstein_distance_nd(u_values, v_values, u_weights=None, v_weights=None):
  7647. r"""
  7648. Compute the Wasserstein-1 distance between two N-D discrete distributions.
  7649. The Wasserstein distance, also called the Earth mover's distance or the
  7650. optimal transport distance, is a similarity metric between two probability
  7651. distributions [1]_. In the discrete case, the Wasserstein distance can be
  7652. understood as the cost of an optimal transport plan to convert one
  7653. distribution into the other. The cost is calculated as the product of the
  7654. amount of probability mass being moved and the distance it is being moved.
  7655. A brief and intuitive introduction can be found at [2]_.
  7656. .. versionadded:: 1.13.0
  7657. Parameters
  7658. ----------
  7659. u_values : 2d array_like
  7660. A sample from a probability distribution or the support (set of all
  7661. possible values) of a probability distribution. Each element along
  7662. axis 0 is an observation or possible value, and axis 1 represents the
  7663. dimensionality of the distribution; i.e., each row is a vector
  7664. observation or possible value.
  7665. v_values : 2d array_like
  7666. A sample from or the support of a second distribution.
  7667. u_weights, v_weights : 1d array_like, optional
  7668. Weights or counts corresponding with the sample or probability masses
  7669. corresponding with the support values. Sum of elements must be positive
  7670. and finite. If unspecified, each value is assigned the same weight.
  7671. Returns
  7672. -------
  7673. distance : float
  7674. The computed distance between the distributions.
  7675. Notes
  7676. -----
  7677. Given two probability mass functions, :math:`u`
  7678. and :math:`v`, the first Wasserstein distance between the distributions
  7679. using the Euclidean norm is:
  7680. .. math::
  7681. l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int \| x-y \|_2 \mathrm{d} \pi (x, y)
  7682. where :math:`\Gamma (u, v)` is the set of (probability) distributions on
  7683. :math:`\mathbb{R}^n \times \mathbb{R}^n` whose marginals are :math:`u` and
  7684. :math:`v` on the first and second factors respectively. For a given value
  7685. :math:`x`, :math:`u(x)` gives the probability of :math:`u` at position
  7686. :math:`x`, and the same for :math:`v(x)`.
  7687. This is also called the optimal transport problem or the Monge problem.
  7688. Let the finite point sets :math:`\{x_i\}` and :math:`\{y_j\}` denote
  7689. the support set of probability mass function :math:`u` and :math:`v`
  7690. respectively. The Monge problem can be expressed as follows,
  7691. Let :math:`\Gamma` denote the transport plan, :math:`D` denote the
  7692. distance matrix and,
  7693. .. math::
  7694. x = \text{vec}(\Gamma) \\
  7695. c = \text{vec}(D) \\
  7696. b = \begin{bmatrix}
  7697. u\\
  7698. v\\
  7699. \end{bmatrix}
  7700. The :math:`\text{vec}()` function denotes the Vectorization function
  7701. that transforms a matrix into a column vector by vertically stacking
  7702. the columns of the matrix.
  7703. The transport plan :math:`\Gamma` is a matrix :math:`[\gamma_{ij}]` in
  7704. which :math:`\gamma_{ij}` is a positive value representing the amount of
  7705. probability mass transported from :math:`u(x_i)` to :math:`v(y_i)`.
  7706. Summing over the rows of :math:`\Gamma` should give the source distribution
  7707. :math:`u` : :math:`\sum_j \gamma_{ij} = u(x_i)` holds for all :math:`i`
  7708. and summing over the columns of :math:`\Gamma` should give the target
  7709. distribution :math:`v`: :math:`\sum_i \gamma_{ij} = v(y_j)` holds for all
  7710. :math:`j`.
  7711. The distance matrix :math:`D` is a matrix :math:`[d_{ij}]`, in which
  7712. :math:`d_{ij} = d(x_i, y_j)`.
  7713. Given :math:`\Gamma`, :math:`D`, :math:`b`, the Monge problem can be
  7714. transformed into a linear programming problem by
  7715. taking :math:`A x = b` as constraints and :math:`z = c^T x` as minimization
  7716. target (sum of costs) , where matrix :math:`A` has the form
  7717. .. math::
  7718. \begin{array} {rrrr|rrrr|r|rrrr}
  7719. 1 & 1 & \dots & 1 & 0 & 0 & \dots & 0 & \dots & 0 & 0 & \dots &
  7720. 0 \cr
  7721. 0 & 0 & \dots & 0 & 1 & 1 & \dots & 1 & \dots & 0 & 0 &\dots &
  7722. 0 \cr
  7723. \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots
  7724. & \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \cr
  7725. 0 & 0 & \dots & 0 & 0 & 0 & \dots & 0 & \dots & 1 & 1 & \dots &
  7726. 1 \cr \hline
  7727. 1 & 0 & \dots & 0 & 1 & 0 & \dots & \dots & \dots & 1 & 0 & \dots &
  7728. 0 \cr
  7729. 0 & 1 & \dots & 0 & 0 & 1 & \dots & \dots & \dots & 0 & 1 & \dots &
  7730. 0 \cr
  7731. \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots &
  7732. \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \cr
  7733. 0 & 0 & \dots & 1 & 0 & 0 & \dots & 1 & \dots & 0 & 0 & \dots & 1
  7734. \end{array}
  7735. By solving the dual form of the above linear programming problem (with
  7736. solution :math:`y^*`), the Wasserstein distance :math:`l_1 (u, v)` can
  7737. be computed as :math:`b^T y^*`.
  7738. The above solution is inspired by Vincent Herrmann's blog [3]_ . For a
  7739. more thorough explanation, see [4]_ .
  7740. The input distributions can be empirical, therefore coming from samples
  7741. whose values are effectively inputs of the function, or they can be seen as
  7742. generalized functions, in which case they are weighted sums of Dirac delta
  7743. functions located at the specified values.
  7744. References
  7745. ----------
  7746. .. [1] "Wasserstein metric",
  7747. https://en.wikipedia.org/wiki/Wasserstein_metric
  7748. .. [2] Lili Weng, "What is Wasserstein distance?", Lil'log,
  7749. https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance.
  7750. .. [3] Hermann, Vincent. "Wasserstein GAN and the Kantorovich-Rubinstein
  7751. Duality". https://vincentherrmann.github.io/blog/wasserstein/.
  7752. .. [4] Peyré, Gabriel, and Marco Cuturi. "Computational optimal
  7753. transport." Center for Research in Economics and Statistics
  7754. Working Papers 2017-86 (2017).
  7755. See Also
  7756. --------
  7757. wasserstein_distance: Compute the Wasserstein-1 distance between two
  7758. 1D discrete distributions.
  7759. Examples
  7760. --------
  7761. Compute the Wasserstein distance between two three-dimensional samples,
  7762. each with two observations.
  7763. >>> from scipy.stats import wasserstein_distance_nd
  7764. >>> wasserstein_distance_nd([[0, 2, 3], [1, 2, 5]], [[3, 2, 3], [4, 2, 5]])
  7765. 3.0
  7766. Compute the Wasserstein distance between two two-dimensional distributions
  7767. with three and two weighted observations, respectively.
  7768. >>> wasserstein_distance_nd([[0, 2.75], [2, 209.3], [0, 0]],
  7769. ... [[0.2, 0.322], [4.5, 25.1808]],
  7770. ... [0.4, 5.2, 0.114], [0.8, 1.5])
  7771. 174.15840245217169
  7772. """
  7773. m, n = len(u_values), len(v_values)
  7774. u_values = asarray(u_values)
  7775. v_values = asarray(v_values)
  7776. if u_values.ndim > 2 or v_values.ndim > 2:
  7777. raise ValueError('Invalid input values. The inputs must have either '
  7778. 'one or two dimensions.')
  7779. # if dimensions are not equal throw error
  7780. if u_values.ndim != v_values.ndim:
  7781. raise ValueError('Invalid input values. Dimensions of inputs must be '
  7782. 'equal.')
  7783. # if data is 1D then call the cdf_distance function
  7784. if u_values.ndim == 1 and v_values.ndim == 1:
  7785. return _cdf_distance(1, u_values, v_values, u_weights, v_weights)
  7786. u_values, u_weights = _validate_distribution(u_values, u_weights)
  7787. v_values, v_weights = _validate_distribution(v_values, v_weights)
  7788. # if number of columns is not equal throw error
  7789. if u_values.shape[1] != v_values.shape[1]:
  7790. raise ValueError('Invalid input values. If two-dimensional, '
  7791. '`u_values` and `v_values` must have the same '
  7792. 'number of columns.')
  7793. # if data contains np.inf then return inf or nan
  7794. if np.any(np.isinf(u_values)) ^ np.any(np.isinf(v_values)):
  7795. return np.inf
  7796. elif np.any(np.isinf(u_values)) and np.any(np.isinf(v_values)):
  7797. return np.nan
  7798. # create constraints
  7799. A_upper_part = sparse.block_diag((np.ones((1, n)), ) * m)
  7800. A_lower_part = sparse.hstack((sparse.eye(n), ) * m)
  7801. # sparse constraint matrix of size (m + n)*(m * n)
  7802. A = sparse.vstack((A_upper_part, A_lower_part))
  7803. A = sparse.coo_array(A)
  7804. # get cost matrix
  7805. D = distance_matrix(u_values, v_values, p=2)
  7806. cost = D.ravel()
  7807. # create the minimization target
  7808. p_u = np.full(m, 1/m) if u_weights is None else u_weights/np.sum(u_weights)
  7809. p_v = np.full(n, 1/n) if v_weights is None else v_weights/np.sum(v_weights)
  7810. b = np.concatenate((p_u, p_v), axis=0)
  7811. # solving LP
  7812. constraints = LinearConstraint(A=A.T, ub=cost)
  7813. opt_res = milp(c=-b, constraints=constraints, bounds=(-np.inf, np.inf))
  7814. return -opt_res.fun
  7815. @xp_capabilities(np_only=True)
  7816. def wasserstein_distance(u_values, v_values, u_weights=None, v_weights=None):
  7817. r"""
  7818. Compute the Wasserstein-1 distance between two 1D discrete distributions.
  7819. The Wasserstein distance, also called the Earth mover's distance or the
  7820. optimal transport distance, is a similarity metric between two probability
  7821. distributions [1]_. In the discrete case, the Wasserstein distance can be
  7822. understood as the cost of an optimal transport plan to convert one
  7823. distribution into the other. The cost is calculated as the product of the
  7824. amount of probability mass being moved and the distance it is being moved.
  7825. A brief and intuitive introduction can be found at [2]_.
  7826. .. versionadded:: 1.0.0
  7827. Parameters
  7828. ----------
  7829. u_values : 1d array_like
  7830. A sample from a probability distribution or the support (set of all
  7831. possible values) of a probability distribution. Each element is an
  7832. observation or possible value.
  7833. v_values : 1d array_like
  7834. A sample from or the support of a second distribution.
  7835. u_weights, v_weights : 1d array_like, optional
  7836. Weights or counts corresponding with the sample or probability masses
  7837. corresponding with the support values. Sum of elements must be positive
  7838. and finite. If unspecified, each value is assigned the same weight.
  7839. Returns
  7840. -------
  7841. distance : float
  7842. The computed distance between the distributions.
  7843. Notes
  7844. -----
  7845. Given two 1D probability mass functions, :math:`u` and :math:`v`, the first
  7846. Wasserstein distance between the distributions is:
  7847. .. math::
  7848. l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int_{\mathbb{R} \times
  7849. \mathbb{R}} |x-y| \mathrm{d} \pi (x, y)
  7850. where :math:`\Gamma (u, v)` is the set of (probability) distributions on
  7851. :math:`\mathbb{R} \times \mathbb{R}` whose marginals are :math:`u` and
  7852. :math:`v` on the first and second factors respectively. For a given value
  7853. :math:`x`, :math:`u(x)` gives the probability of :math:`u` at position
  7854. :math:`x`, and the same for :math:`v(x)`.
  7855. If :math:`U` and :math:`V` are the respective CDFs of :math:`u` and
  7856. :math:`v`, this distance also equals to:
  7857. .. math::
  7858. l_1(u, v) = \int_{-\infty}^{+\infty} |U-V|
  7859. See [3]_ for a proof of the equivalence of both definitions.
  7860. The input distributions can be empirical, therefore coming from samples
  7861. whose values are effectively inputs of the function, or they can be seen as
  7862. generalized functions, in which case they are weighted sums of Dirac delta
  7863. functions located at the specified values.
  7864. References
  7865. ----------
  7866. .. [1] "Wasserstein metric", https://en.wikipedia.org/wiki/Wasserstein_metric
  7867. .. [2] Lili Weng, "What is Wasserstein distance?", Lil'log,
  7868. https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance.
  7869. .. [3] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related
  7870. Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`.
  7871. See Also
  7872. --------
  7873. wasserstein_distance_nd: Compute the Wasserstein-1 distance between two N-D
  7874. discrete distributions.
  7875. Examples
  7876. --------
  7877. >>> from scipy.stats import wasserstein_distance
  7878. >>> wasserstein_distance([0, 1, 3], [5, 6, 8])
  7879. 5.0
  7880. >>> wasserstein_distance([0, 1], [0, 1], [3, 1], [2, 2])
  7881. 0.25
  7882. >>> wasserstein_distance([3.4, 3.9, 7.5, 7.8], [4.5, 1.4],
  7883. ... [1.4, 0.9, 3.1, 7.2], [3.2, 3.5])
  7884. 4.0781331438047861
  7885. """
  7886. return _cdf_distance(1, u_values, v_values, u_weights, v_weights)
  7887. @xp_capabilities(np_only=True)
  7888. def energy_distance(u_values, v_values, u_weights=None, v_weights=None):
  7889. r"""Compute the energy distance between two 1D distributions.
  7890. .. versionadded:: 1.0.0
  7891. Parameters
  7892. ----------
  7893. u_values, v_values : array_like
  7894. Values observed in the (empirical) distribution.
  7895. u_weights, v_weights : array_like, optional
  7896. Weight for each value. If unspecified, each value is assigned the same
  7897. weight.
  7898. `u_weights` (resp. `v_weights`) must have the same length as
  7899. `u_values` (resp. `v_values`). If the weight sum differs from 1, it
  7900. must still be positive and finite so that the weights can be normalized
  7901. to sum to 1.
  7902. Returns
  7903. -------
  7904. distance : float
  7905. The computed distance between the distributions.
  7906. Notes
  7907. -----
  7908. The energy distance between two distributions :math:`u` and :math:`v`, whose
  7909. respective CDFs are :math:`U` and :math:`V`, equals to:
  7910. .. math::
  7911. D(u, v) = \left( 2\mathbb E|X - Y| - \mathbb E|X - X'| -
  7912. \mathbb E|Y - Y'| \right)^{1/2}
  7913. where :math:`X` and :math:`X'` (resp. :math:`Y` and :math:`Y'`) are
  7914. independent random variables whose probability distribution is :math:`u`
  7915. (resp. :math:`v`).
  7916. Sometimes the square of this quantity is referred to as the "energy
  7917. distance" (e.g. in [2]_, [4]_), but as noted in [1]_ and [3]_, only the
  7918. definition above satisfies the axioms of a distance function (metric).
  7919. As shown in [2]_, for one-dimensional real-valued variables, the energy
  7920. distance is linked to the non-distribution-free version of the Cramér-von
  7921. Mises distance:
  7922. .. math::
  7923. D(u, v) = \sqrt{2} l_2(u, v) = \left( 2 \int_{-\infty}^{+\infty} (U-V)^2
  7924. \right)^{1/2}
  7925. Note that the common Cramér-von Mises criterion uses the distribution-free
  7926. version of the distance. See [2]_ (section 2), for more details about both
  7927. versions of the distance.
  7928. The input distributions can be empirical, therefore coming from samples
  7929. whose values are effectively inputs of the function, or they can be seen as
  7930. generalized functions, in which case they are weighted sums of Dirac delta
  7931. functions located at the specified values.
  7932. References
  7933. ----------
  7934. .. [1] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews:
  7935. Computational Statistics, 8(1):27-38 (2015).
  7936. .. [2] Szekely "E-statistics: The energy of statistical samples." Bowling
  7937. Green State University, Department of Mathematics and Statistics,
  7938. Technical Report 02-16 (2002).
  7939. .. [3] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance
  7940. .. [4] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
  7941. Munos "The Cramer Distance as a Solution to Biased Wasserstein
  7942. Gradients" (2017). :arXiv:`1705.10743`.
  7943. Examples
  7944. --------
  7945. >>> from scipy.stats import energy_distance
  7946. >>> energy_distance([0], [2])
  7947. 2.0000000000000004
  7948. >>> energy_distance([0, 8], [0, 8], [3, 1], [2, 2])
  7949. 1.0000000000000002
  7950. >>> energy_distance([0.7, 7.4, 2.4, 6.8], [1.4, 8. ],
  7951. ... [2.1, 4.2, 7.4, 8. ], [7.6, 8.8])
  7952. 0.88003340976158217
  7953. """
  7954. return np.sqrt(2) * _cdf_distance(2, u_values, v_values,
  7955. u_weights, v_weights)
  7956. def _cdf_distance(p, u_values, v_values, u_weights=None, v_weights=None):
  7957. r"""
  7958. Compute, between two one-dimensional distributions :math:`u` and
  7959. :math:`v`, whose respective CDFs are :math:`U` and :math:`V`, the
  7960. statistical distance that is defined as:
  7961. .. math::
  7962. l_p(u, v) = \left( \int_{-\infty}^{+\infty} |U-V|^p \right)^{1/p}
  7963. p is a positive parameter; p = 1 gives the Wasserstein distance, p = 2
  7964. gives the energy distance.
  7965. Parameters
  7966. ----------
  7967. u_values, v_values : array_like
  7968. Values observed in the (empirical) distribution.
  7969. u_weights, v_weights : array_like, optional
  7970. Weight for each value. If unspecified, each value is assigned the same
  7971. weight.
  7972. `u_weights` (resp. `v_weights`) must have the same length as
  7973. `u_values` (resp. `v_values`). If the weight sum differs from 1, it
  7974. must still be positive and finite so that the weights can be normalized
  7975. to sum to 1.
  7976. Returns
  7977. -------
  7978. distance : float
  7979. The computed distance between the distributions.
  7980. Notes
  7981. -----
  7982. The input distributions can be empirical, therefore coming from samples
  7983. whose values are effectively inputs of the function, or they can be seen as
  7984. generalized functions, in which case they are weighted sums of Dirac delta
  7985. functions located at the specified values.
  7986. References
  7987. ----------
  7988. .. [1] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
  7989. Munos "The Cramer Distance as a Solution to Biased Wasserstein
  7990. Gradients" (2017). :arXiv:`1705.10743`.
  7991. """
  7992. u_values, u_weights = _validate_distribution(u_values, u_weights)
  7993. v_values, v_weights = _validate_distribution(v_values, v_weights)
  7994. u_sorter = np.argsort(u_values)
  7995. v_sorter = np.argsort(v_values)
  7996. all_values = np.concatenate((u_values, v_values))
  7997. all_values.sort(kind='mergesort')
  7998. # Compute the differences between pairs of successive values of u and v.
  7999. deltas = np.diff(all_values)
  8000. # Get the respective positions of the values of u and v among the values of
  8001. # both distributions.
  8002. u_cdf_indices = u_values[u_sorter].searchsorted(all_values[:-1], 'right')
  8003. v_cdf_indices = v_values[v_sorter].searchsorted(all_values[:-1], 'right')
  8004. # Calculate the CDFs of u and v using their weights, if specified.
  8005. if u_weights is None:
  8006. u_cdf = u_cdf_indices / u_values.size
  8007. else:
  8008. u_sorted_cumweights = np.concatenate(([0],
  8009. np.cumsum(u_weights[u_sorter])))
  8010. u_cdf = u_sorted_cumweights[u_cdf_indices] / u_sorted_cumweights[-1]
  8011. if v_weights is None:
  8012. v_cdf = v_cdf_indices / v_values.size
  8013. else:
  8014. v_sorted_cumweights = np.concatenate(([0],
  8015. np.cumsum(v_weights[v_sorter])))
  8016. v_cdf = v_sorted_cumweights[v_cdf_indices] / v_sorted_cumweights[-1]
  8017. # Compute the value of the integral based on the CDFs.
  8018. # If p = 1 or p = 2, we avoid using np.power, which introduces an overhead
  8019. # of about 15%.
  8020. if p == 1:
  8021. return np_vecdot(np.abs(u_cdf - v_cdf), deltas)
  8022. if p == 2:
  8023. return np.sqrt(np_vecdot(np.square(u_cdf - v_cdf), deltas))
  8024. return np.power(np_vecdot(np.power(np.abs(u_cdf - v_cdf), p), deltas), 1/p)
  8025. def _validate_distribution(values, weights):
  8026. """
  8027. Validate the values and weights from a distribution input of `cdf_distance`
  8028. and return them as ndarray objects.
  8029. Parameters
  8030. ----------
  8031. values : array_like
  8032. Values observed in the (empirical) distribution.
  8033. weights : array_like
  8034. Weight for each value.
  8035. Returns
  8036. -------
  8037. values : ndarray
  8038. Values as ndarray.
  8039. weights : ndarray
  8040. Weights as ndarray.
  8041. """
  8042. # Validate the value array.
  8043. values = np.asarray(values, dtype=float)
  8044. if len(values) == 0:
  8045. raise ValueError("Distribution can't be empty.")
  8046. # Validate the weight array, if specified.
  8047. if weights is not None:
  8048. weights = np.asarray(weights, dtype=float)
  8049. if len(weights) != len(values):
  8050. raise ValueError('Value and weight array-likes for the same '
  8051. 'empirical distribution must be of the same size.')
  8052. if np.any(weights < 0):
  8053. raise ValueError('All weights must be non-negative.')
  8054. if not 0 < np.sum(weights) < np.inf:
  8055. raise ValueError('Weight array-like sum must be positive and '
  8056. 'finite. Set as None for an equal distribution of '
  8057. 'weight.')
  8058. return values, weights
  8059. return values, None
  8060. @xp_capabilities(skip_backends=[("cupy", "`repeat` can't handle array second arg"),
  8061. ("dask.array", "no `take_along_axis`")],
  8062. jax_jit=False)
  8063. def rankdata(a, method='average', *, axis=None, nan_policy='propagate'):
  8064. """Assign ranks to data, dealing with ties appropriately.
  8065. By default (``axis=None``), the data array is first flattened, and a flat
  8066. array of ranks is returned. Separately reshape the rank array to the
  8067. shape of the data array if desired (see Examples).
  8068. Ranks begin at 1. The `method` argument controls how ranks are assigned
  8069. to equal values. See [1]_ for further discussion of ranking methods.
  8070. Parameters
  8071. ----------
  8072. a : array_like
  8073. The array of values to be ranked.
  8074. method : {'average', 'min', 'max', 'dense', 'ordinal'}, optional
  8075. The method used to assign ranks to tied elements.
  8076. The following methods are available (default is 'average'):
  8077. * 'average': The average of the ranks that would have been assigned to
  8078. all the tied values is assigned to each value.
  8079. * 'min': The minimum of the ranks that would have been assigned to all
  8080. the tied values is assigned to each value. (This is also
  8081. referred to as "competition" ranking.)
  8082. * 'max': The maximum of the ranks that would have been assigned to all
  8083. the tied values is assigned to each value.
  8084. * 'dense': Like 'min', but the rank of the next highest element is
  8085. assigned the rank immediately after those assigned to the tied
  8086. elements.
  8087. * 'ordinal': All values are given a distinct rank, corresponding to
  8088. the order that the values occur in `a`.
  8089. axis : {None, int}, optional
  8090. Axis along which to perform the ranking. If ``None``, the data array
  8091. is first flattened.
  8092. nan_policy : {'propagate', 'omit', 'raise'}, optional
  8093. Defines how to handle when input contains nan.
  8094. The following options are available (default is 'propagate'):
  8095. * 'propagate': propagates nans through the rank calculation
  8096. * 'omit': performs the calculations ignoring nan values
  8097. * 'raise': raises an error
  8098. .. note::
  8099. When `nan_policy` is 'propagate', the output is an array of *all*
  8100. nans because ranks relative to nans in the input are undefined.
  8101. When `nan_policy` is 'omit', nans in `a` are ignored when ranking
  8102. the other values, and the corresponding locations of the output
  8103. are nan.
  8104. .. versionadded:: 1.10
  8105. Returns
  8106. -------
  8107. ranks : ndarray
  8108. An array of size equal to the size of `a`, containing rank
  8109. scores.
  8110. References
  8111. ----------
  8112. .. [1] "Ranking", https://en.wikipedia.org/wiki/Ranking
  8113. Examples
  8114. --------
  8115. >>> import numpy as np
  8116. >>> from scipy.stats import rankdata
  8117. >>> rankdata([0, 2, 3, 2])
  8118. array([ 1. , 2.5, 4. , 2.5])
  8119. >>> rankdata([0, 2, 3, 2], method='min')
  8120. array([ 1, 2, 4, 2])
  8121. >>> rankdata([0, 2, 3, 2], method='max')
  8122. array([ 1, 3, 4, 3])
  8123. >>> rankdata([0, 2, 3, 2], method='dense')
  8124. array([ 1, 2, 3, 2])
  8125. >>> rankdata([0, 2, 3, 2], method='ordinal')
  8126. array([ 1, 2, 4, 3])
  8127. >>> rankdata([[0, 2], [3, 2]]).reshape(2,2)
  8128. array([[1. , 2.5],
  8129. [4. , 2.5]])
  8130. >>> rankdata([[0, 2, 2], [3, 2, 5]], axis=1)
  8131. array([[1. , 2.5, 2.5],
  8132. [2. , 1. , 3. ]])
  8133. >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="propagate")
  8134. array([nan, nan, nan, nan, nan, nan])
  8135. >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="omit")
  8136. array([ 2., 3., 4., nan, 1., nan])
  8137. """
  8138. methods = ('average', 'min', 'max', 'dense', 'ordinal')
  8139. if method not in methods:
  8140. raise ValueError(f'unknown method "{method}"')
  8141. xp = array_namespace(a)
  8142. x = xp.asarray(a)
  8143. if axis is None:
  8144. x = xp_ravel(x)
  8145. axis = -1
  8146. if xp_size(x) == 0:
  8147. dtype = xp.asarray(1.).dtype if method == 'average' else xp.asarray(1).dtype
  8148. return xp.empty(x.shape, dtype=dtype)
  8149. contains_nan = _contains_nan(x, nan_policy)
  8150. x = xp_swapaxes(x, axis, -1, xp=xp)
  8151. ranks = _rankdata(x, method, xp=xp)
  8152. if contains_nan:
  8153. default_float = xp_default_dtype(xp)
  8154. i_nan = (xp.isnan(x) if nan_policy == 'omit'
  8155. else xp.any(xp.isnan(x), axis=-1))
  8156. ranks = xp.asarray(ranks, dtype=default_float) # copy=False when implemented
  8157. ranks[i_nan] = xp.nan
  8158. ranks = xp_swapaxes(ranks, axis, -1, xp=xp)
  8159. return ranks
  8160. def _order_ranks(ranks, j, *, xp):
  8161. # Reorder ascending order `ranks` according to `j`
  8162. xp = array_namespace(ranks) if xp is None else xp
  8163. if is_numpy(xp) or is_cupy(xp):
  8164. ordered_ranks = xp.empty(j.shape, dtype=ranks.dtype)
  8165. xp.put_along_axis(ordered_ranks, j, ranks, axis=-1)
  8166. else:
  8167. # `put_along_axis` not in array API (data-apis/array-api#177)
  8168. # so argsort the argsort and take_along_axis...
  8169. j_inv = xp.argsort(j, axis=-1, stable=True)
  8170. ordered_ranks = xp.take_along_axis(ranks, j_inv, axis=-1)
  8171. return ordered_ranks
  8172. def _rankdata(x, method, return_ties=False, xp=None):
  8173. # Rank data `x` by desired `method`; `return_ties` if desired
  8174. xp = array_namespace(x) if xp is None else xp
  8175. shape = x.shape
  8176. dtype = xp.asarray(1.).dtype if method == 'average' else xp.asarray(1).dtype
  8177. # Get sort order
  8178. j = xp.argsort(x, axis=-1, stable=True)
  8179. ordinal_ranks = xp.broadcast_to(xp.arange(1, shape[-1]+1, dtype=dtype), shape)
  8180. # Ordinal ranks is very easy because ties don't matter. We're done.
  8181. if method == 'ordinal':
  8182. return _order_ranks(ordinal_ranks, j, xp=xp) # never return ties
  8183. # Sort array
  8184. y = xp.take_along_axis(x, j, axis=-1)
  8185. # Logical indices of unique elements
  8186. i = xp.concat([xp.ones(shape[:-1] + (1,), dtype=xp.bool),
  8187. y[..., :-1] != y[..., 1:]], axis=-1)
  8188. # Integer indices of unique elements
  8189. indices = xp.arange(xp_size(y))[xp.reshape(i, (-1,))] # i gets raveled
  8190. # Counts of unique elements
  8191. counts = xp.diff(indices, append=xp.asarray([xp_size(y)], dtype=indices.dtype))
  8192. # Compute `'min'`, `'max'`, and `'mid'` ranks of unique elements
  8193. if method == 'min':
  8194. ranks = ordinal_ranks[i]
  8195. elif method == 'max':
  8196. ranks = ordinal_ranks[i] + counts - 1
  8197. elif method == 'average':
  8198. # array API doesn't promote integers to floats
  8199. ranks = ordinal_ranks[i] + (xp.asarray(counts, dtype=dtype) - 1)/2
  8200. elif method == 'dense':
  8201. ranks = xp.cumulative_sum(xp.astype(i, dtype, copy=False), axis=-1)[i]
  8202. ranks = xp.reshape(xp.repeat(ranks, counts), shape)
  8203. ranks = _order_ranks(ranks, j, xp=xp)
  8204. if return_ties:
  8205. # Tie information is returned in a format that is useful to functions that
  8206. # rely on this (private) function. Example:
  8207. # >>> x = np.asarray([3, 2, 1, 2, 2, 2, 1])
  8208. # >>> _, t = _rankdata(x, 'average', return_ties=True)
  8209. # >>> t # array([2., 0., 4., 0., 0., 0., 1.]) # two 1s, four 2s, and one 3
  8210. # Unlike ranks, tie counts are *not* reordered to correspond with the order of
  8211. # the input; e.g. the number of appearances of the lowest rank element comes
  8212. # first. This is a useful format because:
  8213. # - The shape of the result is the shape of the input. Different slices can
  8214. # have different numbers of tied elements but not result in a ragged array.
  8215. # - Functions that use `t` usually don't need to which each element of the
  8216. # original array is associated with each tie count; they perform a reduction
  8217. # over the tie counts onnly. The tie counts are naturally computed in a
  8218. # sorted order, so this does not unnecessarily reorder them.
  8219. # - One exception is `wilcoxon`, which needs the number of zeros. Zeros always
  8220. # have the lowest rank, so it is easy to find them at the zeroth index.
  8221. t = xp.zeros(shape, dtype=xp.float64)
  8222. t = xpx.at(t)[i].set(xp.astype(counts, t.dtype, copy=False))
  8223. return ranks, t
  8224. return ranks
  8225. @xp_capabilities(np_only=True)
  8226. def expectile(a, alpha=0.5, *, weights=None):
  8227. r"""Compute the expectile at the specified level.
  8228. Expectiles are a generalization of the expectation in the same way as
  8229. quantiles are a generalization of the median. The expectile at level
  8230. `alpha = 0.5` is the mean (average). See Notes for more details.
  8231. Parameters
  8232. ----------
  8233. a : array_like
  8234. Array containing numbers whose expectile is desired.
  8235. alpha : float, default: 0.5
  8236. The level of the expectile; e.g., ``alpha=0.5`` gives the mean.
  8237. weights : array_like, optional
  8238. An array of weights associated with the values in `a`.
  8239. The `weights` must be broadcastable to the same shape as `a`.
  8240. Default is None, which gives each value a weight of 1.0.
  8241. An integer valued weight element acts like repeating the corresponding
  8242. observation in `a` that many times. See Notes for more details.
  8243. Returns
  8244. -------
  8245. expectile : ndarray
  8246. The empirical expectile at level `alpha`.
  8247. See Also
  8248. --------
  8249. numpy.mean : Arithmetic average
  8250. numpy.quantile : Quantile
  8251. Notes
  8252. -----
  8253. In general, the expectile at level :math:`\alpha` of a random variable
  8254. :math:`X` with cumulative distribution function (CDF) :math:`F` is given
  8255. by the unique solution :math:`t` of:
  8256. .. math::
  8257. \alpha E((X - t)_+) = (1 - \alpha) E((t - X)_+) \,.
  8258. Here, :math:`(x)_+ = \max(0, x)` is the positive part of :math:`x`.
  8259. This equation can be equivalently written as:
  8260. .. math::
  8261. \alpha \int_t^\infty (x - t)\mathrm{d}F(x)
  8262. = (1 - \alpha) \int_{-\infty}^t (t - x)\mathrm{d}F(x) \,.
  8263. The empirical expectile at level :math:`\alpha` (`alpha`) of a sample
  8264. :math:`a_i` (the array `a`) is defined by plugging in the empirical CDF of
  8265. `a`. Given sample or case weights :math:`w` (the array `weights`), it
  8266. reads :math:`F_a(x) = \frac{1}{\sum_i w_i} \sum_i w_i 1_{a_i \leq x}`
  8267. with indicator function :math:`1_{A}`. This leads to the definition of the
  8268. empirical expectile at level `alpha` as the unique solution :math:`t` of:
  8269. .. math::
  8270. \alpha \sum_{i=1}^n w_i (a_i - t)_+ =
  8271. (1 - \alpha) \sum_{i=1}^n w_i (t - a_i)_+ \,.
  8272. For :math:`\alpha=0.5`, this simplifies to the weighted average.
  8273. Furthermore, the larger :math:`\alpha`, the larger the value of the
  8274. expectile.
  8275. As a final remark, the expectile at level :math:`\alpha` can also be
  8276. written as a minimization problem. One often used choice is
  8277. .. math::
  8278. \operatorname{argmin}_t
  8279. E(\lvert 1_{t\geq X} - \alpha\rvert(t - X)^2) \,.
  8280. References
  8281. ----------
  8282. .. [1] W. K. Newey and J. L. Powell (1987), "Asymmetric Least Squares
  8283. Estimation and Testing," Econometrica, 55, 819-847.
  8284. .. [2] T. Gneiting (2009). "Making and Evaluating Point Forecasts,"
  8285. Journal of the American Statistical Association, 106, 746 - 762.
  8286. :doi:`10.48550/arXiv.0912.0902`
  8287. Examples
  8288. --------
  8289. >>> import numpy as np
  8290. >>> from scipy.stats import expectile
  8291. >>> a = [1, 4, 2, -1]
  8292. >>> expectile(a, alpha=0.5) == np.mean(a)
  8293. True
  8294. >>> expectile(a, alpha=0.2)
  8295. 0.42857142857142855
  8296. >>> expectile(a, alpha=0.8)
  8297. 2.5714285714285716
  8298. >>> weights = [1, 3, 1, 1]
  8299. >>> expectile(a, alpha=0.8, weights=weights)
  8300. 3.3333333333333335
  8301. """
  8302. if alpha < 0 or alpha > 1:
  8303. raise ValueError(
  8304. "The expectile level alpha must be in the range [0, 1]."
  8305. )
  8306. a = np.asarray(a)
  8307. if weights is not None:
  8308. weights = np.broadcast_to(weights, a.shape)
  8309. # This is the empirical equivalent of Eq. (13) with identification
  8310. # function from Table 9 (omitting a factor of 2) in [2] (their y is our
  8311. # data a, their x is our t)
  8312. def first_order(t):
  8313. return np.average(np.abs((a <= t) - alpha) * (t - a), weights=weights)
  8314. if alpha >= 0.5:
  8315. x0 = np.average(a, weights=weights)
  8316. x1 = np.amax(a)
  8317. else:
  8318. x1 = np.average(a, weights=weights)
  8319. x0 = np.amin(a)
  8320. if x0 == x1:
  8321. # a has a single unique element
  8322. return x0
  8323. # Note that the expectile is the unique solution, so no worries about
  8324. # finding a wrong root.
  8325. res = root_scalar(first_order, x0=x0, x1=x1)
  8326. return res.root
  8327. def _lmoment_iv(sample, order, axis, sorted, standardize, xp):
  8328. # input validation/standardization for `lmoment`
  8329. sample = xp_promote(sample, force_floating=True, xp=xp)
  8330. message = "`sample` must be an array of real numbers."
  8331. if not xp.isdtype(sample.dtype, "real floating"):
  8332. raise ValueError(message)
  8333. message = "`order` must be a scalar or a non-empty array of positive integers."
  8334. order = xp.arange(1, 5) if order is None else xp.asarray(order)
  8335. if (not xp.isdtype(order.dtype, "integral") or xp.any(order <= 0)
  8336. or order.size == 0 or order.ndim > 1):
  8337. raise ValueError(message)
  8338. # input validation of non-array types can still be performed with NumPy
  8339. axis = np.asarray(axis)[()]
  8340. message = "`axis` must be an integer."
  8341. if not np.issubdtype(axis.dtype, np.integer) or axis.ndim != 0:
  8342. raise ValueError(message)
  8343. axis = int(axis)
  8344. sorted = np.asarray(sorted)[()]
  8345. message = "`sorted` must be True or False."
  8346. if not np.issubdtype(sorted.dtype, np.bool_) or sorted.ndim != 0:
  8347. raise ValueError(message)
  8348. sorted = bool(sorted)
  8349. standardize = np.asarray(standardize)[()]
  8350. message = "`standardize` must be True or False."
  8351. if not np.issubdtype(standardize.dtype, np.bool_) or standardize.ndim != 0:
  8352. raise ValueError(message)
  8353. standardize = bool(standardize)
  8354. sample = xp.moveaxis(sample, axis, -1)
  8355. sample = xp.sort(sample, axis=-1) if not sorted else sample
  8356. return sample, order, axis, sorted, standardize
  8357. def _br(x, *, r=0, xp):
  8358. n = x.shape[-1]
  8359. x = xp.expand_dims(x, axis=-2)
  8360. x = xp.broadcast_to(x, x.shape[:-2] + (r.shape[0], n))
  8361. x = xp.triu(x)
  8362. j = xp.arange(n, dtype=x.dtype)
  8363. n = xp.asarray(n, dtype=x.dtype)[()]
  8364. return (xp.vecdot(special.binom(j, r[:, xp.newaxis]), x, axis=-1)
  8365. / special.binom(n-1, r) / n)
  8366. def _prk(r, k):
  8367. # Writen to match [1] Equation 27 closely to facilitate review.
  8368. # This does not protect against overflow, so improvements to
  8369. # robustness would be a welcome follow-up.
  8370. return (-1)**(r-k)*special.binom(r, k)*special.binom(r+k, k)
  8371. @xp_capabilities(skip_backends=[('dask.array', "too many issues")],
  8372. jax_jit=False, cpu_only=True, # torch doesn't have `binom`
  8373. exceptions=('cupy', 'jax.numpy'))
  8374. @_axis_nan_policy_factory( # noqa: E302
  8375. _moment_result_object, n_samples=1, result_to_tuple=_moment_tuple,
  8376. n_outputs=lambda kwds: _moment_outputs(kwds, [1, 2, 3, 4])
  8377. )
  8378. def lmoment(sample, order=None, *, axis=0, sorted=False, standardize=True):
  8379. r"""Compute L-moments of a sample from a continuous distribution
  8380. The L-moments of a probability distribution are summary statistics with
  8381. uses similar to those of conventional moments, but they are defined in
  8382. terms of the expected values of order statistics.
  8383. Sample L-moments are defined analogously to population L-moments, and
  8384. they can serve as estimators of population L-moments. They tend to be less
  8385. sensitive to extreme observations than conventional moments.
  8386. Parameters
  8387. ----------
  8388. sample : array_like
  8389. The real-valued sample whose L-moments are desired.
  8390. order : array_like, optional
  8391. The (positive integer) orders of the desired L-moments.
  8392. Must be a scalar or non-empty 1D array. Default is [1, 2, 3, 4].
  8393. axis : int or None, default=0
  8394. If an int, the axis of the input along which to compute the statistic.
  8395. The statistic of each axis-slice (e.g. row) of the input will appear
  8396. in a corresponding element of the output. If None, the input will be
  8397. raveled before computing the statistic.
  8398. sorted : bool, default=False
  8399. Whether `sample` is already sorted in increasing order along `axis`.
  8400. If False (default), `sample` will be sorted.
  8401. standardize : bool, default=True
  8402. Whether to return L-moment ratios for orders 3 and higher.
  8403. L-moment ratios are analogous to standardized conventional
  8404. moments: they are the non-standardized L-moments divided
  8405. by the L-moment of order 2.
  8406. Returns
  8407. -------
  8408. lmoments : ndarray
  8409. The sample L-moments of order `order`.
  8410. See Also
  8411. --------
  8412. moment
  8413. References
  8414. ----------
  8415. .. [1] D. Bilkova. "L-Moments and TL-Moments as an Alternative Tool of
  8416. Statistical Data Analysis". Journal of Applied Mathematics and
  8417. Physics. 2014. :doi:`10.4236/jamp.2014.210104`
  8418. .. [2] J. R. M. Hosking. "L-Moments: Analysis and Estimation of Distributions
  8419. Using Linear Combinations of Order Statistics". Journal of the Royal
  8420. Statistical Society. 1990. :doi:`10.1111/j.2517-6161.1990.tb01775.x`
  8421. .. [3] "L-moment". *Wikipedia*. https://en.wikipedia.org/wiki/L-moment.
  8422. Examples
  8423. --------
  8424. >>> import numpy as np
  8425. >>> from scipy import stats
  8426. >>> rng = np.random.default_rng(328458568356392)
  8427. >>> sample = rng.exponential(size=100000)
  8428. >>> stats.lmoment(sample)
  8429. array([1.00124272, 0.50111437, 0.3340092 , 0.16755338])
  8430. Note that the first four standardized population L-moments of the standard
  8431. exponential distribution are 1, 1/2, 1/3, and 1/6; the sample L-moments
  8432. provide reasonable estimates.
  8433. """
  8434. xp = array_namespace(sample)
  8435. args = _lmoment_iv(sample, order, axis, sorted, standardize, xp=xp)
  8436. sample, order, axis, sorted, standardize = args
  8437. n_moments = int(xp.max(order))
  8438. k = xp.arange(n_moments, dtype=sample.dtype)
  8439. prk = _prk(xpx.expand_dims(k, axis=tuple(range(1, sample.ndim+1))), k)
  8440. bk = _br(sample, r=k, xp=xp)
  8441. n = sample.shape[-1]
  8442. if n < bk.shape[-1]:
  8443. bk = xpx.at(bk)[..., n:].set(0) # remove NaNs due to n_moments > n
  8444. lmoms = xp.vecdot(prk, bk, axis=-1)
  8445. if standardize and n_moments > 2:
  8446. lmoms = xpx.at(lmoms)[2:, ...].divide(lmoms[1, ...])
  8447. if n < lmoms.shape[0]:
  8448. lmoms = xpx.at(lmoms)[n:, ...].set(xp.nan) # add NaNs where appropriate
  8449. # return lmoms[order-1] # strict can't handle fancy indexing plus ellipses
  8450. return xp.take(lmoms, order - 1, axis=0) if order.ndim == 1 else lmoms[order - 1]
  8451. LinregressResult = _make_tuple_bunch('LinregressResult',
  8452. ['slope', 'intercept', 'rvalue',
  8453. 'pvalue', 'stderr'],
  8454. extra_field_names=['intercept_stderr'])
  8455. def _pack_LinregressResult(slope, intercept, rvalue, pvalue, stderr, intercept_stderr):
  8456. return LinregressResult(slope, intercept, rvalue, pvalue, stderr,
  8457. intercept_stderr=intercept_stderr)
  8458. def _unpack_LinregressResult(res, _):
  8459. return tuple(res) + (res.intercept_stderr,)
  8460. @xp_capabilities(np_only=True)
  8461. @_axis_nan_policy_factory(_pack_LinregressResult, n_samples=2,
  8462. result_to_tuple=_unpack_LinregressResult, paired=True,
  8463. too_small=1, n_outputs=6)
  8464. def linregress(x, y, alternative='two-sided'):
  8465. """
  8466. Calculate a linear least-squares regression for two sets of measurements.
  8467. Parameters
  8468. ----------
  8469. x, y : array_like
  8470. Two sets of measurements. Both arrays should have the same length N.
  8471. alternative : {'two-sided', 'less', 'greater'}, optional
  8472. Defines the alternative hypothesis. Default is 'two-sided'.
  8473. The following options are available:
  8474. * 'two-sided': the slope of the regression line is nonzero
  8475. * 'less': the slope of the regression line is less than zero
  8476. * 'greater': the slope of the regression line is greater than zero
  8477. .. versionadded:: 1.7.0
  8478. Returns
  8479. -------
  8480. result : ``LinregressResult`` instance
  8481. The return value is an object with the following attributes:
  8482. slope : float
  8483. Slope of the regression line.
  8484. intercept : float
  8485. Intercept of the regression line.
  8486. rvalue : float
  8487. The Pearson correlation coefficient. The square of ``rvalue``
  8488. is equal to the coefficient of determination.
  8489. pvalue : float
  8490. The p-value for a hypothesis test whose null hypothesis is
  8491. that the slope is zero, using Wald Test with t-distribution of
  8492. the test statistic. See `alternative` above for alternative
  8493. hypotheses.
  8494. stderr : float
  8495. Standard error of the estimated slope (gradient), under the
  8496. assumption of residual normality.
  8497. intercept_stderr : float
  8498. Standard error of the estimated intercept, under the assumption
  8499. of residual normality.
  8500. See Also
  8501. --------
  8502. scipy.optimize.curve_fit :
  8503. Use non-linear least squares to fit a function to data.
  8504. scipy.optimize.leastsq :
  8505. Minimize the sum of squares of a set of equations.
  8506. Notes
  8507. -----
  8508. For compatibility with older versions of SciPy, the return value acts
  8509. like a ``namedtuple`` of length 5, with fields ``slope``, ``intercept``,
  8510. ``rvalue``, ``pvalue`` and ``stderr``, so one can continue to write::
  8511. slope, intercept, r, p, se = linregress(x, y)
  8512. With that style, however, the standard error of the intercept is not
  8513. available. To have access to all the computed values, including the
  8514. standard error of the intercept, use the return value as an object
  8515. with attributes, e.g.::
  8516. result = linregress(x, y)
  8517. print(result.intercept, result.intercept_stderr)
  8518. Examples
  8519. --------
  8520. >>> import numpy as np
  8521. >>> import matplotlib.pyplot as plt
  8522. >>> from scipy import stats
  8523. >>> rng = np.random.default_rng()
  8524. Generate some data:
  8525. >>> x = rng.random(10)
  8526. >>> y = 1.6*x + rng.random(10)
  8527. Perform the linear regression:
  8528. >>> res = stats.linregress(x, y)
  8529. Coefficient of determination (R-squared):
  8530. >>> print(f"R-squared: {res.rvalue**2:.6f}")
  8531. R-squared: 0.717533
  8532. Plot the data along with the fitted line:
  8533. >>> plt.plot(x, y, 'o', label='original data')
  8534. >>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line')
  8535. >>> plt.legend()
  8536. >>> plt.show()
  8537. Calculate 95% confidence interval on slope and intercept:
  8538. >>> # Two-sided inverse Students t-distribution
  8539. >>> # p - probability, df - degrees of freedom
  8540. >>> from scipy.stats import t
  8541. >>> tinv = lambda p, df: abs(t.ppf(p/2, df))
  8542. >>> ts = tinv(0.05, len(x)-2)
  8543. >>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}")
  8544. slope (95%): 1.453392 +/- 0.743465
  8545. >>> print(f"intercept (95%): {res.intercept:.6f}"
  8546. ... f" +/- {ts*res.intercept_stderr:.6f}")
  8547. intercept (95%): 0.616950 +/- 0.544475
  8548. """
  8549. TINY = 1.0e-20
  8550. x = np.asarray(x)
  8551. y = np.asarray(y)
  8552. if x.size == 0 or y.size == 0:
  8553. raise ValueError("Inputs must not be empty.")
  8554. if np.amax(x) == np.amin(x) and len(x) > 1:
  8555. raise ValueError("Cannot calculate a linear regression "
  8556. "if all x values are identical")
  8557. n = len(x)
  8558. xmean = np.mean(x, None)
  8559. ymean = np.mean(y, None)
  8560. # Average sums of square differences from the mean
  8561. # ssxm = mean( (x-mean(x))^2 )
  8562. # ssxym = mean( (x-mean(x)) * (y-mean(y)) )
  8563. ssxm, ssxym, _, ssym = np.cov(x, y, bias=1).flat
  8564. # R-value
  8565. # r = ssxym / sqrt( ssxm * ssym )
  8566. if ssxm == 0.0 or ssym == 0.0:
  8567. # If the denominator was going to be 0
  8568. r = np.asarray(np.nan if ssxym == 0 else 0.0)[()]
  8569. else:
  8570. r = ssxym / np.sqrt(ssxm * ssym)
  8571. # Test for numerical error propagation (make sure -1 < r < 1)
  8572. if r > 1.0:
  8573. r = 1.0
  8574. elif r < -1.0:
  8575. r = -1.0
  8576. slope = ssxym / ssxm
  8577. intercept = ymean - slope*xmean
  8578. if n == 2:
  8579. # handle case when only two points are passed in
  8580. if y[0] == y[1]:
  8581. prob = 1.0
  8582. else:
  8583. prob = 0.0
  8584. slope_stderr = 0.0
  8585. intercept_stderr = 0.0
  8586. else:
  8587. df = n - 2 # Number of degrees of freedom
  8588. # n-2 degrees of freedom because 2 has been used up
  8589. # to estimate the mean and standard deviation
  8590. t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY)))
  8591. dist = _SimpleStudentT(df)
  8592. prob = _get_pvalue(t, dist, alternative, xp=np)
  8593. prob = prob[()] if prob.ndim == 0 else prob
  8594. slope_stderr = np.sqrt((1 - r**2) * ssym / ssxm / df)
  8595. # Also calculate the standard error of the intercept
  8596. # The following relationship is used:
  8597. # ssxm = mean( (x-mean(x))^2 )
  8598. # = ssx - sx*sx
  8599. # = mean( x^2 ) - mean(x)^2
  8600. intercept_stderr = slope_stderr * np.sqrt(ssxm + xmean**2)
  8601. return LinregressResult(slope=slope, intercept=intercept, rvalue=r,
  8602. pvalue=prob, stderr=slope_stderr,
  8603. intercept_stderr=intercept_stderr)
  8604. def _xp_mean(x, /, *, axis=None, weights=None, keepdims=False, nan_policy='propagate',
  8605. dtype=None, xp=None):
  8606. r"""Compute the arithmetic mean along the specified axis.
  8607. Parameters
  8608. ----------
  8609. x : real array
  8610. Array containing real numbers whose mean is desired.
  8611. axis : int or tuple of ints, default: None
  8612. If an int or tuple of ints, the axis or axes of the input along which
  8613. to compute the statistic. The statistic of each axis-slice (e.g. row)
  8614. of the input will appear in a corresponding element of the output.
  8615. If ``None``, the input will be raveled before computing the statistic.
  8616. weights : real array, optional
  8617. If specified, an array of weights associated with the values in `x`;
  8618. otherwise ``1``. If `weights` and `x` do not have the same shape, the
  8619. arrays will be broadcasted before performing the calculation. See
  8620. Notes for details.
  8621. keepdims : boolean, optional
  8622. If this is set to ``True``, the axes which are reduced are left
  8623. in the result as dimensions with length one. With this option,
  8624. the result will broadcast correctly against the input array.
  8625. nan_policy : {'propagate', 'omit', 'raise'}, default: 'propagate'
  8626. Defines how to handle input NaNs.
  8627. - ``propagate``: if a NaN is present in the axis slice (e.g. row) along
  8628. which the statistic is computed, the corresponding entry of the output
  8629. will be NaN.
  8630. - ``omit``: NaNs will be omitted when performing the calculation.
  8631. If insufficient data remains in the axis slice along which the
  8632. statistic is computed, the corresponding entry of the output will be
  8633. NaN.
  8634. - ``raise``: if a NaN is present, a ``ValueError`` will be raised.
  8635. dtype : dtype, optional
  8636. Type to use in computing the mean. For integer inputs, the default is
  8637. the default float type of the array library; for floating point inputs,
  8638. the dtype is that of the input.
  8639. Returns
  8640. -------
  8641. out : array
  8642. The mean of each slice
  8643. Notes
  8644. -----
  8645. Let :math:`x_i` represent element :math:`i` of data `x` and let :math:`w_i`
  8646. represent the corresponding element of `weights` after broadcasting. Then the
  8647. (weighted) mean :math:`\bar{x}_w` is given by:
  8648. .. math::
  8649. \bar{x}_w = \frac{ \sum_{i=0}^{n-1} w_i x_i }
  8650. { \sum_{i=0}^{n-1} w_i }
  8651. where :math:`n` is the number of elements along a slice. Note that this simplifies
  8652. to the familiar :math:`(\sum_i x_i) / n` when the weights are all ``1`` (default).
  8653. The behavior of this function with respect to weights is somewhat different
  8654. from that of `np.average`. For instance,
  8655. `np.average` raises an error when `axis` is not specified and the shapes of `x`
  8656. and the `weights` array are not the same; `xp_mean` simply broadcasts the two.
  8657. Also, `np.average` raises an error when weights sum to zero along a slice;
  8658. `xp_mean` computes the appropriate result. The intent is for this function's
  8659. interface to be consistent with the rest of `scipy.stats`.
  8660. Note that according to the formula, including NaNs with zero weights is not
  8661. the same as *omitting* NaNs with ``nan_policy='omit'``; in the former case,
  8662. the NaNs will continue to propagate through the calculation whereas in the
  8663. latter case, the NaNs are excluded entirely.
  8664. """
  8665. # ensure that `x` and `weights` are array-API compatible arrays of identical shape
  8666. xp = array_namespace(x) if xp is None else xp
  8667. x = _asarray(x, dtype=dtype, subok=True)
  8668. weights = xp.asarray(weights, dtype=dtype) if weights is not None else weights
  8669. # to ensure that this matches the behavior of decorated functions when one of the
  8670. # arguments has size zero, it's easiest to call a similar decorated function.
  8671. if is_numpy(xp) and (xp_size(x) == 0
  8672. or (weights is not None and xp_size(weights) == 0)):
  8673. return gmean(x, weights=weights, axis=axis, keepdims=keepdims)
  8674. x, weights = xp_promote(x, weights, broadcast=True, force_floating=True, xp=xp)
  8675. if weights is not None:
  8676. x, weights = _share_masks(x, weights, xp=xp)
  8677. # handle the special case of zero-sized arrays
  8678. message = (too_small_1d_not_omit if (x.ndim == 1 or axis is None)
  8679. else too_small_nd_not_omit)
  8680. if xp_size(x) == 0:
  8681. with warnings.catch_warnings():
  8682. warnings.simplefilter("ignore")
  8683. res = xp.mean(x, axis=axis, keepdims=keepdims)
  8684. if xp_size(res) != 0:
  8685. warnings.warn(message, SmallSampleWarning, stacklevel=2)
  8686. return res
  8687. contains_nan = _contains_nan(x, nan_policy, xp_omit_okay=True, xp=xp)
  8688. if weights is not None:
  8689. contains_nan_w = _contains_nan(weights, nan_policy, xp_omit_okay=True, xp=xp)
  8690. contains_nan = contains_nan | contains_nan_w
  8691. # Handle `nan_policy='omit'` by giving zero weight to NaNs, whether they
  8692. # appear in `x` or `weights`. Emit warning if there is an all-NaN slice.
  8693. # Test nan_policy before the implicit call to bool(contains_nan)
  8694. # to avoid raising on lazy xps on the default nan_policy='propagate'
  8695. lazy = is_lazy_array(x)
  8696. if nan_policy == 'omit' and (lazy or contains_nan):
  8697. nan_mask = xp.isnan(x)
  8698. if weights is not None:
  8699. nan_mask |= xp.isnan(weights)
  8700. if not lazy and xp.any(xp.all(nan_mask, axis=axis)):
  8701. message = (too_small_1d_omit if (x.ndim == 1 or axis is None)
  8702. else too_small_nd_omit)
  8703. warnings.warn(message, SmallSampleWarning, stacklevel=2)
  8704. weights = xp.ones_like(x) if weights is None else weights
  8705. x = xp.where(nan_mask, 0., x)
  8706. weights = xp.where(nan_mask, 0., weights)
  8707. # Perform the mean calculation itself
  8708. if weights is None:
  8709. return xp.mean(x, axis=axis, keepdims=keepdims)
  8710. # consider using `vecdot` if `axis` tuple support is added (data-apis/array-api#910)
  8711. norm = xp.sum(weights, axis=axis)
  8712. wsum = xp.sum(x * weights, axis=axis)
  8713. with np.errstate(divide='ignore', invalid='ignore'):
  8714. res = wsum/norm
  8715. # Respect `keepdims` and convert NumPy 0-D arrays to scalars
  8716. if keepdims:
  8717. if axis is None:
  8718. final_shape = (1,) * len(x.shape)
  8719. else:
  8720. # axis can be a scalar or sequence
  8721. axes = (axis,) if not isinstance(axis, Sequence) else axis
  8722. final_shape = list(x.shape)
  8723. for i in axes:
  8724. final_shape[i] = 1
  8725. res = xp.reshape(res, tuple(final_shape))
  8726. return res[()] if res.ndim == 0 else res
  8727. def _xp_var(x, /, *, axis=None, correction=0, keepdims=False, nan_policy='propagate',
  8728. dtype=None, xp=None):
  8729. # an array-api compatible function for variance with scipy.stats interface
  8730. # and features (e.g. `nan_policy`).
  8731. xp = array_namespace(x) if xp is None else xp
  8732. x = _asarray(x, subok=True)
  8733. # use `_xp_mean` instead of `xp.var` for desired warning behavior
  8734. # it would be nice to combine this with `_var`, which uses `_moment`
  8735. # and therefore warns when precision is lost, but that does not support
  8736. # `axis` tuples or keepdims. Eventually, `_axis_nan_policy` will simplify
  8737. # `axis` tuples and implement `keepdims` for non-NumPy arrays; then it will
  8738. # be easy.
  8739. kwargs = dict(axis=axis, nan_policy=nan_policy, dtype=dtype, xp=xp)
  8740. mean = _xp_mean(x, keepdims=True, **kwargs)
  8741. x = _asarray(x, dtype=mean.dtype, subok=True)
  8742. x_mean = _demean(x, mean, axis, xp=xp)
  8743. x_mean_conj = (xp.conj(x_mean) if xp.isdtype(x_mean.dtype, 'complex floating')
  8744. else x_mean) # crossref data-apis/array-api#824
  8745. var = _xp_mean(x_mean * x_mean_conj, keepdims=keepdims, **kwargs)
  8746. if correction != 0:
  8747. n = _length_nonmasked(x, axis, xp=xp)
  8748. # Or two lines with ternaries : )
  8749. # axis = range(x.ndim) if axis is None else axis
  8750. # n = math.prod(x.shape[i] for i in axis) if iterable(axis) else x.shape[axis]
  8751. n = xp.asarray(n, dtype=var.dtype, device=xp_device(x))
  8752. if nan_policy == 'omit':
  8753. nan_mask = xp.astype(xp.isnan(x), var.dtype)
  8754. n = n - xp.sum(nan_mask, axis=axis, keepdims=keepdims)
  8755. # Produce NaNs silently when n - correction <= 0
  8756. nc = n - correction
  8757. factor = xpx.apply_where(nc > 0, (n, nc), operator.truediv, fill_value=xp.nan)
  8758. var *= factor
  8759. return var[()] if var.ndim == 0 else var
  8760. class _SimpleNormal:
  8761. # A very simple, array-API compatible normal distribution for use in
  8762. # hypothesis tests. May be replaced by new infrastructure Normal
  8763. # distribution in due time.
  8764. def cdf(self, x):
  8765. return special.ndtr(x)
  8766. def sf(self, x):
  8767. return special.ndtr(-x)
  8768. def isf(self, x):
  8769. return -special.ndtri(x)
  8770. class _SimpleChi2:
  8771. # A very simple, array-API compatible chi-squared distribution for use in
  8772. # hypothesis tests. May be replaced by new infrastructure chi-squared
  8773. # distribution in due time.
  8774. def __init__(self, df):
  8775. self.df = df
  8776. def cdf(self, x):
  8777. return special.chdtr(self.df, x)
  8778. def sf(self, x):
  8779. return special.chdtrc(self.df, x)
  8780. class _SimpleBeta:
  8781. # A very simple, array-API compatible beta distribution for use in
  8782. # hypothesis tests. May be replaced by new infrastructure beta
  8783. # distribution in due time.
  8784. def __init__(self, a, b, *, loc=None, scale=None):
  8785. self.a = a
  8786. self.b = b
  8787. self.loc = loc
  8788. self.scale = scale
  8789. def cdf(self, x):
  8790. if self.loc is not None or self.scale is not None:
  8791. loc = 0 if self.loc is None else self.loc
  8792. scale = 1 if self.scale is None else self.scale
  8793. return special.betainc(self.a, self.b, (x - loc)/scale)
  8794. return special.betainc(self.a, self.b, x)
  8795. def sf(self, x):
  8796. if self.loc is not None or self.scale is not None:
  8797. loc = 0 if self.loc is None else self.loc
  8798. scale = 1 if self.scale is None else self.scale
  8799. return special.betaincc(self.a, self.b, (x - loc)/scale)
  8800. return special.betaincc(self.a, self.b, x)
  8801. class _SimpleStudentT:
  8802. # A very simple, array-API compatible t distribution for use in
  8803. # hypothesis tests. May be replaced by new infrastructure t
  8804. # distribution in due time.
  8805. def __init__(self, df):
  8806. self.df = df
  8807. def cdf(self, t):
  8808. return special.stdtr(self.df, t)
  8809. def sf(self, t):
  8810. return special.stdtr(self.df, -t)
  8811. class _SimpleF:
  8812. # A very simple, array-API compatible F distribution for use in
  8813. # hypothesis tests.
  8814. def __init__(self, dfn, dfd):
  8815. self.dfn = dfn
  8816. self.dfd = dfd
  8817. def cdf(self, x):
  8818. return special.fdtr(self.dfn, self.dfd, x)
  8819. def sf(self, x):
  8820. return special.fdtrc(self.dfn, self.dfd, x)