_stats_py.py 347 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662
  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 warnings
  27. import math
  28. from math import gcd
  29. from collections import namedtuple, Counter
  30. import numpy as np
  31. from numpy import array, asarray, ma
  32. from numpy.lib import NumpyVersion
  33. from numpy.testing import suppress_warnings
  34. from scipy.spatial.distance import cdist
  35. from scipy.ndimage import _measurements
  36. from scipy._lib._util import (check_random_state, MapWrapper,
  37. rng_integers, _rename_parameter, _contains_nan)
  38. import scipy.special as special
  39. from scipy import linalg
  40. from . import distributions
  41. from . import _mstats_basic as mstats_basic
  42. from ._stats_mstats_common import (_find_repeats, linregress, theilslopes,
  43. siegelslopes)
  44. from ._stats import (_kendall_dis, _toint64, _weightedrankedtau,
  45. _local_correlations)
  46. from dataclasses import make_dataclass
  47. from ._hypotests import _all_partitions
  48. from ._stats_pythran import _compute_outer_prob_inside_method
  49. from ._resampling import _batch_generator
  50. from ._axis_nan_policy import (_axis_nan_policy_factory,
  51. _broadcast_concatenate)
  52. from ._binomtest import _binary_search_for_binom_tst as _binary_search
  53. from scipy._lib._bunch import _make_tuple_bunch
  54. from scipy import stats
  55. from scipy.optimize import root_scalar
  56. # Functions/classes in other files should be added in `__init__.py`, not here
  57. __all__ = ['find_repeats', 'gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar',
  58. 'tmin', 'tmax', 'tstd', 'tsem', 'moment',
  59. 'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',
  60. 'normaltest', 'jarque_bera',
  61. 'scoreatpercentile', 'percentileofscore',
  62. 'cumfreq', 'relfreq', 'obrientransform',
  63. 'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd',
  64. 'median_abs_deviation',
  65. 'sigmaclip', 'trimboth', 'trim1', 'trim_mean',
  66. 'f_oneway', 'pearsonr', 'fisher_exact',
  67. 'spearmanr', 'pointbiserialr',
  68. 'kendalltau', 'weightedtau', 'multiscale_graphcorr',
  69. 'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',
  70. 'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',
  71. 'kstest', 'ks_1samp', 'ks_2samp',
  72. 'chisquare', 'power_divergence',
  73. 'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',
  74. 'rankdata',
  75. 'combine_pvalues', 'wasserstein_distance', 'energy_distance',
  76. 'brunnermunzel', 'alexandergovern',
  77. 'expectile', ]
  78. def _chk_asarray(a, axis):
  79. if axis is None:
  80. a = np.ravel(a)
  81. outaxis = 0
  82. else:
  83. a = np.asarray(a)
  84. outaxis = axis
  85. if a.ndim == 0:
  86. a = np.atleast_1d(a)
  87. return a, outaxis
  88. def _chk2_asarray(a, b, axis):
  89. if axis is None:
  90. a = np.ravel(a)
  91. b = np.ravel(b)
  92. outaxis = 0
  93. else:
  94. a = np.asarray(a)
  95. b = np.asarray(b)
  96. outaxis = axis
  97. if a.ndim == 0:
  98. a = np.atleast_1d(a)
  99. if b.ndim == 0:
  100. b = np.atleast_1d(b)
  101. return a, b, outaxis
  102. def _shape_with_dropped_axis(a, axis):
  103. """
  104. Given an array `a` and an integer `axis`, return the shape
  105. of `a` with the `axis` dimension removed.
  106. Examples
  107. --------
  108. >>> a = np.zeros((3, 5, 2))
  109. >>> _shape_with_dropped_axis(a, 1)
  110. (3, 2)
  111. """
  112. shp = list(a.shape)
  113. try:
  114. del shp[axis]
  115. except IndexError:
  116. raise np.AxisError(axis, a.ndim) from None
  117. return tuple(shp)
  118. def _broadcast_shapes(shape1, shape2):
  119. """
  120. Given two shapes (i.e. tuples of integers), return the shape
  121. that would result from broadcasting two arrays with the given
  122. shapes.
  123. Examples
  124. --------
  125. >>> _broadcast_shapes((2, 1), (4, 1, 3))
  126. (4, 2, 3)
  127. """
  128. d = len(shape1) - len(shape2)
  129. if d <= 0:
  130. shp1 = (1,)*(-d) + shape1
  131. shp2 = shape2
  132. else:
  133. shp1 = shape1
  134. shp2 = (1,)*d + shape2
  135. shape = []
  136. for n1, n2 in zip(shp1, shp2):
  137. if n1 == 1:
  138. n = n2
  139. elif n2 == 1 or n1 == n2:
  140. n = n1
  141. else:
  142. raise ValueError(f'shapes {shape1} and {shape2} could not be '
  143. 'broadcast together')
  144. shape.append(n)
  145. return tuple(shape)
  146. def _broadcast_shapes_with_dropped_axis(a, b, axis):
  147. """
  148. Given two arrays `a` and `b` and an integer `axis`, find the
  149. shape of the broadcast result after dropping `axis` from the
  150. shapes of `a` and `b`.
  151. Examples
  152. --------
  153. >>> a = np.zeros((5, 2, 1))
  154. >>> b = np.zeros((1, 9, 3))
  155. >>> _broadcast_shapes_with_dropped_axis(a, b, 1)
  156. (5, 3)
  157. """
  158. shp1 = _shape_with_dropped_axis(a, axis)
  159. shp2 = _shape_with_dropped_axis(b, axis)
  160. try:
  161. shp = _broadcast_shapes(shp1, shp2)
  162. except ValueError:
  163. raise ValueError(f'non-axis shapes {shp1} and {shp2} could not be '
  164. 'broadcast together') from None
  165. return shp
  166. SignificanceResult = _make_tuple_bunch('SignificanceResult',
  167. ['statistic', 'pvalue'], [])
  168. # note that `weights` are paired with `x`
  169. @_axis_nan_policy_factory(
  170. lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
  171. result_to_tuple=lambda x: (x,), kwd_samples=['weights'])
  172. def gmean(a, axis=0, dtype=None, weights=None):
  173. r"""Compute the weighted geometric mean along the specified axis.
  174. The weighted geometric mean of the array :math:`a_i` associated to weights
  175. :math:`w_i` is:
  176. .. math::
  177. \exp \left( \frac{ \sum_{i=1}^n w_i \ln a_i }{ \sum_{i=1}^n w_i }
  178. \right) \, ,
  179. and, with equal weights, it gives:
  180. .. math::
  181. \sqrt[n]{ \prod_{i=1}^n a_i } \, .
  182. Parameters
  183. ----------
  184. a : array_like
  185. Input array or object that can be converted to an array.
  186. axis : int or None, optional
  187. Axis along which the geometric mean is computed. Default is 0.
  188. If None, compute over the whole array `a`.
  189. dtype : dtype, optional
  190. Type to which the input arrays are cast before the calculation is
  191. performed.
  192. weights : array_like, optional
  193. The `weights` array must be broadcastable to the same shape as `a`.
  194. Default is None, which gives each value a weight of 1.0.
  195. Returns
  196. -------
  197. gmean : ndarray
  198. See `dtype` parameter above.
  199. See Also
  200. --------
  201. numpy.mean : Arithmetic average
  202. numpy.average : Weighted average
  203. hmean : Harmonic mean
  204. References
  205. ----------
  206. .. [1] "Weighted Geometric Mean", *Wikipedia*,
  207. https://en.wikipedia.org/wiki/Weighted_geometric_mean.
  208. Examples
  209. --------
  210. >>> from scipy.stats import gmean
  211. >>> gmean([1, 4])
  212. 2.0
  213. >>> gmean([1, 2, 3, 4, 5, 6, 7])
  214. 3.3800151591412964
  215. >>> gmean([1, 4, 7], weights=[3, 1, 3])
  216. 2.80668351922014
  217. """
  218. a = np.asarray(a, dtype=dtype)
  219. if weights is not None:
  220. weights = np.asarray(weights, dtype=dtype)
  221. with np.errstate(divide='ignore'):
  222. log_a = np.log(a)
  223. return np.exp(np.average(log_a, axis=axis, weights=weights))
  224. @_axis_nan_policy_factory(
  225. lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
  226. result_to_tuple=lambda x: (x,), kwd_samples=['weights'])
  227. def hmean(a, axis=0, dtype=None, *, weights=None):
  228. r"""Calculate the weighted harmonic mean along the specified axis.
  229. The weighted harmonic mean of the array :math:`a_i` associated to weights
  230. :math:`w_i` is:
  231. .. math::
  232. \frac{ \sum_{i=1}^n w_i }{ \sum_{i=1}^n \frac{w_i}{a_i} } \, ,
  233. and, with equal weights, it gives:
  234. .. math::
  235. \frac{ n }{ \sum_{i=1}^n \frac{1}{a_i} } \, .
  236. Parameters
  237. ----------
  238. a : array_like
  239. Input array, masked array or object that can be converted to an array.
  240. axis : int or None, optional
  241. Axis along which the harmonic mean is computed. Default is 0.
  242. If None, compute over the whole array `a`.
  243. dtype : dtype, optional
  244. Type of the returned array and of the accumulator in which the
  245. elements are summed. If `dtype` is not specified, it defaults to the
  246. dtype of `a`, unless `a` has an integer `dtype` with a precision less
  247. than that of the default platform integer. In that case, the default
  248. platform integer is used.
  249. weights : array_like, optional
  250. The weights array can either be 1-D (in which case its length must be
  251. the size of `a` along the given `axis`) or of the same shape as `a`.
  252. Default is None, which gives each value a weight of 1.0.
  253. .. versionadded:: 1.9
  254. Returns
  255. -------
  256. hmean : ndarray
  257. See `dtype` parameter above.
  258. See Also
  259. --------
  260. numpy.mean : Arithmetic average
  261. numpy.average : Weighted average
  262. gmean : Geometric mean
  263. Notes
  264. -----
  265. The harmonic mean is computed over a single dimension of the input
  266. array, axis=0 by default, or all values in the array if axis=None.
  267. float64 intermediate and return values are used for integer inputs.
  268. References
  269. ----------
  270. .. [1] "Weighted Harmonic Mean", *Wikipedia*,
  271. https://en.wikipedia.org/wiki/Harmonic_mean#Weighted_harmonic_mean
  272. .. [2] Ferger, F., "The nature and use of the harmonic mean", Journal of
  273. the American Statistical Association, vol. 26, pp. 36-40, 1931
  274. Examples
  275. --------
  276. >>> from scipy.stats import hmean
  277. >>> hmean([1, 4])
  278. 1.6000000000000001
  279. >>> hmean([1, 2, 3, 4, 5, 6, 7])
  280. 2.6997245179063363
  281. >>> hmean([1, 4, 7], weights=[3, 1, 3])
  282. 1.9029126213592233
  283. """
  284. if not isinstance(a, np.ndarray):
  285. a = np.array(a, dtype=dtype)
  286. elif dtype:
  287. # Must change the default dtype allowing array type
  288. if isinstance(a, np.ma.MaskedArray):
  289. a = np.ma.asarray(a, dtype=dtype)
  290. else:
  291. a = np.asarray(a, dtype=dtype)
  292. if np.all(a >= 0):
  293. # Harmonic mean only defined if greater than or equal to zero.
  294. if weights is not None:
  295. weights = np.asanyarray(weights, dtype=dtype)
  296. with np.errstate(divide='ignore'):
  297. return 1.0 / np.average(1.0 / a, axis=axis, weights=weights)
  298. else:
  299. raise ValueError("Harmonic mean only defined if all elements greater "
  300. "than or equal to zero")
  301. @_axis_nan_policy_factory(
  302. lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
  303. result_to_tuple=lambda x: (x,), kwd_samples=['weights'])
  304. def pmean(a, p, *, axis=0, dtype=None, weights=None):
  305. r"""Calculate the weighted power mean along the specified axis.
  306. The weighted power mean of the array :math:`a_i` associated to weights
  307. :math:`w_i` is:
  308. .. math::
  309. \left( \frac{ \sum_{i=1}^n w_i a_i^p }{ \sum_{i=1}^n w_i }
  310. \right)^{ 1 / p } \, ,
  311. and, with equal weights, it gives:
  312. .. math::
  313. \left( \frac{ 1 }{ n } \sum_{i=1}^n a_i^p \right)^{ 1 / p } \, .
  314. This mean is also called generalized mean or Hölder mean, and must not be
  315. confused with the Kolmogorov generalized mean, also called
  316. quasi-arithmetic mean or generalized f-mean [3]_.
  317. Parameters
  318. ----------
  319. a : array_like
  320. Input array, masked array or object that can be converted to an array.
  321. p : int or float
  322. Exponent.
  323. axis : int or None, optional
  324. Axis along which the power mean is computed. Default is 0.
  325. If None, compute over the whole array `a`.
  326. dtype : dtype, optional
  327. Type of the returned array and of the accumulator in which the
  328. elements are summed. If `dtype` is not specified, it defaults to the
  329. dtype of `a`, unless `a` has an integer `dtype` with a precision less
  330. than that of the default platform integer. In that case, the default
  331. platform integer is used.
  332. weights : array_like, optional
  333. The weights array can either be 1-D (in which case its length must be
  334. the size of `a` along the given `axis`) or of the same shape as `a`.
  335. Default is None, which gives each value a weight of 1.0.
  336. Returns
  337. -------
  338. pmean : ndarray, see `dtype` parameter above.
  339. Output array containing the power mean values.
  340. See Also
  341. --------
  342. numpy.average : Weighted average
  343. gmean : Geometric mean
  344. hmean : Harmonic mean
  345. Notes
  346. -----
  347. The power mean is computed over a single dimension of the input
  348. array, ``axis=0`` by default, or all values in the array if ``axis=None``.
  349. float64 intermediate and return values are used for integer inputs.
  350. .. versionadded:: 1.9
  351. References
  352. ----------
  353. .. [1] "Generalized Mean", *Wikipedia*,
  354. https://en.wikipedia.org/wiki/Generalized_mean
  355. .. [2] Norris, N., "Convexity properties of generalized mean value
  356. functions", The Annals of Mathematical Statistics, vol. 8,
  357. pp. 118-120, 1937
  358. .. [3] Bullen, P.S., Handbook of Means and Their Inequalities, 2003
  359. Examples
  360. --------
  361. >>> from scipy.stats import pmean, hmean, gmean
  362. >>> pmean([1, 4], 1.3)
  363. 2.639372938300652
  364. >>> pmean([1, 2, 3, 4, 5, 6, 7], 1.3)
  365. 4.157111214492084
  366. >>> pmean([1, 4, 7], -2, weights=[3, 1, 3])
  367. 1.4969684896631954
  368. For p=-1, power mean is equal to harmonic mean:
  369. >>> pmean([1, 4, 7], -1, weights=[3, 1, 3])
  370. 1.9029126213592233
  371. >>> hmean([1, 4, 7], weights=[3, 1, 3])
  372. 1.9029126213592233
  373. For p=0, power mean is defined as the geometric mean:
  374. >>> pmean([1, 4, 7], 0, weights=[3, 1, 3])
  375. 2.80668351922014
  376. >>> gmean([1, 4, 7], weights=[3, 1, 3])
  377. 2.80668351922014
  378. """
  379. if not isinstance(p, (int, float)):
  380. raise ValueError("Power mean only defined for exponent of type int or "
  381. "float.")
  382. if p == 0:
  383. return gmean(a, axis=axis, dtype=dtype, weights=weights)
  384. if not isinstance(a, np.ndarray):
  385. a = np.array(a, dtype=dtype)
  386. elif dtype:
  387. # Must change the default dtype allowing array type
  388. if isinstance(a, np.ma.MaskedArray):
  389. a = np.ma.asarray(a, dtype=dtype)
  390. else:
  391. a = np.asarray(a, dtype=dtype)
  392. if np.all(a >= 0):
  393. # Power mean only defined if greater than or equal to zero
  394. if weights is not None:
  395. weights = np.asanyarray(weights, dtype=dtype)
  396. with np.errstate(divide='ignore'):
  397. return np.float_power(
  398. np.average(np.float_power(a, p), axis=axis, weights=weights),
  399. 1/p)
  400. else:
  401. raise ValueError("Power mean only defined if all elements greater "
  402. "than or equal to zero")
  403. ModeResult = namedtuple('ModeResult', ('mode', 'count'))
  404. def mode(a, axis=0, nan_policy='propagate', keepdims=None):
  405. r"""Return an array of the modal (most common) value in the passed array.
  406. If there is more than one such value, only one is returned.
  407. The bin-count for the modal bins is also returned.
  408. Parameters
  409. ----------
  410. a : array_like
  411. n-dimensional array of which to find mode(s).
  412. axis : int or None, optional
  413. Axis along which to operate. Default is 0. If None, compute over
  414. the whole array `a`.
  415. nan_policy : {'propagate', 'raise', 'omit'}, optional
  416. Defines how to handle when input contains nan.
  417. The following options are available (default is 'propagate'):
  418. * 'propagate': treats nan as it would treat any other value
  419. * 'raise': throws an error
  420. * 'omit': performs the calculations ignoring nan values
  421. keepdims : bool, optional
  422. If set to ``False``, the `axis` over which the statistic is taken
  423. is consumed (eliminated from the output array) like other reduction
  424. functions (e.g. `skew`, `kurtosis`). If set to ``True``, the `axis` is
  425. retained with size one, and the result will broadcast correctly
  426. against the input array. The default, ``None``, is undefined legacy
  427. behavior retained for backward compatibility.
  428. .. warning::
  429. Unlike other reduction functions (e.g. `skew`, `kurtosis`), the
  430. default behavior of `mode` usually retains the axis it acts
  431. along. In SciPy 1.11.0, this behavior will change: the default
  432. value of `keepdims` will become ``False``, the `axis` over which
  433. the statistic is taken will be eliminated, and the value ``None``
  434. will no longer be accepted.
  435. .. versionadded:: 1.9.0
  436. Returns
  437. -------
  438. mode : ndarray
  439. Array of modal values.
  440. count : ndarray
  441. Array of counts for each mode.
  442. Notes
  443. -----
  444. The mode of object arrays is calculated using `collections.Counter`, which
  445. treats NaNs with different binary representations as distinct.
  446. .. deprecated:: 1.9.0
  447. Support for non-numeric arrays has been deprecated as of SciPy 1.9.0
  448. and will be removed in 1.11.0. `pandas.DataFrame.mode`_ can
  449. be used instead.
  450. .. _pandas.DataFrame.mode: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.mode.html
  451. The mode of arrays with other dtypes is calculated using `numpy.unique`.
  452. In NumPy versions 1.21 and after, all NaNs - even those with different
  453. binary representations - are treated as equivalent and counted as separate
  454. instances of the same value.
  455. Examples
  456. --------
  457. >>> import numpy as np
  458. >>> a = np.array([[3, 0, 3, 7],
  459. ... [3, 2, 6, 2],
  460. ... [1, 7, 2, 8],
  461. ... [3, 0, 6, 1],
  462. ... [3, 2, 5, 5]])
  463. >>> from scipy import stats
  464. >>> stats.mode(a, keepdims=True)
  465. ModeResult(mode=array([[3, 0, 6, 1]]), count=array([[4, 2, 2, 1]]))
  466. To get mode of whole array, specify ``axis=None``:
  467. >>> stats.mode(a, axis=None, keepdims=True)
  468. ModeResult(mode=[3], count=[5])
  469. >>> stats.mode(a, axis=None, keepdims=False)
  470. ModeResult(mode=3, count=5)
  471. """ # noqa: E501
  472. if keepdims is None:
  473. message = ("Unlike other reduction functions (e.g. `skew`, "
  474. "`kurtosis`), the default behavior of `mode` typically "
  475. "preserves the axis it acts along. In SciPy 1.11.0, "
  476. "this behavior will change: the default value of "
  477. "`keepdims` will become False, the `axis` over which "
  478. "the statistic is taken will be eliminated, and the value "
  479. "None will no longer be accepted. "
  480. "Set `keepdims` to True or False to avoid this warning.")
  481. warnings.warn(message, FutureWarning, stacklevel=2)
  482. a = np.asarray(a)
  483. if a.size == 0:
  484. if keepdims is None:
  485. return ModeResult(np.array([]), np.array([]))
  486. else:
  487. # this is tricky to get right; let np.mean do it
  488. out = np.mean(a, axis=axis, keepdims=keepdims)
  489. return ModeResult(out, out.copy())
  490. a, axis = _chk_asarray(a, axis)
  491. contains_nan, nan_policy = _contains_nan(a, nan_policy)
  492. if contains_nan and nan_policy == 'omit':
  493. a = ma.masked_invalid(a)
  494. return mstats_basic._mode(a, axis, keepdims=keepdims)
  495. if not np.issubdtype(a.dtype, np.number):
  496. warnings.warn("Support for non-numeric arrays has been deprecated "
  497. "as of SciPy 1.9.0 and will be removed in "
  498. "1.11.0. `pandas.DataFrame.mode` can be used instead, "
  499. "see https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.mode.html.", # noqa: E501
  500. DeprecationWarning, stacklevel=2)
  501. if a.dtype == object:
  502. def _mode1D(a):
  503. cntr = Counter(a)
  504. mode = max(cntr, key=lambda x: cntr[x])
  505. return mode, cntr[mode]
  506. else:
  507. def _mode1D(a):
  508. vals, cnts = np.unique(a, return_counts=True)
  509. return vals[cnts.argmax()], cnts.max()
  510. # np.apply_along_axis will convert the _mode1D tuples to a numpy array,
  511. # casting types in the process.
  512. # This recreates the results without that issue
  513. # View of a, rotated so the requested axis is last
  514. a_view = np.moveaxis(a, axis, -1)
  515. inds = np.ndindex(a_view.shape[:-1])
  516. modes = np.empty(a_view.shape[:-1], dtype=a.dtype)
  517. counts = np.empty(a_view.shape[:-1], dtype=np.int_)
  518. for ind in inds:
  519. modes[ind], counts[ind] = _mode1D(a_view[ind])
  520. if keepdims is None or keepdims:
  521. newshape = list(a.shape)
  522. newshape[axis] = 1
  523. return ModeResult(modes.reshape(newshape), counts.reshape(newshape))
  524. else:
  525. return ModeResult(modes[()], counts[()])
  526. def _mask_to_limits(a, limits, inclusive):
  527. """Mask an array for values outside of given limits.
  528. This is primarily a utility function.
  529. Parameters
  530. ----------
  531. a : array
  532. limits : (float or None, float or None)
  533. A tuple consisting of the (lower limit, upper limit). Values in the
  534. input array less than the lower limit or greater than the upper limit
  535. will be masked out. None implies no limit.
  536. inclusive : (bool, bool)
  537. A tuple consisting of the (lower flag, upper flag). These flags
  538. determine whether values exactly equal to lower or upper are allowed.
  539. Returns
  540. -------
  541. A MaskedArray.
  542. Raises
  543. ------
  544. A ValueError if there are no values within the given limits.
  545. """
  546. lower_limit, upper_limit = limits
  547. lower_include, upper_include = inclusive
  548. am = ma.MaskedArray(a)
  549. if lower_limit is not None:
  550. if lower_include:
  551. am = ma.masked_less(am, lower_limit)
  552. else:
  553. am = ma.masked_less_equal(am, lower_limit)
  554. if upper_limit is not None:
  555. if upper_include:
  556. am = ma.masked_greater(am, upper_limit)
  557. else:
  558. am = ma.masked_greater_equal(am, upper_limit)
  559. if am.count() == 0:
  560. raise ValueError("No array values within given limits")
  561. return am
  562. def tmean(a, limits=None, inclusive=(True, True), axis=None):
  563. """Compute the trimmed mean.
  564. This function finds the arithmetic mean of given values, ignoring values
  565. outside the given `limits`.
  566. Parameters
  567. ----------
  568. a : array_like
  569. Array of values.
  570. limits : None or (lower limit, upper limit), optional
  571. Values in the input array less than the lower limit or greater than the
  572. upper limit will be ignored. When limits is None (default), then all
  573. values are used. Either of the limit values in the tuple can also be
  574. None representing a half-open interval.
  575. inclusive : (bool, bool), optional
  576. A tuple consisting of the (lower flag, upper flag). These flags
  577. determine whether values exactly equal to the lower or upper limits
  578. are included. The default value is (True, True).
  579. axis : int or None, optional
  580. Axis along which to compute test. Default is None.
  581. Returns
  582. -------
  583. tmean : ndarray
  584. Trimmed mean.
  585. See Also
  586. --------
  587. trim_mean : Returns mean after trimming a proportion from both tails.
  588. Examples
  589. --------
  590. >>> import numpy as np
  591. >>> from scipy import stats
  592. >>> x = np.arange(20)
  593. >>> stats.tmean(x)
  594. 9.5
  595. >>> stats.tmean(x, (3,17))
  596. 10.0
  597. """
  598. a = asarray(a)
  599. if limits is None:
  600. return np.mean(a, axis)
  601. am = _mask_to_limits(a, limits, inclusive)
  602. mean = np.ma.filled(am.mean(axis=axis), fill_value=np.nan)
  603. return mean if mean.ndim > 0 else mean.item()
  604. def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
  605. """Compute the trimmed variance.
  606. This function computes the sample variance of an array of values,
  607. while ignoring values which are outside of given `limits`.
  608. Parameters
  609. ----------
  610. a : array_like
  611. Array of values.
  612. limits : None or (lower limit, upper limit), optional
  613. Values in the input array less than the lower limit or greater than the
  614. upper limit will be ignored. When limits is None, then all values are
  615. used. Either of the limit values in the tuple can also be None
  616. representing a half-open interval. The default value is None.
  617. inclusive : (bool, bool), optional
  618. A tuple consisting of the (lower flag, upper flag). These flags
  619. determine whether values exactly equal to the lower or upper limits
  620. are included. The default value is (True, True).
  621. axis : int or None, optional
  622. Axis along which to operate. Default is 0. If None, compute over the
  623. whole array `a`.
  624. ddof : int, optional
  625. Delta degrees of freedom. Default is 1.
  626. Returns
  627. -------
  628. tvar : float
  629. Trimmed variance.
  630. Notes
  631. -----
  632. `tvar` computes the unbiased sample variance, i.e. it uses a correction
  633. factor ``n / (n - 1)``.
  634. Examples
  635. --------
  636. >>> import numpy as np
  637. >>> from scipy import stats
  638. >>> x = np.arange(20)
  639. >>> stats.tvar(x)
  640. 35.0
  641. >>> stats.tvar(x, (3,17))
  642. 20.0
  643. """
  644. a = asarray(a)
  645. a = a.astype(float)
  646. if limits is None:
  647. return a.var(ddof=ddof, axis=axis)
  648. am = _mask_to_limits(a, limits, inclusive)
  649. amnan = am.filled(fill_value=np.nan)
  650. return np.nanvar(amnan, ddof=ddof, axis=axis)
  651. def tmin(a, lowerlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
  652. """Compute the trimmed minimum.
  653. This function finds the miminum value of an array `a` along the
  654. specified axis, but only considering values greater than a specified
  655. lower limit.
  656. Parameters
  657. ----------
  658. a : array_like
  659. Array of values.
  660. lowerlimit : None or float, optional
  661. Values in the input array less than the given limit will be ignored.
  662. When lowerlimit is None, then all values are used. The default value
  663. is None.
  664. axis : int or None, optional
  665. Axis along which to operate. Default is 0. If None, compute over the
  666. whole array `a`.
  667. inclusive : {True, False}, optional
  668. This flag determines whether values exactly equal to the lower limit
  669. are included. The default value is True.
  670. nan_policy : {'propagate', 'raise', 'omit'}, optional
  671. Defines how to handle when input contains nan.
  672. The following options are available (default is 'propagate'):
  673. * 'propagate': returns nan
  674. * 'raise': throws an error
  675. * 'omit': performs the calculations ignoring nan values
  676. Returns
  677. -------
  678. tmin : float, int or ndarray
  679. Trimmed minimum.
  680. Examples
  681. --------
  682. >>> import numpy as np
  683. >>> from scipy import stats
  684. >>> x = np.arange(20)
  685. >>> stats.tmin(x)
  686. 0
  687. >>> stats.tmin(x, 13)
  688. 13
  689. >>> stats.tmin(x, 13, inclusive=False)
  690. 14
  691. """
  692. a, axis = _chk_asarray(a, axis)
  693. am = _mask_to_limits(a, (lowerlimit, None), (inclusive, False))
  694. contains_nan, nan_policy = _contains_nan(am, nan_policy)
  695. if contains_nan and nan_policy == 'omit':
  696. am = ma.masked_invalid(am)
  697. res = ma.minimum.reduce(am, axis).data
  698. if res.ndim == 0:
  699. return res[()]
  700. return res
  701. def tmax(a, upperlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
  702. """Compute the trimmed maximum.
  703. This function computes the maximum value of an array along a given axis,
  704. while ignoring values larger than a specified upper limit.
  705. Parameters
  706. ----------
  707. a : array_like
  708. Array of values.
  709. upperlimit : None or float, optional
  710. Values in the input array greater than the given limit will be ignored.
  711. When upperlimit is None, then all values are used. The default value
  712. is None.
  713. axis : int or None, optional
  714. Axis along which to operate. Default is 0. If None, compute over the
  715. whole array `a`.
  716. inclusive : {True, False}, optional
  717. This flag determines whether values exactly equal to the upper limit
  718. are included. The default value is True.
  719. nan_policy : {'propagate', 'raise', 'omit'}, optional
  720. Defines how to handle when input contains nan.
  721. The following options are available (default is 'propagate'):
  722. * 'propagate': returns nan
  723. * 'raise': throws an error
  724. * 'omit': performs the calculations ignoring nan values
  725. Returns
  726. -------
  727. tmax : float, int or ndarray
  728. Trimmed maximum.
  729. Examples
  730. --------
  731. >>> import numpy as np
  732. >>> from scipy import stats
  733. >>> x = np.arange(20)
  734. >>> stats.tmax(x)
  735. 19
  736. >>> stats.tmax(x, 13)
  737. 13
  738. >>> stats.tmax(x, 13, inclusive=False)
  739. 12
  740. """
  741. a, axis = _chk_asarray(a, axis)
  742. am = _mask_to_limits(a, (None, upperlimit), (False, inclusive))
  743. contains_nan, nan_policy = _contains_nan(am, nan_policy)
  744. if contains_nan and nan_policy == 'omit':
  745. am = ma.masked_invalid(am)
  746. res = ma.maximum.reduce(am, axis).data
  747. if res.ndim == 0:
  748. return res[()]
  749. return res
  750. def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
  751. """Compute the trimmed sample standard deviation.
  752. This function finds the sample standard deviation of given values,
  753. ignoring values outside the given `limits`.
  754. Parameters
  755. ----------
  756. a : array_like
  757. Array of values.
  758. limits : None or (lower limit, upper limit), optional
  759. Values in the input array less than the lower limit or greater than the
  760. upper limit will be ignored. When limits is None, then all values are
  761. used. Either of the limit values in the tuple can also be None
  762. representing a half-open interval. The default value is None.
  763. inclusive : (bool, bool), optional
  764. A tuple consisting of the (lower flag, upper flag). These flags
  765. determine whether values exactly equal to the lower or upper limits
  766. are included. The default value is (True, True).
  767. axis : int or None, optional
  768. Axis along which to operate. Default is 0. If None, compute over the
  769. whole array `a`.
  770. ddof : int, optional
  771. Delta degrees of freedom. Default is 1.
  772. Returns
  773. -------
  774. tstd : float
  775. Trimmed sample standard deviation.
  776. Notes
  777. -----
  778. `tstd` computes the unbiased sample standard deviation, i.e. it uses a
  779. correction factor ``n / (n - 1)``.
  780. Examples
  781. --------
  782. >>> import numpy as np
  783. >>> from scipy import stats
  784. >>> x = np.arange(20)
  785. >>> stats.tstd(x)
  786. 5.9160797830996161
  787. >>> stats.tstd(x, (3,17))
  788. 4.4721359549995796
  789. """
  790. return np.sqrt(tvar(a, limits, inclusive, axis, ddof))
  791. def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
  792. """Compute the trimmed standard error of the mean.
  793. This function finds the standard error of the mean for given
  794. values, ignoring values outside the given `limits`.
  795. Parameters
  796. ----------
  797. a : array_like
  798. Array of values.
  799. limits : None or (lower limit, upper limit), optional
  800. Values in the input array less than the lower limit or greater than the
  801. upper limit will be ignored. When limits is None, then all values are
  802. used. Either of the limit values in the tuple can also be None
  803. representing a half-open interval. The default value is None.
  804. inclusive : (bool, bool), optional
  805. A tuple consisting of the (lower flag, upper flag). These flags
  806. determine whether values exactly equal to the lower or upper limits
  807. are included. The default value is (True, True).
  808. axis : int or None, optional
  809. Axis along which to operate. Default is 0. If None, compute over the
  810. whole array `a`.
  811. ddof : int, optional
  812. Delta degrees of freedom. Default is 1.
  813. Returns
  814. -------
  815. tsem : float
  816. Trimmed standard error of the mean.
  817. Notes
  818. -----
  819. `tsem` uses unbiased sample standard deviation, i.e. it uses a
  820. correction factor ``n / (n - 1)``.
  821. Examples
  822. --------
  823. >>> import numpy as np
  824. >>> from scipy import stats
  825. >>> x = np.arange(20)
  826. >>> stats.tsem(x)
  827. 1.3228756555322954
  828. >>> stats.tsem(x, (3,17))
  829. 1.1547005383792515
  830. """
  831. a = np.asarray(a).ravel()
  832. if limits is None:
  833. return a.std(ddof=ddof) / np.sqrt(a.size)
  834. am = _mask_to_limits(a, limits, inclusive)
  835. sd = np.sqrt(np.ma.var(am, ddof=ddof, axis=axis))
  836. return sd / np.sqrt(am.count())
  837. #####################################
  838. # MOMENTS #
  839. #####################################
  840. def _moment_outputs(kwds):
  841. moment = np.atleast_1d(kwds.get('moment', 1))
  842. if moment.size == 0:
  843. raise ValueError("'moment' must be a scalar or a non-empty 1D "
  844. "list/array.")
  845. return len(moment)
  846. def _moment_result_object(*args):
  847. if len(args) == 1:
  848. return args[0]
  849. return np.asarray(args)
  850. # `moment` fits into the `_axis_nan_policy` pattern, but it is a bit unusual
  851. # because the number of outputs is variable. Specifically,
  852. # `result_to_tuple=lambda x: (x,)` may be surprising for a function that
  853. # can produce more than one output, but it is intended here.
  854. # When `moment is called to produce the output:
  855. # - `result_to_tuple` packs the returned array into a single-element tuple,
  856. # - `_moment_result_object` extracts and returns that single element.
  857. # However, when the input array is empty, `moment` is never called. Instead,
  858. # - `_check_empty_inputs` is used to produce an empty array with the
  859. # appropriate dimensions.
  860. # - A list comprehension creates the appropriate number of copies of this
  861. # array, depending on `n_outputs`.
  862. # - This list - which may have multiple elements - is passed into
  863. # `_moment_result_object`.
  864. # - If there is a single output, `_moment_result_object` extracts and returns
  865. # the single output from the list.
  866. # - If there are multiple outputs, and therefore multiple elements in the list,
  867. # `_moment_result_object` converts the list of arrays to a single array and
  868. # returns it.
  869. # Currently this leads to a slight inconsistency: when the input array is
  870. # empty, there is no distinction between the `moment` function being called
  871. # with parameter `moments=1` and `moments=[1]`; the latter *should* produce
  872. # the same as the former but with a singleton zeroth dimension.
  873. @_axis_nan_policy_factory( # noqa: E302
  874. _moment_result_object, n_samples=1, result_to_tuple=lambda x: (x,),
  875. n_outputs=_moment_outputs
  876. )
  877. def moment(a, moment=1, axis=0, nan_policy='propagate'):
  878. r"""Calculate the nth moment about the mean for a sample.
  879. A moment is a specific quantitative measure of the shape of a set of
  880. points. It is often used to calculate coefficients of skewness and kurtosis
  881. due to its close relationship with them.
  882. Parameters
  883. ----------
  884. a : array_like
  885. Input array.
  886. moment : int or array_like of ints, optional
  887. Order of central moment that is returned. Default is 1.
  888. axis : int or None, optional
  889. Axis along which the central moment is computed. Default is 0.
  890. If None, compute over the whole array `a`.
  891. nan_policy : {'propagate', 'raise', 'omit'}, optional
  892. Defines how to handle when input contains nan.
  893. The following options are available (default is 'propagate'):
  894. * 'propagate': returns nan
  895. * 'raise': throws an error
  896. * 'omit': performs the calculations ignoring nan values
  897. Returns
  898. -------
  899. n-th central moment : ndarray or float
  900. The appropriate moment along the given axis or over all values if axis
  901. is None. The denominator for the moment calculation is the number of
  902. observations, no degrees of freedom correction is done.
  903. See Also
  904. --------
  905. kurtosis, skew, describe
  906. Notes
  907. -----
  908. The k-th central moment of a data sample is:
  909. .. math::
  910. m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - \bar{x})^k
  911. Where n is the number of samples and x-bar is the mean. This function uses
  912. exponentiation by squares [1]_ for efficiency.
  913. Note that, if `a` is an empty array (``a.size == 0``), array `moment` with
  914. one element (`moment.size == 1`) is treated the same as scalar `moment`
  915. (``np.isscalar(moment)``). This might produce arrays of unexpected shape.
  916. References
  917. ----------
  918. .. [1] https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
  919. Examples
  920. --------
  921. >>> from scipy.stats import moment
  922. >>> moment([1, 2, 3, 4, 5], moment=1)
  923. 0.0
  924. >>> moment([1, 2, 3, 4, 5], moment=2)
  925. 2.0
  926. """
  927. a, axis = _chk_asarray(a, axis)
  928. contains_nan, nan_policy = _contains_nan(a, nan_policy)
  929. if contains_nan and nan_policy == 'omit':
  930. a = ma.masked_invalid(a)
  931. return mstats_basic.moment(a, moment, axis)
  932. # for array_like moment input, return a value for each.
  933. if not np.isscalar(moment):
  934. mean = a.mean(axis, keepdims=True)
  935. mmnt = [_moment(a, i, axis, mean=mean) for i in moment]
  936. return np.array(mmnt)
  937. else:
  938. return _moment(a, moment, axis)
  939. # Moment with optional pre-computed mean, equal to a.mean(axis, keepdims=True)
  940. def _moment(a, moment, axis, *, mean=None):
  941. if np.abs(moment - np.round(moment)) > 0:
  942. raise ValueError("All moment parameters must be integers")
  943. # moment of empty array is the same regardless of order
  944. if a.size == 0:
  945. return np.mean(a, axis=axis)
  946. if moment == 0 or moment == 1:
  947. # By definition the zeroth moment about the mean is 1, and the first
  948. # moment is 0.
  949. shape = list(a.shape)
  950. del shape[axis]
  951. dtype = a.dtype.type if a.dtype.kind in 'fc' else np.float64
  952. if len(shape) == 0:
  953. return dtype(1.0 if moment == 0 else 0.0)
  954. else:
  955. return (np.ones(shape, dtype=dtype) if moment == 0
  956. else np.zeros(shape, dtype=dtype))
  957. else:
  958. # Exponentiation by squares: form exponent sequence
  959. n_list = [moment]
  960. current_n = moment
  961. while current_n > 2:
  962. if current_n % 2:
  963. current_n = (current_n - 1) / 2
  964. else:
  965. current_n /= 2
  966. n_list.append(current_n)
  967. # Starting point for exponentiation by squares
  968. mean = a.mean(axis, keepdims=True) if mean is None else mean
  969. a_zero_mean = a - mean
  970. eps = np.finfo(a_zero_mean.dtype).resolution * 10
  971. with np.errstate(divide='ignore', invalid='ignore'):
  972. rel_diff = np.max(np.abs(a_zero_mean), axis=axis,
  973. keepdims=True) / np.abs(mean)
  974. with np.errstate(invalid='ignore'):
  975. precision_loss = np.any(rel_diff < eps)
  976. if precision_loss:
  977. message = ("Precision loss occurred in moment calculation due to "
  978. "catastrophic cancellation. This occurs when the data "
  979. "are nearly identical. Results may be unreliable.")
  980. warnings.warn(message, RuntimeWarning, stacklevel=4)
  981. if n_list[-1] == 1:
  982. s = a_zero_mean.copy()
  983. else:
  984. s = a_zero_mean**2
  985. # Perform multiplications
  986. for n in n_list[-2::-1]:
  987. s = s**2
  988. if n % 2:
  989. s *= a_zero_mean
  990. return np.mean(s, axis)
  991. def _var(x, axis=0, ddof=0, mean=None):
  992. # Calculate variance of sample, warning if precision is lost
  993. var = _moment(x, 2, axis, mean=mean)
  994. if ddof != 0:
  995. n = x.shape[axis] if axis is not None else x.size
  996. var *= np.divide(n, n-ddof) # to avoid error on division by zero
  997. return var
  998. @_axis_nan_policy_factory(
  999. lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1
  1000. )
  1001. def skew(a, axis=0, bias=True, nan_policy='propagate'):
  1002. r"""Compute the sample skewness of a data set.
  1003. For normally distributed data, the skewness should be about zero. For
  1004. unimodal continuous distributions, a skewness value greater than zero means
  1005. that there is more weight in the right tail of the distribution. The
  1006. function `skewtest` can be used to determine if the skewness value
  1007. is close enough to zero, statistically speaking.
  1008. Parameters
  1009. ----------
  1010. a : ndarray
  1011. Input array.
  1012. axis : int or None, optional
  1013. Axis along which skewness is calculated. Default is 0.
  1014. If None, compute over the whole array `a`.
  1015. bias : bool, optional
  1016. If False, then the calculations are corrected for statistical bias.
  1017. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1018. Defines how to handle when input contains nan.
  1019. The following options are available (default is 'propagate'):
  1020. * 'propagate': returns nan
  1021. * 'raise': throws an error
  1022. * 'omit': performs the calculations ignoring nan values
  1023. Returns
  1024. -------
  1025. skewness : ndarray
  1026. The skewness of values along an axis, returning NaN where all values
  1027. are equal.
  1028. Notes
  1029. -----
  1030. The sample skewness is computed as the Fisher-Pearson coefficient
  1031. of skewness, i.e.
  1032. .. math::
  1033. g_1=\frac{m_3}{m_2^{3/2}}
  1034. where
  1035. .. math::
  1036. m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i
  1037. is the biased sample :math:`i\texttt{th}` central moment, and
  1038. :math:`\bar{x}` is
  1039. the sample mean. If ``bias`` is False, the calculations are
  1040. corrected for bias and the value computed is the adjusted
  1041. Fisher-Pearson standardized moment coefficient, i.e.
  1042. .. math::
  1043. G_1=\frac{k_3}{k_2^{3/2}}=
  1044. \frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}.
  1045. References
  1046. ----------
  1047. .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
  1048. Probability and Statistics Tables and Formulae. Chapman & Hall: New
  1049. York. 2000.
  1050. Section 2.2.24.1
  1051. Examples
  1052. --------
  1053. >>> from scipy.stats import skew
  1054. >>> skew([1, 2, 3, 4, 5])
  1055. 0.0
  1056. >>> skew([2, 8, 0, 4, 1, 9, 9, 0])
  1057. 0.2650554122698573
  1058. """
  1059. a, axis = _chk_asarray(a, axis)
  1060. n = a.shape[axis]
  1061. contains_nan, nan_policy = _contains_nan(a, nan_policy)
  1062. if contains_nan and nan_policy == 'omit':
  1063. a = ma.masked_invalid(a)
  1064. return mstats_basic.skew(a, axis, bias)
  1065. mean = a.mean(axis, keepdims=True)
  1066. m2 = _moment(a, 2, axis, mean=mean)
  1067. m3 = _moment(a, 3, axis, mean=mean)
  1068. with np.errstate(all='ignore'):
  1069. zero = (m2 <= (np.finfo(m2.dtype).resolution * mean.squeeze(axis))**2)
  1070. vals = np.where(zero, np.nan, m3 / m2**1.5)
  1071. if not bias:
  1072. can_correct = ~zero & (n > 2)
  1073. if can_correct.any():
  1074. m2 = np.extract(can_correct, m2)
  1075. m3 = np.extract(can_correct, m3)
  1076. nval = np.sqrt((n - 1.0) * n) / (n - 2.0) * m3 / m2**1.5
  1077. np.place(vals, can_correct, nval)
  1078. if vals.ndim == 0:
  1079. return vals.item()
  1080. return vals
  1081. @_axis_nan_policy_factory(
  1082. lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1
  1083. )
  1084. def kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate'):
  1085. """Compute the kurtosis (Fisher or Pearson) of a dataset.
  1086. Kurtosis is the fourth central moment divided by the square of the
  1087. variance. If Fisher's definition is used, then 3.0 is subtracted from
  1088. the result to give 0.0 for a normal distribution.
  1089. If bias is False then the kurtosis is calculated using k statistics to
  1090. eliminate bias coming from biased moment estimators
  1091. Use `kurtosistest` to see if result is close enough to normal.
  1092. Parameters
  1093. ----------
  1094. a : array
  1095. Data for which the kurtosis is calculated.
  1096. axis : int or None, optional
  1097. Axis along which the kurtosis is calculated. Default is 0.
  1098. If None, compute over the whole array `a`.
  1099. fisher : bool, optional
  1100. If True, Fisher's definition is used (normal ==> 0.0). If False,
  1101. Pearson's definition is used (normal ==> 3.0).
  1102. bias : bool, optional
  1103. If False, then the calculations are corrected for statistical bias.
  1104. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1105. Defines how to handle when input contains nan. 'propagate' returns nan,
  1106. 'raise' throws an error, 'omit' performs the calculations ignoring nan
  1107. values. Default is 'propagate'.
  1108. Returns
  1109. -------
  1110. kurtosis : array
  1111. The kurtosis of values along an axis, returning NaN where all values
  1112. are equal.
  1113. References
  1114. ----------
  1115. .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
  1116. Probability and Statistics Tables and Formulae. Chapman & Hall: New
  1117. York. 2000.
  1118. Examples
  1119. --------
  1120. In Fisher's definiton, the kurtosis of the normal distribution is zero.
  1121. In the following example, the kurtosis is close to zero, because it was
  1122. calculated from the dataset, not from the continuous distribution.
  1123. >>> import numpy as np
  1124. >>> from scipy.stats import norm, kurtosis
  1125. >>> data = norm.rvs(size=1000, random_state=3)
  1126. >>> kurtosis(data)
  1127. -0.06928694200380558
  1128. The distribution with a higher kurtosis has a heavier tail.
  1129. The zero valued kurtosis of the normal distribution in Fisher's definition
  1130. can serve as a reference point.
  1131. >>> import matplotlib.pyplot as plt
  1132. >>> import scipy.stats as stats
  1133. >>> from scipy.stats import kurtosis
  1134. >>> x = np.linspace(-5, 5, 100)
  1135. >>> ax = plt.subplot()
  1136. >>> distnames = ['laplace', 'norm', 'uniform']
  1137. >>> for distname in distnames:
  1138. ... if distname == 'uniform':
  1139. ... dist = getattr(stats, distname)(loc=-2, scale=4)
  1140. ... else:
  1141. ... dist = getattr(stats, distname)
  1142. ... data = dist.rvs(size=1000)
  1143. ... kur = kurtosis(data, fisher=True)
  1144. ... y = dist.pdf(x)
  1145. ... ax.plot(x, y, label="{}, {}".format(distname, round(kur, 3)))
  1146. ... ax.legend()
  1147. The Laplace distribution has a heavier tail than the normal distribution.
  1148. The uniform distribution (which has negative kurtosis) has the thinnest
  1149. tail.
  1150. """
  1151. a, axis = _chk_asarray(a, axis)
  1152. contains_nan, nan_policy = _contains_nan(a, nan_policy)
  1153. if contains_nan and nan_policy == 'omit':
  1154. a = ma.masked_invalid(a)
  1155. return mstats_basic.kurtosis(a, axis, fisher, bias)
  1156. n = a.shape[axis]
  1157. mean = a.mean(axis, keepdims=True)
  1158. m2 = _moment(a, 2, axis, mean=mean)
  1159. m4 = _moment(a, 4, axis, mean=mean)
  1160. with np.errstate(all='ignore'):
  1161. zero = (m2 <= (np.finfo(m2.dtype).resolution * mean.squeeze(axis))**2)
  1162. vals = np.where(zero, np.nan, m4 / m2**2.0)
  1163. if not bias:
  1164. can_correct = ~zero & (n > 3)
  1165. if can_correct.any():
  1166. m2 = np.extract(can_correct, m2)
  1167. m4 = np.extract(can_correct, m4)
  1168. nval = 1.0/(n-2)/(n-3) * ((n**2-1.0)*m4/m2**2.0 - 3*(n-1)**2.0)
  1169. np.place(vals, can_correct, nval + 3.0)
  1170. if vals.ndim == 0:
  1171. vals = vals.item() # array scalar
  1172. return vals - 3 if fisher else vals
  1173. DescribeResult = namedtuple('DescribeResult',
  1174. ('nobs', 'minmax', 'mean', 'variance', 'skewness',
  1175. 'kurtosis'))
  1176. def describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate'):
  1177. """Compute several descriptive statistics of the passed array.
  1178. Parameters
  1179. ----------
  1180. a : array_like
  1181. Input data.
  1182. axis : int or None, optional
  1183. Axis along which statistics are calculated. Default is 0.
  1184. If None, compute over the whole array `a`.
  1185. ddof : int, optional
  1186. Delta degrees of freedom (only for variance). Default is 1.
  1187. bias : bool, optional
  1188. If False, then the skewness and kurtosis calculations are corrected
  1189. for statistical bias.
  1190. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1191. Defines how to handle when input contains nan.
  1192. The following options are available (default is 'propagate'):
  1193. * 'propagate': returns nan
  1194. * 'raise': throws an error
  1195. * 'omit': performs the calculations ignoring nan values
  1196. Returns
  1197. -------
  1198. nobs : int or ndarray of ints
  1199. Number of observations (length of data along `axis`).
  1200. When 'omit' is chosen as nan_policy, the length along each axis
  1201. slice is counted separately.
  1202. minmax: tuple of ndarrays or floats
  1203. Minimum and maximum value of `a` along the given axis.
  1204. mean : ndarray or float
  1205. Arithmetic mean of `a` along the given axis.
  1206. variance : ndarray or float
  1207. Unbiased variance of `a` along the given axis; denominator is number
  1208. of observations minus one.
  1209. skewness : ndarray or float
  1210. Skewness of `a` along the given axis, based on moment calculations
  1211. with denominator equal to the number of observations, i.e. no degrees
  1212. of freedom correction.
  1213. kurtosis : ndarray or float
  1214. Kurtosis (Fisher) of `a` along the given axis. The kurtosis is
  1215. normalized so that it is zero for the normal distribution. No
  1216. degrees of freedom are used.
  1217. See Also
  1218. --------
  1219. skew, kurtosis
  1220. Examples
  1221. --------
  1222. >>> import numpy as np
  1223. >>> from scipy import stats
  1224. >>> a = np.arange(10)
  1225. >>> stats.describe(a)
  1226. DescribeResult(nobs=10, minmax=(0, 9), mean=4.5,
  1227. variance=9.166666666666666, skewness=0.0,
  1228. kurtosis=-1.2242424242424244)
  1229. >>> b = [[1, 2], [3, 4]]
  1230. >>> stats.describe(b)
  1231. DescribeResult(nobs=2, minmax=(array([1, 2]), array([3, 4])),
  1232. mean=array([2., 3.]), variance=array([2., 2.]),
  1233. skewness=array([0., 0.]), kurtosis=array([-2., -2.]))
  1234. """
  1235. a, axis = _chk_asarray(a, axis)
  1236. contains_nan, nan_policy = _contains_nan(a, nan_policy)
  1237. if contains_nan and nan_policy == 'omit':
  1238. a = ma.masked_invalid(a)
  1239. return mstats_basic.describe(a, axis, ddof, bias)
  1240. if a.size == 0:
  1241. raise ValueError("The input must not be empty.")
  1242. n = a.shape[axis]
  1243. mm = (np.min(a, axis=axis), np.max(a, axis=axis))
  1244. m = np.mean(a, axis=axis)
  1245. v = _var(a, axis=axis, ddof=ddof)
  1246. sk = skew(a, axis, bias=bias)
  1247. kurt = kurtosis(a, axis, bias=bias)
  1248. return DescribeResult(n, mm, m, v, sk, kurt)
  1249. #####################################
  1250. # NORMALITY TESTS #
  1251. #####################################
  1252. def _normtest_finish(z, alternative):
  1253. """Common code between all the normality-test functions."""
  1254. if alternative == 'less':
  1255. prob = distributions.norm.cdf(z)
  1256. elif alternative == 'greater':
  1257. prob = distributions.norm.sf(z)
  1258. elif alternative == 'two-sided':
  1259. prob = 2 * distributions.norm.sf(np.abs(z))
  1260. else:
  1261. raise ValueError("alternative must be "
  1262. "'less', 'greater' or 'two-sided'")
  1263. if z.ndim == 0:
  1264. z = z[()]
  1265. return z, prob
  1266. SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue'))
  1267. def skewtest(a, axis=0, nan_policy='propagate', alternative='two-sided'):
  1268. """Test whether the skew is different from the normal distribution.
  1269. This function tests the null hypothesis that the skewness of
  1270. the population that the sample was drawn from is the same
  1271. as that of a corresponding normal distribution.
  1272. Parameters
  1273. ----------
  1274. a : array
  1275. The data to be tested.
  1276. axis : int or None, optional
  1277. Axis along which statistics are calculated. Default is 0.
  1278. If None, compute over the whole array `a`.
  1279. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1280. Defines how to handle when input contains nan.
  1281. The following options are available (default is 'propagate'):
  1282. * 'propagate': returns nan
  1283. * 'raise': throws an error
  1284. * 'omit': performs the calculations ignoring nan values
  1285. alternative : {'two-sided', 'less', 'greater'}, optional
  1286. Defines the alternative hypothesis. Default is 'two-sided'.
  1287. The following options are available:
  1288. * 'two-sided': the skewness of the distribution underlying the sample
  1289. is different from that of the normal distribution (i.e. 0)
  1290. * 'less': the skewness of the distribution underlying the sample
  1291. is less than that of the normal distribution
  1292. * 'greater': the skewness of the distribution underlying the sample
  1293. is greater than that of the normal distribution
  1294. .. versionadded:: 1.7.0
  1295. Returns
  1296. -------
  1297. statistic : float
  1298. The computed z-score for this test.
  1299. pvalue : float
  1300. The p-value for the hypothesis test.
  1301. Notes
  1302. -----
  1303. The sample size must be at least 8.
  1304. References
  1305. ----------
  1306. .. [1] R. B. D'Agostino, A. J. Belanger and R. B. D'Agostino Jr.,
  1307. "A suggestion for using powerful and informative tests of
  1308. normality", American Statistician 44, pp. 316-321, 1990.
  1309. Examples
  1310. --------
  1311. >>> from scipy.stats import skewtest
  1312. >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8])
  1313. SkewtestResult(statistic=1.0108048609177787, pvalue=0.3121098361421897)
  1314. >>> skewtest([2, 8, 0, 4, 1, 9, 9, 0])
  1315. SkewtestResult(statistic=0.44626385374196975, pvalue=0.6554066631275459)
  1316. >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8000])
  1317. SkewtestResult(statistic=3.571773510360407, pvalue=0.0003545719905823133)
  1318. >>> skewtest([100, 100, 100, 100, 100, 100, 100, 101])
  1319. SkewtestResult(statistic=3.5717766638478072, pvalue=0.000354567720281634)
  1320. >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='less')
  1321. SkewtestResult(statistic=1.0108048609177787, pvalue=0.8439450819289052)
  1322. >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='greater')
  1323. SkewtestResult(statistic=1.0108048609177787, pvalue=0.15605491807109484)
  1324. """
  1325. a, axis = _chk_asarray(a, axis)
  1326. contains_nan, nan_policy = _contains_nan(a, nan_policy)
  1327. if contains_nan and nan_policy == 'omit':
  1328. a = ma.masked_invalid(a)
  1329. return mstats_basic.skewtest(a, axis, alternative)
  1330. if axis is None:
  1331. a = np.ravel(a)
  1332. axis = 0
  1333. b2 = skew(a, axis)
  1334. n = a.shape[axis]
  1335. if n < 8:
  1336. raise ValueError(
  1337. "skewtest is not valid with less than 8 samples; %i samples"
  1338. " were given." % int(n))
  1339. y = b2 * math.sqrt(((n + 1) * (n + 3)) / (6.0 * (n - 2)))
  1340. beta2 = (3.0 * (n**2 + 27*n - 70) * (n+1) * (n+3) /
  1341. ((n-2.0) * (n+5) * (n+7) * (n+9)))
  1342. W2 = -1 + math.sqrt(2 * (beta2 - 1))
  1343. delta = 1 / math.sqrt(0.5 * math.log(W2))
  1344. alpha = math.sqrt(2.0 / (W2 - 1))
  1345. y = np.where(y == 0, 1, y)
  1346. Z = delta * np.log(y / alpha + np.sqrt((y / alpha)**2 + 1))
  1347. return SkewtestResult(*_normtest_finish(Z, alternative))
  1348. KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue'))
  1349. def kurtosistest(a, axis=0, nan_policy='propagate', alternative='two-sided'):
  1350. """Test whether a dataset has normal kurtosis.
  1351. This function tests the null hypothesis that the kurtosis
  1352. of the population from which the sample was drawn is that
  1353. of the normal distribution.
  1354. Parameters
  1355. ----------
  1356. a : array
  1357. Array of the sample data.
  1358. axis : int or None, optional
  1359. Axis along which to compute test. Default is 0. If None,
  1360. compute over the whole array `a`.
  1361. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1362. Defines how to handle when input contains nan.
  1363. The following options are available (default is 'propagate'):
  1364. * 'propagate': returns nan
  1365. * 'raise': throws an error
  1366. * 'omit': performs the calculations ignoring nan values
  1367. alternative : {'two-sided', 'less', 'greater'}, optional
  1368. Defines the alternative hypothesis.
  1369. The following options are available (default is 'two-sided'):
  1370. * 'two-sided': the kurtosis of the distribution underlying the sample
  1371. is different from that of the normal distribution
  1372. * 'less': the kurtosis of the distribution underlying the sample
  1373. is less than that of the normal distribution
  1374. * 'greater': the kurtosis of the distribution underlying the sample
  1375. is greater than that of the normal distribution
  1376. .. versionadded:: 1.7.0
  1377. Returns
  1378. -------
  1379. statistic : float
  1380. The computed z-score for this test.
  1381. pvalue : float
  1382. The p-value for the hypothesis test.
  1383. Notes
  1384. -----
  1385. Valid only for n>20. This function uses the method described in [1]_.
  1386. References
  1387. ----------
  1388. .. [1] see e.g. F. J. Anscombe, W. J. Glynn, "Distribution of the kurtosis
  1389. statistic b2 for normal samples", Biometrika, vol. 70, pp. 227-234, 1983.
  1390. Examples
  1391. --------
  1392. >>> import numpy as np
  1393. >>> from scipy.stats import kurtosistest
  1394. >>> kurtosistest(list(range(20)))
  1395. KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.08804338332528348)
  1396. >>> kurtosistest(list(range(20)), alternative='less')
  1397. KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.04402169166264174)
  1398. >>> kurtosistest(list(range(20)), alternative='greater')
  1399. KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.9559783083373583)
  1400. >>> rng = np.random.default_rng()
  1401. >>> s = rng.normal(0, 1, 1000)
  1402. >>> kurtosistest(s)
  1403. KurtosistestResult(statistic=-1.475047944490622, pvalue=0.14019965402996987)
  1404. """
  1405. a, axis = _chk_asarray(a, axis)
  1406. contains_nan, nan_policy = _contains_nan(a, nan_policy)
  1407. if contains_nan and nan_policy == 'omit':
  1408. a = ma.masked_invalid(a)
  1409. return mstats_basic.kurtosistest(a, axis, alternative)
  1410. n = a.shape[axis]
  1411. if n < 5:
  1412. raise ValueError(
  1413. "kurtosistest requires at least 5 observations; %i observations"
  1414. " were given." % int(n))
  1415. if n < 20:
  1416. warnings.warn("kurtosistest only valid for n>=20 ... continuing "
  1417. "anyway, n=%i" % int(n))
  1418. b2 = kurtosis(a, axis, fisher=False)
  1419. E = 3.0*(n-1) / (n+1)
  1420. varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5)) # [1]_ Eq. 1
  1421. x = (b2-E) / np.sqrt(varb2) # [1]_ Eq. 4
  1422. # [1]_ Eq. 2:
  1423. sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * np.sqrt((6.0*(n+3)*(n+5)) /
  1424. (n*(n-2)*(n-3)))
  1425. # [1]_ Eq. 3:
  1426. A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + np.sqrt(1+4.0/(sqrtbeta1**2)))
  1427. term1 = 1 - 2/(9.0*A)
  1428. denom = 1 + x*np.sqrt(2/(A-4.0))
  1429. term2 = np.sign(denom) * np.where(denom == 0.0, np.nan,
  1430. np.power((1-2.0/A)/np.abs(denom), 1/3.0))
  1431. if np.any(denom == 0):
  1432. msg = "Test statistic not defined in some cases due to division by " \
  1433. "zero. Return nan in that case..."
  1434. warnings.warn(msg, RuntimeWarning)
  1435. Z = (term1 - term2) / np.sqrt(2/(9.0*A)) # [1]_ Eq. 5
  1436. # zprob uses upper tail, so Z needs to be positive
  1437. return KurtosistestResult(*_normtest_finish(Z, alternative))
  1438. NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue'))
  1439. def normaltest(a, axis=0, nan_policy='propagate'):
  1440. """Test whether a sample differs from a normal distribution.
  1441. This function tests the null hypothesis that a sample comes
  1442. from a normal distribution. It is based on D'Agostino and
  1443. Pearson's [1]_, [2]_ test that combines skew and kurtosis to
  1444. produce an omnibus test of normality.
  1445. Parameters
  1446. ----------
  1447. a : array_like
  1448. The array containing the sample to be tested.
  1449. axis : int or None, optional
  1450. Axis along which to compute test. Default is 0. If None,
  1451. compute over the whole array `a`.
  1452. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1453. Defines how to handle when input contains nan.
  1454. The following options are available (default is 'propagate'):
  1455. * 'propagate': returns nan
  1456. * 'raise': throws an error
  1457. * 'omit': performs the calculations ignoring nan values
  1458. Returns
  1459. -------
  1460. statistic : float or array
  1461. ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and
  1462. ``k`` is the z-score returned by `kurtosistest`.
  1463. pvalue : float or array
  1464. A 2-sided chi squared probability for the hypothesis test.
  1465. References
  1466. ----------
  1467. .. [1] D'Agostino, R. B. (1971), "An omnibus test of normality for
  1468. moderate and large sample size", Biometrika, 58, 341-348
  1469. .. [2] D'Agostino, R. and Pearson, E. S. (1973), "Tests for departure from
  1470. normality", Biometrika, 60, 613-622
  1471. Examples
  1472. --------
  1473. >>> import numpy as np
  1474. >>> from scipy import stats
  1475. >>> rng = np.random.default_rng()
  1476. >>> pts = 1000
  1477. >>> a = rng.normal(0, 1, size=pts)
  1478. >>> b = rng.normal(2, 1, size=pts)
  1479. >>> x = np.concatenate((a, b))
  1480. >>> k2, p = stats.normaltest(x)
  1481. >>> alpha = 1e-3
  1482. >>> print("p = {:g}".format(p))
  1483. p = 8.4713e-19
  1484. >>> if p < alpha: # null hypothesis: x comes from a normal distribution
  1485. ... print("The null hypothesis can be rejected")
  1486. ... else:
  1487. ... print("The null hypothesis cannot be rejected")
  1488. The null hypothesis can be rejected
  1489. """
  1490. a, axis = _chk_asarray(a, axis)
  1491. contains_nan, nan_policy = _contains_nan(a, nan_policy)
  1492. if contains_nan and nan_policy == 'omit':
  1493. a = ma.masked_invalid(a)
  1494. return mstats_basic.normaltest(a, axis)
  1495. s, _ = skewtest(a, axis)
  1496. k, _ = kurtosistest(a, axis)
  1497. k2 = s*s + k*k
  1498. return NormaltestResult(k2, distributions.chi2.sf(k2, 2))
  1499. @_axis_nan_policy_factory(SignificanceResult, default_axis=None)
  1500. def jarque_bera(x, *, axis=None):
  1501. """Perform the Jarque-Bera goodness of fit test on sample data.
  1502. The Jarque-Bera test tests whether the sample data has the skewness and
  1503. kurtosis matching a normal distribution.
  1504. Note that this test only works for a large enough number of data samples
  1505. (>2000) as the test statistic asymptotically has a Chi-squared distribution
  1506. with 2 degrees of freedom.
  1507. Parameters
  1508. ----------
  1509. x : array_like
  1510. Observations of a random variable.
  1511. axis : int or None, default: 0
  1512. If an int, the axis of the input along which to compute the statistic.
  1513. The statistic of each axis-slice (e.g. row) of the input will appear in
  1514. a corresponding element of the output.
  1515. If ``None``, the input will be raveled before computing the statistic.
  1516. Returns
  1517. -------
  1518. result : SignificanceResult
  1519. An object with the following attributes:
  1520. statistic : float
  1521. The test statistic.
  1522. pvalue : float
  1523. The p-value for the hypothesis test.
  1524. References
  1525. ----------
  1526. .. [1] Jarque, C. and Bera, A. (1980) "Efficient tests for normality,
  1527. homoscedasticity and serial independence of regression residuals",
  1528. 6 Econometric Letters 255-259.
  1529. Examples
  1530. --------
  1531. >>> import numpy as np
  1532. >>> from scipy import stats
  1533. >>> rng = np.random.default_rng()
  1534. >>> x = rng.normal(0, 1, 100000)
  1535. >>> jarque_bera_test = stats.jarque_bera(x)
  1536. >>> jarque_bera_test
  1537. Jarque_beraResult(statistic=3.3415184718131554, pvalue=0.18810419594996775)
  1538. >>> jarque_bera_test.statistic
  1539. 3.3415184718131554
  1540. >>> jarque_bera_test.pvalue
  1541. 0.18810419594996775
  1542. """
  1543. x = np.asarray(x)
  1544. if axis is None:
  1545. x = x.ravel()
  1546. axis = 0
  1547. n = x.shape[axis]
  1548. if n == 0:
  1549. raise ValueError('At least one observation is required.')
  1550. mu = x.mean(axis=axis, keepdims=True)
  1551. diffx = x - mu
  1552. s = skew(diffx, axis=axis, _no_deco=True)
  1553. k = kurtosis(diffx, axis=axis, _no_deco=True)
  1554. statistic = n / 6 * (s**2 + k**2 / 4)
  1555. pvalue = distributions.chi2.sf(statistic, df=2)
  1556. return SignificanceResult(statistic, pvalue)
  1557. #####################################
  1558. # FREQUENCY FUNCTIONS #
  1559. #####################################
  1560. def scoreatpercentile(a, per, limit=(), interpolation_method='fraction',
  1561. axis=None):
  1562. """Calculate the score at a given percentile of the input sequence.
  1563. For example, the score at `per=50` is the median. If the desired quantile
  1564. lies between two data points, we interpolate between them, according to
  1565. the value of `interpolation`. If the parameter `limit` is provided, it
  1566. should be a tuple (lower, upper) of two values.
  1567. Parameters
  1568. ----------
  1569. a : array_like
  1570. A 1-D array of values from which to extract score.
  1571. per : array_like
  1572. Percentile(s) at which to extract score. Values should be in range
  1573. [0,100].
  1574. limit : tuple, optional
  1575. Tuple of two scalars, the lower and upper limits within which to
  1576. compute the percentile. Values of `a` outside
  1577. this (closed) interval will be ignored.
  1578. interpolation_method : {'fraction', 'lower', 'higher'}, optional
  1579. Specifies the interpolation method to use,
  1580. when the desired quantile lies between two data points `i` and `j`
  1581. The following options are available (default is 'fraction'):
  1582. * 'fraction': ``i + (j - i) * fraction`` where ``fraction`` is the
  1583. fractional part of the index surrounded by ``i`` and ``j``
  1584. * 'lower': ``i``
  1585. * 'higher': ``j``
  1586. axis : int, optional
  1587. Axis along which the percentiles are computed. Default is None. If
  1588. None, compute over the whole array `a`.
  1589. Returns
  1590. -------
  1591. score : float or ndarray
  1592. Score at percentile(s).
  1593. See Also
  1594. --------
  1595. percentileofscore, numpy.percentile
  1596. Notes
  1597. -----
  1598. This function will become obsolete in the future.
  1599. For NumPy 1.9 and higher, `numpy.percentile` provides all the functionality
  1600. that `scoreatpercentile` provides. And it's significantly faster.
  1601. Therefore it's recommended to use `numpy.percentile` for users that have
  1602. numpy >= 1.9.
  1603. Examples
  1604. --------
  1605. >>> import numpy as np
  1606. >>> from scipy import stats
  1607. >>> a = np.arange(100)
  1608. >>> stats.scoreatpercentile(a, 50)
  1609. 49.5
  1610. """
  1611. # adapted from NumPy's percentile function. When we require numpy >= 1.8,
  1612. # the implementation of this function can be replaced by np.percentile.
  1613. a = np.asarray(a)
  1614. if a.size == 0:
  1615. # empty array, return nan(s) with shape matching `per`
  1616. if np.isscalar(per):
  1617. return np.nan
  1618. else:
  1619. return np.full(np.asarray(per).shape, np.nan, dtype=np.float64)
  1620. if limit:
  1621. a = a[(limit[0] <= a) & (a <= limit[1])]
  1622. sorted_ = np.sort(a, axis=axis)
  1623. if axis is None:
  1624. axis = 0
  1625. return _compute_qth_percentile(sorted_, per, interpolation_method, axis)
  1626. # handle sequence of per's without calling sort multiple times
  1627. def _compute_qth_percentile(sorted_, per, interpolation_method, axis):
  1628. if not np.isscalar(per):
  1629. score = [_compute_qth_percentile(sorted_, i,
  1630. interpolation_method, axis)
  1631. for i in per]
  1632. return np.array(score)
  1633. if not (0 <= per <= 100):
  1634. raise ValueError("percentile must be in the range [0, 100]")
  1635. indexer = [slice(None)] * sorted_.ndim
  1636. idx = per / 100. * (sorted_.shape[axis] - 1)
  1637. if int(idx) != idx:
  1638. # round fractional indices according to interpolation method
  1639. if interpolation_method == 'lower':
  1640. idx = int(np.floor(idx))
  1641. elif interpolation_method == 'higher':
  1642. idx = int(np.ceil(idx))
  1643. elif interpolation_method == 'fraction':
  1644. pass # keep idx as fraction and interpolate
  1645. else:
  1646. raise ValueError("interpolation_method can only be 'fraction', "
  1647. "'lower' or 'higher'")
  1648. i = int(idx)
  1649. if i == idx:
  1650. indexer[axis] = slice(i, i + 1)
  1651. weights = array(1)
  1652. sumval = 1.0
  1653. else:
  1654. indexer[axis] = slice(i, i + 2)
  1655. j = i + 1
  1656. weights = array([(j - idx), (idx - i)], float)
  1657. wshape = [1] * sorted_.ndim
  1658. wshape[axis] = 2
  1659. weights.shape = wshape
  1660. sumval = weights.sum()
  1661. # Use np.add.reduce (== np.sum but a little faster) to coerce data type
  1662. return np.add.reduce(sorted_[tuple(indexer)] * weights, axis=axis) / sumval
  1663. def percentileofscore(a, score, kind='rank', nan_policy='propagate'):
  1664. """Compute the percentile rank of a score relative to a list of scores.
  1665. A `percentileofscore` of, for example, 80% means that 80% of the
  1666. scores in `a` are below the given score. In the case of gaps or
  1667. ties, the exact definition depends on the optional keyword, `kind`.
  1668. Parameters
  1669. ----------
  1670. a : array_like
  1671. Array to which `score` is compared.
  1672. score : array_like
  1673. Scores to compute percentiles for.
  1674. kind : {'rank', 'weak', 'strict', 'mean'}, optional
  1675. Specifies the interpretation of the resulting score.
  1676. The following options are available (default is 'rank'):
  1677. * 'rank': Average percentage ranking of score. In case of multiple
  1678. matches, average the percentage rankings of all matching scores.
  1679. * 'weak': This kind corresponds to the definition of a cumulative
  1680. distribution function. A percentileofscore of 80% means that 80%
  1681. of values are less than or equal to the provided score.
  1682. * 'strict': Similar to "weak", except that only values that are
  1683. strictly less than the given score are counted.
  1684. * 'mean': The average of the "weak" and "strict" scores, often used
  1685. in testing. See https://en.wikipedia.org/wiki/Percentile_rank
  1686. nan_policy : {'propagate', 'raise', 'omit'}, optional
  1687. Specifies how to treat `nan` values in `a`.
  1688. The following options are available (default is 'propagate'):
  1689. * 'propagate': returns nan (for each value in `score`).
  1690. * 'raise': throws an error
  1691. * 'omit': performs the calculations ignoring nan values
  1692. Returns
  1693. -------
  1694. pcos : float
  1695. Percentile-position of score (0-100) relative to `a`.
  1696. See Also
  1697. --------
  1698. numpy.percentile
  1699. scipy.stats.scoreatpercentile, scipy.stats.rankdata
  1700. Examples
  1701. --------
  1702. Three-quarters of the given values lie below a given score:
  1703. >>> import numpy as np
  1704. >>> from scipy import stats
  1705. >>> stats.percentileofscore([1, 2, 3, 4], 3)
  1706. 75.0
  1707. With multiple matches, note how the scores of the two matches, 0.6
  1708. and 0.8 respectively, are averaged:
  1709. >>> stats.percentileofscore([1, 2, 3, 3, 4], 3)
  1710. 70.0
  1711. Only 2/5 values are strictly less than 3:
  1712. >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='strict')
  1713. 40.0
  1714. But 4/5 values are less than or equal to 3:
  1715. >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='weak')
  1716. 80.0
  1717. The average between the weak and the strict scores is:
  1718. >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='mean')
  1719. 60.0
  1720. Score arrays (of any dimensionality) are supported:
  1721. >>> stats.percentileofscore([1, 2, 3, 3, 4], [2, 3])
  1722. array([40., 70.])
  1723. The inputs can be infinite:
  1724. >>> stats.percentileofscore([-np.inf, 0, 1, np.inf], [1, 2, np.inf])
  1725. array([75., 75., 100.])
  1726. If `a` is empty, then the resulting percentiles are all `nan`:
  1727. >>> stats.percentileofscore([], [1, 2])
  1728. array([nan, nan])
  1729. """
  1730. a = np.asarray(a)
  1731. n = len(a)
  1732. score = np.asarray(score)
  1733. # Nan treatment
  1734. cna, npa = _contains_nan(a, nan_policy, use_summation=False)
  1735. cns, nps = _contains_nan(score, nan_policy, use_summation=False)
  1736. if (cna or cns) and nan_policy == 'raise':
  1737. raise ValueError("The input contains nan values")
  1738. if cns:
  1739. # If a score is nan, then the output should be nan
  1740. # (also if nan_policy is "omit", because it only applies to `a`)
  1741. score = ma.masked_where(np.isnan(score), score)
  1742. if cna:
  1743. if nan_policy == "omit":
  1744. # Don't count nans
  1745. a = ma.masked_where(np.isnan(a), a)
  1746. n = a.count()
  1747. if nan_policy == "propagate":
  1748. # All outputs should be nans
  1749. n = 0
  1750. # Cannot compare to empty list ==> nan
  1751. if n == 0:
  1752. perct = np.full_like(score, np.nan, dtype=np.float64)
  1753. else:
  1754. # Prepare broadcasting
  1755. score = score[..., None]
  1756. def count(x):
  1757. return np.count_nonzero(x, -1)
  1758. # Despite using masked_array to omit nan values from processing,
  1759. # the CI tests on "Azure pipelines" (but not on the other CI servers)
  1760. # emits warnings when there are nan values, contrarily to the purpose
  1761. # of masked_arrays. As a fix, we simply suppress the warnings.
  1762. with suppress_warnings() as sup:
  1763. sup.filter(RuntimeWarning,
  1764. "invalid value encountered in less")
  1765. sup.filter(RuntimeWarning,
  1766. "invalid value encountered in greater")
  1767. # Main computations/logic
  1768. if kind == 'rank':
  1769. left = count(a < score)
  1770. right = count(a <= score)
  1771. plus1 = left < right
  1772. perct = (left + right + plus1) * (50.0 / n)
  1773. elif kind == 'strict':
  1774. perct = count(a < score) * (100.0 / n)
  1775. elif kind == 'weak':
  1776. perct = count(a <= score) * (100.0 / n)
  1777. elif kind == 'mean':
  1778. left = count(a < score)
  1779. right = count(a <= score)
  1780. perct = (left + right) * (50.0 / n)
  1781. else:
  1782. raise ValueError(
  1783. "kind can only be 'rank', 'strict', 'weak' or 'mean'")
  1784. # Re-insert nan values
  1785. perct = ma.filled(perct, np.nan)
  1786. if perct.ndim == 0:
  1787. return perct[()]
  1788. return perct
  1789. HistogramResult = namedtuple('HistogramResult',
  1790. ('count', 'lowerlimit', 'binsize', 'extrapoints'))
  1791. def _histogram(a, numbins=10, defaultlimits=None, weights=None,
  1792. printextras=False):
  1793. """Create a histogram.
  1794. Separate the range into several bins and return the number of instances
  1795. in each bin.
  1796. Parameters
  1797. ----------
  1798. a : array_like
  1799. Array of scores which will be put into bins.
  1800. numbins : int, optional
  1801. The number of bins to use for the histogram. Default is 10.
  1802. defaultlimits : tuple (lower, upper), optional
  1803. The lower and upper values for the range of the histogram.
  1804. If no value is given, a range slightly larger than the range of the
  1805. values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
  1806. where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
  1807. weights : array_like, optional
  1808. The weights for each value in `a`. Default is None, which gives each
  1809. value a weight of 1.0
  1810. printextras : bool, optional
  1811. If True, if there are extra points (i.e. the points that fall outside
  1812. the bin limits) a warning is raised saying how many of those points
  1813. there are. Default is False.
  1814. Returns
  1815. -------
  1816. count : ndarray
  1817. Number of points (or sum of weights) in each bin.
  1818. lowerlimit : float
  1819. Lowest value of histogram, the lower limit of the first bin.
  1820. binsize : float
  1821. The size of the bins (all bins have the same size).
  1822. extrapoints : int
  1823. The number of points outside the range of the histogram.
  1824. See Also
  1825. --------
  1826. numpy.histogram
  1827. Notes
  1828. -----
  1829. This histogram is based on numpy's histogram but has a larger range by
  1830. default if default limits is not set.
  1831. """
  1832. a = np.ravel(a)
  1833. if defaultlimits is None:
  1834. if a.size == 0:
  1835. # handle empty arrays. Undetermined range, so use 0-1.
  1836. defaultlimits = (0, 1)
  1837. else:
  1838. # no range given, so use values in `a`
  1839. data_min = a.min()
  1840. data_max = a.max()
  1841. # Have bins extend past min and max values slightly
  1842. s = (data_max - data_min) / (2. * (numbins - 1.))
  1843. defaultlimits = (data_min - s, data_max + s)
  1844. # use numpy's histogram method to compute bins
  1845. hist, bin_edges = np.histogram(a, bins=numbins, range=defaultlimits,
  1846. weights=weights)
  1847. # hist are not always floats, convert to keep with old output
  1848. hist = np.array(hist, dtype=float)
  1849. # fixed width for bins is assumed, as numpy's histogram gives
  1850. # fixed width bins for int values for 'bins'
  1851. binsize = bin_edges[1] - bin_edges[0]
  1852. # calculate number of extra points
  1853. extrapoints = len([v for v in a
  1854. if defaultlimits[0] > v or v > defaultlimits[1]])
  1855. if extrapoints > 0 and printextras:
  1856. warnings.warn("Points outside given histogram range = %s"
  1857. % extrapoints)
  1858. return HistogramResult(hist, defaultlimits[0], binsize, extrapoints)
  1859. CumfreqResult = namedtuple('CumfreqResult',
  1860. ('cumcount', 'lowerlimit', 'binsize',
  1861. 'extrapoints'))
  1862. def cumfreq(a, numbins=10, defaultreallimits=None, weights=None):
  1863. """Return a cumulative frequency histogram, using the histogram function.
  1864. A cumulative histogram is a mapping that counts the cumulative number of
  1865. observations in all of the bins up to the specified bin.
  1866. Parameters
  1867. ----------
  1868. a : array_like
  1869. Input array.
  1870. numbins : int, optional
  1871. The number of bins to use for the histogram. Default is 10.
  1872. defaultreallimits : tuple (lower, upper), optional
  1873. The lower and upper values for the range of the histogram.
  1874. If no value is given, a range slightly larger than the range of the
  1875. values in `a` is used. Specifically ``(a.min() - s, a.max() + s)``,
  1876. where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
  1877. weights : array_like, optional
  1878. The weights for each value in `a`. Default is None, which gives each
  1879. value a weight of 1.0
  1880. Returns
  1881. -------
  1882. cumcount : ndarray
  1883. Binned values of cumulative frequency.
  1884. lowerlimit : float
  1885. Lower real limit
  1886. binsize : float
  1887. Width of each bin.
  1888. extrapoints : int
  1889. Extra points.
  1890. Examples
  1891. --------
  1892. >>> import numpy as np
  1893. >>> import matplotlib.pyplot as plt
  1894. >>> from scipy import stats
  1895. >>> rng = np.random.default_rng()
  1896. >>> x = [1, 4, 2, 1, 3, 1]
  1897. >>> res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5))
  1898. >>> res.cumcount
  1899. array([ 1., 2., 3., 3.])
  1900. >>> res.extrapoints
  1901. 3
  1902. Create a normal distribution with 1000 random values
  1903. >>> samples = stats.norm.rvs(size=1000, random_state=rng)
  1904. Calculate cumulative frequencies
  1905. >>> res = stats.cumfreq(samples, numbins=25)
  1906. Calculate space of values for x
  1907. >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.cumcount.size,
  1908. ... res.cumcount.size)
  1909. Plot histogram and cumulative histogram
  1910. >>> fig = plt.figure(figsize=(10, 4))
  1911. >>> ax1 = fig.add_subplot(1, 2, 1)
  1912. >>> ax2 = fig.add_subplot(1, 2, 2)
  1913. >>> ax1.hist(samples, bins=25)
  1914. >>> ax1.set_title('Histogram')
  1915. >>> ax2.bar(x, res.cumcount, width=res.binsize)
  1916. >>> ax2.set_title('Cumulative histogram')
  1917. >>> ax2.set_xlim([x.min(), x.max()])
  1918. >>> plt.show()
  1919. """
  1920. h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
  1921. cumhist = np.cumsum(h * 1, axis=0)
  1922. return CumfreqResult(cumhist, l, b, e)
  1923. RelfreqResult = namedtuple('RelfreqResult',
  1924. ('frequency', 'lowerlimit', 'binsize',
  1925. 'extrapoints'))
  1926. def relfreq(a, numbins=10, defaultreallimits=None, weights=None):
  1927. """Return a relative frequency histogram, using the histogram function.
  1928. A relative frequency histogram is a mapping of the number of
  1929. observations in each of the bins relative to the total of observations.
  1930. Parameters
  1931. ----------
  1932. a : array_like
  1933. Input array.
  1934. numbins : int, optional
  1935. The number of bins to use for the histogram. Default is 10.
  1936. defaultreallimits : tuple (lower, upper), optional
  1937. The lower and upper values for the range of the histogram.
  1938. If no value is given, a range slightly larger than the range of the
  1939. values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
  1940. where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
  1941. weights : array_like, optional
  1942. The weights for each value in `a`. Default is None, which gives each
  1943. value a weight of 1.0
  1944. Returns
  1945. -------
  1946. frequency : ndarray
  1947. Binned values of relative frequency.
  1948. lowerlimit : float
  1949. Lower real limit.
  1950. binsize : float
  1951. Width of each bin.
  1952. extrapoints : int
  1953. Extra points.
  1954. Examples
  1955. --------
  1956. >>> import numpy as np
  1957. >>> import matplotlib.pyplot as plt
  1958. >>> from scipy import stats
  1959. >>> rng = np.random.default_rng()
  1960. >>> a = np.array([2, 4, 1, 2, 3, 2])
  1961. >>> res = stats.relfreq(a, numbins=4)
  1962. >>> res.frequency
  1963. array([ 0.16666667, 0.5 , 0.16666667, 0.16666667])
  1964. >>> np.sum(res.frequency) # relative frequencies should add up to 1
  1965. 1.0
  1966. Create a normal distribution with 1000 random values
  1967. >>> samples = stats.norm.rvs(size=1000, random_state=rng)
  1968. Calculate relative frequencies
  1969. >>> res = stats.relfreq(samples, numbins=25)
  1970. Calculate space of values for x
  1971. >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size,
  1972. ... res.frequency.size)
  1973. Plot relative frequency histogram
  1974. >>> fig = plt.figure(figsize=(5, 4))
  1975. >>> ax = fig.add_subplot(1, 1, 1)
  1976. >>> ax.bar(x, res.frequency, width=res.binsize)
  1977. >>> ax.set_title('Relative frequency histogram')
  1978. >>> ax.set_xlim([x.min(), x.max()])
  1979. >>> plt.show()
  1980. """
  1981. a = np.asanyarray(a)
  1982. h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
  1983. h = h / a.shape[0]
  1984. return RelfreqResult(h, l, b, e)
  1985. #####################################
  1986. # VARIABILITY FUNCTIONS #
  1987. #####################################
  1988. def obrientransform(*samples):
  1989. """Compute the O'Brien transform on input data (any number of arrays).
  1990. Used to test for homogeneity of variance prior to running one-way stats.
  1991. Each array in ``*samples`` is one level of a factor.
  1992. If `f_oneway` is run on the transformed data and found significant,
  1993. the variances are unequal. From Maxwell and Delaney [1]_, p.112.
  1994. Parameters
  1995. ----------
  1996. sample1, sample2, ... : array_like
  1997. Any number of arrays.
  1998. Returns
  1999. -------
  2000. obrientransform : ndarray
  2001. Transformed data for use in an ANOVA. The first dimension
  2002. of the result corresponds to the sequence of transformed
  2003. arrays. If the arrays given are all 1-D of the same length,
  2004. the return value is a 2-D array; otherwise it is a 1-D array
  2005. of type object, with each element being an ndarray.
  2006. References
  2007. ----------
  2008. .. [1] S. E. Maxwell and H. D. Delaney, "Designing Experiments and
  2009. Analyzing Data: A Model Comparison Perspective", Wadsworth, 1990.
  2010. Examples
  2011. --------
  2012. We'll test the following data sets for differences in their variance.
  2013. >>> x = [10, 11, 13, 9, 7, 12, 12, 9, 10]
  2014. >>> y = [13, 21, 5, 10, 8, 14, 10, 12, 7, 15]
  2015. Apply the O'Brien transform to the data.
  2016. >>> from scipy.stats import obrientransform
  2017. >>> tx, ty = obrientransform(x, y)
  2018. Use `scipy.stats.f_oneway` to apply a one-way ANOVA test to the
  2019. transformed data.
  2020. >>> from scipy.stats import f_oneway
  2021. >>> F, p = f_oneway(tx, ty)
  2022. >>> p
  2023. 0.1314139477040335
  2024. If we require that ``p < 0.05`` for significance, we cannot conclude
  2025. that the variances are different.
  2026. """
  2027. TINY = np.sqrt(np.finfo(float).eps)
  2028. # `arrays` will hold the transformed arguments.
  2029. arrays = []
  2030. sLast = None
  2031. for sample in samples:
  2032. a = np.asarray(sample)
  2033. n = len(a)
  2034. mu = np.mean(a)
  2035. sq = (a - mu)**2
  2036. sumsq = sq.sum()
  2037. # The O'Brien transform.
  2038. t = ((n - 1.5) * n * sq - 0.5 * sumsq) / ((n - 1) * (n - 2))
  2039. # Check that the mean of the transformed data is equal to the
  2040. # original variance.
  2041. var = sumsq / (n - 1)
  2042. if abs(var - np.mean(t)) > TINY:
  2043. raise ValueError('Lack of convergence in obrientransform.')
  2044. arrays.append(t)
  2045. sLast = a.shape
  2046. if sLast:
  2047. for arr in arrays[:-1]:
  2048. if sLast != arr.shape:
  2049. return np.array(arrays, dtype=object)
  2050. return np.array(arrays)
  2051. def sem(a, axis=0, ddof=1, nan_policy='propagate'):
  2052. """Compute standard error of the mean.
  2053. Calculate the standard error of the mean (or standard error of
  2054. measurement) of the values in the input array.
  2055. Parameters
  2056. ----------
  2057. a : array_like
  2058. An array containing the values for which the standard error is
  2059. returned.
  2060. axis : int or None, optional
  2061. Axis along which to operate. Default is 0. If None, compute over
  2062. the whole array `a`.
  2063. ddof : int, optional
  2064. Delta degrees-of-freedom. How many degrees of freedom to adjust
  2065. for bias in limited samples relative to the population estimate
  2066. of variance. Defaults to 1.
  2067. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2068. Defines how to handle when input contains nan.
  2069. The following options are available (default is 'propagate'):
  2070. * 'propagate': returns nan
  2071. * 'raise': throws an error
  2072. * 'omit': performs the calculations ignoring nan values
  2073. Returns
  2074. -------
  2075. s : ndarray or float
  2076. The standard error of the mean in the sample(s), along the input axis.
  2077. Notes
  2078. -----
  2079. The default value for `ddof` is different to the default (0) used by other
  2080. ddof containing routines, such as np.std and np.nanstd.
  2081. Examples
  2082. --------
  2083. Find standard error along the first axis:
  2084. >>> import numpy as np
  2085. >>> from scipy import stats
  2086. >>> a = np.arange(20).reshape(5,4)
  2087. >>> stats.sem(a)
  2088. array([ 2.8284, 2.8284, 2.8284, 2.8284])
  2089. Find standard error across the whole array, using n degrees of freedom:
  2090. >>> stats.sem(a, axis=None, ddof=0)
  2091. 1.2893796958227628
  2092. """
  2093. a, axis = _chk_asarray(a, axis)
  2094. contains_nan, nan_policy = _contains_nan(a, nan_policy)
  2095. if contains_nan and nan_policy == 'omit':
  2096. a = ma.masked_invalid(a)
  2097. return mstats_basic.sem(a, axis, ddof)
  2098. n = a.shape[axis]
  2099. s = np.std(a, axis=axis, ddof=ddof) / np.sqrt(n)
  2100. return s
  2101. def _isconst(x):
  2102. """
  2103. Check if all values in x are the same. nans are ignored.
  2104. x must be a 1d array.
  2105. The return value is a 1d array with length 1, so it can be used
  2106. in np.apply_along_axis.
  2107. """
  2108. y = x[~np.isnan(x)]
  2109. if y.size == 0:
  2110. return np.array([True])
  2111. else:
  2112. return (y[0] == y).all(keepdims=True)
  2113. def _quiet_nanmean(x):
  2114. """
  2115. Compute nanmean for the 1d array x, but quietly return nan if x is all nan.
  2116. The return value is a 1d array with length 1, so it can be used
  2117. in np.apply_along_axis.
  2118. """
  2119. y = x[~np.isnan(x)]
  2120. if y.size == 0:
  2121. return np.array([np.nan])
  2122. else:
  2123. return np.mean(y, keepdims=True)
  2124. def _quiet_nanstd(x, ddof=0):
  2125. """
  2126. Compute nanstd for the 1d array x, but quietly return nan if x is all nan.
  2127. The return value is a 1d array with length 1, so it can be used
  2128. in np.apply_along_axis.
  2129. """
  2130. y = x[~np.isnan(x)]
  2131. if y.size == 0:
  2132. return np.array([np.nan])
  2133. else:
  2134. return np.std(y, keepdims=True, ddof=ddof)
  2135. def zscore(a, axis=0, ddof=0, nan_policy='propagate'):
  2136. """
  2137. Compute the z score.
  2138. Compute the z score of each value in the sample, relative to the
  2139. sample mean and standard deviation.
  2140. Parameters
  2141. ----------
  2142. a : array_like
  2143. An array like object containing the sample data.
  2144. axis : int or None, optional
  2145. Axis along which to operate. Default is 0. If None, compute over
  2146. the whole array `a`.
  2147. ddof : int, optional
  2148. Degrees of freedom correction in the calculation of the
  2149. standard deviation. Default is 0.
  2150. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2151. Defines how to handle when input contains nan. 'propagate' returns nan,
  2152. 'raise' throws an error, 'omit' performs the calculations ignoring nan
  2153. values. Default is 'propagate'. Note that when the value is 'omit',
  2154. nans in the input also propagate to the output, but they do not affect
  2155. the z-scores computed for the non-nan values.
  2156. Returns
  2157. -------
  2158. zscore : array_like
  2159. The z-scores, standardized by mean and standard deviation of
  2160. input array `a`.
  2161. Notes
  2162. -----
  2163. This function preserves ndarray subclasses, and works also with
  2164. matrices and masked arrays (it uses `asanyarray` instead of
  2165. `asarray` for parameters).
  2166. Examples
  2167. --------
  2168. >>> import numpy as np
  2169. >>> a = np.array([ 0.7972, 0.0767, 0.4383, 0.7866, 0.8091,
  2170. ... 0.1954, 0.6307, 0.6599, 0.1065, 0.0508])
  2171. >>> from scipy import stats
  2172. >>> stats.zscore(a)
  2173. array([ 1.1273, -1.247 , -0.0552, 1.0923, 1.1664, -0.8559, 0.5786,
  2174. 0.6748, -1.1488, -1.3324])
  2175. Computing along a specified axis, using n-1 degrees of freedom
  2176. (``ddof=1``) to calculate the standard deviation:
  2177. >>> b = np.array([[ 0.3148, 0.0478, 0.6243, 0.4608],
  2178. ... [ 0.7149, 0.0775, 0.6072, 0.9656],
  2179. ... [ 0.6341, 0.1403, 0.9759, 0.4064],
  2180. ... [ 0.5918, 0.6948, 0.904 , 0.3721],
  2181. ... [ 0.0921, 0.2481, 0.1188, 0.1366]])
  2182. >>> stats.zscore(b, axis=1, ddof=1)
  2183. array([[-0.19264823, -1.28415119, 1.07259584, 0.40420358],
  2184. [ 0.33048416, -1.37380874, 0.04251374, 1.00081084],
  2185. [ 0.26796377, -1.12598418, 1.23283094, -0.37481053],
  2186. [-0.22095197, 0.24468594, 1.19042819, -1.21416216],
  2187. [-0.82780366, 1.4457416 , -0.43867764, -0.1792603 ]])
  2188. An example with `nan_policy='omit'`:
  2189. >>> x = np.array([[25.11, 30.10, np.nan, 32.02, 43.15],
  2190. ... [14.95, 16.06, 121.25, 94.35, 29.81]])
  2191. >>> stats.zscore(x, axis=1, nan_policy='omit')
  2192. array([[-1.13490897, -0.37830299, nan, -0.08718406, 1.60039602],
  2193. [-0.91611681, -0.89090508, 1.4983032 , 0.88731639, -0.5785977 ]])
  2194. """
  2195. return zmap(a, a, axis=axis, ddof=ddof, nan_policy=nan_policy)
  2196. def gzscore(a, *, axis=0, ddof=0, nan_policy='propagate'):
  2197. """
  2198. Compute the geometric standard score.
  2199. Compute the geometric z score of each strictly positive value in the
  2200. sample, relative to the geometric mean and standard deviation.
  2201. Mathematically the geometric z score can be evaluated as::
  2202. gzscore = log(a/gmu) / log(gsigma)
  2203. where ``gmu`` (resp. ``gsigma``) is the geometric mean (resp. standard
  2204. deviation).
  2205. Parameters
  2206. ----------
  2207. a : array_like
  2208. Sample data.
  2209. axis : int or None, optional
  2210. Axis along which to operate. Default is 0. If None, compute over
  2211. the whole array `a`.
  2212. ddof : int, optional
  2213. Degrees of freedom correction in the calculation of the
  2214. standard deviation. Default is 0.
  2215. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2216. Defines how to handle when input contains nan. 'propagate' returns nan,
  2217. 'raise' throws an error, 'omit' performs the calculations ignoring nan
  2218. values. Default is 'propagate'. Note that when the value is 'omit',
  2219. nans in the input also propagate to the output, but they do not affect
  2220. the geometric z scores computed for the non-nan values.
  2221. Returns
  2222. -------
  2223. gzscore : array_like
  2224. The geometric z scores, standardized by geometric mean and geometric
  2225. standard deviation of input array `a`.
  2226. See Also
  2227. --------
  2228. gmean : Geometric mean
  2229. gstd : Geometric standard deviation
  2230. zscore : Standard score
  2231. Notes
  2232. -----
  2233. This function preserves ndarray subclasses, and works also with
  2234. matrices and masked arrays (it uses ``asanyarray`` instead of
  2235. ``asarray`` for parameters).
  2236. .. versionadded:: 1.8
  2237. Examples
  2238. --------
  2239. Draw samples from a log-normal distribution:
  2240. >>> import numpy as np
  2241. >>> from scipy.stats import zscore, gzscore
  2242. >>> import matplotlib.pyplot as plt
  2243. >>> rng = np.random.default_rng()
  2244. >>> mu, sigma = 3., 1. # mean and standard deviation
  2245. >>> x = rng.lognormal(mu, sigma, size=500)
  2246. Display the histogram of the samples:
  2247. >>> fig, ax = plt.subplots()
  2248. >>> ax.hist(x, 50)
  2249. >>> plt.show()
  2250. Display the histogram of the samples standardized by the classical zscore.
  2251. Distribution is rescaled but its shape is unchanged.
  2252. >>> fig, ax = plt.subplots()
  2253. >>> ax.hist(zscore(x), 50)
  2254. >>> plt.show()
  2255. Demonstrate that the distribution of geometric zscores is rescaled and
  2256. quasinormal:
  2257. >>> fig, ax = plt.subplots()
  2258. >>> ax.hist(gzscore(x), 50)
  2259. >>> plt.show()
  2260. """
  2261. a = np.asanyarray(a)
  2262. log = ma.log if isinstance(a, ma.MaskedArray) else np.log
  2263. return zscore(log(a), axis=axis, ddof=ddof, nan_policy=nan_policy)
  2264. def zmap(scores, compare, axis=0, ddof=0, nan_policy='propagate'):
  2265. """
  2266. Calculate the relative z-scores.
  2267. Return an array of z-scores, i.e., scores that are standardized to
  2268. zero mean and unit variance, where mean and variance are calculated
  2269. from the comparison array.
  2270. Parameters
  2271. ----------
  2272. scores : array_like
  2273. The input for which z-scores are calculated.
  2274. compare : array_like
  2275. The input from which the mean and standard deviation of the
  2276. normalization are taken; assumed to have the same dimension as
  2277. `scores`.
  2278. axis : int or None, optional
  2279. Axis over which mean and variance of `compare` are calculated.
  2280. Default is 0. If None, compute over the whole array `scores`.
  2281. ddof : int, optional
  2282. Degrees of freedom correction in the calculation of the
  2283. standard deviation. Default is 0.
  2284. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2285. Defines how to handle the occurrence of nans in `compare`.
  2286. 'propagate' returns nan, 'raise' raises an exception, 'omit'
  2287. performs the calculations ignoring nan values. Default is
  2288. 'propagate'. Note that when the value is 'omit', nans in `scores`
  2289. also propagate to the output, but they do not affect the z-scores
  2290. computed for the non-nan values.
  2291. Returns
  2292. -------
  2293. zscore : array_like
  2294. Z-scores, in the same shape as `scores`.
  2295. Notes
  2296. -----
  2297. This function preserves ndarray subclasses, and works also with
  2298. matrices and masked arrays (it uses `asanyarray` instead of
  2299. `asarray` for parameters).
  2300. Examples
  2301. --------
  2302. >>> from scipy.stats import zmap
  2303. >>> a = [0.5, 2.0, 2.5, 3]
  2304. >>> b = [0, 1, 2, 3, 4]
  2305. >>> zmap(a, b)
  2306. array([-1.06066017, 0. , 0.35355339, 0.70710678])
  2307. """
  2308. a = np.asanyarray(compare)
  2309. if a.size == 0:
  2310. return np.empty(a.shape)
  2311. contains_nan, nan_policy = _contains_nan(a, nan_policy)
  2312. if contains_nan and nan_policy == 'omit':
  2313. if axis is None:
  2314. mn = _quiet_nanmean(a.ravel())
  2315. std = _quiet_nanstd(a.ravel(), ddof=ddof)
  2316. isconst = _isconst(a.ravel())
  2317. else:
  2318. mn = np.apply_along_axis(_quiet_nanmean, axis, a)
  2319. std = np.apply_along_axis(_quiet_nanstd, axis, a, ddof=ddof)
  2320. isconst = np.apply_along_axis(_isconst, axis, a)
  2321. else:
  2322. mn = a.mean(axis=axis, keepdims=True)
  2323. std = a.std(axis=axis, ddof=ddof, keepdims=True)
  2324. if axis is None:
  2325. isconst = (a.item(0) == a).all()
  2326. else:
  2327. isconst = (_first(a, axis) == a).all(axis=axis, keepdims=True)
  2328. # Set std deviations that are 0 to 1 to avoid division by 0.
  2329. std[isconst] = 1.0
  2330. z = (scores - mn) / std
  2331. # Set the outputs associated with a constant input to nan.
  2332. z[np.broadcast_to(isconst, z.shape)] = np.nan
  2333. return z
  2334. def gstd(a, axis=0, ddof=1):
  2335. """
  2336. Calculate the geometric standard deviation of an array.
  2337. The geometric standard deviation describes the spread of a set of numbers
  2338. where the geometric mean is preferred. It is a multiplicative factor, and
  2339. so a dimensionless quantity.
  2340. It is defined as the exponent of the standard deviation of ``log(a)``.
  2341. Mathematically the population geometric standard deviation can be
  2342. evaluated as::
  2343. gstd = exp(std(log(a)))
  2344. .. versionadded:: 1.3.0
  2345. Parameters
  2346. ----------
  2347. a : array_like
  2348. An array like object containing the sample data.
  2349. axis : int, tuple or None, optional
  2350. Axis along which to operate. Default is 0. If None, compute over
  2351. the whole array `a`.
  2352. ddof : int, optional
  2353. Degree of freedom correction in the calculation of the
  2354. geometric standard deviation. Default is 1.
  2355. Returns
  2356. -------
  2357. ndarray or float
  2358. An array of the geometric standard deviation. If `axis` is None or `a`
  2359. is a 1d array a float is returned.
  2360. See Also
  2361. --------
  2362. gmean : Geometric mean
  2363. numpy.std : Standard deviation
  2364. Notes
  2365. -----
  2366. As the calculation requires the use of logarithms the geometric standard
  2367. deviation only supports strictly positive values. Any non-positive or
  2368. infinite values will raise a `ValueError`.
  2369. The geometric standard deviation is sometimes confused with the exponent of
  2370. the standard deviation, ``exp(std(a))``. Instead the geometric standard
  2371. deviation is ``exp(std(log(a)))``.
  2372. The default value for `ddof` is different to the default value (0) used
  2373. by other ddof containing functions, such as ``np.std`` and ``np.nanstd``.
  2374. References
  2375. ----------
  2376. .. [1] Kirkwood, T. B., "Geometric means and measures of dispersion",
  2377. Biometrics, vol. 35, pp. 908-909, 1979
  2378. Examples
  2379. --------
  2380. Find the geometric standard deviation of a log-normally distributed sample.
  2381. Note that the standard deviation of the distribution is one, on a
  2382. log scale this evaluates to approximately ``exp(1)``.
  2383. >>> import numpy as np
  2384. >>> from scipy.stats import gstd
  2385. >>> rng = np.random.default_rng()
  2386. >>> sample = rng.lognormal(mean=0, sigma=1, size=1000)
  2387. >>> gstd(sample)
  2388. 2.810010162475324
  2389. Compute the geometric standard deviation of a multidimensional array and
  2390. of a given axis.
  2391. >>> a = np.arange(1, 25).reshape(2, 3, 4)
  2392. >>> gstd(a, axis=None)
  2393. 2.2944076136018947
  2394. >>> gstd(a, axis=2)
  2395. array([[1.82424757, 1.22436866, 1.13183117],
  2396. [1.09348306, 1.07244798, 1.05914985]])
  2397. >>> gstd(a, axis=(1,2))
  2398. array([2.12939215, 1.22120169])
  2399. The geometric standard deviation further handles masked arrays.
  2400. >>> a = np.arange(1, 25).reshape(2, 3, 4)
  2401. >>> ma = np.ma.masked_where(a > 16, a)
  2402. >>> ma
  2403. masked_array(
  2404. data=[[[1, 2, 3, 4],
  2405. [5, 6, 7, 8],
  2406. [9, 10, 11, 12]],
  2407. [[13, 14, 15, 16],
  2408. [--, --, --, --],
  2409. [--, --, --, --]]],
  2410. mask=[[[False, False, False, False],
  2411. [False, False, False, False],
  2412. [False, False, False, False]],
  2413. [[False, False, False, False],
  2414. [ True, True, True, True],
  2415. [ True, True, True, True]]],
  2416. fill_value=999999)
  2417. >>> gstd(ma, axis=2)
  2418. masked_array(
  2419. data=[[1.8242475707663655, 1.2243686572447428, 1.1318311657788478],
  2420. [1.0934830582350938, --, --]],
  2421. mask=[[False, False, False],
  2422. [False, True, True]],
  2423. fill_value=999999)
  2424. """
  2425. a = np.asanyarray(a)
  2426. log = ma.log if isinstance(a, ma.MaskedArray) else np.log
  2427. try:
  2428. with warnings.catch_warnings():
  2429. warnings.simplefilter("error", RuntimeWarning)
  2430. return np.exp(np.std(log(a), axis=axis, ddof=ddof))
  2431. except RuntimeWarning as w:
  2432. if np.isinf(a).any():
  2433. raise ValueError(
  2434. 'Infinite value encountered. The geometric standard deviation '
  2435. 'is defined for strictly positive values only.'
  2436. ) from w
  2437. a_nan = np.isnan(a)
  2438. a_nan_any = a_nan.any()
  2439. # exclude NaN's from negativity check, but
  2440. # avoid expensive masking for arrays with no NaN
  2441. if ((a_nan_any and np.less_equal(np.nanmin(a), 0)) or
  2442. (not a_nan_any and np.less_equal(a, 0).any())):
  2443. raise ValueError(
  2444. 'Non positive value encountered. The geometric standard '
  2445. 'deviation is defined for strictly positive values only.'
  2446. ) from w
  2447. elif 'Degrees of freedom <= 0 for slice' == str(w):
  2448. raise ValueError(w) from w
  2449. else:
  2450. # Remaining warnings don't need to be exceptions.
  2451. return np.exp(np.std(log(a, where=~a_nan), axis=axis, ddof=ddof))
  2452. except TypeError as e:
  2453. raise ValueError(
  2454. 'Invalid array input. The inputs could not be '
  2455. 'safely coerced to any supported types') from e
  2456. # Private dictionary initialized only once at module level
  2457. # See https://en.wikipedia.org/wiki/Robust_measures_of_scale
  2458. _scale_conversions = {'raw': 1.0,
  2459. 'normal': special.erfinv(0.5) * 2.0 * math.sqrt(2.0)}
  2460. def iqr(x, axis=None, rng=(25, 75), scale=1.0, nan_policy='propagate',
  2461. interpolation='linear', keepdims=False):
  2462. r"""
  2463. Compute the interquartile range of the data along the specified axis.
  2464. The interquartile range (IQR) is the difference between the 75th and
  2465. 25th percentile of the data. It is a measure of the dispersion
  2466. similar to standard deviation or variance, but is much more robust
  2467. against outliers [2]_.
  2468. The ``rng`` parameter allows this function to compute other
  2469. percentile ranges than the actual IQR. For example, setting
  2470. ``rng=(0, 100)`` is equivalent to `numpy.ptp`.
  2471. The IQR of an empty array is `np.nan`.
  2472. .. versionadded:: 0.18.0
  2473. Parameters
  2474. ----------
  2475. x : array_like
  2476. Input array or object that can be converted to an array.
  2477. axis : int or sequence of int, optional
  2478. Axis along which the range is computed. The default is to
  2479. compute the IQR for the entire array.
  2480. rng : Two-element sequence containing floats in range of [0,100] optional
  2481. Percentiles over which to compute the range. Each must be
  2482. between 0 and 100, inclusive. The default is the true IQR:
  2483. ``(25, 75)``. The order of the elements is not important.
  2484. scale : scalar or str, optional
  2485. The numerical value of scale will be divided out of the final
  2486. result. The following string values are recognized:
  2487. * 'raw' : No scaling, just return the raw IQR.
  2488. **Deprecated!** Use ``scale=1`` instead.
  2489. * 'normal' : Scale by
  2490. :math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`.
  2491. The default is 1.0. The use of ``scale='raw'`` is deprecated infavor
  2492. of ``scale=1`` and will raise an error in SciPy 1.12.0.
  2493. Array-like `scale` is also allowed, as long
  2494. as it broadcasts correctly to the output such that
  2495. ``out / scale`` is a valid operation. The output dimensions
  2496. depend on the input array, `x`, the `axis` argument, and the
  2497. `keepdims` flag.
  2498. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2499. Defines how to handle when input contains nan.
  2500. The following options are available (default is 'propagate'):
  2501. * 'propagate': returns nan
  2502. * 'raise': throws an error
  2503. * 'omit': performs the calculations ignoring nan values
  2504. interpolation : str, optional
  2505. Specifies the interpolation method to use when the percentile
  2506. boundaries lie between two data points ``i`` and ``j``.
  2507. The following options are available (default is 'linear'):
  2508. * 'linear': ``i + (j - i)*fraction``, where ``fraction`` is the
  2509. fractional part of the index surrounded by ``i`` and ``j``.
  2510. * 'lower': ``i``.
  2511. * 'higher': ``j``.
  2512. * 'nearest': ``i`` or ``j`` whichever is nearest.
  2513. * 'midpoint': ``(i + j)/2``.
  2514. For NumPy >= 1.22.0, the additional options provided by the ``method``
  2515. keyword of `numpy.percentile` are also valid.
  2516. keepdims : bool, optional
  2517. If this is set to True, the reduced axes are left in the
  2518. result as dimensions with size one. With this option, the result
  2519. will broadcast correctly against the original array `x`.
  2520. Returns
  2521. -------
  2522. iqr : scalar or ndarray
  2523. If ``axis=None``, a scalar is returned. If the input contains
  2524. integers or floats of smaller precision than ``np.float64``, then the
  2525. output data-type is ``np.float64``. Otherwise, the output data-type is
  2526. the same as that of the input.
  2527. See Also
  2528. --------
  2529. numpy.std, numpy.var
  2530. References
  2531. ----------
  2532. .. [1] "Interquartile range" https://en.wikipedia.org/wiki/Interquartile_range
  2533. .. [2] "Robust measures of scale" https://en.wikipedia.org/wiki/Robust_measures_of_scale
  2534. .. [3] "Quantile" https://en.wikipedia.org/wiki/Quantile
  2535. Examples
  2536. --------
  2537. >>> import numpy as np
  2538. >>> from scipy.stats import iqr
  2539. >>> x = np.array([[10, 7, 4], [3, 2, 1]])
  2540. >>> x
  2541. array([[10, 7, 4],
  2542. [ 3, 2, 1]])
  2543. >>> iqr(x)
  2544. 4.0
  2545. >>> iqr(x, axis=0)
  2546. array([ 3.5, 2.5, 1.5])
  2547. >>> iqr(x, axis=1)
  2548. array([ 3., 1.])
  2549. >>> iqr(x, axis=1, keepdims=True)
  2550. array([[ 3.],
  2551. [ 1.]])
  2552. """
  2553. x = asarray(x)
  2554. # This check prevents percentile from raising an error later. Also, it is
  2555. # consistent with `np.var` and `np.std`.
  2556. if not x.size:
  2557. return np.nan
  2558. # An error may be raised here, so fail-fast, before doing lengthy
  2559. # computations, even though `scale` is not used until later
  2560. if isinstance(scale, str):
  2561. scale_key = scale.lower()
  2562. if scale_key not in _scale_conversions:
  2563. raise ValueError("{0} not a valid scale for `iqr`".format(scale))
  2564. if scale_key == 'raw':
  2565. msg = ("The use of 'scale=\"raw\"' is deprecated infavor of "
  2566. "'scale=1' and will raise an error in SciPy 1.12.0.")
  2567. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  2568. scale = _scale_conversions[scale_key]
  2569. # Select the percentile function to use based on nans and policy
  2570. contains_nan, nan_policy = _contains_nan(x, nan_policy)
  2571. if contains_nan and nan_policy == 'omit':
  2572. percentile_func = np.nanpercentile
  2573. else:
  2574. percentile_func = np.percentile
  2575. if len(rng) != 2:
  2576. raise TypeError("quantile range must be two element sequence")
  2577. if np.isnan(rng).any():
  2578. raise ValueError("range must not contain NaNs")
  2579. rng = sorted(rng)
  2580. if NumpyVersion(np.__version__) >= '1.22.0':
  2581. pct = percentile_func(x, rng, axis=axis, method=interpolation,
  2582. keepdims=keepdims)
  2583. else:
  2584. pct = percentile_func(x, rng, axis=axis, interpolation=interpolation,
  2585. keepdims=keepdims)
  2586. out = np.subtract(pct[1], pct[0])
  2587. if scale != 1.0:
  2588. out /= scale
  2589. return out
  2590. def _mad_1d(x, center, nan_policy):
  2591. # Median absolute deviation for 1-d array x.
  2592. # This is a helper function for `median_abs_deviation`; it assumes its
  2593. # arguments have been validated already. In particular, x must be a
  2594. # 1-d numpy array, center must be callable, and if nan_policy is not
  2595. # 'propagate', it is assumed to be 'omit', because 'raise' is handled
  2596. # in `median_abs_deviation`.
  2597. # No warning is generated if x is empty or all nan.
  2598. isnan = np.isnan(x)
  2599. if isnan.any():
  2600. if nan_policy == 'propagate':
  2601. return np.nan
  2602. x = x[~isnan]
  2603. if x.size == 0:
  2604. # MAD of an empty array is nan.
  2605. return np.nan
  2606. # Edge cases have been handled, so do the basic MAD calculation.
  2607. med = center(x)
  2608. mad = np.median(np.abs(x - med))
  2609. return mad
  2610. def median_abs_deviation(x, axis=0, center=np.median, scale=1.0,
  2611. nan_policy='propagate'):
  2612. r"""
  2613. Compute the median absolute deviation of the data along the given axis.
  2614. The median absolute deviation (MAD, [1]_) computes the median over the
  2615. absolute deviations from the median. It is a measure of dispersion
  2616. similar to the standard deviation but more robust to outliers [2]_.
  2617. The MAD of an empty array is ``np.nan``.
  2618. .. versionadded:: 1.5.0
  2619. Parameters
  2620. ----------
  2621. x : array_like
  2622. Input array or object that can be converted to an array.
  2623. axis : int or None, optional
  2624. Axis along which the range is computed. Default is 0. If None, compute
  2625. the MAD over the entire array.
  2626. center : callable, optional
  2627. A function that will return the central value. The default is to use
  2628. np.median. Any user defined function used will need to have the
  2629. function signature ``func(arr, axis)``.
  2630. scale : scalar or str, optional
  2631. The numerical value of scale will be divided out of the final
  2632. result. The default is 1.0. The string "normal" is also accepted,
  2633. and results in `scale` being the inverse of the standard normal
  2634. quantile function at 0.75, which is approximately 0.67449.
  2635. Array-like scale is also allowed, as long as it broadcasts correctly
  2636. to the output such that ``out / scale`` is a valid operation. The
  2637. output dimensions depend on the input array, `x`, and the `axis`
  2638. argument.
  2639. nan_policy : {'propagate', 'raise', 'omit'}, optional
  2640. Defines how to handle when input contains nan.
  2641. The following options are available (default is 'propagate'):
  2642. * 'propagate': returns nan
  2643. * 'raise': throws an error
  2644. * 'omit': performs the calculations ignoring nan values
  2645. Returns
  2646. -------
  2647. mad : scalar or ndarray
  2648. If ``axis=None``, a scalar is returned. If the input contains
  2649. integers or floats of smaller precision than ``np.float64``, then the
  2650. output data-type is ``np.float64``. Otherwise, the output data-type is
  2651. the same as that of the input.
  2652. See Also
  2653. --------
  2654. numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean,
  2655. scipy.stats.tstd, scipy.stats.tvar
  2656. Notes
  2657. -----
  2658. The `center` argument only affects the calculation of the central value
  2659. around which the MAD is calculated. That is, passing in ``center=np.mean``
  2660. will calculate the MAD around the mean - it will not calculate the *mean*
  2661. absolute deviation.
  2662. The input array may contain `inf`, but if `center` returns `inf`, the
  2663. corresponding MAD for that data will be `nan`.
  2664. References
  2665. ----------
  2666. .. [1] "Median absolute deviation",
  2667. https://en.wikipedia.org/wiki/Median_absolute_deviation
  2668. .. [2] "Robust measures of scale",
  2669. https://en.wikipedia.org/wiki/Robust_measures_of_scale
  2670. Examples
  2671. --------
  2672. When comparing the behavior of `median_abs_deviation` with ``np.std``,
  2673. the latter is affected when we change a single value of an array to have an
  2674. outlier value while the MAD hardly changes:
  2675. >>> import numpy as np
  2676. >>> from scipy import stats
  2677. >>> x = stats.norm.rvs(size=100, scale=1, random_state=123456)
  2678. >>> x.std()
  2679. 0.9973906394005013
  2680. >>> stats.median_abs_deviation(x)
  2681. 0.82832610097857
  2682. >>> x[0] = 345.6
  2683. >>> x.std()
  2684. 34.42304872314415
  2685. >>> stats.median_abs_deviation(x)
  2686. 0.8323442311590675
  2687. Axis handling example:
  2688. >>> x = np.array([[10, 7, 4], [3, 2, 1]])
  2689. >>> x
  2690. array([[10, 7, 4],
  2691. [ 3, 2, 1]])
  2692. >>> stats.median_abs_deviation(x)
  2693. array([3.5, 2.5, 1.5])
  2694. >>> stats.median_abs_deviation(x, axis=None)
  2695. 2.0
  2696. Scale normal example:
  2697. >>> x = stats.norm.rvs(size=1000000, scale=2, random_state=123456)
  2698. >>> stats.median_abs_deviation(x)
  2699. 1.3487398527041636
  2700. >>> stats.median_abs_deviation(x, scale='normal')
  2701. 1.9996446978061115
  2702. """
  2703. if not callable(center):
  2704. raise TypeError("The argument 'center' must be callable. The given "
  2705. f"value {repr(center)} is not callable.")
  2706. # An error may be raised here, so fail-fast, before doing lengthy
  2707. # computations, even though `scale` is not used until later
  2708. if isinstance(scale, str):
  2709. if scale.lower() == 'normal':
  2710. scale = 0.6744897501960817 # special.ndtri(0.75)
  2711. else:
  2712. raise ValueError(f"{scale} is not a valid scale value.")
  2713. x = asarray(x)
  2714. # Consistent with `np.var` and `np.std`.
  2715. if not x.size:
  2716. if axis is None:
  2717. return np.nan
  2718. nan_shape = tuple(item for i, item in enumerate(x.shape) if i != axis)
  2719. if nan_shape == ():
  2720. # Return nan, not array(nan)
  2721. return np.nan
  2722. return np.full(nan_shape, np.nan)
  2723. contains_nan, nan_policy = _contains_nan(x, nan_policy)
  2724. if contains_nan:
  2725. if axis is None:
  2726. mad = _mad_1d(x.ravel(), center, nan_policy)
  2727. else:
  2728. mad = np.apply_along_axis(_mad_1d, axis, x, center, nan_policy)
  2729. else:
  2730. if axis is None:
  2731. med = center(x, axis=None)
  2732. mad = np.median(np.abs(x - med))
  2733. else:
  2734. # Wrap the call to center() in expand_dims() so it acts like
  2735. # keepdims=True was used.
  2736. med = np.expand_dims(center(x, axis=axis), axis)
  2737. mad = np.median(np.abs(x - med), axis=axis)
  2738. return mad / scale
  2739. #####################################
  2740. # TRIMMING FUNCTIONS #
  2741. #####################################
  2742. SigmaclipResult = namedtuple('SigmaclipResult', ('clipped', 'lower', 'upper'))
  2743. def sigmaclip(a, low=4., high=4.):
  2744. """Perform iterative sigma-clipping of array elements.
  2745. Starting from the full sample, all elements outside the critical range are
  2746. removed, i.e. all elements of the input array `c` that satisfy either of
  2747. the following conditions::
  2748. c < mean(c) - std(c)*low
  2749. c > mean(c) + std(c)*high
  2750. The iteration continues with the updated sample until no
  2751. elements are outside the (updated) range.
  2752. Parameters
  2753. ----------
  2754. a : array_like
  2755. Data array, will be raveled if not 1-D.
  2756. low : float, optional
  2757. Lower bound factor of sigma clipping. Default is 4.
  2758. high : float, optional
  2759. Upper bound factor of sigma clipping. Default is 4.
  2760. Returns
  2761. -------
  2762. clipped : ndarray
  2763. Input array with clipped elements removed.
  2764. lower : float
  2765. Lower threshold value use for clipping.
  2766. upper : float
  2767. Upper threshold value use for clipping.
  2768. Examples
  2769. --------
  2770. >>> import numpy as np
  2771. >>> from scipy.stats import sigmaclip
  2772. >>> a = np.concatenate((np.linspace(9.5, 10.5, 31),
  2773. ... np.linspace(0, 20, 5)))
  2774. >>> fact = 1.5
  2775. >>> c, low, upp = sigmaclip(a, fact, fact)
  2776. >>> c
  2777. array([ 9.96666667, 10. , 10.03333333, 10. ])
  2778. >>> c.var(), c.std()
  2779. (0.00055555555555555165, 0.023570226039551501)
  2780. >>> low, c.mean() - fact*c.std(), c.min()
  2781. (9.9646446609406727, 9.9646446609406727, 9.9666666666666668)
  2782. >>> upp, c.mean() + fact*c.std(), c.max()
  2783. (10.035355339059327, 10.035355339059327, 10.033333333333333)
  2784. >>> a = np.concatenate((np.linspace(9.5, 10.5, 11),
  2785. ... np.linspace(-100, -50, 3)))
  2786. >>> c, low, upp = sigmaclip(a, 1.8, 1.8)
  2787. >>> (c == np.linspace(9.5, 10.5, 11)).all()
  2788. True
  2789. """
  2790. c = np.asarray(a).ravel()
  2791. delta = 1
  2792. while delta:
  2793. c_std = c.std()
  2794. c_mean = c.mean()
  2795. size = c.size
  2796. critlower = c_mean - c_std * low
  2797. critupper = c_mean + c_std * high
  2798. c = c[(c >= critlower) & (c <= critupper)]
  2799. delta = size - c.size
  2800. return SigmaclipResult(c, critlower, critupper)
  2801. def trimboth(a, proportiontocut, axis=0):
  2802. """Slice off a proportion of items from both ends of an array.
  2803. Slice off the passed proportion of items from both ends of the passed
  2804. array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
  2805. rightmost 10% of scores). The trimmed values are the lowest and
  2806. highest ones.
  2807. Slice off less if proportion results in a non-integer slice index (i.e.
  2808. conservatively slices off `proportiontocut`).
  2809. Parameters
  2810. ----------
  2811. a : array_like
  2812. Data to trim.
  2813. proportiontocut : float
  2814. Proportion (in range 0-1) of total data set to trim of each end.
  2815. axis : int or None, optional
  2816. Axis along which to trim data. Default is 0. If None, compute over
  2817. the whole array `a`.
  2818. Returns
  2819. -------
  2820. out : ndarray
  2821. Trimmed version of array `a`. The order of the trimmed content
  2822. is undefined.
  2823. See Also
  2824. --------
  2825. trim_mean
  2826. Examples
  2827. --------
  2828. Create an array of 10 values and trim 10% of those values from each end:
  2829. >>> import numpy as np
  2830. >>> from scipy import stats
  2831. >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  2832. >>> stats.trimboth(a, 0.1)
  2833. array([1, 3, 2, 4, 5, 6, 7, 8])
  2834. Note that the elements of the input array are trimmed by value, but the
  2835. output array is not necessarily sorted.
  2836. The proportion to trim is rounded down to the nearest integer. For
  2837. instance, trimming 25% of the values from each end of an array of 10
  2838. values will return an array of 6 values:
  2839. >>> b = np.arange(10)
  2840. >>> stats.trimboth(b, 1/4).shape
  2841. (6,)
  2842. Multidimensional arrays can be trimmed along any axis or across the entire
  2843. array:
  2844. >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9]
  2845. >>> d = np.array([a, b, c])
  2846. >>> stats.trimboth(d, 0.4, axis=0).shape
  2847. (1, 10)
  2848. >>> stats.trimboth(d, 0.4, axis=1).shape
  2849. (3, 2)
  2850. >>> stats.trimboth(d, 0.4, axis=None).shape
  2851. (6,)
  2852. """
  2853. a = np.asarray(a)
  2854. if a.size == 0:
  2855. return a
  2856. if axis is None:
  2857. a = a.ravel()
  2858. axis = 0
  2859. nobs = a.shape[axis]
  2860. lowercut = int(proportiontocut * nobs)
  2861. uppercut = nobs - lowercut
  2862. if (lowercut >= uppercut):
  2863. raise ValueError("Proportion too big.")
  2864. atmp = np.partition(a, (lowercut, uppercut - 1), axis)
  2865. sl = [slice(None)] * atmp.ndim
  2866. sl[axis] = slice(lowercut, uppercut)
  2867. return atmp[tuple(sl)]
  2868. def trim1(a, proportiontocut, tail='right', axis=0):
  2869. """Slice off a proportion from ONE end of the passed array distribution.
  2870. If `proportiontocut` = 0.1, slices off 'leftmost' or 'rightmost'
  2871. 10% of scores. The lowest or highest values are trimmed (depending on
  2872. the tail).
  2873. Slice off less if proportion results in a non-integer slice index
  2874. (i.e. conservatively slices off `proportiontocut` ).
  2875. Parameters
  2876. ----------
  2877. a : array_like
  2878. Input array.
  2879. proportiontocut : float
  2880. Fraction to cut off of 'left' or 'right' of distribution.
  2881. tail : {'left', 'right'}, optional
  2882. Defaults to 'right'.
  2883. axis : int or None, optional
  2884. Axis along which to trim data. Default is 0. If None, compute over
  2885. the whole array `a`.
  2886. Returns
  2887. -------
  2888. trim1 : ndarray
  2889. Trimmed version of array `a`. The order of the trimmed content is
  2890. undefined.
  2891. Examples
  2892. --------
  2893. Create an array of 10 values and trim 20% of its lowest values:
  2894. >>> import numpy as np
  2895. >>> from scipy import stats
  2896. >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  2897. >>> stats.trim1(a, 0.2, 'left')
  2898. array([2, 4, 3, 5, 6, 7, 8, 9])
  2899. Note that the elements of the input array are trimmed by value, but the
  2900. output array is not necessarily sorted.
  2901. The proportion to trim is rounded down to the nearest integer. For
  2902. instance, trimming 25% of the values from an array of 10 values will
  2903. return an array of 8 values:
  2904. >>> b = np.arange(10)
  2905. >>> stats.trim1(b, 1/4).shape
  2906. (8,)
  2907. Multidimensional arrays can be trimmed along any axis or across the entire
  2908. array:
  2909. >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9]
  2910. >>> d = np.array([a, b, c])
  2911. >>> stats.trim1(d, 0.8, axis=0).shape
  2912. (1, 10)
  2913. >>> stats.trim1(d, 0.8, axis=1).shape
  2914. (3, 2)
  2915. >>> stats.trim1(d, 0.8, axis=None).shape
  2916. (6,)
  2917. """
  2918. a = np.asarray(a)
  2919. if axis is None:
  2920. a = a.ravel()
  2921. axis = 0
  2922. nobs = a.shape[axis]
  2923. # avoid possible corner case
  2924. if proportiontocut >= 1:
  2925. return []
  2926. if tail.lower() == 'right':
  2927. lowercut = 0
  2928. uppercut = nobs - int(proportiontocut * nobs)
  2929. elif tail.lower() == 'left':
  2930. lowercut = int(proportiontocut * nobs)
  2931. uppercut = nobs
  2932. atmp = np.partition(a, (lowercut, uppercut - 1), axis)
  2933. sl = [slice(None)] * atmp.ndim
  2934. sl[axis] = slice(lowercut, uppercut)
  2935. return atmp[tuple(sl)]
  2936. def trim_mean(a, proportiontocut, axis=0):
  2937. """Return mean of array after trimming distribution from both tails.
  2938. If `proportiontocut` = 0.1, slices off 'leftmost' and 'rightmost' 10% of
  2939. scores. The input is sorted before slicing. Slices off less if proportion
  2940. results in a non-integer slice index (i.e., conservatively slices off
  2941. `proportiontocut` ).
  2942. Parameters
  2943. ----------
  2944. a : array_like
  2945. Input array.
  2946. proportiontocut : float
  2947. Fraction to cut off of both tails of the distribution.
  2948. axis : int or None, optional
  2949. Axis along which the trimmed means are computed. Default is 0.
  2950. If None, compute over the whole array `a`.
  2951. Returns
  2952. -------
  2953. trim_mean : ndarray
  2954. Mean of trimmed array.
  2955. See Also
  2956. --------
  2957. trimboth
  2958. tmean : Compute the trimmed mean ignoring values outside given `limits`.
  2959. Examples
  2960. --------
  2961. >>> import numpy as np
  2962. >>> from scipy import stats
  2963. >>> x = np.arange(20)
  2964. >>> stats.trim_mean(x, 0.1)
  2965. 9.5
  2966. >>> x2 = x.reshape(5, 4)
  2967. >>> x2
  2968. array([[ 0, 1, 2, 3],
  2969. [ 4, 5, 6, 7],
  2970. [ 8, 9, 10, 11],
  2971. [12, 13, 14, 15],
  2972. [16, 17, 18, 19]])
  2973. >>> stats.trim_mean(x2, 0.25)
  2974. array([ 8., 9., 10., 11.])
  2975. >>> stats.trim_mean(x2, 0.25, axis=1)
  2976. array([ 1.5, 5.5, 9.5, 13.5, 17.5])
  2977. """
  2978. a = np.asarray(a)
  2979. if a.size == 0:
  2980. return np.nan
  2981. if axis is None:
  2982. a = a.ravel()
  2983. axis = 0
  2984. nobs = a.shape[axis]
  2985. lowercut = int(proportiontocut * nobs)
  2986. uppercut = nobs - lowercut
  2987. if (lowercut > uppercut):
  2988. raise ValueError("Proportion too big.")
  2989. atmp = np.partition(a, (lowercut, uppercut - 1), axis)
  2990. sl = [slice(None)] * atmp.ndim
  2991. sl[axis] = slice(lowercut, uppercut)
  2992. return np.mean(atmp[tuple(sl)], axis=axis)
  2993. F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue'))
  2994. def _create_f_oneway_nan_result(shape, axis):
  2995. """
  2996. This is a helper function for f_oneway for creating the return values
  2997. in certain degenerate conditions. It creates return values that are
  2998. all nan with the appropriate shape for the given `shape` and `axis`.
  2999. """
  3000. axis = np.core.multiarray.normalize_axis_index(axis, len(shape))
  3001. shp = shape[:axis] + shape[axis+1:]
  3002. if shp == ():
  3003. f = np.nan
  3004. prob = np.nan
  3005. else:
  3006. f = np.full(shp, fill_value=np.nan)
  3007. prob = f.copy()
  3008. return F_onewayResult(f, prob)
  3009. def _first(arr, axis):
  3010. """Return arr[..., 0:1, ...] where 0:1 is in the `axis` position."""
  3011. return np.take_along_axis(arr, np.array(0, ndmin=arr.ndim), axis)
  3012. def f_oneway(*samples, axis=0):
  3013. """Perform one-way ANOVA.
  3014. The one-way ANOVA tests the null hypothesis that two or more groups have
  3015. the same population mean. The test is applied to samples from two or
  3016. more groups, possibly with differing sizes.
  3017. Parameters
  3018. ----------
  3019. sample1, sample2, ... : array_like
  3020. The sample measurements for each group. There must be at least
  3021. two arguments. If the arrays are multidimensional, then all the
  3022. dimensions of the array must be the same except for `axis`.
  3023. axis : int, optional
  3024. Axis of the input arrays along which the test is applied.
  3025. Default is 0.
  3026. Returns
  3027. -------
  3028. statistic : float
  3029. The computed F statistic of the test.
  3030. pvalue : float
  3031. The associated p-value from the F distribution.
  3032. Warns
  3033. -----
  3034. `~scipy.stats.ConstantInputWarning`
  3035. Raised if all values within each of the input arrays are identical.
  3036. In this case the F statistic is either infinite or isn't defined,
  3037. so ``np.inf`` or ``np.nan`` is returned.
  3038. `~scipy.stats.DegenerateDataWarning`
  3039. Raised if the length of any input array is 0, or if all the input
  3040. arrays have length 1. ``np.nan`` is returned for the F statistic
  3041. and the p-value in these cases.
  3042. Notes
  3043. -----
  3044. The ANOVA test has important assumptions that must be satisfied in order
  3045. for the associated p-value to be valid.
  3046. 1. The samples are independent.
  3047. 2. Each sample is from a normally distributed population.
  3048. 3. The population standard deviations of the groups are all equal. This
  3049. property is known as homoscedasticity.
  3050. If these assumptions are not true for a given set of data, it may still
  3051. be possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`) or
  3052. the Alexander-Govern test (`scipy.stats.alexandergovern`) although with
  3053. some loss of power.
  3054. The length of each group must be at least one, and there must be at
  3055. least one group with length greater than one. If these conditions
  3056. are not satisfied, a warning is generated and (``np.nan``, ``np.nan``)
  3057. is returned.
  3058. If all values in each group are identical, and there exist at least two
  3059. groups with different values, the function generates a warning and
  3060. returns (``np.inf``, 0).
  3061. If all values in all groups are the same, function generates a warning
  3062. and returns (``np.nan``, ``np.nan``).
  3063. The algorithm is from Heiman [2]_, pp.394-7.
  3064. References
  3065. ----------
  3066. .. [1] R. Lowry, "Concepts and Applications of Inferential Statistics",
  3067. Chapter 14, 2014, http://vassarstats.net/textbook/
  3068. .. [2] G.W. Heiman, "Understanding research methods and statistics: An
  3069. integrated introduction for psychology", Houghton, Mifflin and
  3070. Company, 2001.
  3071. .. [3] G.H. McDonald, "Handbook of Biological Statistics", One-way ANOVA.
  3072. http://www.biostathandbook.com/onewayanova.html
  3073. Examples
  3074. --------
  3075. >>> import numpy as np
  3076. >>> from scipy.stats import f_oneway
  3077. Here are some data [3]_ on a shell measurement (the length of the anterior
  3078. adductor muscle scar, standardized by dividing by length) in the mussel
  3079. Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon;
  3080. Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland, taken from a
  3081. much larger data set used in McDonald et al. (1991).
  3082. >>> tillamook = [0.0571, 0.0813, 0.0831, 0.0976, 0.0817, 0.0859, 0.0735,
  3083. ... 0.0659, 0.0923, 0.0836]
  3084. >>> newport = [0.0873, 0.0662, 0.0672, 0.0819, 0.0749, 0.0649, 0.0835,
  3085. ... 0.0725]
  3086. >>> petersburg = [0.0974, 0.1352, 0.0817, 0.1016, 0.0968, 0.1064, 0.105]
  3087. >>> magadan = [0.1033, 0.0915, 0.0781, 0.0685, 0.0677, 0.0697, 0.0764,
  3088. ... 0.0689]
  3089. >>> tvarminne = [0.0703, 0.1026, 0.0956, 0.0973, 0.1039, 0.1045]
  3090. >>> f_oneway(tillamook, newport, petersburg, magadan, tvarminne)
  3091. F_onewayResult(statistic=7.121019471642447, pvalue=0.0002812242314534544)
  3092. `f_oneway` accepts multidimensional input arrays. When the inputs
  3093. are multidimensional and `axis` is not given, the test is performed
  3094. along the first axis of the input arrays. For the following data, the
  3095. test is performed three times, once for each column.
  3096. >>> a = np.array([[9.87, 9.03, 6.81],
  3097. ... [7.18, 8.35, 7.00],
  3098. ... [8.39, 7.58, 7.68],
  3099. ... [7.45, 6.33, 9.35],
  3100. ... [6.41, 7.10, 9.33],
  3101. ... [8.00, 8.24, 8.44]])
  3102. >>> b = np.array([[6.35, 7.30, 7.16],
  3103. ... [6.65, 6.68, 7.63],
  3104. ... [5.72, 7.73, 6.72],
  3105. ... [7.01, 9.19, 7.41],
  3106. ... [7.75, 7.87, 8.30],
  3107. ... [6.90, 7.97, 6.97]])
  3108. >>> c = np.array([[3.31, 8.77, 1.01],
  3109. ... [8.25, 3.24, 3.62],
  3110. ... [6.32, 8.81, 5.19],
  3111. ... [7.48, 8.83, 8.91],
  3112. ... [8.59, 6.01, 6.07],
  3113. ... [3.07, 9.72, 7.48]])
  3114. >>> F, p = f_oneway(a, b, c)
  3115. >>> F
  3116. array([1.75676344, 0.03701228, 3.76439349])
  3117. >>> p
  3118. array([0.20630784, 0.96375203, 0.04733157])
  3119. """
  3120. if len(samples) < 2:
  3121. raise TypeError('at least two inputs are required;'
  3122. f' got {len(samples)}.')
  3123. samples = [np.asarray(sample, dtype=float) for sample in samples]
  3124. # ANOVA on N groups, each in its own array
  3125. num_groups = len(samples)
  3126. # We haven't explicitly validated axis, but if it is bad, this call of
  3127. # np.concatenate will raise np.AxisError. The call will raise ValueError
  3128. # if the dimensions of all the arrays, except the axis dimension, are not
  3129. # the same.
  3130. alldata = np.concatenate(samples, axis=axis)
  3131. bign = alldata.shape[axis]
  3132. # Check this after forming alldata, so shape errors are detected
  3133. # and reported before checking for 0 length inputs.
  3134. if any(sample.shape[axis] == 0 for sample in samples):
  3135. warnings.warn(stats.DegenerateDataWarning('at least one input '
  3136. 'has length 0'))
  3137. return _create_f_oneway_nan_result(alldata.shape, axis)
  3138. # Must have at least one group with length greater than 1.
  3139. if all(sample.shape[axis] == 1 for sample in samples):
  3140. msg = ('all input arrays have length 1. f_oneway requires that at '
  3141. 'least one input has length greater than 1.')
  3142. warnings.warn(stats.DegenerateDataWarning(msg))
  3143. return _create_f_oneway_nan_result(alldata.shape, axis)
  3144. # Check if all values within each group are identical, and if the common
  3145. # value in at least one group is different from that in another group.
  3146. # Based on https://github.com/scipy/scipy/issues/11669
  3147. # If axis=0, say, and the groups have shape (n0, ...), (n1, ...), ...,
  3148. # then is_const is a boolean array with shape (num_groups, ...).
  3149. # It is True if the values within the groups along the axis slice are
  3150. # identical. In the typical case where each input array is 1-d, is_const is
  3151. # a 1-d array with length num_groups.
  3152. is_const = np.concatenate(
  3153. [(_first(sample, axis) == sample).all(axis=axis,
  3154. keepdims=True)
  3155. for sample in samples],
  3156. axis=axis
  3157. )
  3158. # all_const is a boolean array with shape (...) (see previous comment).
  3159. # It is True if the values within each group along the axis slice are
  3160. # the same (e.g. [[3, 3, 3], [5, 5, 5, 5], [4, 4, 4]]).
  3161. all_const = is_const.all(axis=axis)
  3162. if all_const.any():
  3163. msg = ("Each of the input arrays is constant;"
  3164. "the F statistic is not defined or infinite")
  3165. warnings.warn(stats.ConstantInputWarning(msg))
  3166. # all_same_const is True if all the values in the groups along the axis=0
  3167. # slice are the same (e.g. [[3, 3, 3], [3, 3, 3, 3], [3, 3, 3]]).
  3168. all_same_const = (_first(alldata, axis) == alldata).all(axis=axis)
  3169. # Determine the mean of the data, and subtract that from all inputs to a
  3170. # variance (via sum_of_sq / sq_of_sum) calculation. Variance is invariant
  3171. # to a shift in location, and centering all data around zero vastly
  3172. # improves numerical stability.
  3173. offset = alldata.mean(axis=axis, keepdims=True)
  3174. alldata -= offset
  3175. normalized_ss = _square_of_sums(alldata, axis=axis) / bign
  3176. sstot = _sum_of_squares(alldata, axis=axis) - normalized_ss
  3177. ssbn = 0
  3178. for sample in samples:
  3179. ssbn += _square_of_sums(sample - offset,
  3180. axis=axis) / sample.shape[axis]
  3181. # Naming: variables ending in bn/b are for "between treatments", wn/w are
  3182. # for "within treatments"
  3183. ssbn -= normalized_ss
  3184. sswn = sstot - ssbn
  3185. dfbn = num_groups - 1
  3186. dfwn = bign - num_groups
  3187. msb = ssbn / dfbn
  3188. msw = sswn / dfwn
  3189. with np.errstate(divide='ignore', invalid='ignore'):
  3190. f = msb / msw
  3191. prob = special.fdtrc(dfbn, dfwn, f) # equivalent to stats.f.sf
  3192. # Fix any f values that should be inf or nan because the corresponding
  3193. # inputs were constant.
  3194. if np.isscalar(f):
  3195. if all_same_const:
  3196. f = np.nan
  3197. prob = np.nan
  3198. elif all_const:
  3199. f = np.inf
  3200. prob = 0.0
  3201. else:
  3202. f[all_const] = np.inf
  3203. prob[all_const] = 0.0
  3204. f[all_same_const] = np.nan
  3205. prob[all_same_const] = np.nan
  3206. return F_onewayResult(f, prob)
  3207. def alexandergovern(*samples, nan_policy='propagate'):
  3208. """Performs the Alexander Govern test.
  3209. The Alexander-Govern approximation tests the equality of k independent
  3210. means in the face of heterogeneity of variance. The test is applied to
  3211. samples from two or more groups, possibly with differing sizes.
  3212. Parameters
  3213. ----------
  3214. sample1, sample2, ... : array_like
  3215. The sample measurements for each group. There must be at least
  3216. two samples.
  3217. nan_policy : {'propagate', 'raise', 'omit'}, optional
  3218. Defines how to handle when input contains nan.
  3219. The following options are available (default is 'propagate'):
  3220. * 'propagate': returns nan
  3221. * 'raise': throws an error
  3222. * 'omit': performs the calculations ignoring nan values
  3223. Returns
  3224. -------
  3225. statistic : float
  3226. The computed A statistic of the test.
  3227. pvalue : float
  3228. The associated p-value from the chi-squared distribution.
  3229. Warns
  3230. -----
  3231. `~scipy.stats.ConstantInputWarning`
  3232. Raised if an input is a constant array. The statistic is not defined
  3233. in this case, so ``np.nan`` is returned.
  3234. See Also
  3235. --------
  3236. f_oneway : one-way ANOVA
  3237. Notes
  3238. -----
  3239. The use of this test relies on several assumptions.
  3240. 1. The samples are independent.
  3241. 2. Each sample is from a normally distributed population.
  3242. 3. Unlike `f_oneway`, this test does not assume on homoscedasticity,
  3243. instead relaxing the assumption of equal variances.
  3244. Input samples must be finite, one dimensional, and with size greater than
  3245. one.
  3246. References
  3247. ----------
  3248. .. [1] Alexander, Ralph A., and Diane M. Govern. "A New and Simpler
  3249. Approximation for ANOVA under Variance Heterogeneity." Journal
  3250. of Educational Statistics, vol. 19, no. 2, 1994, pp. 91-101.
  3251. JSTOR, www.jstor.org/stable/1165140. Accessed 12 Sept. 2020.
  3252. Examples
  3253. --------
  3254. >>> from scipy.stats import alexandergovern
  3255. Here are some data on annual percentage rate of interest charged on
  3256. new car loans at nine of the largest banks in four American cities
  3257. taken from the National Institute of Standards and Technology's
  3258. ANOVA dataset.
  3259. We use `alexandergovern` to test the null hypothesis that all cities
  3260. have the same mean APR against the alternative that the cities do not
  3261. all have the same mean APR. We decide that a significance level of 5%
  3262. is required to reject the null hypothesis in favor of the alternative.
  3263. >>> atlanta = [13.75, 13.75, 13.5, 13.5, 13.0, 13.0, 13.0, 12.75, 12.5]
  3264. >>> chicago = [14.25, 13.0, 12.75, 12.5, 12.5, 12.4, 12.3, 11.9, 11.9]
  3265. >>> houston = [14.0, 14.0, 13.51, 13.5, 13.5, 13.25, 13.0, 12.5, 12.5]
  3266. >>> memphis = [15.0, 14.0, 13.75, 13.59, 13.25, 12.97, 12.5, 12.25,
  3267. ... 11.89]
  3268. >>> alexandergovern(atlanta, chicago, houston, memphis)
  3269. AlexanderGovernResult(statistic=4.65087071883494,
  3270. pvalue=0.19922132490385214)
  3271. The p-value is 0.1992, indicating a nearly 20% chance of observing
  3272. such an extreme value of the test statistic under the null hypothesis.
  3273. This exceeds 5%, so we do not reject the null hypothesis in favor of
  3274. the alternative.
  3275. """
  3276. samples = _alexandergovern_input_validation(samples, nan_policy)
  3277. if np.any([(sample == sample[0]).all() for sample in samples]):
  3278. msg = "An input array is constant; the statistic is not defined."
  3279. warnings.warn(stats.ConstantInputWarning(msg))
  3280. return AlexanderGovernResult(np.nan, np.nan)
  3281. # The following formula numbers reference the equation described on
  3282. # page 92 by Alexander, Govern. Formulas 5, 6, and 7 describe other
  3283. # tests that serve as the basis for equation (8) but are not needed
  3284. # to perform the test.
  3285. # precalculate mean and length of each sample
  3286. lengths = np.array([ma.count(sample) if nan_policy == 'omit'
  3287. else len(sample) for sample in samples])
  3288. means = np.array([np.mean(sample) for sample in samples])
  3289. # (1) determine standard error of the mean for each sample
  3290. standard_errors = [np.std(sample, ddof=1) / np.sqrt(length)
  3291. for sample, length in zip(samples, lengths)]
  3292. # (2) define a weight for each sample
  3293. inv_sq_se = 1 / np.square(standard_errors)
  3294. weights = inv_sq_se / np.sum(inv_sq_se)
  3295. # (3) determine variance-weighted estimate of the common mean
  3296. var_w = np.sum(weights * means)
  3297. # (4) determine one-sample t statistic for each group
  3298. t_stats = (means - var_w)/standard_errors
  3299. # calculate parameters to be used in transformation
  3300. v = lengths - 1
  3301. a = v - .5
  3302. b = 48 * a**2
  3303. c = (a * np.log(1 + (t_stats ** 2)/v))**.5
  3304. # (8) perform a normalizing transformation on t statistic
  3305. z = (c + ((c**3 + 3*c)/b) -
  3306. ((4*c**7 + 33*c**5 + 240*c**3 + 855*c) /
  3307. (b**2*10 + 8*b*c**4 + 1000*b)))
  3308. # (9) calculate statistic
  3309. A = np.sum(np.square(z))
  3310. # "[the p value is determined from] central chi-square random deviates
  3311. # with k - 1 degrees of freedom". Alexander, Govern (94)
  3312. p = distributions.chi2.sf(A, len(samples) - 1)
  3313. return AlexanderGovernResult(A, p)
  3314. def _alexandergovern_input_validation(samples, nan_policy):
  3315. if len(samples) < 2:
  3316. raise TypeError(f"2 or more inputs required, got {len(samples)}")
  3317. # input arrays are flattened
  3318. samples = [np.asarray(sample, dtype=float) for sample in samples]
  3319. for i, sample in enumerate(samples):
  3320. if np.size(sample) <= 1:
  3321. raise ValueError("Input sample size must be greater than one.")
  3322. if sample.ndim != 1:
  3323. raise ValueError("Input samples must be one-dimensional")
  3324. if np.isinf(sample).any():
  3325. raise ValueError("Input samples must be finite.")
  3326. contains_nan, nan_policy = _contains_nan(sample,
  3327. nan_policy=nan_policy)
  3328. if contains_nan and nan_policy == 'omit':
  3329. samples[i] = ma.masked_invalid(sample)
  3330. return samples
  3331. AlexanderGovernResult = make_dataclass("AlexanderGovernResult", ("statistic",
  3332. "pvalue"))
  3333. def _pearsonr_fisher_ci(r, n, confidence_level, alternative):
  3334. """
  3335. Compute the confidence interval for Pearson's R.
  3336. Fisher's transformation is used to compute the confidence interval
  3337. (https://en.wikipedia.org/wiki/Fisher_transformation).
  3338. """
  3339. if r == 1:
  3340. zr = np.inf
  3341. elif r == -1:
  3342. zr = -np.inf
  3343. else:
  3344. zr = np.arctanh(r)
  3345. if n > 3:
  3346. se = np.sqrt(1 / (n - 3))
  3347. if alternative == "two-sided":
  3348. h = special.ndtri(0.5 + confidence_level/2)
  3349. zlo = zr - h*se
  3350. zhi = zr + h*se
  3351. rlo = np.tanh(zlo)
  3352. rhi = np.tanh(zhi)
  3353. elif alternative == "less":
  3354. h = special.ndtri(confidence_level)
  3355. zhi = zr + h*se
  3356. rhi = np.tanh(zhi)
  3357. rlo = -1.0
  3358. else:
  3359. # alternative == "greater":
  3360. h = special.ndtri(confidence_level)
  3361. zlo = zr - h*se
  3362. rlo = np.tanh(zlo)
  3363. rhi = 1.0
  3364. else:
  3365. rlo, rhi = -1.0, 1.0
  3366. return ConfidenceInterval(low=rlo, high=rhi)
  3367. ConfidenceInterval = namedtuple('ConfidenceInterval', ['low', 'high'])
  3368. PearsonRResultBase = _make_tuple_bunch('PearsonRResultBase',
  3369. ['statistic', 'pvalue'], [])
  3370. class PearsonRResult(PearsonRResultBase):
  3371. """
  3372. Result of `scipy.stats.pearsonr`
  3373. Attributes
  3374. ----------
  3375. statistic : float
  3376. Pearson product-moment correlation coefficient.
  3377. pvalue : float
  3378. The p-value associated with the chosen alternative.
  3379. Methods
  3380. -------
  3381. confidence_interval
  3382. Computes the confidence interval of the correlation
  3383. coefficient `statistic` for the given confidence level.
  3384. """
  3385. def __init__(self, statistic, pvalue, alternative, n):
  3386. super().__init__(statistic, pvalue)
  3387. self._alternative = alternative
  3388. self._n = n
  3389. # add alias for consistency with other correlation functions
  3390. self.correlation = statistic
  3391. def confidence_interval(self, confidence_level=0.95):
  3392. """
  3393. The confidence interval for the correlation coefficient.
  3394. Compute the confidence interval for the correlation coefficient
  3395. ``statistic`` with the given confidence level.
  3396. The confidence interval is computed using the Fisher transformation
  3397. F(r) = arctanh(r) [1]_. When the sample pairs are drawn from a
  3398. bivariate normal distribution, F(r) approximately follows a normal
  3399. distribution with standard error ``1/sqrt(n - 3)``, where ``n`` is the
  3400. length of the original samples along the calculation axis. When
  3401. ``n <= 3``, this approximation does not yield a finite, real standard
  3402. error, so we define the confidence interval to be -1 to 1.
  3403. Parameters
  3404. ----------
  3405. confidence_level : float
  3406. The confidence level for the calculation of the correlation
  3407. coefficient confidence interval. Default is 0.95.
  3408. Returns
  3409. -------
  3410. ci : namedtuple
  3411. The confidence interval is returned in a ``namedtuple`` with
  3412. fields `low` and `high`.
  3413. References
  3414. ----------
  3415. .. [1] "Pearson correlation coefficient", Wikipedia,
  3416. https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
  3417. """
  3418. return _pearsonr_fisher_ci(self.statistic, self._n, confidence_level,
  3419. self._alternative)
  3420. def pearsonr(x, y, *, alternative='two-sided'):
  3421. r"""
  3422. Pearson correlation coefficient and p-value for testing non-correlation.
  3423. The Pearson correlation coefficient [1]_ measures the linear relationship
  3424. between two datasets. Like other correlation
  3425. coefficients, this one varies between -1 and +1 with 0 implying no
  3426. correlation. Correlations of -1 or +1 imply an exact linear relationship.
  3427. Positive correlations imply that as x increases, so does y. Negative
  3428. correlations imply that as x increases, y decreases.
  3429. This function also performs a test of the null hypothesis that the
  3430. distributions underlying the samples are uncorrelated and normally
  3431. distributed. (See Kowalski [3]_
  3432. for a discussion of the effects of non-normality of the input on the
  3433. distribution of the correlation coefficient.)
  3434. The p-value roughly indicates the probability of an uncorrelated system
  3435. producing datasets that have a Pearson correlation at least as extreme
  3436. as the one computed from these datasets.
  3437. Parameters
  3438. ----------
  3439. x : (N,) array_like
  3440. Input array.
  3441. y : (N,) array_like
  3442. Input array.
  3443. alternative : {'two-sided', 'greater', 'less'}, optional
  3444. Defines the alternative hypothesis. Default is 'two-sided'.
  3445. The following options are available:
  3446. * 'two-sided': the correlation is nonzero
  3447. * 'less': the correlation is negative (less than zero)
  3448. * 'greater': the correlation is positive (greater than zero)
  3449. .. versionadded:: 1.9.0
  3450. Returns
  3451. -------
  3452. result : `~scipy.stats._result_classes.PearsonRResult`
  3453. An object with the following attributes:
  3454. statistic : float
  3455. Pearson product-moment correlation coefficient.
  3456. pvalue : float
  3457. The p-value associated with the chosen alternative.
  3458. The object has the following method:
  3459. confidence_interval(confidence_level=0.95)
  3460. This method computes the confidence interval of the correlation
  3461. coefficient `statistic` for the given confidence level.
  3462. The confidence interval is returned in a ``namedtuple`` with
  3463. fields `low` and `high`. See the Notes for more details.
  3464. Warns
  3465. -----
  3466. `~scipy.stats.ConstantInputWarning`
  3467. Raised if an input is a constant array. The correlation coefficient
  3468. is not defined in this case, so ``np.nan`` is returned.
  3469. `~scipy.stats.NearConstantInputWarning`
  3470. Raised if an input is "nearly" constant. The array ``x`` is considered
  3471. nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``.
  3472. Numerical errors in the calculation ``x - mean(x)`` in this case might
  3473. result in an inaccurate calculation of r.
  3474. See Also
  3475. --------
  3476. spearmanr : Spearman rank-order correlation coefficient.
  3477. kendalltau : Kendall's tau, a correlation measure for ordinal data.
  3478. Notes
  3479. -----
  3480. The correlation coefficient is calculated as follows:
  3481. .. math::
  3482. r = \frac{\sum (x - m_x) (y - m_y)}
  3483. {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}}
  3484. where :math:`m_x` is the mean of the vector x and :math:`m_y` is
  3485. the mean of the vector y.
  3486. Under the assumption that x and y are drawn from
  3487. independent normal distributions (so the population correlation coefficient
  3488. is 0), the probability density function of the sample correlation
  3489. coefficient r is ([1]_, [2]_):
  3490. .. math::
  3491. f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)}
  3492. where n is the number of samples, and B is the beta function. This
  3493. is sometimes referred to as the exact distribution of r. This is
  3494. the distribution that is used in `pearsonr` to compute the p-value.
  3495. The distribution is a beta distribution on the interval [-1, 1],
  3496. with equal shape parameters a = b = n/2 - 1. In terms of SciPy's
  3497. implementation of the beta distribution, the distribution of r is::
  3498. dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2)
  3499. The default p-value returned by `pearsonr` is a two-sided p-value. For a
  3500. given sample with correlation coefficient r, the p-value is
  3501. the probability that abs(r') of a random sample x' and y' drawn from
  3502. the population with zero correlation would be greater than or equal
  3503. to abs(r). In terms of the object ``dist`` shown above, the p-value
  3504. for a given r and length n can be computed as::
  3505. p = 2*dist.cdf(-abs(r))
  3506. When n is 2, the above continuous distribution is not well-defined.
  3507. One can interpret the limit of the beta distribution as the shape
  3508. parameters a and b approach a = b = 0 as a discrete distribution with
  3509. equal probability masses at r = 1 and r = -1. More directly, one
  3510. can observe that, given the data x = [x1, x2] and y = [y1, y2], and
  3511. assuming x1 != x2 and y1 != y2, the only possible values for r are 1
  3512. and -1. Because abs(r') for any sample x' and y' with length 2 will
  3513. be 1, the two-sided p-value for a sample of length 2 is always 1.
  3514. For backwards compatibility, the object that is returned also behaves
  3515. like a tuple of length two that holds the statistic and the p-value.
  3516. References
  3517. ----------
  3518. .. [1] "Pearson correlation coefficient", Wikipedia,
  3519. https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
  3520. .. [2] Student, "Probable error of a correlation coefficient",
  3521. Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310.
  3522. .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution
  3523. of the Sample Product-Moment Correlation Coefficient"
  3524. Journal of the Royal Statistical Society. Series C (Applied
  3525. Statistics), Vol. 21, No. 1 (1972), pp. 1-12.
  3526. Examples
  3527. --------
  3528. >>> import numpy as np
  3529. >>> from scipy import stats
  3530. >>> res = stats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4])
  3531. >>> res
  3532. PearsonRResult(statistic=-0.7426106572325056, pvalue=0.15055580885344558)
  3533. >>> res.confidence_interval()
  3534. ConfidenceInterval(low=-0.9816918044786463, high=0.40501116769030976)
  3535. There is a linear dependence between x and y if y = a + b*x + e, where
  3536. a,b are constants and e is a random error term, assumed to be independent
  3537. of x. For simplicity, assume that x is standard normal, a=0, b=1 and let
  3538. e follow a normal distribution with mean zero and standard deviation s>0.
  3539. >>> rng = np.random.default_rng()
  3540. >>> s = 0.5
  3541. >>> x = stats.norm.rvs(size=500, random_state=rng)
  3542. >>> e = stats.norm.rvs(scale=s, size=500, random_state=rng)
  3543. >>> y = x + e
  3544. >>> stats.pearsonr(x, y).statistic
  3545. 0.9001942438244763
  3546. This should be close to the exact value given by
  3547. >>> 1/np.sqrt(1 + s**2)
  3548. 0.8944271909999159
  3549. For s=0.5, we observe a high level of correlation. In general, a large
  3550. variance of the noise reduces the correlation, while the correlation
  3551. approaches one as the variance of the error goes to zero.
  3552. It is important to keep in mind that no correlation does not imply
  3553. independence unless (x, y) is jointly normal. Correlation can even be zero
  3554. when there is a very simple dependence structure: if X follows a
  3555. standard normal distribution, let y = abs(x). Note that the correlation
  3556. between x and y is zero. Indeed, since the expectation of x is zero,
  3557. cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero
  3558. by symmetry. The following lines of code illustrate this observation:
  3559. >>> y = np.abs(x)
  3560. >>> stats.pearsonr(x, y)
  3561. PearsonRResult(statistic=-0.05444919272687482, pvalue=0.22422294836207743)
  3562. A non-zero correlation coefficient can be misleading. For example, if X has
  3563. a standard normal distribution, define y = x if x < 0 and y = 0 otherwise.
  3564. A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797...,
  3565. implying a high level of correlation:
  3566. >>> y = np.where(x < 0, x, 0)
  3567. >>> stats.pearsonr(x, y)
  3568. PearsonRResult(statistic=0.861985781588, pvalue=4.813432002751103e-149)
  3569. This is unintuitive since there is no dependence of x and y if x is larger
  3570. than zero which happens in about half of the cases if we sample x and y.
  3571. """
  3572. n = len(x)
  3573. if n != len(y):
  3574. raise ValueError('x and y must have the same length.')
  3575. if n < 2:
  3576. raise ValueError('x and y must have length at least 2.')
  3577. x = np.asarray(x)
  3578. y = np.asarray(y)
  3579. if (np.issubdtype(x.dtype, np.complexfloating)
  3580. or np.issubdtype(y.dtype, np.complexfloating)):
  3581. raise ValueError('This function does not support complex data')
  3582. # If an input is constant, the correlation coefficient is not defined.
  3583. if (x == x[0]).all() or (y == y[0]).all():
  3584. msg = ("An input array is constant; the correlation coefficient "
  3585. "is not defined.")
  3586. warnings.warn(stats.ConstantInputWarning(msg))
  3587. result = PearsonRResult(statistic=np.nan, pvalue=np.nan, n=n,
  3588. alternative=alternative)
  3589. return result
  3590. # dtype is the data type for the calculations. This expression ensures
  3591. # that the data type is at least 64 bit floating point. It might have
  3592. # more precision if the input is, for example, np.longdouble.
  3593. dtype = type(1.0 + x[0] + y[0])
  3594. if n == 2:
  3595. r = dtype(np.sign(x[1] - x[0])*np.sign(y[1] - y[0]))
  3596. result = PearsonRResult(statistic=r, pvalue=1.0, n=n,
  3597. alternative=alternative)
  3598. return result
  3599. xmean = x.mean(dtype=dtype)
  3600. ymean = y.mean(dtype=dtype)
  3601. # By using `astype(dtype)`, we ensure that the intermediate calculations
  3602. # use at least 64 bit floating point.
  3603. xm = x.astype(dtype) - xmean
  3604. ym = y.astype(dtype) - ymean
  3605. # Unlike np.linalg.norm or the expression sqrt((xm*xm).sum()),
  3606. # scipy.linalg.norm(xm) does not overflow if xm is, for example,
  3607. # [-5e210, 5e210, 3e200, -3e200]
  3608. normxm = linalg.norm(xm)
  3609. normym = linalg.norm(ym)
  3610. threshold = 1e-13
  3611. if normxm < threshold*abs(xmean) or normym < threshold*abs(ymean):
  3612. # If all the values in x (likewise y) are very close to the mean,
  3613. # the loss of precision that occurs in the subtraction xm = x - xmean
  3614. # might result in large errors in r.
  3615. msg = ("An input array is nearly constant; the computed "
  3616. "correlation coefficient may be inaccurate.")
  3617. warnings.warn(stats.NearConstantInputWarning(msg))
  3618. r = np.dot(xm/normxm, ym/normym)
  3619. # Presumably, if abs(r) > 1, then it is only some small artifact of
  3620. # floating point arithmetic.
  3621. r = max(min(r, 1.0), -1.0)
  3622. # As explained in the docstring, the distribution of `r` under the null
  3623. # hypothesis is the beta distribution on (-1, 1) with a = b = n/2 - 1.
  3624. ab = n/2 - 1
  3625. dist = stats.beta(ab, ab, loc=-1, scale=2)
  3626. if alternative == 'two-sided':
  3627. prob = 2*dist.sf(abs(r))
  3628. elif alternative == 'less':
  3629. prob = dist.cdf(r)
  3630. elif alternative == 'greater':
  3631. prob = dist.sf(r)
  3632. else:
  3633. raise ValueError('alternative must be one of '
  3634. '["two-sided", "less", "greater"]')
  3635. return PearsonRResult(statistic=r, pvalue=prob, n=n,
  3636. alternative=alternative)
  3637. def fisher_exact(table, alternative='two-sided'):
  3638. """Perform a Fisher exact test on a 2x2 contingency table.
  3639. The null hypothesis is that the true odds ratio of the populations
  3640. underlying the observations is one, and the observations were sampled
  3641. from these populations under a condition: the marginals of the
  3642. resulting table must equal those of the observed table. The statistic
  3643. returned is the unconditional maximum likelihood estimate of the odds
  3644. ratio, and the p-value is the probability under the null hypothesis of
  3645. obtaining a table at least as extreme as the one that was actually
  3646. observed. There are other possible choices of statistic and two-sided
  3647. p-value definition associated with Fisher's exact test; please see the
  3648. Notes for more information.
  3649. Parameters
  3650. ----------
  3651. table : array_like of ints
  3652. A 2x2 contingency table. Elements must be non-negative integers.
  3653. alternative : {'two-sided', 'less', 'greater'}, optional
  3654. Defines the alternative hypothesis.
  3655. The following options are available (default is 'two-sided'):
  3656. * 'two-sided': the odds ratio of the underlying population is not one
  3657. * 'less': the odds ratio of the underlying population is less than one
  3658. * 'greater': the odds ratio of the underlying population is greater
  3659. than one
  3660. See the Notes for more details.
  3661. Returns
  3662. -------
  3663. res : SignificanceResult
  3664. An object containing attributes:
  3665. statistic : float
  3666. This is the prior odds ratio, not a posterior estimate.
  3667. pvalue : float
  3668. The probability under the null hypothesis of obtaining a
  3669. table at least as extreme as the one that was actually observed.
  3670. See Also
  3671. --------
  3672. chi2_contingency : Chi-square test of independence of variables in a
  3673. contingency table. This can be used as an alternative to
  3674. `fisher_exact` when the numbers in the table are large.
  3675. contingency.odds_ratio : Compute the odds ratio (sample or conditional
  3676. MLE) for a 2x2 contingency table.
  3677. barnard_exact : Barnard's exact test, which is a more powerful alternative
  3678. than Fisher's exact test for 2x2 contingency tables.
  3679. boschloo_exact : Boschloo's exact test, which is a more powerful alternative
  3680. than Fisher's exact test for 2x2 contingency tables.
  3681. Notes
  3682. -----
  3683. *Null hypothesis and p-values*
  3684. The null hypothesis is that the true odds ratio of the populations
  3685. underlying the observations is one, and the observations were sampled at
  3686. random from these populations under a condition: the marginals of the
  3687. resulting table must equal those of the observed table. Equivalently,
  3688. the null hypothesis is that the input table is from the hypergeometric
  3689. distribution with parameters (as used in `hypergeom`)
  3690. ``M = a + b + c + d``, ``n = a + b`` and ``N = a + c``, where the
  3691. input table is ``[[a, b], [c, d]]``. This distribution has support
  3692. ``max(0, N + n - M) <= x <= min(N, n)``, or, in terms of the values
  3693. in the input table, ``min(0, a - d) <= x <= a + min(b, c)``. ``x``
  3694. can be interpreted as the upper-left element of a 2x2 table, so the
  3695. tables in the distribution have form::
  3696. [ x n - x ]
  3697. [N - x M - (n + N) + x]
  3698. For example, if::
  3699. table = [6 2]
  3700. [1 4]
  3701. then the support is ``2 <= x <= 7``, and the tables in the distribution
  3702. are::
  3703. [2 6] [3 5] [4 4] [5 3] [6 2] [7 1]
  3704. [5 0] [4 1] [3 2] [2 3] [1 4] [0 5]
  3705. The probability of each table is given by the hypergeometric distribution
  3706. ``hypergeom.pmf(x, M, n, N)``. For this example, these are (rounded to
  3707. three significant digits)::
  3708. x 2 3 4 5 6 7
  3709. p 0.0163 0.163 0.408 0.326 0.0816 0.00466
  3710. These can be computed with::
  3711. >>> import numpy as np
  3712. >>> from scipy.stats import hypergeom
  3713. >>> table = np.array([[6, 2], [1, 4]])
  3714. >>> M = table.sum()
  3715. >>> n = table[0].sum()
  3716. >>> N = table[:, 0].sum()
  3717. >>> start, end = hypergeom.support(M, n, N)
  3718. >>> hypergeom.pmf(np.arange(start, end+1), M, n, N)
  3719. array([0.01631702, 0.16317016, 0.40792541, 0.32634033, 0.08158508,
  3720. 0.004662 ])
  3721. The two-sided p-value is the probability that, under the null hypothesis,
  3722. a random table would have a probability equal to or less than the
  3723. probability of the input table. For our example, the probability of
  3724. the input table (where ``x = 6``) is 0.0816. The x values where the
  3725. probability does not exceed this are 2, 6 and 7, so the two-sided p-value
  3726. is ``0.0163 + 0.0816 + 0.00466 ~= 0.10256``::
  3727. >>> from scipy.stats import fisher_exact
  3728. >>> res = fisher_exact(table, alternative='two-sided')
  3729. >>> res.pvalue
  3730. 0.10256410256410257
  3731. The one-sided p-value for ``alternative='greater'`` is the probability
  3732. that a random table has ``x >= a``, which in our example is ``x >= 6``,
  3733. or ``0.0816 + 0.00466 ~= 0.08626``::
  3734. >>> res = fisher_exact(table, alternative='greater')
  3735. >>> res.pvalue
  3736. 0.08624708624708627
  3737. This is equivalent to computing the survival function of the
  3738. distribution at ``x = 5`` (one less than ``x`` from the input table,
  3739. because we want to include the probability of ``x = 6`` in the sum)::
  3740. >>> hypergeom.sf(5, M, n, N)
  3741. 0.08624708624708627
  3742. For ``alternative='less'``, the one-sided p-value is the probability
  3743. that a random table has ``x <= a``, (i.e. ``x <= 6`` in our example),
  3744. or ``0.0163 + 0.163 + 0.408 + 0.326 + 0.0816 ~= 0.9949``::
  3745. >>> res = fisher_exact(table, alternative='less')
  3746. >>> res.pvalue
  3747. 0.9953379953379957
  3748. This is equivalent to computing the cumulative distribution function
  3749. of the distribution at ``x = 6``:
  3750. >>> hypergeom.cdf(6, M, n, N)
  3751. 0.9953379953379957
  3752. *Odds ratio*
  3753. The calculated odds ratio is different from the value computed by the
  3754. R function ``fisher.test``. This implementation returns the "sample"
  3755. or "unconditional" maximum likelihood estimate, while ``fisher.test``
  3756. in R uses the conditional maximum likelihood estimate. To compute the
  3757. conditional maximum likelihood estimate of the odds ratio, use
  3758. `scipy.stats.contingency.odds_ratio`.
  3759. Examples
  3760. --------
  3761. Say we spend a few days counting whales and sharks in the Atlantic and
  3762. Indian oceans. In the Atlantic ocean we find 8 whales and 1 shark, in the
  3763. Indian ocean 2 whales and 5 sharks. Then our contingency table is::
  3764. Atlantic Indian
  3765. whales 8 2
  3766. sharks 1 5
  3767. We use this table to find the p-value:
  3768. >>> from scipy.stats import fisher_exact
  3769. >>> res = fisher_exact([[8, 2], [1, 5]])
  3770. >>> res.pvalue
  3771. 0.0349...
  3772. The probability that we would observe this or an even more imbalanced ratio
  3773. by chance is about 3.5%. A commonly used significance level is 5%--if we
  3774. adopt that, we can therefore conclude that our observed imbalance is
  3775. statistically significant; whales prefer the Atlantic while sharks prefer
  3776. the Indian ocean.
  3777. """
  3778. hypergeom = distributions.hypergeom
  3779. # int32 is not enough for the algorithm
  3780. c = np.asarray(table, dtype=np.int64)
  3781. if not c.shape == (2, 2):
  3782. raise ValueError("The input `table` must be of shape (2, 2).")
  3783. if np.any(c < 0):
  3784. raise ValueError("All values in `table` must be nonnegative.")
  3785. if 0 in c.sum(axis=0) or 0 in c.sum(axis=1):
  3786. # If both values in a row or column are zero, the p-value is 1 and
  3787. # the odds ratio is NaN.
  3788. return SignificanceResult(np.nan, 1.0)
  3789. if c[1, 0] > 0 and c[0, 1] > 0:
  3790. oddsratio = c[0, 0] * c[1, 1] / (c[1, 0] * c[0, 1])
  3791. else:
  3792. oddsratio = np.inf
  3793. n1 = c[0, 0] + c[0, 1]
  3794. n2 = c[1, 0] + c[1, 1]
  3795. n = c[0, 0] + c[1, 0]
  3796. def pmf(x):
  3797. return hypergeom.pmf(x, n1 + n2, n1, n)
  3798. if alternative == 'less':
  3799. pvalue = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
  3800. elif alternative == 'greater':
  3801. # Same formula as the 'less' case, but with the second column.
  3802. pvalue = hypergeom.cdf(c[0, 1], n1 + n2, n1, c[0, 1] + c[1, 1])
  3803. elif alternative == 'two-sided':
  3804. mode = int((n + 1) * (n1 + 1) / (n1 + n2 + 2))
  3805. pexact = hypergeom.pmf(c[0, 0], n1 + n2, n1, n)
  3806. pmode = hypergeom.pmf(mode, n1 + n2, n1, n)
  3807. epsilon = 1e-14
  3808. gamma = 1 + epsilon
  3809. if np.abs(pexact - pmode) / np.maximum(pexact, pmode) <= epsilon:
  3810. return SignificanceResult(oddsratio, 1.)
  3811. elif c[0, 0] < mode:
  3812. plower = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
  3813. if hypergeom.pmf(n, n1 + n2, n1, n) > pexact * gamma:
  3814. return SignificanceResult(oddsratio, plower)
  3815. guess = _binary_search(lambda x: -pmf(x), -pexact * gamma, mode, n)
  3816. pvalue = plower + hypergeom.sf(guess, n1 + n2, n1, n)
  3817. else:
  3818. pupper = hypergeom.sf(c[0, 0] - 1, n1 + n2, n1, n)
  3819. if hypergeom.pmf(0, n1 + n2, n1, n) > pexact * gamma:
  3820. return SignificanceResult(oddsratio, pupper)
  3821. guess = _binary_search(pmf, pexact * gamma, 0, mode)
  3822. pvalue = pupper + hypergeom.cdf(guess, n1 + n2, n1, n)
  3823. else:
  3824. msg = "`alternative` should be one of {'two-sided', 'less', 'greater'}"
  3825. raise ValueError(msg)
  3826. pvalue = min(pvalue, 1.0)
  3827. return SignificanceResult(oddsratio, pvalue)
  3828. def spearmanr(a, b=None, axis=0, nan_policy='propagate',
  3829. alternative='two-sided'):
  3830. """Calculate a Spearman correlation coefficient with associated p-value.
  3831. The Spearman rank-order correlation coefficient is a nonparametric measure
  3832. of the monotonicity of the relationship between two datasets.
  3833. Like other correlation coefficients,
  3834. this one varies between -1 and +1 with 0 implying no correlation.
  3835. Correlations of -1 or +1 imply an exact monotonic relationship. Positive
  3836. correlations imply that as x increases, so does y. Negative correlations
  3837. imply that as x increases, y decreases.
  3838. The p-value roughly indicates the probability of an uncorrelated system
  3839. producing datasets that have a Spearman correlation at least as extreme
  3840. as the one computed from these datasets. Although calculation of the
  3841. p-value does not make strong assumptions about the distributions underlying
  3842. the samples, it is only accurate for very large samples (>500
  3843. observations). For smaller sample sizes, consider a permutation test (see
  3844. Examples section below).
  3845. Parameters
  3846. ----------
  3847. a, b : 1D or 2D array_like, b is optional
  3848. One or two 1-D or 2-D arrays containing multiple variables and
  3849. observations. When these are 1-D, each represents a vector of
  3850. observations of a single variable. For the behavior in the 2-D case,
  3851. see under ``axis``, below.
  3852. Both arrays need to have the same length in the ``axis`` dimension.
  3853. axis : int or None, optional
  3854. If axis=0 (default), then each column represents a variable, with
  3855. observations in the rows. If axis=1, the relationship is transposed:
  3856. each row represents a variable, while the columns contain observations.
  3857. If axis=None, then both arrays will be raveled.
  3858. nan_policy : {'propagate', 'raise', 'omit'}, optional
  3859. Defines how to handle when input contains nan.
  3860. The following options are available (default is 'propagate'):
  3861. * 'propagate': returns nan
  3862. * 'raise': throws an error
  3863. * 'omit': performs the calculations ignoring nan values
  3864. alternative : {'two-sided', 'less', 'greater'}, optional
  3865. Defines the alternative hypothesis. Default is 'two-sided'.
  3866. The following options are available:
  3867. * 'two-sided': the correlation is nonzero
  3868. * 'less': the correlation is negative (less than zero)
  3869. * 'greater': the correlation is positive (greater than zero)
  3870. .. versionadded:: 1.7.0
  3871. Returns
  3872. -------
  3873. res : SignificanceResult
  3874. An object containing attributes:
  3875. statistic : float or ndarray (2-D square)
  3876. Spearman correlation matrix or correlation coefficient (if only 2
  3877. variables are given as parameters). Correlation matrix is square
  3878. with length equal to total number of variables (columns or rows) in
  3879. ``a`` and ``b`` combined.
  3880. pvalue : float
  3881. The p-value for a hypothesis test whose null hypothesis
  3882. is that two sets of data are linearly uncorrelated. See
  3883. `alternative` above for alternative hypotheses. `pvalue` has the
  3884. same shape as `statistic`.
  3885. Warns
  3886. -----
  3887. `~scipy.stats.ConstantInputWarning`
  3888. Raised if an input is a constant array. The correlation coefficient
  3889. is not defined in this case, so ``np.nan`` is returned.
  3890. References
  3891. ----------
  3892. .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
  3893. Probability and Statistics Tables and Formulae. Chapman & Hall: New
  3894. York. 2000.
  3895. Section 14.7
  3896. .. [2] Kendall, M. G. and Stuart, A. (1973).
  3897. The Advanced Theory of Statistics, Volume 2: Inference and Relationship.
  3898. Griffin. 1973.
  3899. Section 31.18
  3900. Examples
  3901. --------
  3902. >>> import numpy as np
  3903. >>> from scipy import stats
  3904. >>> res = stats.spearmanr([1, 2, 3, 4, 5], [5, 6, 7, 8, 7])
  3905. >>> res.statistic
  3906. 0.8207826816681233
  3907. >>> res.pvalue
  3908. 0.08858700531354381
  3909. >>> rng = np.random.default_rng()
  3910. >>> x2n = rng.standard_normal((100, 2))
  3911. >>> y2n = rng.standard_normal((100, 2))
  3912. >>> res = stats.spearmanr(x2n)
  3913. >>> res.statistic, res.pvalue
  3914. (-0.07960396039603959, 0.4311168705769747)
  3915. >>> res = stats.spearmanr(x2n[:, 0], x2n[:, 1])
  3916. >>> res.statistic, res.pvalue
  3917. (-0.07960396039603959, 0.4311168705769747)
  3918. >>> res = stats.spearmanr(x2n, y2n)
  3919. >>> res.statistic
  3920. array([[ 1. , -0.07960396, -0.08314431, 0.09662166],
  3921. [-0.07960396, 1. , -0.14448245, 0.16738074],
  3922. [-0.08314431, -0.14448245, 1. , 0.03234323],
  3923. [ 0.09662166, 0.16738074, 0.03234323, 1. ]])
  3924. >>> res.pvalue
  3925. array([[0. , 0.43111687, 0.41084066, 0.33891628],
  3926. [0.43111687, 0. , 0.15151618, 0.09600687],
  3927. [0.41084066, 0.15151618, 0. , 0.74938561],
  3928. [0.33891628, 0.09600687, 0.74938561, 0. ]])
  3929. >>> res = stats.spearmanr(x2n.T, y2n.T, axis=1)
  3930. >>> res.statistic
  3931. array([[ 1. , -0.07960396, -0.08314431, 0.09662166],
  3932. [-0.07960396, 1. , -0.14448245, 0.16738074],
  3933. [-0.08314431, -0.14448245, 1. , 0.03234323],
  3934. [ 0.09662166, 0.16738074, 0.03234323, 1. ]])
  3935. >>> res = stats.spearmanr(x2n, y2n, axis=None)
  3936. >>> res.statistic, res.pvalue
  3937. (0.044981624540613524, 0.5270803651336189)
  3938. >>> res = stats.spearmanr(x2n.ravel(), y2n.ravel())
  3939. >>> res.statistic, res.pvalue
  3940. (0.044981624540613524, 0.5270803651336189)
  3941. >>> rng = np.random.default_rng()
  3942. >>> xint = rng.integers(10, size=(100, 2))
  3943. >>> res = stats.spearmanr(xint)
  3944. >>> res.statistic, res.pvalue
  3945. (0.09800224850707953, 0.3320271757932076)
  3946. For small samples, consider performing a permutation test instead of
  3947. relying on the asymptotic p-value. Note that to calculate the null
  3948. distribution of the statistic (for all possibly pairings between
  3949. observations in sample ``x`` and ``y``), only one of the two inputs needs
  3950. to be permuted.
  3951. >>> x = [1.76405235, 0.40015721, 0.97873798,
  3952. ... 2.2408932, 1.86755799, -0.97727788]
  3953. >>> y = [2.71414076, 0.2488, 0.87551913,
  3954. ... 2.6514917, 2.01160156, 0.47699563]
  3955. >>> def statistic(x): # permute only `x`
  3956. ... return stats.spearmanr(x, y).statistic
  3957. >>> res_exact = stats.permutation_test((x,), statistic,
  3958. ... permutation_type='pairings')
  3959. >>> res_asymptotic = stats.spearmanr(x, y)
  3960. >>> res_exact.pvalue, res_asymptotic.pvalue # asymptotic pvalue is too low
  3961. (0.10277777777777777, 0.07239650145772594)
  3962. """
  3963. if axis is not None and axis > 1:
  3964. raise ValueError("spearmanr only handles 1-D or 2-D arrays, "
  3965. "supplied axis argument {}, please use only "
  3966. "values 0, 1 or None for axis".format(axis))
  3967. a, axisout = _chk_asarray(a, axis)
  3968. if a.ndim > 2:
  3969. raise ValueError("spearmanr only handles 1-D or 2-D arrays")
  3970. if b is None:
  3971. if a.ndim < 2:
  3972. raise ValueError("`spearmanr` needs at least 2 "
  3973. "variables to compare")
  3974. else:
  3975. # Concatenate a and b, so that we now only have to handle the case
  3976. # of a 2-D `a`.
  3977. b, _ = _chk_asarray(b, axis)
  3978. if axisout == 0:
  3979. a = np.column_stack((a, b))
  3980. else:
  3981. a = np.row_stack((a, b))
  3982. n_vars = a.shape[1 - axisout]
  3983. n_obs = a.shape[axisout]
  3984. if n_obs <= 1:
  3985. # Handle empty arrays or single observations.
  3986. res = SignificanceResult(np.nan, np.nan)
  3987. res.correlation = np.nan
  3988. return res
  3989. warn_msg = ("An input array is constant; the correlation coefficient "
  3990. "is not defined.")
  3991. if axisout == 0:
  3992. if (a[:, 0][0] == a[:, 0]).all() or (a[:, 1][0] == a[:, 1]).all():
  3993. # If an input is constant, the correlation coefficient
  3994. # is not defined.
  3995. warnings.warn(stats.ConstantInputWarning(warn_msg))
  3996. res = SignificanceResult(np.nan, np.nan)
  3997. res.correlation = np.nan
  3998. return res
  3999. else: # case when axisout == 1 b/c a is 2 dim only
  4000. if (a[0, :][0] == a[0, :]).all() or (a[1, :][0] == a[1, :]).all():
  4001. # If an input is constant, the correlation coefficient
  4002. # is not defined.
  4003. warnings.warn(stats.ConstantInputWarning(warn_msg))
  4004. res = SignificanceResult(np.nan, np.nan)
  4005. res.correlation = np.nan
  4006. return res
  4007. a_contains_nan, nan_policy = _contains_nan(a, nan_policy)
  4008. variable_has_nan = np.zeros(n_vars, dtype=bool)
  4009. if a_contains_nan:
  4010. if nan_policy == 'omit':
  4011. return mstats_basic.spearmanr(a, axis=axis, nan_policy=nan_policy,
  4012. alternative=alternative)
  4013. elif nan_policy == 'propagate':
  4014. if a.ndim == 1 or n_vars <= 2:
  4015. res = SignificanceResult(np.nan, np.nan)
  4016. res.correlation = np.nan
  4017. return res
  4018. else:
  4019. # Keep track of variables with NaNs, set the outputs to NaN
  4020. # only for those variables
  4021. variable_has_nan = np.isnan(a).any(axis=axisout)
  4022. a_ranked = np.apply_along_axis(rankdata, axisout, a)
  4023. rs = np.corrcoef(a_ranked, rowvar=axisout)
  4024. dof = n_obs - 2 # degrees of freedom
  4025. # rs can have elements equal to 1, so avoid zero division warnings
  4026. with np.errstate(divide='ignore'):
  4027. # clip the small negative values possibly caused by rounding
  4028. # errors before taking the square root
  4029. t = rs * np.sqrt((dof/((rs+1.0)*(1.0-rs))).clip(0))
  4030. t, prob = _ttest_finish(dof, t, alternative)
  4031. # For backwards compatibility, return scalars when comparing 2 columns
  4032. if rs.shape == (2, 2):
  4033. res = SignificanceResult(rs[1, 0], prob[1, 0])
  4034. res.correlation = rs[1, 0]
  4035. return res
  4036. else:
  4037. rs[variable_has_nan, :] = np.nan
  4038. rs[:, variable_has_nan] = np.nan
  4039. res = SignificanceResult(rs, prob)
  4040. res.correlation = rs
  4041. return res
  4042. def pointbiserialr(x, y):
  4043. r"""Calculate a point biserial correlation coefficient and its p-value.
  4044. The point biserial correlation is used to measure the relationship
  4045. between a binary variable, x, and a continuous variable, y. Like other
  4046. correlation coefficients, this one varies between -1 and +1 with 0
  4047. implying no correlation. Correlations of -1 or +1 imply a determinative
  4048. relationship.
  4049. This function may be computed using a shortcut formula but produces the
  4050. same result as `pearsonr`.
  4051. Parameters
  4052. ----------
  4053. x : array_like of bools
  4054. Input array.
  4055. y : array_like
  4056. Input array.
  4057. Returns
  4058. -------
  4059. res: SignificanceResult
  4060. An object containing attributes:
  4061. statistic : float
  4062. The R value.
  4063. pvalue : float
  4064. The two-sided p-value.
  4065. Notes
  4066. -----
  4067. `pointbiserialr` uses a t-test with ``n-1`` degrees of freedom.
  4068. It is equivalent to `pearsonr`.
  4069. The value of the point-biserial correlation can be calculated from:
  4070. .. math::
  4071. r_{pb} = \frac{\overline{Y_{1}} -
  4072. \overline{Y_{0}}}{s_{y}}\sqrt{\frac{N_{1} N_{2}}{N (N - 1))}}
  4073. Where :math:`Y_{0}` and :math:`Y_{1}` are means of the metric
  4074. observations coded 0 and 1 respectively; :math:`N_{0}` and :math:`N_{1}`
  4075. are number of observations coded 0 and 1 respectively; :math:`N` is the
  4076. total number of observations and :math:`s_{y}` is the standard
  4077. deviation of all the metric observations.
  4078. A value of :math:`r_{pb}` that is significantly different from zero is
  4079. completely equivalent to a significant difference in means between the two
  4080. groups. Thus, an independent groups t Test with :math:`N-2` degrees of
  4081. freedom may be used to test whether :math:`r_{pb}` is nonzero. The
  4082. relation between the t-statistic for comparing two independent groups and
  4083. :math:`r_{pb}` is given by:
  4084. .. math::
  4085. t = \sqrt{N - 2}\frac{r_{pb}}{\sqrt{1 - r^{2}_{pb}}}
  4086. References
  4087. ----------
  4088. .. [1] J. Lev, "The Point Biserial Coefficient of Correlation", Ann. Math.
  4089. Statist., Vol. 20, no.1, pp. 125-126, 1949.
  4090. .. [2] R.F. Tate, "Correlation Between a Discrete and a Continuous
  4091. Variable. Point-Biserial Correlation.", Ann. Math. Statist., Vol. 25,
  4092. np. 3, pp. 603-607, 1954.
  4093. .. [3] D. Kornbrot "Point Biserial Correlation", In Wiley StatsRef:
  4094. Statistics Reference Online (eds N. Balakrishnan, et al.), 2014.
  4095. :doi:`10.1002/9781118445112.stat06227`
  4096. Examples
  4097. --------
  4098. >>> import numpy as np
  4099. >>> from scipy import stats
  4100. >>> a = np.array([0, 0, 0, 1, 1, 1, 1])
  4101. >>> b = np.arange(7)
  4102. >>> stats.pointbiserialr(a, b)
  4103. (0.8660254037844386, 0.011724811003954652)
  4104. >>> stats.pearsonr(a, b)
  4105. (0.86602540378443871, 0.011724811003954626)
  4106. >>> np.corrcoef(a, b)
  4107. array([[ 1. , 0.8660254],
  4108. [ 0.8660254, 1. ]])
  4109. """
  4110. rpb, prob = pearsonr(x, y)
  4111. # create result object with alias for backward compatibility
  4112. res = SignificanceResult(rpb, prob)
  4113. res.correlation = rpb
  4114. return res
  4115. def kendalltau(x, y, initial_lexsort=None, nan_policy='propagate',
  4116. method='auto', variant='b', alternative='two-sided'):
  4117. """Calculate Kendall's tau, a correlation measure for ordinal data.
  4118. Kendall's tau is a measure of the correspondence between two rankings.
  4119. Values close to 1 indicate strong agreement, and values close to -1
  4120. indicate strong disagreement. This implements two variants of Kendall's
  4121. tau: tau-b (the default) and tau-c (also known as Stuart's tau-c). These
  4122. differ only in how they are normalized to lie within the range -1 to 1;
  4123. the hypothesis tests (their p-values) are identical. Kendall's original
  4124. tau-a is not implemented separately because both tau-b and tau-c reduce
  4125. to tau-a in the absence of ties.
  4126. Parameters
  4127. ----------
  4128. x, y : array_like
  4129. Arrays of rankings, of the same shape. If arrays are not 1-D, they
  4130. will be flattened to 1-D.
  4131. initial_lexsort : bool, optional, deprecated
  4132. This argument is unused.
  4133. .. deprecated:: 1.10.0
  4134. `kendalltau` keyword argument `initial_lexsort` is deprecated as it
  4135. is unused and will be removed in SciPy 1.12.0.
  4136. nan_policy : {'propagate', 'raise', 'omit'}, optional
  4137. Defines how to handle when input contains nan.
  4138. The following options are available (default is 'propagate'):
  4139. * 'propagate': returns nan
  4140. * 'raise': throws an error
  4141. * 'omit': performs the calculations ignoring nan values
  4142. method : {'auto', 'asymptotic', 'exact'}, optional
  4143. Defines which method is used to calculate the p-value [5]_.
  4144. The following options are available (default is 'auto'):
  4145. * 'auto': selects the appropriate method based on a trade-off
  4146. between speed and accuracy
  4147. * 'asymptotic': uses a normal approximation valid for large samples
  4148. * 'exact': computes the exact p-value, but can only be used if no ties
  4149. are present. As the sample size increases, the 'exact' computation
  4150. time may grow and the result may lose some precision.
  4151. variant : {'b', 'c'}, optional
  4152. Defines which variant of Kendall's tau is returned. Default is 'b'.
  4153. alternative : {'two-sided', 'less', 'greater'}, optional
  4154. Defines the alternative hypothesis. Default is 'two-sided'.
  4155. The following options are available:
  4156. * 'two-sided': the rank correlation is nonzero
  4157. * 'less': the rank correlation is negative (less than zero)
  4158. * 'greater': the rank correlation is positive (greater than zero)
  4159. Returns
  4160. -------
  4161. res : SignificanceResult
  4162. An object containing attributes:
  4163. statistic : float
  4164. The tau statistic.
  4165. pvalue : float
  4166. The p-value for a hypothesis test whose null hypothesis is
  4167. an absence of association, tau = 0.
  4168. See Also
  4169. --------
  4170. spearmanr : Calculates a Spearman rank-order correlation coefficient.
  4171. theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
  4172. weightedtau : Computes a weighted version of Kendall's tau.
  4173. Notes
  4174. -----
  4175. The definition of Kendall's tau that is used is [2]_::
  4176. tau_b = (P - Q) / sqrt((P + Q + T) * (P + Q + U))
  4177. tau_c = 2 (P - Q) / (n**2 * (m - 1) / m)
  4178. where P is the number of concordant pairs, Q the number of discordant
  4179. pairs, T the number of ties only in `x`, and U the number of ties only in
  4180. `y`. If a tie occurs for the same pair in both `x` and `y`, it is not
  4181. added to either T or U. n is the total number of samples, and m is the
  4182. number of unique values in either `x` or `y`, whichever is smaller.
  4183. References
  4184. ----------
  4185. .. [1] Maurice G. Kendall, "A New Measure of Rank Correlation", Biometrika
  4186. Vol. 30, No. 1/2, pp. 81-93, 1938.
  4187. .. [2] Maurice G. Kendall, "The treatment of ties in ranking problems",
  4188. Biometrika Vol. 33, No. 3, pp. 239-251. 1945.
  4189. .. [3] Gottfried E. Noether, "Elements of Nonparametric Statistics", John
  4190. Wiley & Sons, 1967.
  4191. .. [4] Peter M. Fenwick, "A new data structure for cumulative frequency
  4192. tables", Software: Practice and Experience, Vol. 24, No. 3,
  4193. pp. 327-336, 1994.
  4194. .. [5] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
  4195. Charles Griffin & Co., 1970.
  4196. Examples
  4197. --------
  4198. >>> from scipy import stats
  4199. >>> x1 = [12, 2, 1, 12, 2]
  4200. >>> x2 = [1, 4, 7, 1, 0]
  4201. >>> res = stats.kendalltau(x1, x2)
  4202. >>> res.statistic
  4203. -0.47140452079103173
  4204. >>> res.pvalue
  4205. 0.2827454599327748
  4206. """
  4207. if initial_lexsort is not None:
  4208. msg = ("'kendalltau' keyword argument 'initial_lexsort' is deprecated"
  4209. " as it is unused and will be removed in SciPy 1.12.0.")
  4210. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  4211. x = np.asarray(x).ravel()
  4212. y = np.asarray(y).ravel()
  4213. if x.size != y.size:
  4214. raise ValueError("All inputs to `kendalltau` must be of the same "
  4215. f"size, found x-size {x.size} and y-size {y.size}")
  4216. elif not x.size or not y.size:
  4217. # Return NaN if arrays are empty
  4218. res = SignificanceResult(np.nan, np.nan)
  4219. res.correlation = np.nan
  4220. return res
  4221. # check both x and y
  4222. cnx, npx = _contains_nan(x, nan_policy)
  4223. cny, npy = _contains_nan(y, nan_policy)
  4224. contains_nan = cnx or cny
  4225. if npx == 'omit' or npy == 'omit':
  4226. nan_policy = 'omit'
  4227. if contains_nan and nan_policy == 'propagate':
  4228. res = SignificanceResult(np.nan, np.nan)
  4229. res.correlation = np.nan
  4230. return res
  4231. elif contains_nan and nan_policy == 'omit':
  4232. x = ma.masked_invalid(x)
  4233. y = ma.masked_invalid(y)
  4234. if variant == 'b':
  4235. return mstats_basic.kendalltau(x, y, method=method, use_ties=True,
  4236. alternative=alternative)
  4237. else:
  4238. message = ("nan_policy='omit' is currently compatible only with "
  4239. "variant='b'.")
  4240. raise ValueError(message)
  4241. def count_rank_tie(ranks):
  4242. cnt = np.bincount(ranks).astype('int64', copy=False)
  4243. cnt = cnt[cnt > 1]
  4244. return ((cnt * (cnt - 1) // 2).sum(),
  4245. (cnt * (cnt - 1.) * (cnt - 2)).sum(),
  4246. (cnt * (cnt - 1.) * (2*cnt + 5)).sum())
  4247. size = x.size
  4248. perm = np.argsort(y) # sort on y and convert y to dense ranks
  4249. x, y = x[perm], y[perm]
  4250. y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp)
  4251. # stable sort on x and convert x to dense ranks
  4252. perm = np.argsort(x, kind='mergesort')
  4253. x, y = x[perm], y[perm]
  4254. x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp)
  4255. dis = _kendall_dis(x, y) # discordant pairs
  4256. obs = np.r_[True, (x[1:] != x[:-1]) | (y[1:] != y[:-1]), True]
  4257. cnt = np.diff(np.nonzero(obs)[0]).astype('int64', copy=False)
  4258. ntie = (cnt * (cnt - 1) // 2).sum() # joint ties
  4259. xtie, x0, x1 = count_rank_tie(x) # ties in x, stats
  4260. ytie, y0, y1 = count_rank_tie(y) # ties in y, stats
  4261. tot = (size * (size - 1)) // 2
  4262. if xtie == tot or ytie == tot:
  4263. res = SignificanceResult(np.nan, np.nan)
  4264. res.correlation = np.nan
  4265. return res
  4266. # Note that tot = con + dis + (xtie - ntie) + (ytie - ntie) + ntie
  4267. # = con + dis + xtie + ytie - ntie
  4268. con_minus_dis = tot - xtie - ytie + ntie - 2 * dis
  4269. if variant == 'b':
  4270. tau = con_minus_dis / np.sqrt(tot - xtie) / np.sqrt(tot - ytie)
  4271. elif variant == 'c':
  4272. minclasses = min(len(set(x)), len(set(y)))
  4273. tau = 2*con_minus_dis / (size**2 * (minclasses-1)/minclasses)
  4274. else:
  4275. raise ValueError(f"Unknown variant of the method chosen: {variant}. "
  4276. "variant must be 'b' or 'c'.")
  4277. # Limit range to fix computational errors
  4278. tau = min(1., max(-1., tau))
  4279. # The p-value calculation is the same for all variants since the p-value
  4280. # depends only on con_minus_dis.
  4281. if method == 'exact' and (xtie != 0 or ytie != 0):
  4282. raise ValueError("Ties found, exact method cannot be used.")
  4283. if method == 'auto':
  4284. if (xtie == 0 and ytie == 0) and (size <= 33 or
  4285. min(dis, tot-dis) <= 1):
  4286. method = 'exact'
  4287. else:
  4288. method = 'asymptotic'
  4289. if xtie == 0 and ytie == 0 and method == 'exact':
  4290. pvalue = mstats_basic._kendall_p_exact(size, tot-dis, alternative)
  4291. elif method == 'asymptotic':
  4292. # con_minus_dis is approx normally distributed with this variance [3]_
  4293. m = size * (size - 1.)
  4294. var = ((m * (2*size + 5) - x1 - y1) / 18 +
  4295. (2 * xtie * ytie) / m + x0 * y0 / (9 * m * (size - 2)))
  4296. z = con_minus_dis / np.sqrt(var)
  4297. _, pvalue = _normtest_finish(z, alternative)
  4298. else:
  4299. raise ValueError(f"Unknown method {method} specified. Use 'auto', "
  4300. "'exact' or 'asymptotic'.")
  4301. # create result object with alias for backward compatibility
  4302. res = SignificanceResult(tau, pvalue)
  4303. res.correlation = tau
  4304. return res
  4305. def weightedtau(x, y, rank=True, weigher=None, additive=True):
  4306. r"""Compute a weighted version of Kendall's :math:`\tau`.
  4307. The weighted :math:`\tau` is a weighted version of Kendall's
  4308. :math:`\tau` in which exchanges of high weight are more influential than
  4309. exchanges of low weight. The default parameters compute the additive
  4310. hyperbolic version of the index, :math:`\tau_\mathrm h`, which has
  4311. been shown to provide the best balance between important and
  4312. unimportant elements [1]_.
  4313. The weighting is defined by means of a rank array, which assigns a
  4314. nonnegative rank to each element (higher importance ranks being
  4315. associated with smaller values, e.g., 0 is the highest possible rank),
  4316. and a weigher function, which assigns a weight based on the rank to
  4317. each element. The weight of an exchange is then the sum or the product
  4318. of the weights of the ranks of the exchanged elements. The default
  4319. parameters compute :math:`\tau_\mathrm h`: an exchange between
  4320. elements with rank :math:`r` and :math:`s` (starting from zero) has
  4321. weight :math:`1/(r+1) + 1/(s+1)`.
  4322. Specifying a rank array is meaningful only if you have in mind an
  4323. external criterion of importance. If, as it usually happens, you do
  4324. not have in mind a specific rank, the weighted :math:`\tau` is
  4325. defined by averaging the values obtained using the decreasing
  4326. lexicographical rank by (`x`, `y`) and by (`y`, `x`). This is the
  4327. behavior with default parameters. Note that the convention used
  4328. here for ranking (lower values imply higher importance) is opposite
  4329. to that used by other SciPy statistical functions.
  4330. Parameters
  4331. ----------
  4332. x, y : array_like
  4333. Arrays of scores, of the same shape. If arrays are not 1-D, they will
  4334. be flattened to 1-D.
  4335. rank : array_like of ints or bool, optional
  4336. A nonnegative rank assigned to each element. If it is None, the
  4337. decreasing lexicographical rank by (`x`, `y`) will be used: elements of
  4338. higher rank will be those with larger `x`-values, using `y`-values to
  4339. break ties (in particular, swapping `x` and `y` will give a different
  4340. result). If it is False, the element indices will be used
  4341. directly as ranks. The default is True, in which case this
  4342. function returns the average of the values obtained using the
  4343. decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`).
  4344. weigher : callable, optional
  4345. The weigher function. Must map nonnegative integers (zero
  4346. representing the most important element) to a nonnegative weight.
  4347. The default, None, provides hyperbolic weighing, that is,
  4348. rank :math:`r` is mapped to weight :math:`1/(r+1)`.
  4349. additive : bool, optional
  4350. If True, the weight of an exchange is computed by adding the
  4351. weights of the ranks of the exchanged elements; otherwise, the weights
  4352. are multiplied. The default is True.
  4353. Returns
  4354. -------
  4355. res: SignificanceResult
  4356. An object containing attributes:
  4357. statistic : float
  4358. The weighted :math:`\tau` correlation index.
  4359. pvalue : float
  4360. Presently ``np.nan``, as the null distribution of the statistic is
  4361. unknown (even in the additive hyperbolic case).
  4362. See Also
  4363. --------
  4364. kendalltau : Calculates Kendall's tau.
  4365. spearmanr : Calculates a Spearman rank-order correlation coefficient.
  4366. theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
  4367. Notes
  4368. -----
  4369. This function uses an :math:`O(n \log n)`, mergesort-based algorithm
  4370. [1]_ that is a weighted extension of Knight's algorithm for Kendall's
  4371. :math:`\tau` [2]_. It can compute Shieh's weighted :math:`\tau` [3]_
  4372. between rankings without ties (i.e., permutations) by setting
  4373. `additive` and `rank` to False, as the definition given in [1]_ is a
  4374. generalization of Shieh's.
  4375. NaNs are considered the smallest possible score.
  4376. .. versionadded:: 0.19.0
  4377. References
  4378. ----------
  4379. .. [1] Sebastiano Vigna, "A weighted correlation index for rankings with
  4380. ties", Proceedings of the 24th international conference on World
  4381. Wide Web, pp. 1166-1176, ACM, 2015.
  4382. .. [2] W.R. Knight, "A Computer Method for Calculating Kendall's Tau with
  4383. Ungrouped Data", Journal of the American Statistical Association,
  4384. Vol. 61, No. 314, Part 1, pp. 436-439, 1966.
  4385. .. [3] Grace S. Shieh. "A weighted Kendall's tau statistic", Statistics &
  4386. Probability Letters, Vol. 39, No. 1, pp. 17-24, 1998.
  4387. Examples
  4388. --------
  4389. >>> import numpy as np
  4390. >>> from scipy import stats
  4391. >>> x = [12, 2, 1, 12, 2]
  4392. >>> y = [1, 4, 7, 1, 0]
  4393. >>> res = stats.weightedtau(x, y)
  4394. >>> res.statistic
  4395. -0.56694968153682723
  4396. >>> res.pvalue
  4397. nan
  4398. >>> res = stats.weightedtau(x, y, additive=False)
  4399. >>> res.statistic
  4400. -0.62205716951801038
  4401. NaNs are considered the smallest possible score:
  4402. >>> x = [12, 2, 1, 12, 2]
  4403. >>> y = [1, 4, 7, 1, np.nan]
  4404. >>> res = stats.weightedtau(x, y)
  4405. >>> res.statistic
  4406. -0.56694968153682723
  4407. This is exactly Kendall's tau:
  4408. >>> x = [12, 2, 1, 12, 2]
  4409. >>> y = [1, 4, 7, 1, 0]
  4410. >>> res = stats.weightedtau(x, y, weigher=lambda x: 1)
  4411. >>> res.statistic
  4412. -0.47140452079103173
  4413. >>> x = [12, 2, 1, 12, 2]
  4414. >>> y = [1, 4, 7, 1, 0]
  4415. >>> stats.weightedtau(x, y, rank=None)
  4416. SignificanceResult(statistic=-0.4157652301037516, pvalue=nan)
  4417. >>> stats.weightedtau(y, x, rank=None)
  4418. SignificanceResult(statistic=-0.7181341329699028, pvalue=nan)
  4419. """
  4420. x = np.asarray(x).ravel()
  4421. y = np.asarray(y).ravel()
  4422. if x.size != y.size:
  4423. raise ValueError("All inputs to `weightedtau` must be "
  4424. "of the same size, "
  4425. "found x-size %s and y-size %s" % (x.size, y.size))
  4426. if not x.size:
  4427. # Return NaN if arrays are empty
  4428. res = SignificanceResult(np.nan, np.nan)
  4429. res.correlation = np.nan
  4430. return res
  4431. # If there are NaNs we apply _toint64()
  4432. if np.isnan(np.sum(x)):
  4433. x = _toint64(x)
  4434. if np.isnan(np.sum(y)):
  4435. y = _toint64(y)
  4436. # Reduce to ranks unsupported types
  4437. if x.dtype != y.dtype:
  4438. if x.dtype != np.int64:
  4439. x = _toint64(x)
  4440. if y.dtype != np.int64:
  4441. y = _toint64(y)
  4442. else:
  4443. if x.dtype not in (np.int32, np.int64, np.float32, np.float64):
  4444. x = _toint64(x)
  4445. y = _toint64(y)
  4446. if rank is True:
  4447. tau = (
  4448. _weightedrankedtau(x, y, None, weigher, additive) +
  4449. _weightedrankedtau(y, x, None, weigher, additive)
  4450. ) / 2
  4451. res = SignificanceResult(tau, np.nan)
  4452. res.correlation = tau
  4453. return res
  4454. if rank is False:
  4455. rank = np.arange(x.size, dtype=np.intp)
  4456. elif rank is not None:
  4457. rank = np.asarray(rank).ravel()
  4458. if rank.size != x.size:
  4459. raise ValueError(
  4460. "All inputs to `weightedtau` must be of the same size, "
  4461. "found x-size %s and rank-size %s" % (x.size, rank.size)
  4462. )
  4463. tau = _weightedrankedtau(x, y, rank, weigher, additive)
  4464. res = SignificanceResult(tau, np.nan)
  4465. res.correlation = tau
  4466. return res
  4467. # FROM MGCPY: https://github.com/neurodata/mgcpy
  4468. class _ParallelP:
  4469. """Helper function to calculate parallel p-value."""
  4470. def __init__(self, x, y, random_states):
  4471. self.x = x
  4472. self.y = y
  4473. self.random_states = random_states
  4474. def __call__(self, index):
  4475. order = self.random_states[index].permutation(self.y.shape[0])
  4476. permy = self.y[order][:, order]
  4477. # calculate permuted stats, store in null distribution
  4478. perm_stat = _mgc_stat(self.x, permy)[0]
  4479. return perm_stat
  4480. def _perm_test(x, y, stat, reps=1000, workers=-1, random_state=None):
  4481. r"""Helper function that calculates the p-value. See below for uses.
  4482. Parameters
  4483. ----------
  4484. x, y : ndarray
  4485. `x` and `y` have shapes `(n, p)` and `(n, q)`.
  4486. stat : float
  4487. The sample test statistic.
  4488. reps : int, optional
  4489. The number of replications used to estimate the null when using the
  4490. permutation test. The default is 1000 replications.
  4491. workers : int or map-like callable, optional
  4492. If `workers` is an int the population is subdivided into `workers`
  4493. sections and evaluated in parallel (uses
  4494. `multiprocessing.Pool <multiprocessing>`). Supply `-1` to use all cores
  4495. available to the Process. Alternatively supply a map-like callable,
  4496. such as `multiprocessing.Pool.map` for evaluating the population in
  4497. parallel. This evaluation is carried out as `workers(func, iterable)`.
  4498. Requires that `func` be pickleable.
  4499. random_state : {None, int, `numpy.random.Generator`,
  4500. `numpy.random.RandomState`}, optional
  4501. If `seed` is None (or `np.random`), the `numpy.random.RandomState`
  4502. singleton is used.
  4503. If `seed` is an int, a new ``RandomState`` instance is used,
  4504. seeded with `seed`.
  4505. If `seed` is already a ``Generator`` or ``RandomState`` instance then
  4506. that instance is used.
  4507. Returns
  4508. -------
  4509. pvalue : float
  4510. The sample test p-value.
  4511. null_dist : list
  4512. The approximated null distribution.
  4513. """
  4514. # generate seeds for each rep (change to new parallel random number
  4515. # capabilities in numpy >= 1.17+)
  4516. random_state = check_random_state(random_state)
  4517. random_states = [np.random.RandomState(rng_integers(random_state, 1 << 32,
  4518. size=4, dtype=np.uint32)) for _ in range(reps)]
  4519. # parallelizes with specified workers over number of reps and set seeds
  4520. parallelp = _ParallelP(x=x, y=y, random_states=random_states)
  4521. with MapWrapper(workers) as mapwrapper:
  4522. null_dist = np.array(list(mapwrapper(parallelp, range(reps))))
  4523. # calculate p-value and significant permutation map through list
  4524. pvalue = (1 + (null_dist >= stat).sum()) / (1 + reps)
  4525. return pvalue, null_dist
  4526. def _euclidean_dist(x):
  4527. return cdist(x, x)
  4528. MGCResult = _make_tuple_bunch('MGCResult',
  4529. ['statistic', 'pvalue', 'mgc_dict'], [])
  4530. def multiscale_graphcorr(x, y, compute_distance=_euclidean_dist, reps=1000,
  4531. workers=1, is_twosamp=False, random_state=None):
  4532. r"""Computes the Multiscale Graph Correlation (MGC) test statistic.
  4533. Specifically, for each point, MGC finds the :math:`k`-nearest neighbors for
  4534. one property (e.g. cloud density), and the :math:`l`-nearest neighbors for
  4535. the other property (e.g. grass wetness) [1]_. This pair :math:`(k, l)` is
  4536. called the "scale". A priori, however, it is not know which scales will be
  4537. most informative. So, MGC computes all distance pairs, and then efficiently
  4538. computes the distance correlations for all scales. The local correlations
  4539. illustrate which scales are relatively informative about the relationship.
  4540. The key, therefore, to successfully discover and decipher relationships
  4541. between disparate data modalities is to adaptively determine which scales
  4542. are the most informative, and the geometric implication for the most
  4543. informative scales. Doing so not only provides an estimate of whether the
  4544. modalities are related, but also provides insight into how the
  4545. determination was made. This is especially important in high-dimensional
  4546. data, where simple visualizations do not reveal relationships to the
  4547. unaided human eye. Characterizations of this implementation in particular
  4548. have been derived from and benchmarked within in [2]_.
  4549. Parameters
  4550. ----------
  4551. x, y : ndarray
  4552. If ``x`` and ``y`` have shapes ``(n, p)`` and ``(n, q)`` where `n` is
  4553. the number of samples and `p` and `q` are the number of dimensions,
  4554. then the MGC independence test will be run. Alternatively, ``x`` and
  4555. ``y`` can have shapes ``(n, n)`` if they are distance or similarity
  4556. matrices, and ``compute_distance`` must be sent to ``None``. If ``x``
  4557. and ``y`` have shapes ``(n, p)`` and ``(m, p)``, an unpaired
  4558. two-sample MGC test will be run.
  4559. compute_distance : callable, optional
  4560. A function that computes the distance or similarity among the samples
  4561. within each data matrix. Set to ``None`` if ``x`` and ``y`` are
  4562. already distance matrices. The default uses the euclidean norm metric.
  4563. If you are calling a custom function, either create the distance
  4564. matrix before-hand or create a function of the form
  4565. ``compute_distance(x)`` where `x` is the data matrix for which
  4566. pairwise distances are calculated.
  4567. reps : int, optional
  4568. The number of replications used to estimate the null when using the
  4569. permutation test. The default is ``1000``.
  4570. workers : int or map-like callable, optional
  4571. If ``workers`` is an int the population is subdivided into ``workers``
  4572. sections and evaluated in parallel (uses ``multiprocessing.Pool
  4573. <multiprocessing>``). Supply ``-1`` to use all cores available to the
  4574. Process. Alternatively supply a map-like callable, such as
  4575. ``multiprocessing.Pool.map`` for evaluating the p-value in parallel.
  4576. This evaluation is carried out as ``workers(func, iterable)``.
  4577. Requires that `func` be pickleable. The default is ``1``.
  4578. is_twosamp : bool, optional
  4579. If `True`, a two sample test will be run. If ``x`` and ``y`` have
  4580. shapes ``(n, p)`` and ``(m, p)``, this optional will be overridden and
  4581. set to ``True``. Set to ``True`` if ``x`` and ``y`` both have shapes
  4582. ``(n, p)`` and a two sample test is desired. The default is ``False``.
  4583. Note that this will not run if inputs are distance matrices.
  4584. random_state : {None, int, `numpy.random.Generator`,
  4585. `numpy.random.RandomState`}, optional
  4586. If `seed` is None (or `np.random`), the `numpy.random.RandomState`
  4587. singleton is used.
  4588. If `seed` is an int, a new ``RandomState`` instance is used,
  4589. seeded with `seed`.
  4590. If `seed` is already a ``Generator`` or ``RandomState`` instance then
  4591. that instance is used.
  4592. Returns
  4593. -------
  4594. res : MGCResult
  4595. An object containing attributes:
  4596. statistic : float
  4597. The sample MGC test statistic within `[-1, 1]`.
  4598. pvalue : float
  4599. The p-value obtained via permutation.
  4600. mgc_dict : dict
  4601. Contains additional useful results:
  4602. - mgc_map : ndarray
  4603. A 2D representation of the latent geometry of the
  4604. relationship.
  4605. - opt_scale : (int, int)
  4606. The estimated optimal scale as a `(x, y)` pair.
  4607. - null_dist : list
  4608. The null distribution derived from the permuted matrices.
  4609. See Also
  4610. --------
  4611. pearsonr : Pearson correlation coefficient and p-value for testing
  4612. non-correlation.
  4613. kendalltau : Calculates Kendall's tau.
  4614. spearmanr : Calculates a Spearman rank-order correlation coefficient.
  4615. Notes
  4616. -----
  4617. A description of the process of MGC and applications on neuroscience data
  4618. can be found in [1]_. It is performed using the following steps:
  4619. #. Two distance matrices :math:`D^X` and :math:`D^Y` are computed and
  4620. modified to be mean zero columnwise. This results in two
  4621. :math:`n \times n` distance matrices :math:`A` and :math:`B` (the
  4622. centering and unbiased modification) [3]_.
  4623. #. For all values :math:`k` and :math:`l` from :math:`1, ..., n`,
  4624. * The :math:`k`-nearest neighbor and :math:`l`-nearest neighbor graphs
  4625. are calculated for each property. Here, :math:`G_k (i, j)` indicates
  4626. the :math:`k`-smallest values of the :math:`i`-th row of :math:`A`
  4627. and :math:`H_l (i, j)` indicates the :math:`l` smallested values of
  4628. the :math:`i`-th row of :math:`B`
  4629. * Let :math:`\circ` denotes the entry-wise matrix product, then local
  4630. correlations are summed and normalized using the following statistic:
  4631. .. math::
  4632. c^{kl} = \frac{\sum_{ij} A G_k B H_l}
  4633. {\sqrt{\sum_{ij} A^2 G_k \times \sum_{ij} B^2 H_l}}
  4634. #. The MGC test statistic is the smoothed optimal local correlation of
  4635. :math:`\{ c^{kl} \}`. Denote the smoothing operation as :math:`R(\cdot)`
  4636. (which essentially set all isolated large correlations) as 0 and
  4637. connected large correlations the same as before, see [3]_.) MGC is,
  4638. .. math::
  4639. MGC_n (x, y) = \max_{(k, l)} R \left(c^{kl} \left( x_n, y_n \right)
  4640. \right)
  4641. The test statistic returns a value between :math:`(-1, 1)` since it is
  4642. normalized.
  4643. The p-value returned is calculated using a permutation test. This process
  4644. is completed by first randomly permuting :math:`y` to estimate the null
  4645. distribution and then calculating the probability of observing a test
  4646. statistic, under the null, at least as extreme as the observed test
  4647. statistic.
  4648. MGC requires at least 5 samples to run with reliable results. It can also
  4649. handle high-dimensional data sets.
  4650. In addition, by manipulating the input data matrices, the two-sample
  4651. testing problem can be reduced to the independence testing problem [4]_.
  4652. Given sample data :math:`U` and :math:`V` of sizes :math:`p \times n`
  4653. :math:`p \times m`, data matrix :math:`X` and :math:`Y` can be created as
  4654. follows:
  4655. .. math::
  4656. X = [U | V] \in \mathcal{R}^{p \times (n + m)}
  4657. Y = [0_{1 \times n} | 1_{1 \times m}] \in \mathcal{R}^{(n + m)}
  4658. Then, the MGC statistic can be calculated as normal. This methodology can
  4659. be extended to similar tests such as distance correlation [4]_.
  4660. .. versionadded:: 1.4.0
  4661. References
  4662. ----------
  4663. .. [1] Vogelstein, J. T., Bridgeford, E. W., Wang, Q., Priebe, C. E.,
  4664. Maggioni, M., & Shen, C. (2019). Discovering and deciphering
  4665. relationships across disparate data modalities. ELife.
  4666. .. [2] Panda, S., Palaniappan, S., Xiong, J., Swaminathan, A.,
  4667. Ramachandran, S., Bridgeford, E. W., ... Vogelstein, J. T. (2019).
  4668. mgcpy: A Comprehensive High Dimensional Independence Testing Python
  4669. Package. :arXiv:`1907.02088`
  4670. .. [3] Shen, C., Priebe, C.E., & Vogelstein, J. T. (2019). From distance
  4671. correlation to multiscale graph correlation. Journal of the American
  4672. Statistical Association.
  4673. .. [4] Shen, C. & Vogelstein, J. T. (2018). The Exact Equivalence of
  4674. Distance and Kernel Methods for Hypothesis Testing.
  4675. :arXiv:`1806.05514`
  4676. Examples
  4677. --------
  4678. >>> import numpy as np
  4679. >>> from scipy.stats import multiscale_graphcorr
  4680. >>> x = np.arange(100)
  4681. >>> y = x
  4682. >>> res = multiscale_graphcorr(x, y)
  4683. >>> res.statistic, res.pvalue
  4684. (1.0, 0.001)
  4685. To run an unpaired two-sample test,
  4686. >>> x = np.arange(100)
  4687. >>> y = np.arange(79)
  4688. >>> res = multiscale_graphcorr(x, y)
  4689. >>> res.statistic, res.pvalue # doctest: +SKIP
  4690. (0.033258146255703246, 0.023)
  4691. or, if shape of the inputs are the same,
  4692. >>> x = np.arange(100)
  4693. >>> y = x
  4694. >>> res = multiscale_graphcorr(x, y, is_twosamp=True)
  4695. >>> res.statistic, res.pvalue # doctest: +SKIP
  4696. (-0.008021809890200488, 1.0)
  4697. """
  4698. if not isinstance(x, np.ndarray) or not isinstance(y, np.ndarray):
  4699. raise ValueError("x and y must be ndarrays")
  4700. # convert arrays of type (n,) to (n, 1)
  4701. if x.ndim == 1:
  4702. x = x[:, np.newaxis]
  4703. elif x.ndim != 2:
  4704. raise ValueError("Expected a 2-D array `x`, found shape "
  4705. "{}".format(x.shape))
  4706. if y.ndim == 1:
  4707. y = y[:, np.newaxis]
  4708. elif y.ndim != 2:
  4709. raise ValueError("Expected a 2-D array `y`, found shape "
  4710. "{}".format(y.shape))
  4711. nx, px = x.shape
  4712. ny, py = y.shape
  4713. # check for NaNs
  4714. _contains_nan(x, nan_policy='raise')
  4715. _contains_nan(y, nan_policy='raise')
  4716. # check for positive or negative infinity and raise error
  4717. if np.sum(np.isinf(x)) > 0 or np.sum(np.isinf(y)) > 0:
  4718. raise ValueError("Inputs contain infinities")
  4719. if nx != ny:
  4720. if px == py:
  4721. # reshape x and y for two sample testing
  4722. is_twosamp = True
  4723. else:
  4724. raise ValueError("Shape mismatch, x and y must have shape [n, p] "
  4725. "and [n, q] or have shape [n, p] and [m, p].")
  4726. if nx < 5 or ny < 5:
  4727. raise ValueError("MGC requires at least 5 samples to give reasonable "
  4728. "results.")
  4729. # convert x and y to float
  4730. x = x.astype(np.float64)
  4731. y = y.astype(np.float64)
  4732. # check if compute_distance_matrix if a callable()
  4733. if not callable(compute_distance) and compute_distance is not None:
  4734. raise ValueError("Compute_distance must be a function.")
  4735. # check if number of reps exists, integer, or > 0 (if under 1000 raises
  4736. # warning)
  4737. if not isinstance(reps, int) or reps < 0:
  4738. raise ValueError("Number of reps must be an integer greater than 0.")
  4739. elif reps < 1000:
  4740. msg = ("The number of replications is low (under 1000), and p-value "
  4741. "calculations may be unreliable. Use the p-value result, with "
  4742. "caution!")
  4743. warnings.warn(msg, RuntimeWarning)
  4744. if is_twosamp:
  4745. if compute_distance is None:
  4746. raise ValueError("Cannot run if inputs are distance matrices")
  4747. x, y = _two_sample_transform(x, y)
  4748. if compute_distance is not None:
  4749. # compute distance matrices for x and y
  4750. x = compute_distance(x)
  4751. y = compute_distance(y)
  4752. # calculate MGC stat
  4753. stat, stat_dict = _mgc_stat(x, y)
  4754. stat_mgc_map = stat_dict["stat_mgc_map"]
  4755. opt_scale = stat_dict["opt_scale"]
  4756. # calculate permutation MGC p-value
  4757. pvalue, null_dist = _perm_test(x, y, stat, reps=reps, workers=workers,
  4758. random_state=random_state)
  4759. # save all stats (other than stat/p-value) in dictionary
  4760. mgc_dict = {"mgc_map": stat_mgc_map,
  4761. "opt_scale": opt_scale,
  4762. "null_dist": null_dist}
  4763. # create result object with alias for backward compatibility
  4764. res = MGCResult(stat, pvalue, mgc_dict)
  4765. res.stat = stat
  4766. return res
  4767. def _mgc_stat(distx, disty):
  4768. r"""Helper function that calculates the MGC stat. See above for use.
  4769. Parameters
  4770. ----------
  4771. distx, disty : ndarray
  4772. `distx` and `disty` have shapes `(n, p)` and `(n, q)` or
  4773. `(n, n)` and `(n, n)`
  4774. if distance matrices.
  4775. Returns
  4776. -------
  4777. stat : float
  4778. The sample MGC test statistic within `[-1, 1]`.
  4779. stat_dict : dict
  4780. Contains additional useful additional returns containing the following
  4781. keys:
  4782. - stat_mgc_map : ndarray
  4783. MGC-map of the statistics.
  4784. - opt_scale : (float, float)
  4785. The estimated optimal scale as a `(x, y)` pair.
  4786. """
  4787. # calculate MGC map and optimal scale
  4788. stat_mgc_map = _local_correlations(distx, disty, global_corr='mgc')
  4789. n, m = stat_mgc_map.shape
  4790. if m == 1 or n == 1:
  4791. # the global scale at is the statistic calculated at maximial nearest
  4792. # neighbors. There is not enough local scale to search over, so
  4793. # default to global scale
  4794. stat = stat_mgc_map[m - 1][n - 1]
  4795. opt_scale = m * n
  4796. else:
  4797. samp_size = len(distx) - 1
  4798. # threshold to find connected region of significant local correlations
  4799. sig_connect = _threshold_mgc_map(stat_mgc_map, samp_size)
  4800. # maximum within the significant region
  4801. stat, opt_scale = _smooth_mgc_map(sig_connect, stat_mgc_map)
  4802. stat_dict = {"stat_mgc_map": stat_mgc_map,
  4803. "opt_scale": opt_scale}
  4804. return stat, stat_dict
  4805. def _threshold_mgc_map(stat_mgc_map, samp_size):
  4806. r"""
  4807. Finds a connected region of significance in the MGC-map by thresholding.
  4808. Parameters
  4809. ----------
  4810. stat_mgc_map : ndarray
  4811. All local correlations within `[-1,1]`.
  4812. samp_size : int
  4813. The sample size of original data.
  4814. Returns
  4815. -------
  4816. sig_connect : ndarray
  4817. A binary matrix with 1's indicating the significant region.
  4818. """
  4819. m, n = stat_mgc_map.shape
  4820. # 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05
  4821. # with varying levels of performance. Threshold is based on a beta
  4822. # approximation.
  4823. per_sig = 1 - (0.02 / samp_size) # Percentile to consider as significant
  4824. threshold = samp_size * (samp_size - 3)/4 - 1/2 # Beta approximation
  4825. threshold = distributions.beta.ppf(per_sig, threshold, threshold) * 2 - 1
  4826. # the global scale at is the statistic calculated at maximial nearest
  4827. # neighbors. Threshold is the maximum on the global and local scales
  4828. threshold = max(threshold, stat_mgc_map[m - 1][n - 1])
  4829. # find the largest connected component of significant correlations
  4830. sig_connect = stat_mgc_map > threshold
  4831. if np.sum(sig_connect) > 0:
  4832. sig_connect, _ = _measurements.label(sig_connect)
  4833. _, label_counts = np.unique(sig_connect, return_counts=True)
  4834. # skip the first element in label_counts, as it is count(zeros)
  4835. max_label = np.argmax(label_counts[1:]) + 1
  4836. sig_connect = sig_connect == max_label
  4837. else:
  4838. sig_connect = np.array([[False]])
  4839. return sig_connect
  4840. def _smooth_mgc_map(sig_connect, stat_mgc_map):
  4841. """Finds the smoothed maximal within the significant region R.
  4842. If area of R is too small it returns the last local correlation. Otherwise,
  4843. returns the maximum within significant_connected_region.
  4844. Parameters
  4845. ----------
  4846. sig_connect : ndarray
  4847. A binary matrix with 1's indicating the significant region.
  4848. stat_mgc_map : ndarray
  4849. All local correlations within `[-1, 1]`.
  4850. Returns
  4851. -------
  4852. stat : float
  4853. The sample MGC statistic within `[-1, 1]`.
  4854. opt_scale: (float, float)
  4855. The estimated optimal scale as an `(x, y)` pair.
  4856. """
  4857. m, n = stat_mgc_map.shape
  4858. # the global scale at is the statistic calculated at maximial nearest
  4859. # neighbors. By default, statistic and optimal scale are global.
  4860. stat = stat_mgc_map[m - 1][n - 1]
  4861. opt_scale = [m, n]
  4862. if np.linalg.norm(sig_connect) != 0:
  4863. # proceed only when the connected region's area is sufficiently large
  4864. # 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05
  4865. # with varying levels of performance
  4866. if np.sum(sig_connect) >= np.ceil(0.02 * max(m, n)) * min(m, n):
  4867. max_corr = max(stat_mgc_map[sig_connect])
  4868. # find all scales within significant_connected_region that maximize
  4869. # the local correlation
  4870. max_corr_index = np.where((stat_mgc_map >= max_corr) & sig_connect)
  4871. if max_corr >= stat:
  4872. stat = max_corr
  4873. k, l = max_corr_index
  4874. one_d_indices = k * n + l # 2D to 1D indexing
  4875. k = np.max(one_d_indices) // n
  4876. l = np.max(one_d_indices) % n
  4877. opt_scale = [k+1, l+1] # adding 1s to match R indexing
  4878. return stat, opt_scale
  4879. def _two_sample_transform(u, v):
  4880. """Helper function that concatenates x and y for two sample MGC stat.
  4881. See above for use.
  4882. Parameters
  4883. ----------
  4884. u, v : ndarray
  4885. `u` and `v` have shapes `(n, p)` and `(m, p)`.
  4886. Returns
  4887. -------
  4888. x : ndarray
  4889. Concatenate `u` and `v` along the `axis = 0`. `x` thus has shape
  4890. `(2n, p)`.
  4891. y : ndarray
  4892. Label matrix for `x` where 0 refers to samples that comes from `u` and
  4893. 1 refers to samples that come from `v`. `y` thus has shape `(2n, 1)`.
  4894. """
  4895. nx = u.shape[0]
  4896. ny = v.shape[0]
  4897. x = np.concatenate([u, v], axis=0)
  4898. y = np.concatenate([np.zeros(nx), np.ones(ny)], axis=0).reshape(-1, 1)
  4899. return x, y
  4900. #####################################
  4901. # INFERENTIAL STATISTICS #
  4902. #####################################
  4903. TtestResultBase = _make_tuple_bunch('TtestResultBase',
  4904. ['statistic', 'pvalue'], ['df'])
  4905. class TtestResult(TtestResultBase):
  4906. """
  4907. Result of a t-test.
  4908. See the documentation of the particular t-test function for more
  4909. information about the definition of the statistic and meaning of
  4910. the confidence interval.
  4911. Attributes
  4912. ----------
  4913. statistic : float or array
  4914. The t-statistic of the sample.
  4915. pvalue : float or array
  4916. The p-value associated with the given alternative.
  4917. df : float or array
  4918. The number of degrees of freedom used in calculation of the
  4919. t-statistic; this is one less than the size of the sample
  4920. (``a.shape[axis]-1`` if there are no masked elements or omitted NaNs).
  4921. Methods
  4922. -------
  4923. confidence_interval
  4924. Computes a confidence interval around the population statistic
  4925. for the given confidence level.
  4926. The confidence interval is returned in a ``namedtuple`` with
  4927. fields `low` and `high`.
  4928. """
  4929. def __init__(self, statistic, pvalue, df, # public
  4930. alternative, standard_error, estimate): # private
  4931. super().__init__(statistic, pvalue, df=df)
  4932. self._alternative = alternative
  4933. self._standard_error = standard_error # denominator of t-statistic
  4934. self._estimate = estimate # point estimate of sample mean
  4935. def confidence_interval(self, confidence_level=0.95):
  4936. """
  4937. Parameters
  4938. ----------
  4939. confidence_level : float
  4940. The confidence level for the calculation of the population mean
  4941. confidence interval. Default is 0.95.
  4942. Returns
  4943. -------
  4944. ci : namedtuple
  4945. The confidence interval is returned in a ``namedtuple`` with
  4946. fields `low` and `high`.
  4947. """
  4948. low, high = _t_confidence_interval(self.df, self.statistic,
  4949. confidence_level, self._alternative)
  4950. low = low * self._standard_error + self._estimate
  4951. high = high * self._standard_error + self._estimate
  4952. return ConfidenceInterval(low=low, high=high)
  4953. def pack_TtestResult(statistic, pvalue, df, alternative, standard_error,
  4954. estimate):
  4955. # this could be any number of dimensions (including 0d), but there is
  4956. # at most one unique value
  4957. alternative = np.atleast_1d(alternative).ravel()
  4958. alternative = alternative[0] if alternative.size else np.nan
  4959. return TtestResult(statistic, pvalue, df=df, alternative=alternative,
  4960. standard_error=standard_error, estimate=estimate)
  4961. def unpack_TtestResult(res):
  4962. return (res.statistic, res.pvalue, res.df, res._alternative,
  4963. res._standard_error, res._estimate)
  4964. @_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
  4965. result_to_tuple=unpack_TtestResult, n_outputs=6)
  4966. def ttest_1samp(a, popmean, axis=0, nan_policy='propagate',
  4967. alternative="two-sided"):
  4968. """Calculate the T-test for the mean of ONE group of scores.
  4969. This is a test for the null hypothesis that the expected value
  4970. (mean) of a sample of independent observations `a` is equal to the given
  4971. population mean, `popmean`.
  4972. Parameters
  4973. ----------
  4974. a : array_like
  4975. Sample observation.
  4976. popmean : float or array_like
  4977. Expected value in null hypothesis. If array_like, then its length along
  4978. `axis` must equal 1, and it must otherwise be broadcastable with `a`.
  4979. axis : int or None, optional
  4980. Axis along which to compute test; default is 0. If None, compute over
  4981. the whole array `a`.
  4982. nan_policy : {'propagate', 'raise', 'omit'}, optional
  4983. Defines how to handle when input contains nan.
  4984. The following options are available (default is 'propagate'):
  4985. * 'propagate': returns nan
  4986. * 'raise': throws an error
  4987. * 'omit': performs the calculations ignoring nan values
  4988. alternative : {'two-sided', 'less', 'greater'}, optional
  4989. Defines the alternative hypothesis.
  4990. The following options are available (default is 'two-sided'):
  4991. * 'two-sided': the mean of the underlying distribution of the sample
  4992. is different than the given population mean (`popmean`)
  4993. * 'less': the mean of the underlying distribution of the sample is
  4994. less than the given population mean (`popmean`)
  4995. * 'greater': the mean of the underlying distribution of the sample is
  4996. greater than the given population mean (`popmean`)
  4997. Returns
  4998. -------
  4999. result : `~scipy.stats._result_classes.TtestResult`
  5000. An object with the following attributes:
  5001. statistic : float or array
  5002. The t-statistic.
  5003. pvalue : float or array
  5004. The p-value associated with the given alternative.
  5005. df : float or array
  5006. The number of degrees of freedom used in calculation of the
  5007. t-statistic; this is one less than the size of the sample
  5008. (``a.shape[axis]``).
  5009. .. versionadded:: 1.10.0
  5010. The object also has the following method:
  5011. confidence_interval(confidence_level=0.95)
  5012. Computes a confidence interval around the population
  5013. mean for the given confidence level.
  5014. The confidence interval is returned in a ``namedtuple`` with
  5015. fields `low` and `high`.
  5016. .. versionadded:: 1.10.0
  5017. Notes
  5018. -----
  5019. The statistic is calculated as ``(np.mean(a) - popmean)/se``, where
  5020. ``se`` is the standard error. Therefore, the statistic will be positive
  5021. when the sample mean is greater than the population mean and negative when
  5022. the sample mean is less than the population mean.
  5023. Examples
  5024. --------
  5025. Suppose we wish to test the null hypothesis that the mean of a population
  5026. is equal to 0.5. We choose a confidence level of 99%; that is, we will
  5027. reject the null hypothesis in favor of the alternative if the p-value is
  5028. less than 0.01.
  5029. When testing random variates from the standard uniform distribution, which
  5030. has a mean of 0.5, we expect the data to be consistent with the null
  5031. hypothesis most of the time.
  5032. >>> import numpy as np
  5033. >>> from scipy import stats
  5034. >>> rng = np.random.default_rng()
  5035. >>> rvs = stats.uniform.rvs(size=50, random_state=rng)
  5036. >>> stats.ttest_1samp(rvs, popmean=0.5)
  5037. TtestResult(statistic=2.456308468440, pvalue=0.017628209047638, df=49)
  5038. As expected, the p-value of 0.017 is not below our threshold of 0.01, so
  5039. we cannot reject the null hypothesis.
  5040. When testing data from the standard *normal* distribution, which has a mean
  5041. of 0, we would expect the null hypothesis to be rejected.
  5042. >>> rvs = stats.norm.rvs(size=50, random_state=rng)
  5043. >>> stats.ttest_1samp(rvs, popmean=0.5)
  5044. TtestResult(statistic=-7.433605518875, pvalue=1.416760157221e-09, df=49)
  5045. Indeed, the p-value is lower than our threshold of 0.01, so we reject the
  5046. null hypothesis in favor of the default "two-sided" alternative: the mean
  5047. of the population is *not* equal to 0.5.
  5048. However, suppose we were to test the null hypothesis against the
  5049. one-sided alternative that the mean of the population is *greater* than
  5050. 0.5. Since the mean of the standard normal is less than 0.5, we would not
  5051. expect the null hypothesis to be rejected.
  5052. >>> stats.ttest_1samp(rvs, popmean=0.5, alternative='greater')
  5053. TtestResult(statistic=-7.433605518875, pvalue=0.99999999929, df=49)
  5054. Unsurprisingly, with a p-value greater than our threshold, we would not
  5055. reject the null hypothesis.
  5056. Note that when working with a confidence level of 99%, a true null
  5057. hypothesis will be rejected approximately 1% of the time.
  5058. >>> rvs = stats.uniform.rvs(size=(100, 50), random_state=rng)
  5059. >>> res = stats.ttest_1samp(rvs, popmean=0.5, axis=1)
  5060. >>> np.sum(res.pvalue < 0.01)
  5061. 1
  5062. Indeed, even though all 100 samples above were drawn from the standard
  5063. uniform distribution, which *does* have a population mean of 0.5, we would
  5064. mistakenly reject the null hypothesis for one of them.
  5065. `ttest_1samp` can also compute a confidence interval around the population
  5066. mean.
  5067. >>> rvs = stats.norm.rvs(size=50, random_state=rng)
  5068. >>> res = stats.ttest_1samp(rvs, popmean=0)
  5069. >>> ci = res.confidence_interval(confidence_level=0.95)
  5070. >>> ci
  5071. ConfidenceInterval(low=-0.3193887540880017, high=0.2898583388980972)
  5072. The bounds of the 95% confidence interval are the
  5073. minimum and maximum values of the parameter `popmean` for which the
  5074. p-value of the test would be 0.05.
  5075. >>> res = stats.ttest_1samp(rvs, popmean=ci.low)
  5076. >>> np.testing.assert_allclose(res.pvalue, 0.05)
  5077. >>> res = stats.ttest_1samp(rvs, popmean=ci.high)
  5078. >>> np.testing.assert_allclose(res.pvalue, 0.05)
  5079. Under certain assumptions about the population from which a sample
  5080. is drawn, the confidence interval with confidence level 95% is expected
  5081. to contain the true population mean in 95% of sample replications.
  5082. >>> rvs = stats.norm.rvs(size=(50, 1000), loc=1, random_state=rng)
  5083. >>> res = stats.ttest_1samp(rvs, popmean=0)
  5084. >>> ci = res.confidence_interval()
  5085. >>> contains_pop_mean = (ci.low < 1) & (ci.high > 1)
  5086. >>> contains_pop_mean.sum()
  5087. 953
  5088. """
  5089. a, axis = _chk_asarray(a, axis)
  5090. n = a.shape[axis]
  5091. df = n - 1
  5092. mean = np.mean(a, axis)
  5093. try:
  5094. popmean = np.squeeze(popmean, axis=axis)
  5095. except ValueError as e:
  5096. raise ValueError("`popmean.shape[axis]` must equal 1.") from e
  5097. d = mean - popmean
  5098. v = _var(a, axis, ddof=1)
  5099. denom = np.sqrt(v / n)
  5100. with np.errstate(divide='ignore', invalid='ignore'):
  5101. t = np.divide(d, denom)
  5102. t, prob = _ttest_finish(df, t, alternative)
  5103. # when nan_policy='omit', `df` can be different for different axis-slices
  5104. df = np.broadcast_to(df, t.shape)[()]
  5105. # _axis_nan_policy decorator doesn't play well with strings
  5106. alternative_num = {"less": -1, "two-sided": 0, "greater": 1}[alternative]
  5107. return TtestResult(t, prob, df=df, alternative=alternative_num,
  5108. standard_error=denom, estimate=mean)
  5109. def _t_confidence_interval(df, t, confidence_level, alternative):
  5110. # Input validation on `alternative` is already done
  5111. # We just need IV on confidence_level
  5112. if confidence_level < 0 or confidence_level > 1:
  5113. message = "`confidence_level` must be a number between 0 and 1."
  5114. raise ValueError(message)
  5115. if alternative < 0: # 'less'
  5116. p = confidence_level
  5117. low, high = np.broadcast_arrays(-np.inf, special.stdtrit(df, p))
  5118. elif alternative > 0: # 'greater'
  5119. p = 1 - confidence_level
  5120. low, high = np.broadcast_arrays(special.stdtrit(df, p), np.inf)
  5121. elif alternative == 0: # 'two-sided'
  5122. tail_probability = (1 - confidence_level)/2
  5123. p = tail_probability, 1-tail_probability
  5124. # axis of p must be the zeroth and orthogonal to all the rest
  5125. p = np.reshape(p, [2] + [1]*np.asarray(df).ndim)
  5126. low, high = special.stdtrit(df, p)
  5127. else: # alternative is NaN when input is empty (see _axis_nan_policy)
  5128. p, nans = np.broadcast_arrays(t, np.nan)
  5129. low, high = nans, nans
  5130. return low[()], high[()]
  5131. def _ttest_finish(df, t, alternative):
  5132. """Common code between all 3 t-test functions."""
  5133. # We use ``stdtr`` directly here as it handles the case when ``nan``
  5134. # values are present in the data and masked arrays are passed
  5135. # while ``t.cdf`` emits runtime warnings. This way ``_ttest_finish``
  5136. # can be shared between the ``stats`` and ``mstats`` versions.
  5137. if alternative == 'less':
  5138. pval = special.stdtr(df, t)
  5139. elif alternative == 'greater':
  5140. pval = special.stdtr(df, -t)
  5141. elif alternative == 'two-sided':
  5142. pval = special.stdtr(df, -np.abs(t))*2
  5143. else:
  5144. raise ValueError("alternative must be "
  5145. "'less', 'greater' or 'two-sided'")
  5146. if t.ndim == 0:
  5147. t = t[()]
  5148. if pval.ndim == 0:
  5149. pval = pval[()]
  5150. return t, pval
  5151. def _ttest_ind_from_stats(mean1, mean2, denom, df, alternative):
  5152. d = mean1 - mean2
  5153. with np.errstate(divide='ignore', invalid='ignore'):
  5154. t = np.divide(d, denom)
  5155. t, prob = _ttest_finish(df, t, alternative)
  5156. return (t, prob)
  5157. def _unequal_var_ttest_denom(v1, n1, v2, n2):
  5158. vn1 = v1 / n1
  5159. vn2 = v2 / n2
  5160. with np.errstate(divide='ignore', invalid='ignore'):
  5161. df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1))
  5162. # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0).
  5163. # Hence it doesn't matter what df is as long as it's not NaN.
  5164. df = np.where(np.isnan(df), 1, df)
  5165. denom = np.sqrt(vn1 + vn2)
  5166. return df, denom
  5167. def _equal_var_ttest_denom(v1, n1, v2, n2):
  5168. df = n1 + n2 - 2.0
  5169. svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df
  5170. denom = np.sqrt(svar * (1.0 / n1 + 1.0 / n2))
  5171. return df, denom
  5172. Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue'))
  5173. def ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2,
  5174. equal_var=True, alternative="two-sided"):
  5175. r"""
  5176. T-test for means of two independent samples from descriptive statistics.
  5177. This is a test for the null hypothesis that two independent
  5178. samples have identical average (expected) values.
  5179. Parameters
  5180. ----------
  5181. mean1 : array_like
  5182. The mean(s) of sample 1.
  5183. std1 : array_like
  5184. The corrected sample standard deviation of sample 1 (i.e. ``ddof=1``).
  5185. nobs1 : array_like
  5186. The number(s) of observations of sample 1.
  5187. mean2 : array_like
  5188. The mean(s) of sample 2.
  5189. std2 : array_like
  5190. The corrected sample standard deviation of sample 2 (i.e. ``ddof=1``).
  5191. nobs2 : array_like
  5192. The number(s) of observations of sample 2.
  5193. equal_var : bool, optional
  5194. If True (default), perform a standard independent 2 sample test
  5195. that assumes equal population variances [1]_.
  5196. If False, perform Welch's t-test, which does not assume equal
  5197. population variance [2]_.
  5198. alternative : {'two-sided', 'less', 'greater'}, optional
  5199. Defines the alternative hypothesis.
  5200. The following options are available (default is 'two-sided'):
  5201. * 'two-sided': the means of the distributions are unequal.
  5202. * 'less': the mean of the first distribution is less than the
  5203. mean of the second distribution.
  5204. * 'greater': the mean of the first distribution is greater than the
  5205. mean of the second distribution.
  5206. .. versionadded:: 1.6.0
  5207. Returns
  5208. -------
  5209. statistic : float or array
  5210. The calculated t-statistics.
  5211. pvalue : float or array
  5212. The two-tailed p-value.
  5213. See Also
  5214. --------
  5215. scipy.stats.ttest_ind
  5216. Notes
  5217. -----
  5218. The statistic is calculated as ``(mean1 - mean2)/se``, where ``se`` is the
  5219. standard error. Therefore, the statistic will be positive when `mean1` is
  5220. greater than `mean2` and negative when `mean1` is less than `mean2`.
  5221. References
  5222. ----------
  5223. .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
  5224. .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
  5225. Examples
  5226. --------
  5227. Suppose we have the summary data for two samples, as follows (with the
  5228. Sample Variance being the corrected sample variance)::
  5229. Sample Sample
  5230. Size Mean Variance
  5231. Sample 1 13 15.0 87.5
  5232. Sample 2 11 12.0 39.0
  5233. Apply the t-test to this data (with the assumption that the population
  5234. variances are equal):
  5235. >>> import numpy as np
  5236. >>> from scipy.stats import ttest_ind_from_stats
  5237. >>> ttest_ind_from_stats(mean1=15.0, std1=np.sqrt(87.5), nobs1=13,
  5238. ... mean2=12.0, std2=np.sqrt(39.0), nobs2=11)
  5239. Ttest_indResult(statistic=0.9051358093310269, pvalue=0.3751996797581487)
  5240. For comparison, here is the data from which those summary statistics
  5241. were taken. With this data, we can compute the same result using
  5242. `scipy.stats.ttest_ind`:
  5243. >>> a = np.array([1, 3, 4, 6, 11, 13, 15, 19, 22, 24, 25, 26, 26])
  5244. >>> b = np.array([2, 4, 6, 9, 11, 13, 14, 15, 18, 19, 21])
  5245. >>> from scipy.stats import ttest_ind
  5246. >>> ttest_ind(a, b)
  5247. Ttest_indResult(statistic=0.905135809331027, pvalue=0.3751996797581486)
  5248. Suppose we instead have binary data and would like to apply a t-test to
  5249. compare the proportion of 1s in two independent groups::
  5250. Number of Sample Sample
  5251. Size ones Mean Variance
  5252. Sample 1 150 30 0.2 0.161073
  5253. Sample 2 200 45 0.225 0.175251
  5254. The sample mean :math:`\hat{p}` is the proportion of ones in the sample
  5255. and the variance for a binary observation is estimated by
  5256. :math:`\hat{p}(1-\hat{p})`.
  5257. >>> ttest_ind_from_stats(mean1=0.2, std1=np.sqrt(0.161073), nobs1=150,
  5258. ... mean2=0.225, std2=np.sqrt(0.175251), nobs2=200)
  5259. Ttest_indResult(statistic=-0.5627187905196761, pvalue=0.5739887114209541)
  5260. For comparison, we could compute the t statistic and p-value using
  5261. arrays of 0s and 1s and `scipy.stat.ttest_ind`, as above.
  5262. >>> group1 = np.array([1]*30 + [0]*(150-30))
  5263. >>> group2 = np.array([1]*45 + [0]*(200-45))
  5264. >>> ttest_ind(group1, group2)
  5265. Ttest_indResult(statistic=-0.5627179589855622, pvalue=0.573989277115258)
  5266. """
  5267. mean1 = np.asarray(mean1)
  5268. std1 = np.asarray(std1)
  5269. mean2 = np.asarray(mean2)
  5270. std2 = np.asarray(std2)
  5271. if equal_var:
  5272. df, denom = _equal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2)
  5273. else:
  5274. df, denom = _unequal_var_ttest_denom(std1**2, nobs1,
  5275. std2**2, nobs2)
  5276. res = _ttest_ind_from_stats(mean1, mean2, denom, df, alternative)
  5277. return Ttest_indResult(*res)
  5278. def _ttest_nans(a, b, axis, namedtuple_type):
  5279. """
  5280. Generate an array of `nan`, with shape determined by `a`, `b` and `axis`.
  5281. This function is used by ttest_ind and ttest_rel to create the return
  5282. value when one of the inputs has size 0.
  5283. The shapes of the arrays are determined by dropping `axis` from the
  5284. shapes of `a` and `b` and broadcasting what is left.
  5285. The return value is a named tuple of the type given in `namedtuple_type`.
  5286. Examples
  5287. --------
  5288. >>> import numpy as np
  5289. >>> a = np.zeros((9, 2))
  5290. >>> b = np.zeros((5, 1))
  5291. >>> _ttest_nans(a, b, 0, Ttest_indResult)
  5292. Ttest_indResult(statistic=array([nan, nan]), pvalue=array([nan, nan]))
  5293. >>> a = np.zeros((3, 0, 9))
  5294. >>> b = np.zeros((1, 10))
  5295. >>> stat, p = _ttest_nans(a, b, -1, Ttest_indResult)
  5296. >>> stat
  5297. array([], shape=(3, 0), dtype=float64)
  5298. >>> p
  5299. array([], shape=(3, 0), dtype=float64)
  5300. >>> a = np.zeros(10)
  5301. >>> b = np.zeros(7)
  5302. >>> _ttest_nans(a, b, 0, Ttest_indResult)
  5303. Ttest_indResult(statistic=nan, pvalue=nan)
  5304. """
  5305. shp = _broadcast_shapes_with_dropped_axis(a, b, axis)
  5306. if len(shp) == 0:
  5307. t = np.nan
  5308. p = np.nan
  5309. else:
  5310. t = np.full(shp, fill_value=np.nan)
  5311. p = t.copy()
  5312. return namedtuple_type(t, p)
  5313. def ttest_ind(a, b, axis=0, equal_var=True, nan_policy='propagate',
  5314. permutations=None, random_state=None, alternative="two-sided",
  5315. trim=0):
  5316. """
  5317. Calculate the T-test for the means of *two independent* samples of scores.
  5318. This is a test for the null hypothesis that 2 independent samples
  5319. have identical average (expected) values. This test assumes that the
  5320. populations have identical variances by default.
  5321. Parameters
  5322. ----------
  5323. a, b : array_like
  5324. The arrays must have the same shape, except in the dimension
  5325. corresponding to `axis` (the first, by default).
  5326. axis : int or None, optional
  5327. Axis along which to compute test. If None, compute over the whole
  5328. arrays, `a`, and `b`.
  5329. equal_var : bool, optional
  5330. If True (default), perform a standard independent 2 sample test
  5331. that assumes equal population variances [1]_.
  5332. If False, perform Welch's t-test, which does not assume equal
  5333. population variance [2]_.
  5334. .. versionadded:: 0.11.0
  5335. nan_policy : {'propagate', 'raise', 'omit'}, optional
  5336. Defines how to handle when input contains nan.
  5337. The following options are available (default is 'propagate'):
  5338. * 'propagate': returns nan
  5339. * 'raise': throws an error
  5340. * 'omit': performs the calculations ignoring nan values
  5341. The 'omit' option is not currently available for permutation tests or
  5342. one-sided asympyotic tests.
  5343. permutations : non-negative int, np.inf, or None (default), optional
  5344. If 0 or None (default), use the t-distribution to calculate p-values.
  5345. Otherwise, `permutations` is the number of random permutations that
  5346. will be used to estimate p-values using a permutation test. If
  5347. `permutations` equals or exceeds the number of distinct partitions of
  5348. the pooled data, an exact test is performed instead (i.e. each
  5349. distinct partition is used exactly once). See Notes for details.
  5350. .. versionadded:: 1.7.0
  5351. random_state : {None, int, `numpy.random.Generator`,
  5352. `numpy.random.RandomState`}, optional
  5353. If `seed` is None (or `np.random`), the `numpy.random.RandomState`
  5354. singleton is used.
  5355. If `seed` is an int, a new ``RandomState`` instance is used,
  5356. seeded with `seed`.
  5357. If `seed` is already a ``Generator`` or ``RandomState`` instance then
  5358. that instance is used.
  5359. Pseudorandom number generator state used to generate permutations
  5360. (used only when `permutations` is not None).
  5361. .. versionadded:: 1.7.0
  5362. alternative : {'two-sided', 'less', 'greater'}, optional
  5363. Defines the alternative hypothesis.
  5364. The following options are available (default is 'two-sided'):
  5365. * 'two-sided': the means of the distributions underlying the samples
  5366. are unequal.
  5367. * 'less': the mean of the distribution underlying the first sample
  5368. is less than the mean of the distribution underlying the second
  5369. sample.
  5370. * 'greater': the mean of the distribution underlying the first
  5371. sample is greater than the mean of the distribution underlying
  5372. the second sample.
  5373. .. versionadded:: 1.6.0
  5374. trim : float, optional
  5375. If nonzero, performs a trimmed (Yuen's) t-test.
  5376. Defines the fraction of elements to be trimmed from each end of the
  5377. input samples. If 0 (default), no elements will be trimmed from either
  5378. side. The number of trimmed elements from each tail is the floor of the
  5379. trim times the number of elements. Valid range is [0, .5).
  5380. .. versionadded:: 1.7
  5381. Returns
  5382. -------
  5383. statistic : float or array
  5384. The calculated t-statistic.
  5385. pvalue : float or array
  5386. The p-value.
  5387. Notes
  5388. -----
  5389. Suppose we observe two independent samples, e.g. flower petal lengths, and
  5390. we are considering whether the two samples were drawn from the same
  5391. population (e.g. the same species of flower or two species with similar
  5392. petal characteristics) or two different populations.
  5393. The t-test quantifies the difference between the arithmetic means
  5394. of the two samples. The p-value quantifies the probability of observing
  5395. as or more extreme values assuming the null hypothesis, that the
  5396. samples are drawn from populations with the same population means, is true.
  5397. A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that
  5398. our observation is not so unlikely to have occurred by chance. Therefore,
  5399. we do not reject the null hypothesis of equal population means.
  5400. If the p-value is smaller than our threshold, then we have evidence
  5401. against the null hypothesis of equal population means.
  5402. By default, the p-value is determined by comparing the t-statistic of the
  5403. observed data against a theoretical t-distribution.
  5404. When ``1 < permutations < binom(n, k)``, where
  5405. * ``k`` is the number of observations in `a`,
  5406. * ``n`` is the total number of observations in `a` and `b`, and
  5407. * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``),
  5408. the data are pooled (concatenated), randomly assigned to either group `a`
  5409. or `b`, and the t-statistic is calculated. This process is performed
  5410. repeatedly (`permutation` times), generating a distribution of the
  5411. t-statistic under the null hypothesis, and the t-statistic of the observed
  5412. data is compared to this distribution to determine the p-value.
  5413. Specifically, the p-value reported is the "achieved significance level"
  5414. (ASL) as defined in 4.4 of [3]_. Note that there are other ways of
  5415. estimating p-values using randomized permutation tests; for other
  5416. options, see the more general `permutation_test`.
  5417. When ``permutations >= binom(n, k)``, an exact test is performed: the data
  5418. are partitioned between the groups in each distinct way exactly once.
  5419. The permutation test can be computationally expensive and not necessarily
  5420. more accurate than the analytical test, but it does not make strong
  5421. assumptions about the shape of the underlying distribution.
  5422. Use of trimming is commonly referred to as the trimmed t-test. At times
  5423. called Yuen's t-test, this is an extension of Welch's t-test, with the
  5424. difference being the use of winsorized means in calculation of the variance
  5425. and the trimmed sample size in calculation of the statistic. Trimming is
  5426. recommended if the underlying distribution is long-tailed or contaminated
  5427. with outliers [4]_.
  5428. The statistic is calculated as ``(np.mean(a) - np.mean(b))/se``, where
  5429. ``se`` is the standard error. Therefore, the statistic will be positive
  5430. when the sample mean of `a` is greater than the sample mean of `b` and
  5431. negative when the sample mean of `a` is less than the sample mean of
  5432. `b`.
  5433. References
  5434. ----------
  5435. .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
  5436. .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
  5437. .. [3] B. Efron and T. Hastie. Computer Age Statistical Inference. (2016).
  5438. .. [4] Yuen, Karen K. "The Two-Sample Trimmed t for Unequal Population
  5439. Variances." Biometrika, vol. 61, no. 1, 1974, pp. 165-170. JSTOR,
  5440. www.jstor.org/stable/2334299. Accessed 30 Mar. 2021.
  5441. .. [5] Yuen, Karen K., and W. J. Dixon. "The Approximate Behaviour and
  5442. Performance of the Two-Sample Trimmed t." Biometrika, vol. 60,
  5443. no. 2, 1973, pp. 369-374. JSTOR, www.jstor.org/stable/2334550.
  5444. Accessed 30 Mar. 2021.
  5445. Examples
  5446. --------
  5447. >>> import numpy as np
  5448. >>> from scipy import stats
  5449. >>> rng = np.random.default_rng()
  5450. Test with sample with identical means:
  5451. >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
  5452. >>> rvs2 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
  5453. >>> stats.ttest_ind(rvs1, rvs2)
  5454. Ttest_indResult(statistic=-0.4390847099199348, pvalue=0.6606952038870015)
  5455. >>> stats.ttest_ind(rvs1, rvs2, equal_var=False)
  5456. Ttest_indResult(statistic=-0.4390847099199348, pvalue=0.6606952553131064)
  5457. `ttest_ind` underestimates p for unequal variances:
  5458. >>> rvs3 = stats.norm.rvs(loc=5, scale=20, size=500, random_state=rng)
  5459. >>> stats.ttest_ind(rvs1, rvs3)
  5460. Ttest_indResult(statistic=-1.6370984482905417, pvalue=0.1019251574705033)
  5461. >>> stats.ttest_ind(rvs1, rvs3, equal_var=False)
  5462. Ttest_indResult(statistic=-1.637098448290542, pvalue=0.10202110497954867)
  5463. When ``n1 != n2``, the equal variance t-statistic is no longer equal to the
  5464. unequal variance t-statistic:
  5465. >>> rvs4 = stats.norm.rvs(loc=5, scale=20, size=100, random_state=rng)
  5466. >>> stats.ttest_ind(rvs1, rvs4)
  5467. Ttest_indResult(statistic=-1.9481646859513422, pvalue=0.05186270935842703)
  5468. >>> stats.ttest_ind(rvs1, rvs4, equal_var=False)
  5469. Ttest_indResult(statistic=-1.3146566100751664, pvalue=0.1913495266513811)
  5470. T-test with different means, variance, and n:
  5471. >>> rvs5 = stats.norm.rvs(loc=8, scale=20, size=100, random_state=rng)
  5472. >>> stats.ttest_ind(rvs1, rvs5)
  5473. Ttest_indResult(statistic=-2.8415950600298774, pvalue=0.0046418707568707885)
  5474. >>> stats.ttest_ind(rvs1, rvs5, equal_var=False)
  5475. Ttest_indResult(statistic=-1.8686598649188084, pvalue=0.06434714193919686)
  5476. When performing a permutation test, more permutations typically yields
  5477. more accurate results. Use a ``np.random.Generator`` to ensure
  5478. reproducibility:
  5479. >>> stats.ttest_ind(rvs1, rvs5, permutations=10000,
  5480. ... random_state=rng)
  5481. Ttest_indResult(statistic=-2.8415950600298774, pvalue=0.0052994700529947)
  5482. Take these two samples, one of which has an extreme tail.
  5483. >>> a = (56, 128.6, 12, 123.8, 64.34, 78, 763.3)
  5484. >>> b = (1.1, 2.9, 4.2)
  5485. Use the `trim` keyword to perform a trimmed (Yuen) t-test. For example,
  5486. using 20% trimming, ``trim=.2``, the test will reduce the impact of one
  5487. (``np.floor(trim*len(a))``) element from each tail of sample `a`. It will
  5488. have no effect on sample `b` because ``np.floor(trim*len(b))`` is 0.
  5489. >>> stats.ttest_ind(a, b, trim=.2)
  5490. Ttest_indResult(statistic=3.4463884028073513,
  5491. pvalue=0.01369338726499547)
  5492. """
  5493. if not (0 <= trim < .5):
  5494. raise ValueError("Trimming percentage should be 0 <= `trim` < .5.")
  5495. a, b, axis = _chk2_asarray(a, b, axis)
  5496. # check both a and b
  5497. cna, npa = _contains_nan(a, nan_policy)
  5498. cnb, npb = _contains_nan(b, nan_policy)
  5499. contains_nan = cna or cnb
  5500. if npa == 'omit' or npb == 'omit':
  5501. nan_policy = 'omit'
  5502. if contains_nan and nan_policy == 'omit':
  5503. if permutations or trim != 0:
  5504. raise ValueError("nan-containing/masked inputs with "
  5505. "nan_policy='omit' are currently not "
  5506. "supported by permutation tests or "
  5507. "trimmed tests.")
  5508. a = ma.masked_invalid(a)
  5509. b = ma.masked_invalid(b)
  5510. return mstats_basic.ttest_ind(a, b, axis, equal_var, alternative)
  5511. if a.size == 0 or b.size == 0:
  5512. return _ttest_nans(a, b, axis, Ttest_indResult)
  5513. if permutations is not None and permutations != 0:
  5514. if trim != 0:
  5515. raise ValueError("Permutations are currently not supported "
  5516. "with trimming.")
  5517. if permutations < 0 or (np.isfinite(permutations) and
  5518. int(permutations) != permutations):
  5519. raise ValueError("Permutations must be a non-negative integer.")
  5520. res = _permutation_ttest(a, b, permutations=permutations,
  5521. axis=axis, equal_var=equal_var,
  5522. nan_policy=nan_policy,
  5523. random_state=random_state,
  5524. alternative=alternative)
  5525. else:
  5526. n1 = a.shape[axis]
  5527. n2 = b.shape[axis]
  5528. if trim == 0:
  5529. v1 = _var(a, axis, ddof=1)
  5530. v2 = _var(b, axis, ddof=1)
  5531. m1 = np.mean(a, axis)
  5532. m2 = np.mean(b, axis)
  5533. else:
  5534. v1, m1, n1 = _ttest_trim_var_mean_len(a, trim, axis)
  5535. v2, m2, n2 = _ttest_trim_var_mean_len(b, trim, axis)
  5536. if equal_var:
  5537. df, denom = _equal_var_ttest_denom(v1, n1, v2, n2)
  5538. else:
  5539. df, denom = _unequal_var_ttest_denom(v1, n1, v2, n2)
  5540. res = _ttest_ind_from_stats(m1, m2, denom, df, alternative)
  5541. return Ttest_indResult(*res)
  5542. def _ttest_trim_var_mean_len(a, trim, axis):
  5543. """Variance, mean, and length of winsorized input along specified axis"""
  5544. # for use with `ttest_ind` when trimming.
  5545. # further calculations in this test assume that the inputs are sorted.
  5546. # From [4] Section 1 "Let x_1, ..., x_n be n ordered observations..."
  5547. a = np.sort(a, axis=axis)
  5548. # `g` is the number of elements to be replaced on each tail, converted
  5549. # from a percentage amount of trimming
  5550. n = a.shape[axis]
  5551. g = int(n * trim)
  5552. # Calculate the Winsorized variance of the input samples according to
  5553. # specified `g`
  5554. v = _calculate_winsorized_variance(a, g, axis)
  5555. # the total number of elements in the trimmed samples
  5556. n -= 2 * g
  5557. # calculate the g-times trimmed mean, as defined in [4] (1-1)
  5558. m = trim_mean(a, trim, axis=axis)
  5559. return v, m, n
  5560. def _calculate_winsorized_variance(a, g, axis):
  5561. """Calculates g-times winsorized variance along specified axis"""
  5562. # it is expected that the input `a` is sorted along the correct axis
  5563. if g == 0:
  5564. return _var(a, ddof=1, axis=axis)
  5565. # move the intended axis to the end that way it is easier to manipulate
  5566. a_win = np.moveaxis(a, axis, -1)
  5567. # save where NaNs are for later use.
  5568. nans_indices = np.any(np.isnan(a_win), axis=-1)
  5569. # Winsorization and variance calculation are done in one step in [4]
  5570. # (1-3), but here winsorization is done first; replace the left and
  5571. # right sides with the repeating value. This can be see in effect in (
  5572. # 1-3) in [4], where the leftmost and rightmost tails are replaced with
  5573. # `(g + 1) * x_{g + 1}` on the left and `(g + 1) * x_{n - g}` on the
  5574. # right. Zero-indexing turns `g + 1` to `g`, and `n - g` to `- g - 1` in
  5575. # array indexing.
  5576. a_win[..., :g] = a_win[..., [g]]
  5577. a_win[..., -g:] = a_win[..., [-g - 1]]
  5578. # Determine the variance. In [4], the degrees of freedom is expressed as
  5579. # `h - 1`, where `h = n - 2g` (unnumbered equations in Section 1, end of
  5580. # page 369, beginning of page 370). This is converted to NumPy's format,
  5581. # `n - ddof` for use with `np.var`. The result is converted to an
  5582. # array to accommodate indexing later.
  5583. var_win = np.asarray(_var(a_win, ddof=(2 * g + 1), axis=-1))
  5584. # with `nan_policy='propagate'`, NaNs may be completely trimmed out
  5585. # because they were sorted into the tail of the array. In these cases,
  5586. # replace computed variances with `np.nan`.
  5587. var_win[nans_indices] = np.nan
  5588. return var_win
  5589. def _permutation_distribution_t(data, permutations, size_a, equal_var,
  5590. random_state=None):
  5591. """Generation permutation distribution of t statistic"""
  5592. random_state = check_random_state(random_state)
  5593. # prepare permutation indices
  5594. size = data.shape[-1]
  5595. # number of distinct combinations
  5596. n_max = special.comb(size, size_a)
  5597. if permutations < n_max:
  5598. perm_generator = (random_state.permutation(size)
  5599. for i in range(permutations))
  5600. else:
  5601. permutations = n_max
  5602. perm_generator = (np.concatenate(z)
  5603. for z in _all_partitions(size_a, size-size_a))
  5604. t_stat = []
  5605. for indices in _batch_generator(perm_generator, batch=50):
  5606. # get one batch from perm_generator at a time as a list
  5607. indices = np.array(indices)
  5608. # generate permutations
  5609. data_perm = data[..., indices]
  5610. # move axis indexing permutations to position 0 to broadcast
  5611. # nicely with t_stat_observed, which doesn't have this dimension
  5612. data_perm = np.moveaxis(data_perm, -2, 0)
  5613. a = data_perm[..., :size_a]
  5614. b = data_perm[..., size_a:]
  5615. t_stat.append(_calc_t_stat(a, b, equal_var))
  5616. t_stat = np.concatenate(t_stat, axis=0)
  5617. return t_stat, permutations, n_max
  5618. def _calc_t_stat(a, b, equal_var, axis=-1):
  5619. """Calculate the t statistic along the given dimension."""
  5620. na = a.shape[axis]
  5621. nb = b.shape[axis]
  5622. avg_a = np.mean(a, axis=axis)
  5623. avg_b = np.mean(b, axis=axis)
  5624. var_a = _var(a, axis=axis, ddof=1)
  5625. var_b = _var(b, axis=axis, ddof=1)
  5626. if not equal_var:
  5627. denom = _unequal_var_ttest_denom(var_a, na, var_b, nb)[1]
  5628. else:
  5629. denom = _equal_var_ttest_denom(var_a, na, var_b, nb)[1]
  5630. return (avg_a-avg_b)/denom
  5631. def _permutation_ttest(a, b, permutations, axis=0, equal_var=True,
  5632. nan_policy='propagate', random_state=None,
  5633. alternative="two-sided"):
  5634. """
  5635. Calculates the T-test for the means of TWO INDEPENDENT samples of scores
  5636. using permutation methods.
  5637. This test is similar to `stats.ttest_ind`, except it doesn't rely on an
  5638. approximate normality assumption since it uses a permutation test.
  5639. This function is only called from ttest_ind when permutations is not None.
  5640. Parameters
  5641. ----------
  5642. a, b : array_like
  5643. The arrays must be broadcastable, except along the dimension
  5644. corresponding to `axis` (the zeroth, by default).
  5645. axis : int, optional
  5646. The axis over which to operate on a and b.
  5647. permutations : int, optional
  5648. Number of permutations used to calculate p-value. If greater than or
  5649. equal to the number of distinct permutations, perform an exact test.
  5650. equal_var : bool, optional
  5651. If False, an equal variance (Welch's) t-test is conducted. Otherwise,
  5652. an ordinary t-test is conducted.
  5653. random_state : {None, int, `numpy.random.Generator`}, optional
  5654. If `seed` is None the `numpy.random.Generator` singleton is used.
  5655. If `seed` is an int, a new ``Generator`` instance is used,
  5656. seeded with `seed`.
  5657. If `seed` is already a ``Generator`` instance then that instance is
  5658. used.
  5659. Pseudorandom number generator state used for generating random
  5660. permutations.
  5661. Returns
  5662. -------
  5663. statistic : float or array
  5664. The calculated t-statistic.
  5665. pvalue : float or array
  5666. The p-value.
  5667. """
  5668. random_state = check_random_state(random_state)
  5669. t_stat_observed = _calc_t_stat(a, b, equal_var, axis=axis)
  5670. na = a.shape[axis]
  5671. mat = _broadcast_concatenate((a, b), axis=axis)
  5672. mat = np.moveaxis(mat, axis, -1)
  5673. t_stat, permutations, n_max = _permutation_distribution_t(
  5674. mat, permutations, size_a=na, equal_var=equal_var,
  5675. random_state=random_state)
  5676. compare = {"less": np.less_equal,
  5677. "greater": np.greater_equal,
  5678. "two-sided": lambda x, y: (x <= -np.abs(y)) | (x >= np.abs(y))}
  5679. # Calculate the p-values
  5680. cmps = compare[alternative](t_stat, t_stat_observed)
  5681. # Randomized test p-value calculation should use biased estimate; see e.g.
  5682. # https://www.degruyter.com/document/doi/10.2202/1544-6115.1585/
  5683. adjustment = 1 if n_max > permutations else 0
  5684. pvalues = (cmps.sum(axis=0) + adjustment) / (permutations + adjustment)
  5685. # nans propagate naturally in statistic calculation, but need to be
  5686. # propagated manually into pvalues
  5687. if nan_policy == 'propagate' and np.isnan(t_stat_observed).any():
  5688. if np.ndim(pvalues) == 0:
  5689. pvalues = np.float64(np.nan)
  5690. else:
  5691. pvalues[np.isnan(t_stat_observed)] = np.nan
  5692. return (t_stat_observed, pvalues)
  5693. def _get_len(a, axis, msg):
  5694. try:
  5695. n = a.shape[axis]
  5696. except IndexError:
  5697. raise np.AxisError(axis, a.ndim, msg) from None
  5698. return n
  5699. @_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
  5700. result_to_tuple=unpack_TtestResult, n_outputs=6,
  5701. paired=True)
  5702. def ttest_rel(a, b, axis=0, nan_policy='propagate', alternative="two-sided"):
  5703. """Calculate the t-test on TWO RELATED samples of scores, a and b.
  5704. This is a test for the null hypothesis that two related or
  5705. repeated samples have identical average (expected) values.
  5706. Parameters
  5707. ----------
  5708. a, b : array_like
  5709. The arrays must have the same shape.
  5710. axis : int or None, optional
  5711. Axis along which to compute test. If None, compute over the whole
  5712. arrays, `a`, and `b`.
  5713. nan_policy : {'propagate', 'raise', 'omit'}, optional
  5714. Defines how to handle when input contains nan.
  5715. The following options are available (default is 'propagate'):
  5716. * 'propagate': returns nan
  5717. * 'raise': throws an error
  5718. * 'omit': performs the calculations ignoring nan values
  5719. alternative : {'two-sided', 'less', 'greater'}, optional
  5720. Defines the alternative hypothesis.
  5721. The following options are available (default is 'two-sided'):
  5722. * 'two-sided': the means of the distributions underlying the samples
  5723. are unequal.
  5724. * 'less': the mean of the distribution underlying the first sample
  5725. is less than the mean of the distribution underlying the second
  5726. sample.
  5727. * 'greater': the mean of the distribution underlying the first
  5728. sample is greater than the mean of the distribution underlying
  5729. the second sample.
  5730. .. versionadded:: 1.6.0
  5731. Returns
  5732. -------
  5733. result : `~scipy.stats._result_classes.TtestResult`
  5734. An object with the following attributes:
  5735. statistic : float or array
  5736. The t-statistic.
  5737. pvalue : float or array
  5738. The p-value associated with the given alternative.
  5739. df : float or array
  5740. The number of degrees of freedom used in calculation of the
  5741. t-statistic; this is one less than the size of the sample
  5742. (``a.shape[axis]``).
  5743. .. versionadded:: 1.10.0
  5744. The object also has the following method:
  5745. confidence_interval(confidence_level=0.95)
  5746. Computes a confidence interval around the difference in
  5747. population means for the given confidence level.
  5748. The confidence interval is returned in a ``namedtuple`` with
  5749. fields `low` and `high`.
  5750. .. versionadded:: 1.10.0
  5751. Notes
  5752. -----
  5753. Examples for use are scores of the same set of student in
  5754. different exams, or repeated sampling from the same units. The
  5755. test measures whether the average score differs significantly
  5756. across samples (e.g. exams). If we observe a large p-value, for
  5757. example greater than 0.05 or 0.1 then we cannot reject the null
  5758. hypothesis of identical average scores. If the p-value is smaller
  5759. than the threshold, e.g. 1%, 5% or 10%, then we reject the null
  5760. hypothesis of equal averages. Small p-values are associated with
  5761. large t-statistics.
  5762. The t-statistic is calculated as ``np.mean(a - b)/se``, where ``se`` is the
  5763. standard error. Therefore, the t-statistic will be positive when the sample
  5764. mean of ``a - b`` is greater than zero and negative when the sample mean of
  5765. ``a - b`` is less than zero.
  5766. References
  5767. ----------
  5768. https://en.wikipedia.org/wiki/T-test#Dependent_t-test_for_paired_samples
  5769. Examples
  5770. --------
  5771. >>> import numpy as np
  5772. >>> from scipy import stats
  5773. >>> rng = np.random.default_rng()
  5774. >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
  5775. >>> rvs2 = (stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
  5776. ... + stats.norm.rvs(scale=0.2, size=500, random_state=rng))
  5777. >>> stats.ttest_rel(rvs1, rvs2)
  5778. TtestResult(statistic=-0.4549717054410304, pvalue=0.6493274702088672, df=499) # noqa
  5779. >>> rvs3 = (stats.norm.rvs(loc=8, scale=10, size=500, random_state=rng)
  5780. ... + stats.norm.rvs(scale=0.2, size=500, random_state=rng))
  5781. >>> stats.ttest_rel(rvs1, rvs3)
  5782. TtestResult(statistic=-5.879467544540889, pvalue=7.540777129099917e-09, df=499) # noqa
  5783. """
  5784. a, b, axis = _chk2_asarray(a, b, axis)
  5785. na = _get_len(a, axis, "first argument")
  5786. nb = _get_len(b, axis, "second argument")
  5787. if na != nb:
  5788. raise ValueError('unequal length arrays')
  5789. if na == 0 or nb == 0:
  5790. # _axis_nan_policy decorator ensures this only happens with 1d input
  5791. return TtestResult(np.nan, np.nan, df=np.nan, alternative=np.nan,
  5792. standard_error=np.nan, estimate=np.nan)
  5793. n = a.shape[axis]
  5794. df = n - 1
  5795. d = (a - b).astype(np.float64)
  5796. v = _var(d, axis, ddof=1)
  5797. dm = np.mean(d, axis)
  5798. denom = np.sqrt(v / n)
  5799. with np.errstate(divide='ignore', invalid='ignore'):
  5800. t = np.divide(dm, denom)
  5801. t, prob = _ttest_finish(df, t, alternative)
  5802. # when nan_policy='omit', `df` can be different for different axis-slices
  5803. df = np.broadcast_to(df, t.shape)[()]
  5804. # _axis_nan_policy decorator doesn't play well with strings
  5805. alternative_num = {"less": -1, "two-sided": 0, "greater": 1}[alternative]
  5806. return TtestResult(t, prob, df=df, alternative=alternative_num,
  5807. standard_error=denom, estimate=dm)
  5808. # Map from names to lambda_ values used in power_divergence().
  5809. _power_div_lambda_names = {
  5810. "pearson": 1,
  5811. "log-likelihood": 0,
  5812. "freeman-tukey": -0.5,
  5813. "mod-log-likelihood": -1,
  5814. "neyman": -2,
  5815. "cressie-read": 2/3,
  5816. }
  5817. def _count(a, axis=None):
  5818. """Count the number of non-masked elements of an array.
  5819. This function behaves like `np.ma.count`, but is much faster
  5820. for ndarrays.
  5821. """
  5822. if hasattr(a, 'count'):
  5823. num = a.count(axis=axis)
  5824. if isinstance(num, np.ndarray) and num.ndim == 0:
  5825. # In some cases, the `count` method returns a scalar array (e.g.
  5826. # np.array(3)), but we want a plain integer.
  5827. num = int(num)
  5828. else:
  5829. if axis is None:
  5830. num = a.size
  5831. else:
  5832. num = a.shape[axis]
  5833. return num
  5834. def _m_broadcast_to(a, shape):
  5835. if np.ma.isMaskedArray(a):
  5836. return np.ma.masked_array(np.broadcast_to(a, shape),
  5837. mask=np.broadcast_to(a.mask, shape))
  5838. return np.broadcast_to(a, shape, subok=True)
  5839. Power_divergenceResult = namedtuple('Power_divergenceResult',
  5840. ('statistic', 'pvalue'))
  5841. def power_divergence(f_obs, f_exp=None, ddof=0, axis=0, lambda_=None):
  5842. """Cressie-Read power divergence statistic and goodness of fit test.
  5843. This function tests the null hypothesis that the categorical data
  5844. has the given frequencies, using the Cressie-Read power divergence
  5845. statistic.
  5846. Parameters
  5847. ----------
  5848. f_obs : array_like
  5849. Observed frequencies in each category.
  5850. f_exp : array_like, optional
  5851. Expected frequencies in each category. By default the categories are
  5852. assumed to be equally likely.
  5853. ddof : int, optional
  5854. "Delta degrees of freedom": adjustment to the degrees of freedom
  5855. for the p-value. The p-value is computed using a chi-squared
  5856. distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
  5857. is the number of observed frequencies. The default value of `ddof`
  5858. is 0.
  5859. axis : int or None, optional
  5860. The axis of the broadcast result of `f_obs` and `f_exp` along which to
  5861. apply the test. If axis is None, all values in `f_obs` are treated
  5862. as a single data set. Default is 0.
  5863. lambda_ : float or str, optional
  5864. The power in the Cressie-Read power divergence statistic. The default
  5865. is 1. For convenience, `lambda_` may be assigned one of the following
  5866. strings, in which case the corresponding numerical value is used:
  5867. * ``"pearson"`` (value 1)
  5868. Pearson's chi-squared statistic. In this case, the function is
  5869. equivalent to `chisquare`.
  5870. * ``"log-likelihood"`` (value 0)
  5871. Log-likelihood ratio. Also known as the G-test [3]_.
  5872. * ``"freeman-tukey"`` (value -1/2)
  5873. Freeman-Tukey statistic.
  5874. * ``"mod-log-likelihood"`` (value -1)
  5875. Modified log-likelihood ratio.
  5876. * ``"neyman"`` (value -2)
  5877. Neyman's statistic.
  5878. * ``"cressie-read"`` (value 2/3)
  5879. The power recommended in [5]_.
  5880. Returns
  5881. -------
  5882. statistic : float or ndarray
  5883. The Cressie-Read power divergence test statistic. The value is
  5884. a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D.
  5885. pvalue : float or ndarray
  5886. The p-value of the test. The value is a float if `ddof` and the
  5887. return value `stat` are scalars.
  5888. See Also
  5889. --------
  5890. chisquare
  5891. Notes
  5892. -----
  5893. This test is invalid when the observed or expected frequencies in each
  5894. category are too small. A typical rule is that all of the observed
  5895. and expected frequencies should be at least 5.
  5896. Also, the sum of the observed and expected frequencies must be the same
  5897. for the test to be valid; `power_divergence` raises an error if the sums
  5898. do not agree within a relative tolerance of ``1e-8``.
  5899. When `lambda_` is less than zero, the formula for the statistic involves
  5900. dividing by `f_obs`, so a warning or error may be generated if any value
  5901. in `f_obs` is 0.
  5902. Similarly, a warning or error may be generated if any value in `f_exp` is
  5903. zero when `lambda_` >= 0.
  5904. The default degrees of freedom, k-1, are for the case when no parameters
  5905. of the distribution are estimated. If p parameters are estimated by
  5906. efficient maximum likelihood then the correct degrees of freedom are
  5907. k-1-p. If the parameters are estimated in a different way, then the
  5908. dof can be between k-1-p and k-1. However, it is also possible that
  5909. the asymptotic distribution is not a chisquare, in which case this
  5910. test is not appropriate.
  5911. This function handles masked arrays. If an element of `f_obs` or `f_exp`
  5912. is masked, then data at that position is ignored, and does not count
  5913. towards the size of the data set.
  5914. .. versionadded:: 0.13.0
  5915. References
  5916. ----------
  5917. .. [1] Lowry, Richard. "Concepts and Applications of Inferential
  5918. Statistics". Chapter 8.
  5919. https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html
  5920. .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
  5921. .. [3] "G-test", https://en.wikipedia.org/wiki/G-test
  5922. .. [4] Sokal, R. R. and Rohlf, F. J. "Biometry: the principles and
  5923. practice of statistics in biological research", New York: Freeman
  5924. (1981)
  5925. .. [5] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
  5926. Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
  5927. pp. 440-464.
  5928. Examples
  5929. --------
  5930. (See `chisquare` for more examples.)
  5931. When just `f_obs` is given, it is assumed that the expected frequencies
  5932. are uniform and given by the mean of the observed frequencies. Here we
  5933. perform a G-test (i.e. use the log-likelihood ratio statistic):
  5934. >>> import numpy as np
  5935. >>> from scipy.stats import power_divergence
  5936. >>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood')
  5937. (2.006573162632538, 0.84823476779463769)
  5938. The expected frequencies can be given with the `f_exp` argument:
  5939. >>> power_divergence([16, 18, 16, 14, 12, 12],
  5940. ... f_exp=[16, 16, 16, 16, 16, 8],
  5941. ... lambda_='log-likelihood')
  5942. (3.3281031458963746, 0.6495419288047497)
  5943. When `f_obs` is 2-D, by default the test is applied to each column.
  5944. >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
  5945. >>> obs.shape
  5946. (6, 2)
  5947. >>> power_divergence(obs, lambda_="log-likelihood")
  5948. (array([ 2.00657316, 6.77634498]), array([ 0.84823477, 0.23781225]))
  5949. By setting ``axis=None``, the test is applied to all data in the array,
  5950. which is equivalent to applying the test to the flattened array.
  5951. >>> power_divergence(obs, axis=None)
  5952. (23.31034482758621, 0.015975692534127565)
  5953. >>> power_divergence(obs.ravel())
  5954. (23.31034482758621, 0.015975692534127565)
  5955. `ddof` is the change to make to the default degrees of freedom.
  5956. >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1)
  5957. (2.0, 0.73575888234288467)
  5958. The calculation of the p-values is done by broadcasting the
  5959. test statistic with `ddof`.
  5960. >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
  5961. (2.0, array([ 0.84914504, 0.73575888, 0.5724067 ]))
  5962. `f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has
  5963. shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
  5964. `f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared
  5965. statistics, we must use ``axis=1``:
  5966. >>> power_divergence([16, 18, 16, 14, 12, 12],
  5967. ... f_exp=[[16, 16, 16, 16, 16, 8],
  5968. ... [8, 20, 20, 16, 12, 12]],
  5969. ... axis=1)
  5970. (array([ 3.5 , 9.25]), array([ 0.62338763, 0.09949846]))
  5971. """
  5972. # Convert the input argument `lambda_` to a numerical value.
  5973. if isinstance(lambda_, str):
  5974. if lambda_ not in _power_div_lambda_names:
  5975. names = repr(list(_power_div_lambda_names.keys()))[1:-1]
  5976. raise ValueError("invalid string for lambda_: {0!r}. "
  5977. "Valid strings are {1}".format(lambda_, names))
  5978. lambda_ = _power_div_lambda_names[lambda_]
  5979. elif lambda_ is None:
  5980. lambda_ = 1
  5981. f_obs = np.asanyarray(f_obs)
  5982. f_obs_float = f_obs.astype(np.float64)
  5983. if f_exp is not None:
  5984. f_exp = np.asanyarray(f_exp)
  5985. bshape = _broadcast_shapes(f_obs_float.shape, f_exp.shape)
  5986. f_obs_float = _m_broadcast_to(f_obs_float, bshape)
  5987. f_exp = _m_broadcast_to(f_exp, bshape)
  5988. rtol = 1e-8 # to pass existing tests
  5989. with np.errstate(invalid='ignore'):
  5990. f_obs_sum = f_obs_float.sum(axis=axis)
  5991. f_exp_sum = f_exp.sum(axis=axis)
  5992. relative_diff = (np.abs(f_obs_sum - f_exp_sum) /
  5993. np.minimum(f_obs_sum, f_exp_sum))
  5994. diff_gt_tol = (relative_diff > rtol).any()
  5995. if diff_gt_tol:
  5996. msg = (f"For each axis slice, the sum of the observed "
  5997. f"frequencies must agree with the sum of the "
  5998. f"expected frequencies to a relative tolerance "
  5999. f"of {rtol}, but the percent differences are:\n"
  6000. f"{relative_diff}")
  6001. raise ValueError(msg)
  6002. else:
  6003. # Ignore 'invalid' errors so the edge case of a data set with length 0
  6004. # is handled without spurious warnings.
  6005. with np.errstate(invalid='ignore'):
  6006. f_exp = f_obs.mean(axis=axis, keepdims=True)
  6007. # `terms` is the array of terms that are summed along `axis` to create
  6008. # the test statistic. We use some specialized code for a few special
  6009. # cases of lambda_.
  6010. if lambda_ == 1:
  6011. # Pearson's chi-squared statistic
  6012. terms = (f_obs_float - f_exp)**2 / f_exp
  6013. elif lambda_ == 0:
  6014. # Log-likelihood ratio (i.e. G-test)
  6015. terms = 2.0 * special.xlogy(f_obs, f_obs / f_exp)
  6016. elif lambda_ == -1:
  6017. # Modified log-likelihood ratio
  6018. terms = 2.0 * special.xlogy(f_exp, f_exp / f_obs)
  6019. else:
  6020. # General Cressie-Read power divergence.
  6021. terms = f_obs * ((f_obs / f_exp)**lambda_ - 1)
  6022. terms /= 0.5 * lambda_ * (lambda_ + 1)
  6023. stat = terms.sum(axis=axis)
  6024. num_obs = _count(terms, axis=axis)
  6025. ddof = asarray(ddof)
  6026. p = distributions.chi2.sf(stat, num_obs - 1 - ddof)
  6027. return Power_divergenceResult(stat, p)
  6028. def chisquare(f_obs, f_exp=None, ddof=0, axis=0):
  6029. """Calculate a one-way chi-square test.
  6030. The chi-square test tests the null hypothesis that the categorical data
  6031. has the given frequencies.
  6032. Parameters
  6033. ----------
  6034. f_obs : array_like
  6035. Observed frequencies in each category.
  6036. f_exp : array_like, optional
  6037. Expected frequencies in each category. By default the categories are
  6038. assumed to be equally likely.
  6039. ddof : int, optional
  6040. "Delta degrees of freedom": adjustment to the degrees of freedom
  6041. for the p-value. The p-value is computed using a chi-squared
  6042. distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
  6043. is the number of observed frequencies. The default value of `ddof`
  6044. is 0.
  6045. axis : int or None, optional
  6046. The axis of the broadcast result of `f_obs` and `f_exp` along which to
  6047. apply the test. If axis is None, all values in `f_obs` are treated
  6048. as a single data set. Default is 0.
  6049. Returns
  6050. -------
  6051. chisq : float or ndarray
  6052. The chi-squared test statistic. The value is a float if `axis` is
  6053. None or `f_obs` and `f_exp` are 1-D.
  6054. p : float or ndarray
  6055. The p-value of the test. The value is a float if `ddof` and the
  6056. return value `chisq` are scalars.
  6057. See Also
  6058. --------
  6059. scipy.stats.power_divergence
  6060. scipy.stats.fisher_exact : Fisher exact test on a 2x2 contingency table.
  6061. scipy.stats.barnard_exact : An unconditional exact test. An alternative
  6062. to chi-squared test for small sample sizes.
  6063. Notes
  6064. -----
  6065. This test is invalid when the observed or expected frequencies in each
  6066. category are too small. A typical rule is that all of the observed
  6067. and expected frequencies should be at least 5. According to [3]_, the
  6068. total number of samples is recommended to be greater than 13,
  6069. otherwise exact tests (such as Barnard's Exact test) should be used
  6070. because they do not overreject.
  6071. Also, the sum of the observed and expected frequencies must be the same
  6072. for the test to be valid; `chisquare` raises an error if the sums do not
  6073. agree within a relative tolerance of ``1e-8``.
  6074. The default degrees of freedom, k-1, are for the case when no parameters
  6075. of the distribution are estimated. If p parameters are estimated by
  6076. efficient maximum likelihood then the correct degrees of freedom are
  6077. k-1-p. If the parameters are estimated in a different way, then the
  6078. dof can be between k-1-p and k-1. However, it is also possible that
  6079. the asymptotic distribution is not chi-square, in which case this test
  6080. is not appropriate.
  6081. References
  6082. ----------
  6083. .. [1] Lowry, Richard. "Concepts and Applications of Inferential
  6084. Statistics". Chapter 8.
  6085. https://web.archive.org/web/20171022032306/http://vassarstats.net:80/textbook/ch8pt1.html
  6086. .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
  6087. .. [3] Pearson, Karl. "On the criterion that a given system of deviations from the probable
  6088. in the case of a correlated system of variables is such that it can be reasonably
  6089. supposed to have arisen from random sampling", Philosophical Magazine. Series 5. 50
  6090. (1900), pp. 157-175.
  6091. Examples
  6092. --------
  6093. When just `f_obs` is given, it is assumed that the expected frequencies
  6094. are uniform and given by the mean of the observed frequencies.
  6095. >>> import numpy as np
  6096. >>> from scipy.stats import chisquare
  6097. >>> chisquare([16, 18, 16, 14, 12, 12])
  6098. (2.0, 0.84914503608460956)
  6099. With `f_exp` the expected frequencies can be given.
  6100. >>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8])
  6101. (3.5, 0.62338762774958223)
  6102. When `f_obs` is 2-D, by default the test is applied to each column.
  6103. >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
  6104. >>> obs.shape
  6105. (6, 2)
  6106. >>> chisquare(obs)
  6107. (array([ 2. , 6.66666667]), array([ 0.84914504, 0.24663415]))
  6108. By setting ``axis=None``, the test is applied to all data in the array,
  6109. which is equivalent to applying the test to the flattened array.
  6110. >>> chisquare(obs, axis=None)
  6111. (23.31034482758621, 0.015975692534127565)
  6112. >>> chisquare(obs.ravel())
  6113. (23.31034482758621, 0.015975692534127565)
  6114. `ddof` is the change to make to the default degrees of freedom.
  6115. >>> chisquare([16, 18, 16, 14, 12, 12], ddof=1)
  6116. (2.0, 0.73575888234288467)
  6117. The calculation of the p-values is done by broadcasting the
  6118. chi-squared statistic with `ddof`.
  6119. >>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
  6120. (2.0, array([ 0.84914504, 0.73575888, 0.5724067 ]))
  6121. `f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has
  6122. shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
  6123. `f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared
  6124. statistics, we use ``axis=1``:
  6125. >>> chisquare([16, 18, 16, 14, 12, 12],
  6126. ... f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]],
  6127. ... axis=1)
  6128. (array([ 3.5 , 9.25]), array([ 0.62338763, 0.09949846]))
  6129. """
  6130. return power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis,
  6131. lambda_="pearson")
  6132. KstestResult = _make_tuple_bunch('KstestResult', ['statistic', 'pvalue'],
  6133. ['statistic_location', 'statistic_sign'])
  6134. def _compute_dplus(cdfvals, x):
  6135. """Computes D+ as used in the Kolmogorov-Smirnov test.
  6136. Parameters
  6137. ----------
  6138. cdfvals : array_like
  6139. Sorted array of CDF values between 0 and 1
  6140. x: array_like
  6141. Sorted array of the stochastic variable itself
  6142. Returns
  6143. -------
  6144. res: Pair with the following elements:
  6145. - The maximum distance of the CDF values below Uniform(0, 1).
  6146. - The location at which the maximum is reached.
  6147. """
  6148. n = len(cdfvals)
  6149. dplus = (np.arange(1.0, n + 1) / n - cdfvals)
  6150. amax = dplus.argmax()
  6151. loc_max = x[amax]
  6152. return (dplus[amax], loc_max)
  6153. def _compute_dminus(cdfvals, x):
  6154. """Computes D- as used in the Kolmogorov-Smirnov test.
  6155. Parameters
  6156. ----------
  6157. cdfvals : array_like
  6158. Sorted array of CDF values between 0 and 1
  6159. x: array_like
  6160. Sorted array of the stochastic variable itself
  6161. Returns
  6162. -------
  6163. res: Pair with the following elements:
  6164. - Maximum distance of the CDF values above Uniform(0, 1)
  6165. - The location at which the maximum is reached.
  6166. """
  6167. n = len(cdfvals)
  6168. dminus = (cdfvals - np.arange(0.0, n)/n)
  6169. amax = dminus.argmax()
  6170. loc_max = x[amax]
  6171. return (dminus[amax], loc_max)
  6172. @_rename_parameter("mode", "method")
  6173. def ks_1samp(x, cdf, args=(), alternative='two-sided', method='auto'):
  6174. """
  6175. Performs the one-sample Kolmogorov-Smirnov test for goodness of fit.
  6176. This test compares the underlying distribution F(x) of a sample
  6177. against a given continuous distribution G(x). See Notes for a description
  6178. of the available null and alternative hypotheses.
  6179. Parameters
  6180. ----------
  6181. x : array_like
  6182. a 1-D array of observations of iid random variables.
  6183. cdf : callable
  6184. callable used to calculate the cdf.
  6185. args : tuple, sequence, optional
  6186. Distribution parameters, used with `cdf`.
  6187. alternative : {'two-sided', 'less', 'greater'}, optional
  6188. Defines the null and alternative hypotheses. Default is 'two-sided'.
  6189. Please see explanations in the Notes below.
  6190. method : {'auto', 'exact', 'approx', 'asymp'}, optional
  6191. Defines the distribution used for calculating the p-value.
  6192. The following options are available (default is 'auto'):
  6193. * 'auto' : selects one of the other options.
  6194. * 'exact' : uses the exact distribution of test statistic.
  6195. * 'approx' : approximates the two-sided probability with twice
  6196. the one-sided probability
  6197. * 'asymp': uses asymptotic distribution of test statistic
  6198. Returns
  6199. -------
  6200. res: KstestResult
  6201. An object containing attributes:
  6202. statistic : float
  6203. KS test statistic, either D+, D-, or D (the maximum of the two)
  6204. pvalue : float
  6205. One-tailed or two-tailed p-value.
  6206. statistic_location : float
  6207. Value of `x` corresponding with the KS statistic; i.e., the
  6208. distance between the empirical distribution function and the
  6209. hypothesized cumulative distribution function is measured at this
  6210. observation.
  6211. statistic_sign : int
  6212. +1 if the KS statistic is the maximum positive difference between
  6213. the empirical distribution function and the hypothesized cumulative
  6214. distribution function (D+); -1 if the KS statistic is the maximum
  6215. negative difference (D-).
  6216. See Also
  6217. --------
  6218. ks_2samp, kstest
  6219. Notes
  6220. -----
  6221. There are three options for the null and corresponding alternative
  6222. hypothesis that can be selected using the `alternative` parameter.
  6223. - `two-sided`: The null hypothesis is that the two distributions are
  6224. identical, F(x)=G(x) for all x; the alternative is that they are not
  6225. identical.
  6226. - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
  6227. alternative is that F(x) < G(x) for at least one x.
  6228. - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
  6229. alternative is that F(x) > G(x) for at least one x.
  6230. Note that the alternative hypotheses describe the *CDFs* of the
  6231. underlying distributions, not the observed values. For example,
  6232. suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
  6233. x1 tend to be less than those in x2.
  6234. Examples
  6235. --------
  6236. Suppose we wish to test the null hypothesis that a sample is distributed
  6237. according to the standard normal.
  6238. We choose a confidence level of 95%; that is, we will reject the null
  6239. hypothesis in favor of the alternative if the p-value is less than 0.05.
  6240. When testing uniformly distributed data, we would expect the
  6241. null hypothesis to be rejected.
  6242. >>> import numpy as np
  6243. >>> from scipy import stats
  6244. >>> rng = np.random.default_rng()
  6245. >>> stats.ks_1samp(stats.uniform.rvs(size=100, random_state=rng),
  6246. ... stats.norm.cdf)
  6247. KstestResult(statistic=0.5001899973268688, pvalue=1.1616392184763533e-23)
  6248. Indeed, the p-value is lower than our threshold of 0.05, so we reject the
  6249. null hypothesis in favor of the default "two-sided" alternative: the data
  6250. are *not* distributed according to the standard normal.
  6251. When testing random variates from the standard normal distribution, we
  6252. expect the data to be consistent with the null hypothesis most of the time.
  6253. >>> x = stats.norm.rvs(size=100, random_state=rng)
  6254. >>> stats.ks_1samp(x, stats.norm.cdf)
  6255. KstestResult(statistic=0.05345882212970396, pvalue=0.9227159037744717)
  6256. As expected, the p-value of 0.92 is not below our threshold of 0.05, so
  6257. we cannot reject the null hypothesis.
  6258. Suppose, however, that the random variates are distributed according to
  6259. a normal distribution that is shifted toward greater values. In this case,
  6260. the cumulative density function (CDF) of the underlying distribution tends
  6261. to be *less* than the CDF of the standard normal. Therefore, we would
  6262. expect the null hypothesis to be rejected with ``alternative='less'``:
  6263. >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng)
  6264. >>> stats.ks_1samp(x, stats.norm.cdf, alternative='less')
  6265. KstestResult(statistic=0.17482387821055168, pvalue=0.001913921057766743)
  6266. and indeed, with p-value smaller than our threshold, we reject the null
  6267. hypothesis in favor of the alternative.
  6268. """
  6269. mode = method
  6270. alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
  6271. alternative.lower()[0], alternative)
  6272. if alternative not in ['two-sided', 'greater', 'less']:
  6273. raise ValueError("Unexpected alternative %s" % alternative)
  6274. if np.ma.is_masked(x):
  6275. x = x.compressed()
  6276. N = len(x)
  6277. x = np.sort(x)
  6278. cdfvals = cdf(x, *args)
  6279. if alternative == 'greater':
  6280. Dplus, d_location = _compute_dplus(cdfvals, x)
  6281. return KstestResult(Dplus, distributions.ksone.sf(Dplus, N),
  6282. statistic_location=d_location,
  6283. statistic_sign=1)
  6284. if alternative == 'less':
  6285. Dminus, d_location = _compute_dminus(cdfvals, x)
  6286. return KstestResult(Dminus, distributions.ksone.sf(Dminus, N),
  6287. statistic_location=d_location,
  6288. statistic_sign=-1)
  6289. # alternative == 'two-sided':
  6290. Dplus, dplus_location = _compute_dplus(cdfvals, x)
  6291. Dminus, dminus_location = _compute_dminus(cdfvals, x)
  6292. if Dplus > Dminus:
  6293. D = Dplus
  6294. d_location = dplus_location
  6295. d_sign = 1
  6296. else:
  6297. D = Dminus
  6298. d_location = dminus_location
  6299. d_sign = -1
  6300. if mode == 'auto': # Always select exact
  6301. mode = 'exact'
  6302. if mode == 'exact':
  6303. prob = distributions.kstwo.sf(D, N)
  6304. elif mode == 'asymp':
  6305. prob = distributions.kstwobign.sf(D * np.sqrt(N))
  6306. else:
  6307. # mode == 'approx'
  6308. prob = 2 * distributions.ksone.sf(D, N)
  6309. prob = np.clip(prob, 0, 1)
  6310. return KstestResult(D, prob,
  6311. statistic_location=d_location,
  6312. statistic_sign=d_sign)
  6313. Ks_2sampResult = KstestResult
  6314. def _compute_prob_outside_square(n, h):
  6315. """
  6316. Compute the proportion of paths that pass outside the two diagonal lines.
  6317. Parameters
  6318. ----------
  6319. n : integer
  6320. n > 0
  6321. h : integer
  6322. 0 <= h <= n
  6323. Returns
  6324. -------
  6325. p : float
  6326. The proportion of paths that pass outside the lines x-y = +/-h.
  6327. """
  6328. # Compute Pr(D_{n,n} >= h/n)
  6329. # Prob = 2 * ( binom(2n, n-h) - binom(2n, n-2a) + binom(2n, n-3a) - ... )
  6330. # / binom(2n, n)
  6331. # This formulation exhibits subtractive cancellation.
  6332. # Instead divide each term by binom(2n, n), then factor common terms
  6333. # and use a Horner-like algorithm
  6334. # P = 2 * A0 * (1 - A1*(1 - A2*(1 - A3*(1 - A4*(...)))))
  6335. P = 0.0
  6336. k = int(np.floor(n / h))
  6337. while k >= 0:
  6338. p1 = 1.0
  6339. # Each of the Ai terms has numerator and denominator with
  6340. # h simple terms.
  6341. for j in range(h):
  6342. p1 = (n - k * h - j) * p1 / (n + k * h + j + 1)
  6343. P = p1 * (1.0 - P)
  6344. k -= 1
  6345. return 2 * P
  6346. def _count_paths_outside_method(m, n, g, h):
  6347. """Count the number of paths that pass outside the specified diagonal.
  6348. Parameters
  6349. ----------
  6350. m : integer
  6351. m > 0
  6352. n : integer
  6353. n > 0
  6354. g : integer
  6355. g is greatest common divisor of m and n
  6356. h : integer
  6357. 0 <= h <= lcm(m,n)
  6358. Returns
  6359. -------
  6360. p : float
  6361. The number of paths that go low.
  6362. The calculation may overflow - check for a finite answer.
  6363. Notes
  6364. -----
  6365. Count the integer lattice paths from (0, 0) to (m, n), which at some
  6366. point (x, y) along the path, satisfy:
  6367. m*y <= n*x - h*g
  6368. The paths make steps of size +1 in either positive x or positive y
  6369. directions.
  6370. We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
  6371. Hodges, J.L. Jr.,
  6372. "The Significance Probability of the Smirnov Two-Sample Test,"
  6373. Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
  6374. """
  6375. # Compute #paths which stay lower than x/m-y/n = h/lcm(m,n)
  6376. # B(x, y) = #{paths from (0,0) to (x,y) without
  6377. # previously crossing the boundary}
  6378. # = binom(x, y) - #{paths which already reached the boundary}
  6379. # Multiply by the number of path extensions going from (x, y) to (m, n)
  6380. # Sum.
  6381. # Probability is symmetrical in m, n. Computation below assumes m >= n.
  6382. if m < n:
  6383. m, n = n, m
  6384. mg = m // g
  6385. ng = n // g
  6386. # Not every x needs to be considered.
  6387. # xj holds the list of x values to be checked.
  6388. # Wherever n*x/m + ng*h crosses an integer
  6389. lxj = n + (mg-h)//mg
  6390. xj = [(h + mg * j + ng-1)//ng for j in range(lxj)]
  6391. # B is an array just holding a few values of B(x,y), the ones needed.
  6392. # B[j] == B(x_j, j)
  6393. if lxj == 0:
  6394. return special.binom(m + n, n)
  6395. B = np.zeros(lxj)
  6396. B[0] = 1
  6397. # Compute the B(x, y) terms
  6398. for j in range(1, lxj):
  6399. Bj = special.binom(xj[j] + j, j)
  6400. for i in range(j):
  6401. bin = special.binom(xj[j] - xj[i] + j - i, j-i)
  6402. Bj -= bin * B[i]
  6403. B[j] = Bj
  6404. # Compute the number of path extensions...
  6405. num_paths = 0
  6406. for j in range(lxj):
  6407. bin = special.binom((m-xj[j]) + (n - j), n-j)
  6408. term = B[j] * bin
  6409. num_paths += term
  6410. return num_paths
  6411. def _attempt_exact_2kssamp(n1, n2, g, d, alternative):
  6412. """Attempts to compute the exact 2sample probability.
  6413. n1, n2 are the sample sizes
  6414. g is the gcd(n1, n2)
  6415. d is the computed max difference in ECDFs
  6416. Returns (success, d, probability)
  6417. """
  6418. lcm = (n1 // g) * n2
  6419. h = int(np.round(d * lcm))
  6420. d = h * 1.0 / lcm
  6421. if h == 0:
  6422. return True, d, 1.0
  6423. saw_fp_error, prob = False, np.nan
  6424. try:
  6425. with np.errstate(invalid="raise", over="raise"):
  6426. if alternative == 'two-sided':
  6427. if n1 == n2:
  6428. prob = _compute_prob_outside_square(n1, h)
  6429. else:
  6430. prob = _compute_outer_prob_inside_method(n1, n2, g, h)
  6431. else:
  6432. if n1 == n2:
  6433. # prob = binom(2n, n-h) / binom(2n, n)
  6434. # Evaluating in that form incurs roundoff errors
  6435. # from special.binom. Instead calculate directly
  6436. jrange = np.arange(h)
  6437. prob = np.prod((n1 - jrange) / (n1 + jrange + 1.0))
  6438. else:
  6439. with np.errstate(over='raise'):
  6440. num_paths = _count_paths_outside_method(n1, n2, g, h)
  6441. bin = special.binom(n1 + n2, n1)
  6442. if num_paths > bin or np.isinf(bin):
  6443. saw_fp_error = True
  6444. else:
  6445. prob = num_paths / bin
  6446. except (FloatingPointError, OverflowError):
  6447. saw_fp_error = True
  6448. if saw_fp_error:
  6449. return False, d, np.nan
  6450. if not (0 <= prob <= 1):
  6451. return False, d, prob
  6452. return True, d, prob
  6453. @_rename_parameter("mode", "method")
  6454. def ks_2samp(data1, data2, alternative='two-sided', method='auto'):
  6455. """
  6456. Performs the two-sample Kolmogorov-Smirnov test for goodness of fit.
  6457. This test compares the underlying continuous distributions F(x) and G(x)
  6458. of two independent samples. See Notes for a description of the available
  6459. null and alternative hypotheses.
  6460. Parameters
  6461. ----------
  6462. data1, data2 : array_like, 1-Dimensional
  6463. Two arrays of sample observations assumed to be drawn from a continuous
  6464. distribution, sample sizes can be different.
  6465. alternative : {'two-sided', 'less', 'greater'}, optional
  6466. Defines the null and alternative hypotheses. Default is 'two-sided'.
  6467. Please see explanations in the Notes below.
  6468. method : {'auto', 'exact', 'asymp'}, optional
  6469. Defines the method used for calculating the p-value.
  6470. The following options are available (default is 'auto'):
  6471. * 'auto' : use 'exact' for small size arrays, 'asymp' for large
  6472. * 'exact' : use exact distribution of test statistic
  6473. * 'asymp' : use asymptotic distribution of test statistic
  6474. Returns
  6475. -------
  6476. res: KstestResult
  6477. An object containing attributes:
  6478. statistic : float
  6479. KS test statistic.
  6480. pvalue : float
  6481. One-tailed or two-tailed p-value.
  6482. statistic_location : float
  6483. Value from `data1` or `data2` corresponding with the KS statistic;
  6484. i.e., the distance between the empirical distribution functions is
  6485. measured at this observation.
  6486. statistic_sign : int
  6487. +1 if the empirical distribution function of `data1` exceeds
  6488. the empirical distribution function of `data2` at
  6489. `statistic_location`, otherwise -1.
  6490. See Also
  6491. --------
  6492. kstest, ks_1samp, epps_singleton_2samp, anderson_ksamp
  6493. Notes
  6494. -----
  6495. There are three options for the null and corresponding alternative
  6496. hypothesis that can be selected using the `alternative` parameter.
  6497. - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
  6498. alternative is that F(x) < G(x) for at least one x. The statistic
  6499. is the magnitude of the minimum (most negative) difference between the
  6500. empirical distribution functions of the samples.
  6501. - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
  6502. alternative is that F(x) > G(x) for at least one x. The statistic
  6503. is the maximum (most positive) difference between the empirical
  6504. distribution functions of the samples.
  6505. - `two-sided`: The null hypothesis is that the two distributions are
  6506. identical, F(x)=G(x) for all x; the alternative is that they are not
  6507. identical. The statistic is the maximum absolute difference between the
  6508. empirical distribution functions of the samples.
  6509. Note that the alternative hypotheses describe the *CDFs* of the
  6510. underlying distributions, not the observed values of the data. For example,
  6511. suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
  6512. x1 tend to be less than those in x2.
  6513. If the KS statistic is large, then the p-value will be small, and this may
  6514. be taken as evidence against the null hypothesis in favor of the
  6515. alternative.
  6516. If ``method='exact'``, `ks_2samp` attempts to compute an exact p-value,
  6517. that is, the probability under the null hypothesis of obtaining a test
  6518. statistic value as extreme as the value computed from the data.
  6519. If ``method='asymp'``, the asymptotic Kolmogorov-Smirnov distribution is
  6520. used to compute an approximate p-value.
  6521. If ``method='auto'``, an exact p-value computation is attempted if both
  6522. sample sizes are less than 10000; otherwise, the asymptotic method is used.
  6523. In any case, if an exact p-value calculation is attempted and fails, a
  6524. warning will be emitted, and the asymptotic p-value will be returned.
  6525. The 'two-sided' 'exact' computation computes the complementary probability
  6526. and then subtracts from 1. As such, the minimum probability it can return
  6527. is about 1e-16. While the algorithm itself is exact, numerical
  6528. errors may accumulate for large sample sizes. It is most suited to
  6529. situations in which one of the sample sizes is only a few thousand.
  6530. We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk [1]_.
  6531. References
  6532. ----------
  6533. .. [1] Hodges, J.L. Jr., "The Significance Probability of the Smirnov
  6534. Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
  6535. Examples
  6536. --------
  6537. Suppose we wish to test the null hypothesis that two samples were drawn
  6538. from the same distribution.
  6539. We choose a confidence level of 95%; that is, we will reject the null
  6540. hypothesis in favor of the alternative if the p-value is less than 0.05.
  6541. If the first sample were drawn from a uniform distribution and the second
  6542. were drawn from the standard normal, we would expect the null hypothesis
  6543. to be rejected.
  6544. >>> import numpy as np
  6545. >>> from scipy import stats
  6546. >>> rng = np.random.default_rng()
  6547. >>> sample1 = stats.uniform.rvs(size=100, random_state=rng)
  6548. >>> sample2 = stats.norm.rvs(size=110, random_state=rng)
  6549. >>> stats.ks_2samp(sample1, sample2)
  6550. KstestResult(statistic=0.5454545454545454, pvalue=7.37417839555191e-15)
  6551. Indeed, the p-value is lower than our threshold of 0.05, so we reject the
  6552. null hypothesis in favor of the default "two-sided" alternative: the data
  6553. were *not* drawn from the same distribution.
  6554. When both samples are drawn from the same distribution, we expect the data
  6555. to be consistent with the null hypothesis most of the time.
  6556. >>> sample1 = stats.norm.rvs(size=105, random_state=rng)
  6557. >>> sample2 = stats.norm.rvs(size=95, random_state=rng)
  6558. >>> stats.ks_2samp(sample1, sample2)
  6559. KstestResult(statistic=0.10927318295739348, pvalue=0.5438289009927495)
  6560. As expected, the p-value of 0.54 is not below our threshold of 0.05, so
  6561. we cannot reject the null hypothesis.
  6562. Suppose, however, that the first sample were drawn from
  6563. a normal distribution shifted toward greater values. In this case,
  6564. the cumulative density function (CDF) of the underlying distribution tends
  6565. to be *less* than the CDF underlying the second sample. Therefore, we would
  6566. expect the null hypothesis to be rejected with ``alternative='less'``:
  6567. >>> sample1 = stats.norm.rvs(size=105, loc=0.5, random_state=rng)
  6568. >>> stats.ks_2samp(sample1, sample2, alternative='less')
  6569. KstestResult(statistic=0.4055137844611529, pvalue=3.5474563068855554e-08)
  6570. and indeed, with p-value smaller than our threshold, we reject the null
  6571. hypothesis in favor of the alternative.
  6572. """
  6573. mode = method
  6574. if mode not in ['auto', 'exact', 'asymp']:
  6575. raise ValueError(f'Invalid value for mode: {mode}')
  6576. alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
  6577. alternative.lower()[0], alternative)
  6578. if alternative not in ['two-sided', 'less', 'greater']:
  6579. raise ValueError(f'Invalid value for alternative: {alternative}')
  6580. MAX_AUTO_N = 10000 # 'auto' will attempt to be exact if n1,n2 <= MAX_AUTO_N
  6581. if np.ma.is_masked(data1):
  6582. data1 = data1.compressed()
  6583. if np.ma.is_masked(data2):
  6584. data2 = data2.compressed()
  6585. data1 = np.sort(data1)
  6586. data2 = np.sort(data2)
  6587. n1 = data1.shape[0]
  6588. n2 = data2.shape[0]
  6589. if min(n1, n2) == 0:
  6590. raise ValueError('Data passed to ks_2samp must not be empty')
  6591. data_all = np.concatenate([data1, data2])
  6592. # using searchsorted solves equal data problem
  6593. cdf1 = np.searchsorted(data1, data_all, side='right') / n1
  6594. cdf2 = np.searchsorted(data2, data_all, side='right') / n2
  6595. cddiffs = cdf1 - cdf2
  6596. # Identify the location of the statistic
  6597. argminS = np.argmin(cddiffs)
  6598. argmaxS = np.argmax(cddiffs)
  6599. loc_minS = data_all[argminS]
  6600. loc_maxS = data_all[argmaxS]
  6601. # Ensure sign of minS is not negative.
  6602. minS = np.clip(-cddiffs[argminS], 0, 1)
  6603. maxS = cddiffs[argmaxS]
  6604. if alternative == 'less' or (alternative == 'two-sided' and minS > maxS):
  6605. d = minS
  6606. d_location = loc_minS
  6607. d_sign = -1
  6608. else:
  6609. d = maxS
  6610. d_location = loc_maxS
  6611. d_sign = 1
  6612. g = gcd(n1, n2)
  6613. n1g = n1 // g
  6614. n2g = n2 // g
  6615. prob = -np.inf
  6616. if mode == 'auto':
  6617. mode = 'exact' if max(n1, n2) <= MAX_AUTO_N else 'asymp'
  6618. elif mode == 'exact':
  6619. # If lcm(n1, n2) is too big, switch from exact to asymp
  6620. if n1g >= np.iinfo(np.int32).max / n2g:
  6621. mode = 'asymp'
  6622. warnings.warn(
  6623. f"Exact ks_2samp calculation not possible with samples sizes "
  6624. f"{n1} and {n2}. Switching to 'asymp'.", RuntimeWarning,
  6625. stacklevel=3)
  6626. if mode == 'exact':
  6627. success, d, prob = _attempt_exact_2kssamp(n1, n2, g, d, alternative)
  6628. if not success:
  6629. mode = 'asymp'
  6630. warnings.warn(f"ks_2samp: Exact calculation unsuccessful. "
  6631. f"Switching to method={mode}.", RuntimeWarning,
  6632. stacklevel=3)
  6633. if mode == 'asymp':
  6634. # The product n1*n2 is large. Use Smirnov's asymptoptic formula.
  6635. # Ensure float to avoid overflow in multiplication
  6636. # sorted because the one-sided formula is not symmetric in n1, n2
  6637. m, n = sorted([float(n1), float(n2)], reverse=True)
  6638. en = m * n / (m + n)
  6639. if alternative == 'two-sided':
  6640. prob = distributions.kstwo.sf(d, np.round(en))
  6641. else:
  6642. z = np.sqrt(en) * d
  6643. # Use Hodges' suggested approximation Eqn 5.3
  6644. # Requires m to be the larger of (n1, n2)
  6645. expt = -2 * z**2 - 2 * z * (m + 2*n)/np.sqrt(m*n*(m+n))/3.0
  6646. prob = np.exp(expt)
  6647. prob = np.clip(prob, 0, 1)
  6648. return KstestResult(d, prob, statistic_location=d_location,
  6649. statistic_sign=d_sign)
  6650. def _parse_kstest_args(data1, data2, args, N):
  6651. # kstest allows many different variations of arguments.
  6652. # Pull out the parsing into a separate function
  6653. # (xvals, yvals, ) # 2sample
  6654. # (xvals, cdf function,..)
  6655. # (xvals, name of distribution, ...)
  6656. # (name of distribution, name of distribution, ...)
  6657. # Returns xvals, yvals, cdf
  6658. # where cdf is a cdf function, or None
  6659. # and yvals is either an array_like of values, or None
  6660. # and xvals is array_like.
  6661. rvsfunc, cdf = None, None
  6662. if isinstance(data1, str):
  6663. rvsfunc = getattr(distributions, data1).rvs
  6664. elif callable(data1):
  6665. rvsfunc = data1
  6666. if isinstance(data2, str):
  6667. cdf = getattr(distributions, data2).cdf
  6668. data2 = None
  6669. elif callable(data2):
  6670. cdf = data2
  6671. data2 = None
  6672. data1 = np.sort(rvsfunc(*args, size=N) if rvsfunc else data1)
  6673. return data1, data2, cdf
  6674. @_rename_parameter("mode", "method")
  6675. def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', method='auto'):
  6676. """
  6677. Performs the (one-sample or two-sample) Kolmogorov-Smirnov test for
  6678. goodness of fit.
  6679. The one-sample test compares the underlying distribution F(x) of a sample
  6680. against a given distribution G(x). The two-sample test compares the
  6681. underlying distributions of two independent samples. Both tests are valid
  6682. only for continuous distributions.
  6683. Parameters
  6684. ----------
  6685. rvs : str, array_like, or callable
  6686. If an array, it should be a 1-D array of observations of random
  6687. variables.
  6688. If a callable, it should be a function to generate random variables;
  6689. it is required to have a keyword argument `size`.
  6690. If a string, it should be the name of a distribution in `scipy.stats`,
  6691. which will be used to generate random variables.
  6692. cdf : str, array_like or callable
  6693. If array_like, it should be a 1-D array of observations of random
  6694. variables, and the two-sample test is performed
  6695. (and rvs must be array_like).
  6696. If a callable, that callable is used to calculate the cdf.
  6697. If a string, it should be the name of a distribution in `scipy.stats`,
  6698. which will be used as the cdf function.
  6699. args : tuple, sequence, optional
  6700. Distribution parameters, used if `rvs` or `cdf` are strings or
  6701. callables.
  6702. N : int, optional
  6703. Sample size if `rvs` is string or callable. Default is 20.
  6704. alternative : {'two-sided', 'less', 'greater'}, optional
  6705. Defines the null and alternative hypotheses. Default is 'two-sided'.
  6706. Please see explanations in the Notes below.
  6707. method : {'auto', 'exact', 'approx', 'asymp'}, optional
  6708. Defines the distribution used for calculating the p-value.
  6709. The following options are available (default is 'auto'):
  6710. * 'auto' : selects one of the other options.
  6711. * 'exact' : uses the exact distribution of test statistic.
  6712. * 'approx' : approximates the two-sided probability with twice the
  6713. one-sided probability
  6714. * 'asymp': uses asymptotic distribution of test statistic
  6715. Returns
  6716. -------
  6717. res: KstestResult
  6718. An object containing attributes:
  6719. statistic : float
  6720. KS test statistic, either D+, D-, or D (the maximum of the two)
  6721. pvalue : float
  6722. One-tailed or two-tailed p-value.
  6723. statistic_location : float
  6724. In a one-sample test, this is the value of `rvs`
  6725. corresponding with the KS statistic; i.e., the distance between
  6726. the empirical distribution function and the hypothesized cumulative
  6727. distribution function is measured at this observation.
  6728. In a two-sample test, this is the value from `rvs` or `cdf`
  6729. corresponding with the KS statistic; i.e., the distance between
  6730. the empirical distribution functions is measured at this
  6731. observation.
  6732. statistic_sign : int
  6733. In a one-sample test, this is +1 if the KS statistic is the
  6734. maximum positive difference between the empirical distribution
  6735. function and the hypothesized cumulative distribution function
  6736. (D+); it is -1 if the KS statistic is the maximum negative
  6737. difference (D-).
  6738. In a two-sample test, this is +1 if the empirical distribution
  6739. function of `rvs` exceeds the empirical distribution
  6740. function of `cdf` at `statistic_location`, otherwise -1.
  6741. See Also
  6742. --------
  6743. ks_1samp, ks_2samp
  6744. Notes
  6745. -----
  6746. There are three options for the null and corresponding alternative
  6747. hypothesis that can be selected using the `alternative` parameter.
  6748. - `two-sided`: The null hypothesis is that the two distributions are
  6749. identical, F(x)=G(x) for all x; the alternative is that they are not
  6750. identical.
  6751. - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
  6752. alternative is that F(x) < G(x) for at least one x.
  6753. - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
  6754. alternative is that F(x) > G(x) for at least one x.
  6755. Note that the alternative hypotheses describe the *CDFs* of the
  6756. underlying distributions, not the observed values. For example,
  6757. suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
  6758. x1 tend to be less than those in x2.
  6759. Examples
  6760. --------
  6761. Suppose we wish to test the null hypothesis that a sample is distributed
  6762. according to the standard normal.
  6763. We choose a confidence level of 95%; that is, we will reject the null
  6764. hypothesis in favor of the alternative if the p-value is less than 0.05.
  6765. When testing uniformly distributed data, we would expect the
  6766. null hypothesis to be rejected.
  6767. >>> import numpy as np
  6768. >>> from scipy import stats
  6769. >>> rng = np.random.default_rng()
  6770. >>> stats.kstest(stats.uniform.rvs(size=100, random_state=rng),
  6771. ... stats.norm.cdf)
  6772. KstestResult(statistic=0.5001899973268688, pvalue=1.1616392184763533e-23)
  6773. Indeed, the p-value is lower than our threshold of 0.05, so we reject the
  6774. null hypothesis in favor of the default "two-sided" alternative: the data
  6775. are *not* distributed according to the standard normal.
  6776. When testing random variates from the standard normal distribution, we
  6777. expect the data to be consistent with the null hypothesis most of the time.
  6778. >>> x = stats.norm.rvs(size=100, random_state=rng)
  6779. >>> stats.kstest(x, stats.norm.cdf)
  6780. KstestResult(statistic=0.05345882212970396, pvalue=0.9227159037744717)
  6781. As expected, the p-value of 0.92 is not below our threshold of 0.05, so
  6782. we cannot reject the null hypothesis.
  6783. Suppose, however, that the random variates are distributed according to
  6784. a normal distribution that is shifted toward greater values. In this case,
  6785. the cumulative density function (CDF) of the underlying distribution tends
  6786. to be *less* than the CDF of the standard normal. Therefore, we would
  6787. expect the null hypothesis to be rejected with ``alternative='less'``:
  6788. >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng)
  6789. >>> stats.kstest(x, stats.norm.cdf, alternative='less')
  6790. KstestResult(statistic=0.17482387821055168, pvalue=0.001913921057766743)
  6791. and indeed, with p-value smaller than our threshold, we reject the null
  6792. hypothesis in favor of the alternative.
  6793. For convenience, the previous test can be performed using the name of the
  6794. distribution as the second argument.
  6795. >>> stats.kstest(x, "norm", alternative='less')
  6796. KstestResult(statistic=0.17482387821055168, pvalue=0.001913921057766743)
  6797. The examples above have all been one-sample tests identical to those
  6798. performed by `ks_1samp`. Note that `kstest` can also perform two-sample
  6799. tests identical to those performed by `ks_2samp`. For example, when two
  6800. samples are drawn from the same distribution, we expect the data to be
  6801. consistent with the null hypothesis most of the time.
  6802. >>> sample1 = stats.laplace.rvs(size=105, random_state=rng)
  6803. >>> sample2 = stats.laplace.rvs(size=95, random_state=rng)
  6804. >>> stats.kstest(sample1, sample2)
  6805. KstestResult(statistic=0.11779448621553884, pvalue=0.4494256912629795)
  6806. As expected, the p-value of 0.45 is not below our threshold of 0.05, so
  6807. we cannot reject the null hypothesis.
  6808. """
  6809. # to not break compatibility with existing code
  6810. if alternative == 'two_sided':
  6811. alternative = 'two-sided'
  6812. if alternative not in ['two-sided', 'greater', 'less']:
  6813. raise ValueError("Unexpected alternative %s" % alternative)
  6814. xvals, yvals, cdf = _parse_kstest_args(rvs, cdf, args, N)
  6815. if cdf:
  6816. return ks_1samp(xvals, cdf, args=args, alternative=alternative,
  6817. method=method)
  6818. return ks_2samp(xvals, yvals, alternative=alternative, method=method)
  6819. def tiecorrect(rankvals):
  6820. """Tie correction factor for Mann-Whitney U and Kruskal-Wallis H tests.
  6821. Parameters
  6822. ----------
  6823. rankvals : array_like
  6824. A 1-D sequence of ranks. Typically this will be the array
  6825. returned by `~scipy.stats.rankdata`.
  6826. Returns
  6827. -------
  6828. factor : float
  6829. Correction factor for U or H.
  6830. See Also
  6831. --------
  6832. rankdata : Assign ranks to the data
  6833. mannwhitneyu : Mann-Whitney rank test
  6834. kruskal : Kruskal-Wallis H test
  6835. References
  6836. ----------
  6837. .. [1] Siegel, S. (1956) Nonparametric Statistics for the Behavioral
  6838. Sciences. New York: McGraw-Hill.
  6839. Examples
  6840. --------
  6841. >>> from scipy.stats import tiecorrect, rankdata
  6842. >>> tiecorrect([1, 2.5, 2.5, 4])
  6843. 0.9
  6844. >>> ranks = rankdata([1, 3, 2, 4, 5, 7, 2, 8, 4])
  6845. >>> ranks
  6846. array([ 1. , 4. , 2.5, 5.5, 7. , 8. , 2.5, 9. , 5.5])
  6847. >>> tiecorrect(ranks)
  6848. 0.9833333333333333
  6849. """
  6850. arr = np.sort(rankvals)
  6851. idx = np.nonzero(np.r_[True, arr[1:] != arr[:-1], True])[0]
  6852. cnt = np.diff(idx).astype(np.float64)
  6853. size = np.float64(arr.size)
  6854. return 1.0 if size < 2 else 1.0 - (cnt**3 - cnt).sum() / (size**3 - size)
  6855. RanksumsResult = namedtuple('RanksumsResult', ('statistic', 'pvalue'))
  6856. @_axis_nan_policy_factory(RanksumsResult, n_samples=2)
  6857. def ranksums(x, y, alternative='two-sided'):
  6858. """Compute the Wilcoxon rank-sum statistic for two samples.
  6859. The Wilcoxon rank-sum test tests the null hypothesis that two sets
  6860. of measurements are drawn from the same distribution. The alternative
  6861. hypothesis is that values in one sample are more likely to be
  6862. larger than the values in the other sample.
  6863. This test should be used to compare two samples from continuous
  6864. distributions. It does not handle ties between measurements
  6865. in x and y. For tie-handling and an optional continuity correction
  6866. see `scipy.stats.mannwhitneyu`.
  6867. Parameters
  6868. ----------
  6869. x,y : array_like
  6870. The data from the two samples.
  6871. alternative : {'two-sided', 'less', 'greater'}, optional
  6872. Defines the alternative hypothesis. Default is 'two-sided'.
  6873. The following options are available:
  6874. * 'two-sided': one of the distributions (underlying `x` or `y`) is
  6875. stochastically greater than the other.
  6876. * 'less': the distribution underlying `x` is stochastically less
  6877. than the distribution underlying `y`.
  6878. * 'greater': the distribution underlying `x` is stochastically greater
  6879. than the distribution underlying `y`.
  6880. .. versionadded:: 1.7.0
  6881. Returns
  6882. -------
  6883. statistic : float
  6884. The test statistic under the large-sample approximation that the
  6885. rank sum statistic is normally distributed.
  6886. pvalue : float
  6887. The p-value of the test.
  6888. References
  6889. ----------
  6890. .. [1] https://en.wikipedia.org/wiki/Wilcoxon_rank-sum_test
  6891. Examples
  6892. --------
  6893. We can test the hypothesis that two independent unequal-sized samples are
  6894. drawn from the same distribution with computing the Wilcoxon rank-sum
  6895. statistic.
  6896. >>> import numpy as np
  6897. >>> from scipy.stats import ranksums
  6898. >>> rng = np.random.default_rng()
  6899. >>> sample1 = rng.uniform(-1, 1, 200)
  6900. >>> sample2 = rng.uniform(-0.5, 1.5, 300) # a shifted distribution
  6901. >>> ranksums(sample1, sample2)
  6902. RanksumsResult(statistic=-7.887059, pvalue=3.09390448e-15) # may vary
  6903. >>> ranksums(sample1, sample2, alternative='less')
  6904. RanksumsResult(statistic=-7.750585297581713, pvalue=4.573497606342543e-15) # may vary
  6905. >>> ranksums(sample1, sample2, alternative='greater')
  6906. RanksumsResult(statistic=-7.750585297581713, pvalue=0.9999999999999954) # may vary
  6907. The p-value of less than ``0.05`` indicates that this test rejects the
  6908. hypothesis at the 5% significance level.
  6909. """
  6910. x, y = map(np.asarray, (x, y))
  6911. n1 = len(x)
  6912. n2 = len(y)
  6913. alldata = np.concatenate((x, y))
  6914. ranked = rankdata(alldata)
  6915. x = ranked[:n1]
  6916. s = np.sum(x, axis=0)
  6917. expected = n1 * (n1+n2+1) / 2.0
  6918. z = (s - expected) / np.sqrt(n1*n2*(n1+n2+1)/12.0)
  6919. z, prob = _normtest_finish(z, alternative)
  6920. return RanksumsResult(z, prob)
  6921. KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue'))
  6922. @_axis_nan_policy_factory(KruskalResult, n_samples=None)
  6923. def kruskal(*samples, nan_policy='propagate'):
  6924. """Compute the Kruskal-Wallis H-test for independent samples.
  6925. The Kruskal-Wallis H-test tests the null hypothesis that the population
  6926. median of all of the groups are equal. It is a non-parametric version of
  6927. ANOVA. The test works on 2 or more independent samples, which may have
  6928. different sizes. Note that rejecting the null hypothesis does not
  6929. indicate which of the groups differs. Post hoc comparisons between
  6930. groups are required to determine which groups are different.
  6931. Parameters
  6932. ----------
  6933. sample1, sample2, ... : array_like
  6934. Two or more arrays with the sample measurements can be given as
  6935. arguments. Samples must be one-dimensional.
  6936. nan_policy : {'propagate', 'raise', 'omit'}, optional
  6937. Defines how to handle when input contains nan.
  6938. The following options are available (default is 'propagate'):
  6939. * 'propagate': returns nan
  6940. * 'raise': throws an error
  6941. * 'omit': performs the calculations ignoring nan values
  6942. Returns
  6943. -------
  6944. statistic : float
  6945. The Kruskal-Wallis H statistic, corrected for ties.
  6946. pvalue : float
  6947. The p-value for the test using the assumption that H has a chi
  6948. square distribution. The p-value returned is the survival function of
  6949. the chi square distribution evaluated at H.
  6950. See Also
  6951. --------
  6952. f_oneway : 1-way ANOVA.
  6953. mannwhitneyu : Mann-Whitney rank test on two samples.
  6954. friedmanchisquare : Friedman test for repeated measurements.
  6955. Notes
  6956. -----
  6957. Due to the assumption that H has a chi square distribution, the number
  6958. of samples in each group must not be too small. A typical rule is
  6959. that each sample must have at least 5 measurements.
  6960. References
  6961. ----------
  6962. .. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in
  6963. One-Criterion Variance Analysis", Journal of the American Statistical
  6964. Association, Vol. 47, Issue 260, pp. 583-621, 1952.
  6965. .. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance
  6966. Examples
  6967. --------
  6968. >>> from scipy import stats
  6969. >>> x = [1, 3, 5, 7, 9]
  6970. >>> y = [2, 4, 6, 8, 10]
  6971. >>> stats.kruskal(x, y)
  6972. KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895)
  6973. >>> x = [1, 1, 1]
  6974. >>> y = [2, 2, 2]
  6975. >>> z = [2, 2]
  6976. >>> stats.kruskal(x, y, z)
  6977. KruskalResult(statistic=7.0, pvalue=0.0301973834223185)
  6978. """
  6979. samples = list(map(np.asarray, samples))
  6980. num_groups = len(samples)
  6981. if num_groups < 2:
  6982. raise ValueError("Need at least two groups in stats.kruskal()")
  6983. for sample in samples:
  6984. if sample.size == 0:
  6985. return KruskalResult(np.nan, np.nan)
  6986. elif sample.ndim != 1:
  6987. raise ValueError("Samples must be one-dimensional.")
  6988. n = np.asarray(list(map(len, samples)))
  6989. if nan_policy not in ('propagate', 'raise', 'omit'):
  6990. raise ValueError("nan_policy must be 'propagate', 'raise' or 'omit'")
  6991. contains_nan = False
  6992. for sample in samples:
  6993. cn = _contains_nan(sample, nan_policy)
  6994. if cn[0]:
  6995. contains_nan = True
  6996. break
  6997. if contains_nan and nan_policy == 'omit':
  6998. for sample in samples:
  6999. sample = ma.masked_invalid(sample)
  7000. return mstats_basic.kruskal(*samples)
  7001. if contains_nan and nan_policy == 'propagate':
  7002. return KruskalResult(np.nan, np.nan)
  7003. alldata = np.concatenate(samples)
  7004. ranked = rankdata(alldata)
  7005. ties = tiecorrect(ranked)
  7006. if ties == 0:
  7007. raise ValueError('All numbers are identical in kruskal')
  7008. # Compute sum^2/n for each group and sum
  7009. j = np.insert(np.cumsum(n), 0, 0)
  7010. ssbn = 0
  7011. for i in range(num_groups):
  7012. ssbn += _square_of_sums(ranked[j[i]:j[i+1]]) / n[i]
  7013. totaln = np.sum(n, dtype=float)
  7014. h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3 * (totaln + 1)
  7015. df = num_groups - 1
  7016. h /= ties
  7017. return KruskalResult(h, distributions.chi2.sf(h, df))
  7018. FriedmanchisquareResult = namedtuple('FriedmanchisquareResult',
  7019. ('statistic', 'pvalue'))
  7020. def friedmanchisquare(*samples):
  7021. """Compute the Friedman test for repeated samples.
  7022. The Friedman test tests the null hypothesis that repeated samples of
  7023. the same individuals have the same distribution. It is often used
  7024. to test for consistency among samples obtained in different ways.
  7025. For example, if two sampling techniques are used on the same set of
  7026. individuals, the Friedman test can be used to determine if the two
  7027. sampling techniques are consistent.
  7028. Parameters
  7029. ----------
  7030. sample1, sample2, sample3... : array_like
  7031. Arrays of observations. All of the arrays must have the same number
  7032. of elements. At least three samples must be given.
  7033. Returns
  7034. -------
  7035. statistic : float
  7036. The test statistic, correcting for ties.
  7037. pvalue : float
  7038. The associated p-value assuming that the test statistic has a chi
  7039. squared distribution.
  7040. Notes
  7041. -----
  7042. Due to the assumption that the test statistic has a chi squared
  7043. distribution, the p-value is only reliable for n > 10 and more than
  7044. 6 repeated samples.
  7045. References
  7046. ----------
  7047. .. [1] https://en.wikipedia.org/wiki/Friedman_test
  7048. """
  7049. k = len(samples)
  7050. if k < 3:
  7051. raise ValueError('At least 3 sets of samples must be given '
  7052. 'for Friedman test, got {}.'.format(k))
  7053. n = len(samples[0])
  7054. for i in range(1, k):
  7055. if len(samples[i]) != n:
  7056. raise ValueError('Unequal N in friedmanchisquare. Aborting.')
  7057. # Rank data
  7058. data = np.vstack(samples).T
  7059. data = data.astype(float)
  7060. for i in range(len(data)):
  7061. data[i] = rankdata(data[i])
  7062. # Handle ties
  7063. ties = 0
  7064. for d in data:
  7065. replist, repnum = find_repeats(array(d))
  7066. for t in repnum:
  7067. ties += t * (t*t - 1)
  7068. c = 1 - ties / (k*(k*k - 1)*n)
  7069. ssbn = np.sum(data.sum(axis=0)**2)
  7070. chisq = (12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)) / c
  7071. return FriedmanchisquareResult(chisq, distributions.chi2.sf(chisq, k - 1))
  7072. BrunnerMunzelResult = namedtuple('BrunnerMunzelResult',
  7073. ('statistic', 'pvalue'))
  7074. def brunnermunzel(x, y, alternative="two-sided", distribution="t",
  7075. nan_policy='propagate'):
  7076. """Compute the Brunner-Munzel test on samples x and y.
  7077. The Brunner-Munzel test is a nonparametric test of the null hypothesis that
  7078. when values are taken one by one from each group, the probabilities of
  7079. getting large values in both groups are equal.
  7080. Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the
  7081. assumption of equivariance of two groups. Note that this does not assume
  7082. the distributions are same. This test works on two independent samples,
  7083. which may have different sizes.
  7084. Parameters
  7085. ----------
  7086. x, y : array_like
  7087. Array of samples, should be one-dimensional.
  7088. alternative : {'two-sided', 'less', 'greater'}, optional
  7089. Defines the alternative hypothesis.
  7090. The following options are available (default is 'two-sided'):
  7091. * 'two-sided'
  7092. * 'less': one-sided
  7093. * 'greater': one-sided
  7094. distribution : {'t', 'normal'}, optional
  7095. Defines how to get the p-value.
  7096. The following options are available (default is 't'):
  7097. * 't': get the p-value by t-distribution
  7098. * 'normal': get the p-value by standard normal distribution.
  7099. nan_policy : {'propagate', 'raise', 'omit'}, optional
  7100. Defines how to handle when input contains nan.
  7101. The following options are available (default is 'propagate'):
  7102. * 'propagate': returns nan
  7103. * 'raise': throws an error
  7104. * 'omit': performs the calculations ignoring nan values
  7105. Returns
  7106. -------
  7107. statistic : float
  7108. The Brunner-Munzer W statistic.
  7109. pvalue : float
  7110. p-value assuming an t distribution. One-sided or
  7111. two-sided, depending on the choice of `alternative` and `distribution`.
  7112. See Also
  7113. --------
  7114. mannwhitneyu : Mann-Whitney rank test on two samples.
  7115. Notes
  7116. -----
  7117. Brunner and Munzel recommended to estimate the p-value by t-distribution
  7118. when the size of data is 50 or less. If the size is lower than 10, it would
  7119. be better to use permuted Brunner Munzel test (see [2]_).
  7120. References
  7121. ----------
  7122. .. [1] Brunner, E. and Munzel, U. "The nonparametric Benhrens-Fisher
  7123. problem: Asymptotic theory and a small-sample approximation".
  7124. Biometrical Journal. Vol. 42(2000): 17-25.
  7125. .. [2] Neubert, K. and Brunner, E. "A studentized permutation test for the
  7126. non-parametric Behrens-Fisher problem". Computational Statistics and
  7127. Data Analysis. Vol. 51(2007): 5192-5204.
  7128. Examples
  7129. --------
  7130. >>> from scipy import stats
  7131. >>> x1 = [1,2,1,1,1,1,1,1,1,1,2,4,1,1]
  7132. >>> x2 = [3,3,4,3,1,2,3,1,1,5,4]
  7133. >>> w, p_value = stats.brunnermunzel(x1, x2)
  7134. >>> w
  7135. 3.1374674823029505
  7136. >>> p_value
  7137. 0.0057862086661515377
  7138. """
  7139. x = np.asarray(x)
  7140. y = np.asarray(y)
  7141. # check both x and y
  7142. cnx, npx = _contains_nan(x, nan_policy)
  7143. cny, npy = _contains_nan(y, nan_policy)
  7144. contains_nan = cnx or cny
  7145. if npx == "omit" or npy == "omit":
  7146. nan_policy = "omit"
  7147. if contains_nan and nan_policy == "propagate":
  7148. return BrunnerMunzelResult(np.nan, np.nan)
  7149. elif contains_nan and nan_policy == "omit":
  7150. x = ma.masked_invalid(x)
  7151. y = ma.masked_invalid(y)
  7152. return mstats_basic.brunnermunzel(x, y, alternative, distribution)
  7153. nx = len(x)
  7154. ny = len(y)
  7155. if nx == 0 or ny == 0:
  7156. return BrunnerMunzelResult(np.nan, np.nan)
  7157. rankc = rankdata(np.concatenate((x, y)))
  7158. rankcx = rankc[0:nx]
  7159. rankcy = rankc[nx:nx+ny]
  7160. rankcx_mean = np.mean(rankcx)
  7161. rankcy_mean = np.mean(rankcy)
  7162. rankx = rankdata(x)
  7163. ranky = rankdata(y)
  7164. rankx_mean = np.mean(rankx)
  7165. ranky_mean = np.mean(ranky)
  7166. Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0))
  7167. Sx /= nx - 1
  7168. Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0))
  7169. Sy /= ny - 1
  7170. wbfn = nx * ny * (rankcy_mean - rankcx_mean)
  7171. wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy)
  7172. if distribution == "t":
  7173. df_numer = np.power(nx * Sx + ny * Sy, 2.0)
  7174. df_denom = np.power(nx * Sx, 2.0) / (nx - 1)
  7175. df_denom += np.power(ny * Sy, 2.0) / (ny - 1)
  7176. df = df_numer / df_denom
  7177. if (df_numer == 0) and (df_denom == 0):
  7178. message = ("p-value cannot be estimated with `distribution='t' "
  7179. "because degrees of freedom parameter is undefined "
  7180. "(0/0). Try using `distribution='normal'")
  7181. warnings.warn(message, RuntimeWarning)
  7182. p = distributions.t.cdf(wbfn, df)
  7183. elif distribution == "normal":
  7184. p = distributions.norm.cdf(wbfn)
  7185. else:
  7186. raise ValueError(
  7187. "distribution should be 't' or 'normal'")
  7188. if alternative == "greater":
  7189. pass
  7190. elif alternative == "less":
  7191. p = 1 - p
  7192. elif alternative == "two-sided":
  7193. p = 2 * np.min([p, 1-p])
  7194. else:
  7195. raise ValueError(
  7196. "alternative should be 'less', 'greater' or 'two-sided'")
  7197. return BrunnerMunzelResult(wbfn, p)
  7198. def combine_pvalues(pvalues, method='fisher', weights=None):
  7199. """
  7200. Combine p-values from independent tests that bear upon the same hypothesis.
  7201. These methods are intended only for combining p-values from hypothesis
  7202. tests based upon continuous distributions.
  7203. Each method assumes that under the null hypothesis, the p-values are
  7204. sampled independently and uniformly from the interval [0, 1]. A test
  7205. statistic (different for each method) is computed and a combined
  7206. p-value is calculated based upon the distribution of this test statistic
  7207. under the null hypothesis.
  7208. Parameters
  7209. ----------
  7210. pvalues : array_like, 1-D
  7211. Array of p-values assumed to come from independent tests based on
  7212. continuous distributions.
  7213. method : {'fisher', 'pearson', 'tippett', 'stouffer', 'mudholkar_george'}
  7214. Name of method to use to combine p-values.
  7215. The available methods are (see Notes for details):
  7216. * 'fisher': Fisher's method (Fisher's combined probability test)
  7217. * 'pearson': Pearson's method
  7218. * 'mudholkar_george': Mudholkar's and George's method
  7219. * 'tippett': Tippett's method
  7220. * 'stouffer': Stouffer's Z-score method
  7221. weights : array_like, 1-D, optional
  7222. Optional array of weights used only for Stouffer's Z-score method.
  7223. Returns
  7224. -------
  7225. res : SignificanceResult
  7226. An object containing attributes:
  7227. statistic : float
  7228. The statistic calculated by the specified method.
  7229. pvalue : float
  7230. The combined p-value.
  7231. Notes
  7232. -----
  7233. If this function is applied to tests with a discrete statistics such as
  7234. any rank test or contingency-table test, it will yield systematically
  7235. wrong results, e.g. Fisher's method will systematically overestimate the
  7236. p-value [1]_. This problem becomes less severe for large sample sizes
  7237. when the discrete distributions become approximately continuous.
  7238. The differences between the methods can be best illustrated by their
  7239. statistics and what aspects of a combination of p-values they emphasise
  7240. when considering significance [2]_. For example, methods emphasising large
  7241. p-values are more sensitive to strong false and true negatives; conversely
  7242. methods focussing on small p-values are sensitive to positives.
  7243. * The statistics of Fisher's method (also known as Fisher's combined
  7244. probability test) [3]_ is :math:`-2\\sum_i \\log(p_i)`, which is
  7245. equivalent (as a test statistics) to the product of individual p-values:
  7246. :math:`\\prod_i p_i`. Under the null hypothesis, this statistics follows
  7247. a :math:`\\chi^2` distribution. This method emphasises small p-values.
  7248. * Pearson's method uses :math:`-2\\sum_i\\log(1-p_i)`, which is equivalent
  7249. to :math:`\\prod_i \\frac{1}{1-p_i}` [2]_.
  7250. It thus emphasises large p-values.
  7251. * Mudholkar and George compromise between Fisher's and Pearson's method by
  7252. averaging their statistics [4]_. Their method emphasises extreme
  7253. p-values, both close to 1 and 0.
  7254. * Stouffer's method [5]_ uses Z-scores and the statistic:
  7255. :math:`\\sum_i \\Phi^{-1} (p_i)`, where :math:`\\Phi` is the CDF of the
  7256. standard normal distribution. The advantage of this method is that it is
  7257. straightforward to introduce weights, which can make Stouffer's method
  7258. more powerful than Fisher's method when the p-values are from studies
  7259. of different size [6]_ [7]_.
  7260. * Tippett's method uses the smallest p-value as a statistic.
  7261. (Mind that this minimum is not the combined p-value.)
  7262. Fisher's method may be extended to combine p-values from dependent tests
  7263. [8]_. Extensions such as Brown's method and Kost's method are not currently
  7264. implemented.
  7265. .. versionadded:: 0.15.0
  7266. References
  7267. ----------
  7268. .. [1] Kincaid, W. M., "The Combination of Tests Based on Discrete
  7269. Distributions." Journal of the American Statistical Association 57,
  7270. no. 297 (1962), 10-19.
  7271. .. [2] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of
  7272. combining p-values." Biometrika 105.1 (2018): 239-246.
  7273. .. [3] https://en.wikipedia.org/wiki/Fisher%27s_method
  7274. .. [4] George, E. O., and G. S. Mudholkar. "On the convolution of logistic
  7275. random variables." Metrika 30.1 (1983): 1-13.
  7276. .. [5] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method
  7277. .. [6] Whitlock, M. C. "Combining probability from independent tests: the
  7278. weighted Z-method is superior to Fisher's approach." Journal of
  7279. Evolutionary Biology 18, no. 5 (2005): 1368-1373.
  7280. .. [7] Zaykin, Dmitri V. "Optimally weighted Z-test is a powerful method
  7281. for combining probabilities in meta-analysis." Journal of
  7282. Evolutionary Biology 24, no. 8 (2011): 1836-1841.
  7283. .. [8] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method
  7284. """
  7285. pvalues = np.asarray(pvalues)
  7286. if pvalues.ndim != 1:
  7287. raise ValueError("pvalues is not 1-D")
  7288. if method == 'fisher':
  7289. statistic = -2 * np.sum(np.log(pvalues))
  7290. pval = distributions.chi2.sf(statistic, 2 * len(pvalues))
  7291. elif method == 'pearson':
  7292. statistic = 2 * np.sum(np.log1p(-pvalues))
  7293. pval = distributions.chi2.cdf(-statistic, 2 * len(pvalues))
  7294. elif method == 'mudholkar_george':
  7295. normalizing_factor = np.sqrt(3/len(pvalues))/np.pi
  7296. statistic = -np.sum(np.log(pvalues)) + np.sum(np.log1p(-pvalues))
  7297. nu = 5 * len(pvalues) + 4
  7298. approx_factor = np.sqrt(nu / (nu - 2))
  7299. pval = distributions.t.sf(statistic * normalizing_factor
  7300. * approx_factor, nu)
  7301. elif method == 'tippett':
  7302. statistic = np.min(pvalues)
  7303. pval = distributions.beta.cdf(statistic, 1, len(pvalues))
  7304. elif method == 'stouffer':
  7305. if weights is None:
  7306. weights = np.ones_like(pvalues)
  7307. elif len(weights) != len(pvalues):
  7308. raise ValueError("pvalues and weights must be of the same size.")
  7309. weights = np.asarray(weights)
  7310. if weights.ndim != 1:
  7311. raise ValueError("weights is not 1-D")
  7312. Zi = distributions.norm.isf(pvalues)
  7313. statistic = np.dot(weights, Zi) / np.linalg.norm(weights)
  7314. pval = distributions.norm.sf(statistic)
  7315. else:
  7316. raise ValueError(
  7317. f"Invalid method {method!r}. Valid methods are 'fisher', "
  7318. "'pearson', 'mudholkar_george', 'tippett', and 'stouffer'"
  7319. )
  7320. return SignificanceResult(statistic, pval)
  7321. #####################################
  7322. # STATISTICAL DISTANCES #
  7323. #####################################
  7324. def wasserstein_distance(u_values, v_values, u_weights=None, v_weights=None):
  7325. r"""
  7326. Compute the first Wasserstein distance between two 1D distributions.
  7327. This distance is also known as the earth mover's distance, since it can be
  7328. seen as the minimum amount of "work" required to transform :math:`u` into
  7329. :math:`v`, where "work" is measured as the amount of distribution weight
  7330. that must be moved, multiplied by the distance it has to be moved.
  7331. .. versionadded:: 1.0.0
  7332. Parameters
  7333. ----------
  7334. u_values, v_values : array_like
  7335. Values observed in the (empirical) distribution.
  7336. u_weights, v_weights : array_like, optional
  7337. Weight for each value. If unspecified, each value is assigned the same
  7338. weight.
  7339. `u_weights` (resp. `v_weights`) must have the same length as
  7340. `u_values` (resp. `v_values`). If the weight sum differs from 1, it
  7341. must still be positive and finite so that the weights can be normalized
  7342. to sum to 1.
  7343. Returns
  7344. -------
  7345. distance : float
  7346. The computed distance between the distributions.
  7347. Notes
  7348. -----
  7349. The first Wasserstein distance between the distributions :math:`u` and
  7350. :math:`v` is:
  7351. .. math::
  7352. l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int_{\mathbb{R} \times
  7353. \mathbb{R}} |x-y| \mathrm{d} \pi (x, y)
  7354. where :math:`\Gamma (u, v)` is the set of (probability) distributions on
  7355. :math:`\mathbb{R} \times \mathbb{R}` whose marginals are :math:`u` and
  7356. :math:`v` on the first and second factors respectively.
  7357. If :math:`U` and :math:`V` are the respective CDFs of :math:`u` and
  7358. :math:`v`, this distance also equals to:
  7359. .. math::
  7360. l_1(u, v) = \int_{-\infty}^{+\infty} |U-V|
  7361. See [2]_ for a proof of the equivalence of both definitions.
  7362. The input distributions can be empirical, therefore coming from samples
  7363. whose values are effectively inputs of the function, or they can be seen as
  7364. generalized functions, in which case they are weighted sums of Dirac delta
  7365. functions located at the specified values.
  7366. References
  7367. ----------
  7368. .. [1] "Wasserstein metric", https://en.wikipedia.org/wiki/Wasserstein_metric
  7369. .. [2] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related
  7370. Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`.
  7371. Examples
  7372. --------
  7373. >>> from scipy.stats import wasserstein_distance
  7374. >>> wasserstein_distance([0, 1, 3], [5, 6, 8])
  7375. 5.0
  7376. >>> wasserstein_distance([0, 1], [0, 1], [3, 1], [2, 2])
  7377. 0.25
  7378. >>> wasserstein_distance([3.4, 3.9, 7.5, 7.8], [4.5, 1.4],
  7379. ... [1.4, 0.9, 3.1, 7.2], [3.2, 3.5])
  7380. 4.0781331438047861
  7381. """
  7382. return _cdf_distance(1, u_values, v_values, u_weights, v_weights)
  7383. def energy_distance(u_values, v_values, u_weights=None, v_weights=None):
  7384. r"""Compute the energy distance between two 1D distributions.
  7385. .. versionadded:: 1.0.0
  7386. Parameters
  7387. ----------
  7388. u_values, v_values : array_like
  7389. Values observed in the (empirical) distribution.
  7390. u_weights, v_weights : array_like, optional
  7391. Weight for each value. If unspecified, each value is assigned the same
  7392. weight.
  7393. `u_weights` (resp. `v_weights`) must have the same length as
  7394. `u_values` (resp. `v_values`). If the weight sum differs from 1, it
  7395. must still be positive and finite so that the weights can be normalized
  7396. to sum to 1.
  7397. Returns
  7398. -------
  7399. distance : float
  7400. The computed distance between the distributions.
  7401. Notes
  7402. -----
  7403. The energy distance between two distributions :math:`u` and :math:`v`, whose
  7404. respective CDFs are :math:`U` and :math:`V`, equals to:
  7405. .. math::
  7406. D(u, v) = \left( 2\mathbb E|X - Y| - \mathbb E|X - X'| -
  7407. \mathbb E|Y - Y'| \right)^{1/2}
  7408. where :math:`X` and :math:`X'` (resp. :math:`Y` and :math:`Y'`) are
  7409. independent random variables whose probability distribution is :math:`u`
  7410. (resp. :math:`v`).
  7411. Sometimes the square of this quantity is referred to as the "energy
  7412. distance" (e.g. in [2]_, [4]_), but as noted in [1]_ and [3]_, only the
  7413. definition above satisfies the axioms of a distance function (metric).
  7414. As shown in [2]_, for one-dimensional real-valued variables, the energy
  7415. distance is linked to the non-distribution-free version of the Cramér-von
  7416. Mises distance:
  7417. .. math::
  7418. D(u, v) = \sqrt{2} l_2(u, v) = \left( 2 \int_{-\infty}^{+\infty} (U-V)^2
  7419. \right)^{1/2}
  7420. Note that the common Cramér-von Mises criterion uses the distribution-free
  7421. version of the distance. See [2]_ (section 2), for more details about both
  7422. versions of the distance.
  7423. The input distributions can be empirical, therefore coming from samples
  7424. whose values are effectively inputs of the function, or they can be seen as
  7425. generalized functions, in which case they are weighted sums of Dirac delta
  7426. functions located at the specified values.
  7427. References
  7428. ----------
  7429. .. [1] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews:
  7430. Computational Statistics, 8(1):27-38 (2015).
  7431. .. [2] Szekely "E-statistics: The energy of statistical samples." Bowling
  7432. Green State University, Department of Mathematics and Statistics,
  7433. Technical Report 02-16 (2002).
  7434. .. [3] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance
  7435. .. [4] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
  7436. Munos "The Cramer Distance as a Solution to Biased Wasserstein
  7437. Gradients" (2017). :arXiv:`1705.10743`.
  7438. Examples
  7439. --------
  7440. >>> from scipy.stats import energy_distance
  7441. >>> energy_distance([0], [2])
  7442. 2.0000000000000004
  7443. >>> energy_distance([0, 8], [0, 8], [3, 1], [2, 2])
  7444. 1.0000000000000002
  7445. >>> energy_distance([0.7, 7.4, 2.4, 6.8], [1.4, 8. ],
  7446. ... [2.1, 4.2, 7.4, 8. ], [7.6, 8.8])
  7447. 0.88003340976158217
  7448. """
  7449. return np.sqrt(2) * _cdf_distance(2, u_values, v_values,
  7450. u_weights, v_weights)
  7451. def _cdf_distance(p, u_values, v_values, u_weights=None, v_weights=None):
  7452. r"""
  7453. Compute, between two one-dimensional distributions :math:`u` and
  7454. :math:`v`, whose respective CDFs are :math:`U` and :math:`V`, the
  7455. statistical distance that is defined as:
  7456. .. math::
  7457. l_p(u, v) = \left( \int_{-\infty}^{+\infty} |U-V|^p \right)^{1/p}
  7458. p is a positive parameter; p = 1 gives the Wasserstein distance, p = 2
  7459. gives the energy distance.
  7460. Parameters
  7461. ----------
  7462. u_values, v_values : array_like
  7463. Values observed in the (empirical) distribution.
  7464. u_weights, v_weights : array_like, optional
  7465. Weight for each value. If unspecified, each value is assigned the same
  7466. weight.
  7467. `u_weights` (resp. `v_weights`) must have the same length as
  7468. `u_values` (resp. `v_values`). If the weight sum differs from 1, it
  7469. must still be positive and finite so that the weights can be normalized
  7470. to sum to 1.
  7471. Returns
  7472. -------
  7473. distance : float
  7474. The computed distance between the distributions.
  7475. Notes
  7476. -----
  7477. The input distributions can be empirical, therefore coming from samples
  7478. whose values are effectively inputs of the function, or they can be seen as
  7479. generalized functions, in which case they are weighted sums of Dirac delta
  7480. functions located at the specified values.
  7481. References
  7482. ----------
  7483. .. [1] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
  7484. Munos "The Cramer Distance as a Solution to Biased Wasserstein
  7485. Gradients" (2017). :arXiv:`1705.10743`.
  7486. """
  7487. u_values, u_weights = _validate_distribution(u_values, u_weights)
  7488. v_values, v_weights = _validate_distribution(v_values, v_weights)
  7489. u_sorter = np.argsort(u_values)
  7490. v_sorter = np.argsort(v_values)
  7491. all_values = np.concatenate((u_values, v_values))
  7492. all_values.sort(kind='mergesort')
  7493. # Compute the differences between pairs of successive values of u and v.
  7494. deltas = np.diff(all_values)
  7495. # Get the respective positions of the values of u and v among the values of
  7496. # both distributions.
  7497. u_cdf_indices = u_values[u_sorter].searchsorted(all_values[:-1], 'right')
  7498. v_cdf_indices = v_values[v_sorter].searchsorted(all_values[:-1], 'right')
  7499. # Calculate the CDFs of u and v using their weights, if specified.
  7500. if u_weights is None:
  7501. u_cdf = u_cdf_indices / u_values.size
  7502. else:
  7503. u_sorted_cumweights = np.concatenate(([0],
  7504. np.cumsum(u_weights[u_sorter])))
  7505. u_cdf = u_sorted_cumweights[u_cdf_indices] / u_sorted_cumweights[-1]
  7506. if v_weights is None:
  7507. v_cdf = v_cdf_indices / v_values.size
  7508. else:
  7509. v_sorted_cumweights = np.concatenate(([0],
  7510. np.cumsum(v_weights[v_sorter])))
  7511. v_cdf = v_sorted_cumweights[v_cdf_indices] / v_sorted_cumweights[-1]
  7512. # Compute the value of the integral based on the CDFs.
  7513. # If p = 1 or p = 2, we avoid using np.power, which introduces an overhead
  7514. # of about 15%.
  7515. if p == 1:
  7516. return np.sum(np.multiply(np.abs(u_cdf - v_cdf), deltas))
  7517. if p == 2:
  7518. return np.sqrt(np.sum(np.multiply(np.square(u_cdf - v_cdf), deltas)))
  7519. return np.power(np.sum(np.multiply(np.power(np.abs(u_cdf - v_cdf), p),
  7520. deltas)), 1/p)
  7521. def _validate_distribution(values, weights):
  7522. """
  7523. Validate the values and weights from a distribution input of `cdf_distance`
  7524. and return them as ndarray objects.
  7525. Parameters
  7526. ----------
  7527. values : array_like
  7528. Values observed in the (empirical) distribution.
  7529. weights : array_like
  7530. Weight for each value.
  7531. Returns
  7532. -------
  7533. values : ndarray
  7534. Values as ndarray.
  7535. weights : ndarray
  7536. Weights as ndarray.
  7537. """
  7538. # Validate the value array.
  7539. values = np.asarray(values, dtype=float)
  7540. if len(values) == 0:
  7541. raise ValueError("Distribution can't be empty.")
  7542. # Validate the weight array, if specified.
  7543. if weights is not None:
  7544. weights = np.asarray(weights, dtype=float)
  7545. if len(weights) != len(values):
  7546. raise ValueError('Value and weight array-likes for the same '
  7547. 'empirical distribution must be of the same size.')
  7548. if np.any(weights < 0):
  7549. raise ValueError('All weights must be non-negative.')
  7550. if not 0 < np.sum(weights) < np.inf:
  7551. raise ValueError('Weight array-like sum must be positive and '
  7552. 'finite. Set as None for an equal distribution of '
  7553. 'weight.')
  7554. return values, weights
  7555. return values, None
  7556. #####################################
  7557. # SUPPORT FUNCTIONS #
  7558. #####################################
  7559. RepeatedResults = namedtuple('RepeatedResults', ('values', 'counts'))
  7560. def find_repeats(arr):
  7561. """Find repeats and repeat counts.
  7562. Parameters
  7563. ----------
  7564. arr : array_like
  7565. Input array. This is cast to float64.
  7566. Returns
  7567. -------
  7568. values : ndarray
  7569. The unique values from the (flattened) input that are repeated.
  7570. counts : ndarray
  7571. Number of times the corresponding 'value' is repeated.
  7572. Notes
  7573. -----
  7574. In numpy >= 1.9 `numpy.unique` provides similar functionality. The main
  7575. difference is that `find_repeats` only returns repeated values.
  7576. Examples
  7577. --------
  7578. >>> from scipy import stats
  7579. >>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5])
  7580. RepeatedResults(values=array([2.]), counts=array([4]))
  7581. >>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
  7582. RepeatedResults(values=array([4., 5.]), counts=array([2, 2]))
  7583. """
  7584. # Note: always copies.
  7585. return RepeatedResults(*_find_repeats(np.array(arr, dtype=np.float64)))
  7586. def _sum_of_squares(a, axis=0):
  7587. """Square each element of the input array, and return the sum(s) of that.
  7588. Parameters
  7589. ----------
  7590. a : array_like
  7591. Input array.
  7592. axis : int or None, optional
  7593. Axis along which to calculate. Default is 0. If None, compute over
  7594. the whole array `a`.
  7595. Returns
  7596. -------
  7597. sum_of_squares : ndarray
  7598. The sum along the given axis for (a**2).
  7599. See Also
  7600. --------
  7601. _square_of_sums : The square(s) of the sum(s) (the opposite of
  7602. `_sum_of_squares`).
  7603. """
  7604. a, axis = _chk_asarray(a, axis)
  7605. return np.sum(a*a, axis)
  7606. def _square_of_sums(a, axis=0):
  7607. """Sum elements of the input array, and return the square(s) of that sum.
  7608. Parameters
  7609. ----------
  7610. a : array_like
  7611. Input array.
  7612. axis : int or None, optional
  7613. Axis along which to calculate. Default is 0. If None, compute over
  7614. the whole array `a`.
  7615. Returns
  7616. -------
  7617. square_of_sums : float or ndarray
  7618. The square of the sum over `axis`.
  7619. See Also
  7620. --------
  7621. _sum_of_squares : The sum of squares (the opposite of `square_of_sums`).
  7622. """
  7623. a, axis = _chk_asarray(a, axis)
  7624. s = np.sum(a, axis)
  7625. if not np.isscalar(s):
  7626. return s.astype(float) * s
  7627. else:
  7628. return float(s) * s
  7629. def rankdata(a, method='average', *, axis=None, nan_policy='propagate'):
  7630. """Assign ranks to data, dealing with ties appropriately.
  7631. By default (``axis=None``), the data array is first flattened, and a flat
  7632. array of ranks is returned. Separately reshape the rank array to the
  7633. shape of the data array if desired (see Examples).
  7634. Ranks begin at 1. The `method` argument controls how ranks are assigned
  7635. to equal values. See [1]_ for further discussion of ranking methods.
  7636. Parameters
  7637. ----------
  7638. a : array_like
  7639. The array of values to be ranked.
  7640. method : {'average', 'min', 'max', 'dense', 'ordinal'}, optional
  7641. The method used to assign ranks to tied elements.
  7642. The following methods are available (default is 'average'):
  7643. * 'average': The average of the ranks that would have been assigned to
  7644. all the tied values is assigned to each value.
  7645. * 'min': The minimum of the ranks that would have been assigned to all
  7646. the tied values is assigned to each value. (This is also
  7647. referred to as "competition" ranking.)
  7648. * 'max': The maximum of the ranks that would have been assigned to all
  7649. the tied values is assigned to each value.
  7650. * 'dense': Like 'min', but the rank of the next highest element is
  7651. assigned the rank immediately after those assigned to the tied
  7652. elements.
  7653. * 'ordinal': All values are given a distinct rank, corresponding to
  7654. the order that the values occur in `a`.
  7655. axis : {None, int}, optional
  7656. Axis along which to perform the ranking. If ``None``, the data array
  7657. is first flattened.
  7658. nan_policy : {'propagate', 'omit', 'raise'}, optional
  7659. Defines how to handle when input contains nan.
  7660. The following options are available (default is 'propagate'):
  7661. * 'propagate': propagates nans through the rank calculation
  7662. * 'omit': performs the calculations ignoring nan values
  7663. * 'raise': raises an error
  7664. .. note::
  7665. When `nan_policy` is 'propagate', the output is an array of *all*
  7666. nans because ranks relative to nans in the input are undefined.
  7667. When `nan_policy` is 'omit', nans in `a` are ignored when ranking
  7668. the other values, and the corresponding locations of the output
  7669. are nan.
  7670. .. versionadded:: 1.10
  7671. Returns
  7672. -------
  7673. ranks : ndarray
  7674. An array of size equal to the size of `a`, containing rank
  7675. scores.
  7676. References
  7677. ----------
  7678. .. [1] "Ranking", https://en.wikipedia.org/wiki/Ranking
  7679. Examples
  7680. --------
  7681. >>> import numpy as np
  7682. >>> from scipy.stats import rankdata
  7683. >>> rankdata([0, 2, 3, 2])
  7684. array([ 1. , 2.5, 4. , 2.5])
  7685. >>> rankdata([0, 2, 3, 2], method='min')
  7686. array([ 1, 2, 4, 2])
  7687. >>> rankdata([0, 2, 3, 2], method='max')
  7688. array([ 1, 3, 4, 3])
  7689. >>> rankdata([0, 2, 3, 2], method='dense')
  7690. array([ 1, 2, 3, 2])
  7691. >>> rankdata([0, 2, 3, 2], method='ordinal')
  7692. array([ 1, 2, 4, 3])
  7693. >>> rankdata([[0, 2], [3, 2]]).reshape(2,2)
  7694. array([[1. , 2.5],
  7695. [4. , 2.5]])
  7696. >>> rankdata([[0, 2, 2], [3, 2, 5]], axis=1)
  7697. array([[1. , 2.5, 2.5],
  7698. [2. , 1. , 3. ]])
  7699. >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="propagate")
  7700. array([nan, nan, nan, nan, nan, nan])
  7701. >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="omit")
  7702. array([ 2., 3., 4., nan, 1., nan])
  7703. """
  7704. if method not in ('average', 'min', 'max', 'dense', 'ordinal'):
  7705. raise ValueError('unknown method "{0}"'.format(method))
  7706. a = np.asarray(a)
  7707. if axis is not None:
  7708. if a.size == 0:
  7709. # The return values of `normalize_axis_index` are ignored. The
  7710. # call validates `axis`, even though we won't use it.
  7711. # use scipy._lib._util._normalize_axis_index when available
  7712. np.core.multiarray.normalize_axis_index(axis, a.ndim)
  7713. dt = np.float64 if method == 'average' else np.int_
  7714. return np.empty(a.shape, dtype=dt)
  7715. return np.apply_along_axis(rankdata, axis, a, method,
  7716. nan_policy=nan_policy)
  7717. arr = np.ravel(a)
  7718. contains_nan, nan_policy = _contains_nan(arr, nan_policy)
  7719. nan_indexes = None
  7720. if contains_nan:
  7721. if nan_policy == 'omit':
  7722. nan_indexes = np.isnan(arr)
  7723. if nan_policy == 'propagate':
  7724. return np.full_like(arr, np.nan)
  7725. algo = 'mergesort' if method == 'ordinal' else 'quicksort'
  7726. sorter = np.argsort(arr, kind=algo)
  7727. inv = np.empty(sorter.size, dtype=np.intp)
  7728. inv[sorter] = np.arange(sorter.size, dtype=np.intp)
  7729. if method == 'ordinal':
  7730. result = inv + 1
  7731. arr = arr[sorter]
  7732. obs = np.r_[True, arr[1:] != arr[:-1]]
  7733. dense = obs.cumsum()[inv]
  7734. if method == 'dense':
  7735. result = dense
  7736. # cumulative counts of each unique value
  7737. count = np.r_[np.nonzero(obs)[0], len(obs)]
  7738. if method == 'max':
  7739. result = count[dense]
  7740. if method == 'min':
  7741. result = count[dense - 1] + 1
  7742. if method == 'average':
  7743. result = .5 * (count[dense] + count[dense - 1] + 1)
  7744. if nan_indexes is not None:
  7745. result = result.astype('float64')
  7746. result[nan_indexes] = np.nan
  7747. return result
  7748. def expectile(a, alpha=0.5, *, weights=None):
  7749. r"""Compute the expectile at the specified level.
  7750. Expectiles are a generalization of the expectation in the same way as
  7751. quantiles are a generalization of the median. The expectile at level
  7752. `alpha = 0.5` is the mean (average). See Notes for more details.
  7753. Parameters
  7754. ----------
  7755. a : array_like
  7756. Array containing numbers whose expectile is desired.
  7757. alpha : float, default: 0.5
  7758. The level of the expectile; e.g., `alpha=0.5` gives the mean.
  7759. weights : array_like, optional
  7760. An array of weights associated with the values in `a`.
  7761. The `weights` must be broadcastable to the same shape as `a`.
  7762. Default is None, which gives each value a weight of 1.0.
  7763. An integer valued weight element acts like repeating the corresponding
  7764. observation in `a` that many times. See Notes for more details.
  7765. Returns
  7766. -------
  7767. expectile : ndarray
  7768. The empirical expectile at level `alpha`.
  7769. See Also
  7770. --------
  7771. numpy.mean : Arithmetic average
  7772. numpy.quantile : Quantile
  7773. Notes
  7774. -----
  7775. In general, the expectile at level :math:`\alpha` of a random variable
  7776. :math:`X` with cumulative distribution function (CDF) :math:`F` is given
  7777. by the unique solution :math:`t` of:
  7778. .. math::
  7779. \alpha E((X - t)_+) = (1 - \alpha) E((t - X)_+) \,.
  7780. Here, :math:`(x)_+ = \max(0, x)` is the positive part of :math:`x`.
  7781. This equation can be equivalently written as:
  7782. .. math::
  7783. \alpha \int_t^\infty (x - t)\mathrm{d}F(x)
  7784. = (1 - \alpha) \int_{-\infty}^t (t - x)\mathrm{d}F(x) \,.
  7785. The empirical expectile at level :math:`\alpha` (`alpha`) of a sample
  7786. :math:`a_i` (the array `a`) is defined by plugging in the empirical CDF of
  7787. `a`. Given sample or case weights :math:`w` (the array `weights`), it
  7788. reads :math:`F_a(x) = \frac{1}{\sum_i a_i} \sum_i w_i 1_{a_i \leq x}`
  7789. with indicator function :math:`1_{A}`. This leads to the definition of the
  7790. empirical expectile at level `alpha` as the unique solution :math:`t` of:
  7791. .. math::
  7792. \alpha \sum_{i=1}^n w_i (a_i - t)_+ =
  7793. (1 - \alpha) \sum_{i=1}^n w_i (t - a_i)_+ \,.
  7794. For :math:`\alpha=0.5`, this simplifies to the weighted average.
  7795. Furthermore, the larger :math:`\alpha`, the larger the value of the
  7796. expectile.
  7797. As a final remark, the expectile at level :math:`\alpha` can also be
  7798. written as a minimization problem. One often used choice is
  7799. .. math::
  7800. \operatorname{argmin}_t
  7801. E(\lvert 1_{t\geq X} - \alpha\rvert(t - X)^2) \,.
  7802. References
  7803. ----------
  7804. .. [1] W. K. Newey and J. L. Powell (1987), "Asymmetric Least Squares
  7805. Estimation and Testing," Econometrica, 55, 819-847.
  7806. .. [2] T. Gneiting (2009). "Making and Evaluating Point Forecasts,"
  7807. Journal of the American Statistical Association, 106, 746 - 762.
  7808. :doi:`10.48550/arXiv.0912.0902`
  7809. Examples
  7810. --------
  7811. >>> import numpy as np
  7812. >>> from scipy.stats import expectile
  7813. >>> a = [1, 4, 2, -1]
  7814. >>> expectile(a, alpha=0.5) == np.mean(a)
  7815. True
  7816. >>> expectile(a, alpha=0.2)
  7817. 0.42857142857142855
  7818. >>> expectile(a, alpha=0.8)
  7819. 2.5714285714285716
  7820. >>> weights = [1, 3, 1, 1]
  7821. """
  7822. if alpha < 0 or alpha > 1:
  7823. raise ValueError(
  7824. "The expectile level alpha must be in the range [0, 1]."
  7825. )
  7826. a = np.asarray(a)
  7827. if weights is not None:
  7828. weights = np.broadcast_to(weights, a.shape)
  7829. # This is the empirical equivalent of Eq. (13) with identification
  7830. # function from Table 9 (omitting a factor of 2) in [2] (their y is our
  7831. # data a, their x is our t)
  7832. def first_order(t):
  7833. return np.average(np.abs((a <= t) - alpha) * (t - a), weights=weights)
  7834. if alpha >= 0.5:
  7835. x0 = np.average(a, weights=weights)
  7836. x1 = np.amax(a)
  7837. else:
  7838. x1 = np.average(a, weights=weights)
  7839. x0 = np.amin(a)
  7840. if x0 == x1:
  7841. # a has a single unique element
  7842. return x0
  7843. # Note that the expectile is the unique solution, so no worries about
  7844. # finding a wrong root.
  7845. res = root_scalar(first_order, x0=x0, x1=x1)
  7846. return res.root