_morestats.py 180 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862
  1. import itertools
  2. import math
  3. import warnings
  4. import threading
  5. from collections import namedtuple
  6. import numpy as np
  7. from numpy import (isscalar, log, around, zeros,
  8. arange, sort, amin, amax, sqrt, array,
  9. pi, exp, ravel, count_nonzero)
  10. from scipy import optimize, special, interpolate, stats
  11. from scipy._lib._bunch import _make_tuple_bunch
  12. from scipy._lib._util import _rename_parameter, _contains_nan, _get_nan
  13. from scipy._lib.deprecation import _NoValue
  14. import scipy._lib.array_api_extra as xpx
  15. from scipy._lib._array_api import (
  16. array_namespace,
  17. is_marray,
  18. xp_capabilities,
  19. is_numpy,
  20. is_jax,
  21. is_dask,
  22. xp_size,
  23. xp_vector_norm,
  24. xp_promote,
  25. xp_result_type,
  26. xp_device,
  27. xp_ravel,
  28. _length_nonmasked,
  29. )
  30. from ._ansari_swilk_statistics import gscale, swilk
  31. from . import _stats_py, _wilcoxon
  32. from ._fit import FitResult
  33. from ._stats_py import (_get_pvalue, SignificanceResult, # noqa:F401
  34. _SimpleNormal, _SimpleChi2, _SimpleF)
  35. from .contingency import chi2_contingency
  36. from . import distributions
  37. from ._distn_infrastructure import rv_generic
  38. from ._axis_nan_policy import _axis_nan_policy_factory, _broadcast_arrays
  39. __all__ = ['mvsdist',
  40. 'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot',
  41. 'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot',
  42. 'shapiro', 'anderson', 'ansari', 'bartlett', 'levene',
  43. 'fligner', 'mood', 'wilcoxon', 'median_test',
  44. 'circmean', 'circvar', 'circstd', 'anderson_ksamp',
  45. 'yeojohnson_llf', 'yeojohnson', 'yeojohnson_normmax',
  46. 'yeojohnson_normplot', 'directional_stats',
  47. 'false_discovery_control'
  48. ]
  49. Mean = namedtuple('Mean', ('statistic', 'minmax'))
  50. Variance = namedtuple('Variance', ('statistic', 'minmax'))
  51. Std_dev = namedtuple('Std_dev', ('statistic', 'minmax'))
  52. @xp_capabilities(np_only=True)
  53. def bayes_mvs(data, alpha=0.90):
  54. r"""
  55. Bayesian confidence intervals for the mean, var, and std.
  56. Parameters
  57. ----------
  58. data : array_like
  59. Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`.
  60. Requires 2 or more data points.
  61. alpha : float, optional
  62. Probability that the returned confidence interval contains
  63. the true parameter.
  64. Returns
  65. -------
  66. mean_cntr, var_cntr, std_cntr : tuple
  67. The three results are for the mean, variance and standard deviation,
  68. respectively. Each result is a tuple of the form::
  69. (center, (lower, upper))
  70. with ``center`` the mean of the conditional pdf of the value given the
  71. data, and ``(lower, upper)`` a confidence interval, centered on the
  72. median, containing the estimate to a probability ``alpha``.
  73. See Also
  74. --------
  75. mvsdist
  76. Notes
  77. -----
  78. Each tuple of mean, variance, and standard deviation estimates represent
  79. the (center, (lower, upper)) with center the mean of the conditional pdf
  80. of the value given the data and (lower, upper) is a confidence interval
  81. centered on the median, containing the estimate to a probability
  82. ``alpha``.
  83. Converts data to 1-D and assumes all data has the same mean and variance.
  84. Uses Jeffrey's prior for variance and std.
  85. Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))``
  86. References
  87. ----------
  88. T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
  89. standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278,
  90. 2006.
  91. Examples
  92. --------
  93. First a basic example to demonstrate the outputs:
  94. >>> from scipy import stats
  95. >>> data = [6, 9, 12, 7, 8, 8, 13]
  96. >>> mean, var, std = stats.bayes_mvs(data)
  97. >>> mean
  98. Mean(statistic=9.0, minmax=(7.103650222612533, 10.896349777387467))
  99. >>> var
  100. Variance(statistic=10.0, minmax=(3.176724206, 24.45910382))
  101. >>> std
  102. Std_dev(statistic=2.9724954732045084,
  103. minmax=(1.7823367265645143, 4.945614605014631))
  104. Now we generate some normally distributed random data, and get estimates of
  105. mean and standard deviation with 95% confidence intervals for those
  106. estimates:
  107. >>> n_samples = 100000
  108. >>> data = stats.norm.rvs(size=n_samples)
  109. >>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95)
  110. >>> import matplotlib.pyplot as plt
  111. >>> fig = plt.figure()
  112. >>> ax = fig.add_subplot(111)
  113. >>> ax.hist(data, bins=100, density=True, label='Histogram of data')
  114. >>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean')
  115. >>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r',
  116. ... alpha=0.2, label=r'Estimated mean (95% limits)')
  117. >>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale')
  118. >>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2,
  119. ... label=r'Estimated scale (95% limits)')
  120. >>> ax.legend(fontsize=10)
  121. >>> ax.set_xlim([-4, 4])
  122. >>> ax.set_ylim([0, 0.5])
  123. >>> plt.show()
  124. """
  125. m, v, s = mvsdist(data)
  126. if alpha >= 1 or alpha <= 0:
  127. raise ValueError(f"0 < alpha < 1 is required, but {alpha=} was given.")
  128. m_res = Mean(m.mean(), m.interval(alpha))
  129. v_res = Variance(v.mean(), v.interval(alpha))
  130. s_res = Std_dev(s.mean(), s.interval(alpha))
  131. return m_res, v_res, s_res
  132. @xp_capabilities(np_only=True)
  133. def mvsdist(data):
  134. """
  135. 'Frozen' distributions for mean, variance, and standard deviation of data.
  136. Parameters
  137. ----------
  138. data : array_like
  139. Input array. Converted to 1-D using ravel.
  140. Requires 2 or more data-points.
  141. Returns
  142. -------
  143. mdist : "frozen" distribution object
  144. Distribution object representing the mean of the data.
  145. vdist : "frozen" distribution object
  146. Distribution object representing the variance of the data.
  147. sdist : "frozen" distribution object
  148. Distribution object representing the standard deviation of the data.
  149. See Also
  150. --------
  151. bayes_mvs
  152. Notes
  153. -----
  154. The return values from ``bayes_mvs(data)`` is equivalent to
  155. ``tuple((x.mean(), x.interval(0.90)) for x in mvsdist(data))``.
  156. In other words, calling ``<dist>.mean()`` and ``<dist>.interval(0.90)``
  157. on the three distribution objects returned from this function will give
  158. the same results that are returned from `bayes_mvs`.
  159. References
  160. ----------
  161. T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
  162. standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278,
  163. 2006.
  164. Examples
  165. --------
  166. >>> from scipy import stats
  167. >>> data = [6, 9, 12, 7, 8, 8, 13]
  168. >>> mean, var, std = stats.mvsdist(data)
  169. We now have frozen distribution objects "mean", "var" and "std" that we can
  170. examine:
  171. >>> mean.mean()
  172. 9.0
  173. >>> mean.interval(0.95)
  174. (6.6120585482655692, 11.387941451734431)
  175. >>> mean.std()
  176. 1.1952286093343936
  177. """
  178. x = ravel(data)
  179. n = len(x)
  180. if n < 2:
  181. raise ValueError("Need at least 2 data-points.")
  182. xbar = x.mean()
  183. C = x.var()
  184. if n > 1000: # gaussian approximations for large n
  185. mdist = distributions.norm(loc=xbar, scale=math.sqrt(C / n))
  186. sdist = distributions.norm(loc=math.sqrt(C), scale=math.sqrt(C / (2. * n)))
  187. vdist = distributions.norm(loc=C, scale=math.sqrt(2.0 / n) * C)
  188. else:
  189. nm1 = n - 1
  190. fac = n * C / 2.
  191. val = nm1 / 2.
  192. mdist = distributions.t(nm1, loc=xbar, scale=math.sqrt(C / nm1))
  193. sdist = distributions.gengamma(val, -2, scale=math.sqrt(fac))
  194. vdist = distributions.invgamma(val, scale=fac)
  195. return mdist, vdist, sdist
  196. @xp_capabilities()
  197. @_axis_nan_policy_factory(
  198. lambda x: x, result_to_tuple=lambda x, _: (x,), n_outputs=1, default_axis=None
  199. )
  200. def kstat(data, n=2, *, axis=None):
  201. r"""
  202. Return the `n` th k-statistic ( ``1<=n<=4`` so far).
  203. The `n` th k-statistic ``k_n`` is the unique symmetric unbiased estimator of the
  204. `n` th cumulant :math:`\kappa_n` [1]_ [2]_.
  205. Parameters
  206. ----------
  207. data : array_like
  208. Input array.
  209. n : int, {1, 2, 3, 4}, optional
  210. Default is equal to 2.
  211. axis : int or None, default: None
  212. If an int, the axis of the input along which to compute the statistic.
  213. The statistic of each axis-slice (e.g. row) of the input will appear
  214. in a corresponding element of the output. If ``None``, the input will
  215. be raveled before computing the statistic.
  216. Returns
  217. -------
  218. kstat : float
  219. The `n` th k-statistic.
  220. See Also
  221. --------
  222. kstatvar : Returns an unbiased estimator of the variance of the k-statistic
  223. moment : Returns the n-th central moment about the mean for a sample.
  224. Notes
  225. -----
  226. For a sample size :math:`n`, the first few k-statistics are given by
  227. .. math::
  228. k_1 &= \frac{S_1}{n}, \\
  229. k_2 &= \frac{nS_2 - S_1^2}{n(n-1)}, \\
  230. k_3 &= \frac{2S_1^3 - 3nS_1S_2 + n^2S_3}{n(n-1)(n-2)}, \\
  231. k_4 &= \frac{-6S_1^4 + 12nS_1^2S_2 - 3n(n-1)S_2^2 - 4n(n+1)S_1S_3
  232. + n^2(n+1)S_4}{n (n-1)(n-2)(n-3)},
  233. where
  234. .. math::
  235. S_r \equiv \sum_{i=1}^n X_i^r,
  236. and :math:`X_i` is the :math:`i` th data point.
  237. References
  238. ----------
  239. .. [1] http://mathworld.wolfram.com/k-Statistic.html
  240. .. [2] http://mathworld.wolfram.com/Cumulant.html
  241. Examples
  242. --------
  243. >>> from scipy import stats
  244. >>> from numpy.random import default_rng
  245. >>> rng = default_rng()
  246. As sample size increases, `n`-th moment and `n`-th k-statistic converge to the
  247. same number (although they aren't identical). In the case of the normal
  248. distribution, they converge to zero.
  249. >>> for i in range(2,8):
  250. ... x = rng.normal(size=10**i)
  251. ... m, k = stats.moment(x, 3), stats.kstat(x, 3)
  252. ... print(f"{i=}: {m=:.3g}, {k=:.3g}, {(m-k)=:.3g}")
  253. i=2: m=-0.631, k=-0.651, (m-k)=0.0194 # random
  254. i=3: m=0.0282, k=0.0283, (m-k)=-8.49e-05
  255. i=4: m=-0.0454, k=-0.0454, (m-k)=1.36e-05
  256. i=6: m=7.53e-05, k=7.53e-05, (m-k)=-2.26e-09
  257. i=7: m=0.00166, k=0.00166, (m-k)=-4.99e-09
  258. i=8: m=-2.88e-06 k=-2.88e-06, (m-k)=8.63e-13
  259. """
  260. xp = array_namespace(data)
  261. data = xp.asarray(data)
  262. if n > 4 or n < 1:
  263. raise ValueError("k-statistics only supported for 1<=n<=4")
  264. n = int(n)
  265. if axis is None:
  266. data = xp.reshape(data, (-1,))
  267. axis = 0
  268. N = _length_nonmasked(data, axis, xp=xp)
  269. S = [None] + [xp.sum(data**k, axis=axis) for k in range(1, n + 1)]
  270. if n == 1:
  271. return S[1] * 1.0/N
  272. elif n == 2:
  273. return (N*S[2] - S[1]**2.0) / (N*(N - 1.0))
  274. elif n == 3:
  275. return (2*S[1]**3 - 3*N*S[1]*S[2] + N*N*S[3]) / (N*(N - 1.0)*(N - 2.0))
  276. elif n == 4:
  277. return ((-6*S[1]**4 + 12*N*S[1]**2 * S[2] - 3*N*(N-1.0)*S[2]**2 -
  278. 4*N*(N+1)*S[1]*S[3] + N*N*(N+1)*S[4]) /
  279. (N*(N-1.0)*(N-2.0)*(N-3.0)))
  280. else:
  281. raise ValueError("Should not be here.")
  282. @xp_capabilities()
  283. @_axis_nan_policy_factory(
  284. lambda x: x, result_to_tuple=lambda x, _: (x,), n_outputs=1, default_axis=None
  285. )
  286. def kstatvar(data, n=2, *, axis=None):
  287. r"""Return an unbiased estimator of the variance of the k-statistic.
  288. See `kstat` and [1]_ for more details about the k-statistic.
  289. Parameters
  290. ----------
  291. data : array_like
  292. Input array.
  293. n : int, {1, 2}, optional
  294. Default is equal to 2.
  295. axis : int or None, default: None
  296. If an int, the axis of the input along which to compute the statistic.
  297. The statistic of each axis-slice (e.g. row) of the input will appear
  298. in a corresponding element of the output. If ``None``, the input will
  299. be raveled before computing the statistic.
  300. Returns
  301. -------
  302. kstatvar : float
  303. The `n` th k-statistic variance.
  304. See Also
  305. --------
  306. kstat : Returns the n-th k-statistic.
  307. moment : Returns the n-th central moment about the mean for a sample.
  308. Notes
  309. -----
  310. Unbiased estimators of the variances of the first two k-statistics are given by
  311. .. math::
  312. \mathrm{var}(k_1) &= \frac{k_2}{n}, \\
  313. \mathrm{var}(k_2) &= \frac{2k_2^2n + (n-1)k_4}{n(n + 1)}.
  314. References
  315. ----------
  316. .. [1] http://mathworld.wolfram.com/k-Statistic.html
  317. """ # noqa: E501
  318. xp = array_namespace(data)
  319. data = xp.asarray(data)
  320. if axis is None:
  321. data = xp.reshape(data, (-1,))
  322. axis = 0
  323. N = _length_nonmasked(data, axis, xp=xp)
  324. if n == 1:
  325. return kstat(data, n=2, axis=axis, _no_deco=True) * 1.0/N
  326. elif n == 2:
  327. k2 = kstat(data, n=2, axis=axis, _no_deco=True)
  328. k4 = kstat(data, n=4, axis=axis, _no_deco=True)
  329. return (2*N*k2**2 + (N-1)*k4) / (N*(N+1))
  330. else:
  331. raise ValueError("Only n=1 or n=2 supported.")
  332. def _calc_uniform_order_statistic_medians(n):
  333. """Approximations of uniform order statistic medians.
  334. Parameters
  335. ----------
  336. n : int
  337. Sample size.
  338. Returns
  339. -------
  340. v : 1d float array
  341. Approximations of the order statistic medians.
  342. References
  343. ----------
  344. .. [1] James J. Filliben, "The Probability Plot Correlation Coefficient
  345. Test for Normality", Technometrics, Vol. 17, pp. 111-117, 1975.
  346. Examples
  347. --------
  348. Order statistics of the uniform distribution on the unit interval
  349. are marginally distributed according to beta distributions.
  350. The expectations of these order statistic are evenly spaced across
  351. the interval, but the distributions are skewed in a way that
  352. pushes the medians slightly towards the endpoints of the unit interval:
  353. >>> import numpy as np
  354. >>> n = 4
  355. >>> k = np.arange(1, n+1)
  356. >>> from scipy.stats import beta
  357. >>> a = k
  358. >>> b = n-k+1
  359. >>> beta.mean(a, b)
  360. array([0.2, 0.4, 0.6, 0.8])
  361. >>> beta.median(a, b)
  362. array([0.15910358, 0.38572757, 0.61427243, 0.84089642])
  363. The Filliben approximation uses the exact medians of the smallest
  364. and greatest order statistics, and the remaining medians are approximated
  365. by points spread evenly across a sub-interval of the unit interval:
  366. >>> from scipy.stats._morestats import _calc_uniform_order_statistic_medians
  367. >>> _calc_uniform_order_statistic_medians(n)
  368. array([0.15910358, 0.38545246, 0.61454754, 0.84089642])
  369. This plot shows the skewed distributions of the order statistics
  370. of a sample of size four from a uniform distribution on the unit interval:
  371. >>> import matplotlib.pyplot as plt
  372. >>> x = np.linspace(0.0, 1.0, num=50, endpoint=True)
  373. >>> pdfs = [beta.pdf(x, a[i], b[i]) for i in range(n)]
  374. >>> plt.figure()
  375. >>> plt.plot(x, pdfs[0], x, pdfs[1], x, pdfs[2], x, pdfs[3])
  376. """
  377. v = np.empty(n, dtype=np.float64)
  378. v[-1] = 0.5**(1.0 / n)
  379. v[0] = 1 - v[-1]
  380. i = np.arange(2, n)
  381. v[1:-1] = (i - 0.3175) / (n + 0.365)
  382. return v
  383. def _parse_dist_kw(dist, enforce_subclass=True):
  384. """Parse `dist` keyword.
  385. Parameters
  386. ----------
  387. dist : str or stats.distributions instance.
  388. Several functions take `dist` as a keyword, hence this utility
  389. function.
  390. enforce_subclass : bool, optional
  391. If True (default), `dist` needs to be a
  392. `_distn_infrastructure.rv_generic` instance.
  393. It can sometimes be useful to set this keyword to False, if a function
  394. wants to accept objects that just look somewhat like such an instance
  395. (for example, they have a ``ppf`` method).
  396. """
  397. if isinstance(dist, rv_generic):
  398. pass
  399. elif isinstance(dist, str):
  400. try:
  401. dist = getattr(distributions, dist)
  402. except AttributeError as e:
  403. raise ValueError(f"{dist} is not a valid distribution name") from e
  404. elif enforce_subclass:
  405. msg = ("`dist` should be a stats.distributions instance or a string "
  406. "with the name of such a distribution.")
  407. raise ValueError(msg)
  408. return dist
  409. def _add_axis_labels_title(plot, xlabel, ylabel, title):
  410. """Helper function to add axes labels and a title to stats plots."""
  411. try:
  412. if hasattr(plot, 'set_title'):
  413. # Matplotlib Axes instance or something that looks like it
  414. plot.set_title(title)
  415. plot.set_xlabel(xlabel)
  416. plot.set_ylabel(ylabel)
  417. else:
  418. # matplotlib.pyplot module
  419. plot.title(title)
  420. plot.xlabel(xlabel)
  421. plot.ylabel(ylabel)
  422. except Exception:
  423. # Not an MPL object or something that looks (enough) like it.
  424. # Don't crash on adding labels or title
  425. pass
  426. @xp_capabilities(np_only=True)
  427. def probplot(x, sparams=(), dist='norm', fit=True, plot=None, rvalue=False):
  428. """
  429. Calculate quantiles for a probability plot, and optionally show the plot.
  430. Generates a probability plot of sample data against the quantiles of a
  431. specified theoretical distribution (the normal distribution by default).
  432. `probplot` optionally calculates a best-fit line for the data and plots the
  433. results using Matplotlib or a given plot function.
  434. Parameters
  435. ----------
  436. x : array_like
  437. Sample/response data from which `probplot` creates the plot.
  438. sparams : tuple, optional
  439. Distribution-specific shape parameters (shape parameters plus location
  440. and scale).
  441. dist : str or stats.distributions instance, optional
  442. Distribution or distribution function name. The default is 'norm' for a
  443. normal probability plot. Objects that look enough like a
  444. stats.distributions instance (i.e. they have a ``ppf`` method) are also
  445. accepted.
  446. fit : bool, optional
  447. Fit a least-squares regression (best-fit) line to the sample data if
  448. True (default).
  449. plot : object, optional
  450. If given, plots the quantiles.
  451. If given and `fit` is True, also plots the least squares fit.
  452. `plot` is an object that has to have methods "plot" and "text".
  453. The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
  454. or a custom object with the same methods.
  455. Default is None, which means that no plot is created.
  456. rvalue : bool, optional
  457. If `plot` is provided and `fit` is True, setting `rvalue` to True
  458. includes the coefficient of determination on the plot.
  459. Default is False.
  460. Returns
  461. -------
  462. (osm, osr) : tuple of ndarrays
  463. Tuple of theoretical quantiles (osm, or order statistic medians) and
  464. ordered responses (osr). `osr` is simply sorted input `x`.
  465. For details on how `osm` is calculated see the Notes section.
  466. (slope, intercept, r) : tuple of floats, optional
  467. Tuple containing the result of the least-squares fit, if that is
  468. performed by `probplot`. `r` is the square root of the coefficient of
  469. determination. If ``fit=False`` and ``plot=None``, this tuple is not
  470. returned.
  471. Notes
  472. -----
  473. Even if `plot` is given, the figure is not shown or saved by `probplot`;
  474. ``plt.show()`` or ``plt.savefig('figname.png')`` should be used after
  475. calling `probplot`.
  476. `probplot` generates a probability plot, which should not be confused with
  477. a Q-Q or a P-P plot. Statsmodels has more extensive functionality of this
  478. type, see ``statsmodels.api.ProbPlot``.
  479. The formula used for the theoretical quantiles (horizontal axis of the
  480. probability plot) is Filliben's estimate::
  481. quantiles = dist.ppf(val), for
  482. 0.5**(1/n), for i = n
  483. val = (i - 0.3175) / (n + 0.365), for i = 2, ..., n-1
  484. 1 - 0.5**(1/n), for i = 1
  485. where ``i`` indicates the i-th ordered value and ``n`` is the total number
  486. of values.
  487. Examples
  488. --------
  489. >>> import numpy as np
  490. >>> from scipy import stats
  491. >>> import matplotlib.pyplot as plt
  492. >>> nsample = 100
  493. >>> rng = np.random.default_rng()
  494. A t distribution with small degrees of freedom:
  495. >>> ax1 = plt.subplot(221)
  496. >>> x = stats.t.rvs(3, size=nsample, random_state=rng)
  497. >>> res = stats.probplot(x, plot=plt)
  498. A t distribution with larger degrees of freedom:
  499. >>> ax2 = plt.subplot(222)
  500. >>> x = stats.t.rvs(25, size=nsample, random_state=rng)
  501. >>> res = stats.probplot(x, plot=plt)
  502. A mixture of two normal distributions with broadcasting:
  503. >>> ax3 = plt.subplot(223)
  504. >>> x = stats.norm.rvs(loc=[0,5], scale=[1,1.5],
  505. ... size=(nsample//2,2), random_state=rng).ravel()
  506. >>> res = stats.probplot(x, plot=plt)
  507. A standard normal distribution:
  508. >>> ax4 = plt.subplot(224)
  509. >>> x = stats.norm.rvs(loc=0, scale=1, size=nsample, random_state=rng)
  510. >>> res = stats.probplot(x, plot=plt)
  511. Produce a new figure with a loggamma distribution, using the ``dist`` and
  512. ``sparams`` keywords:
  513. >>> fig = plt.figure()
  514. >>> ax = fig.add_subplot(111)
  515. >>> x = stats.loggamma.rvs(c=2.5, size=500, random_state=rng)
  516. >>> res = stats.probplot(x, dist=stats.loggamma, sparams=(2.5,), plot=ax)
  517. >>> ax.set_title("Probplot for loggamma dist with shape parameter 2.5")
  518. Show the results with Matplotlib:
  519. >>> plt.show()
  520. """
  521. x = np.asarray(x)
  522. if x.size == 0:
  523. if fit:
  524. return (x, x), (np.nan, np.nan, 0.0)
  525. else:
  526. return x, x
  527. osm_uniform = _calc_uniform_order_statistic_medians(len(x))
  528. dist = _parse_dist_kw(dist, enforce_subclass=False)
  529. if sparams is None:
  530. sparams = ()
  531. if isscalar(sparams):
  532. sparams = (sparams,)
  533. if not isinstance(sparams, tuple):
  534. sparams = tuple(sparams)
  535. osm = dist.ppf(osm_uniform, *sparams)
  536. osr = sort(x)
  537. if fit:
  538. # perform a linear least squares fit.
  539. slope, intercept, r, prob, _ = _stats_py.linregress(osm, osr)
  540. if plot is not None:
  541. plot.plot(osm, osr, 'bo')
  542. if fit:
  543. plot.plot(osm, slope*osm + intercept, 'r-')
  544. _add_axis_labels_title(plot, xlabel='Theoretical quantiles',
  545. ylabel='Ordered Values',
  546. title='Probability Plot')
  547. # Add R^2 value to the plot as text
  548. if fit and rvalue:
  549. xmin = amin(osm)
  550. xmax = amax(osm)
  551. ymin = amin(x)
  552. ymax = amax(x)
  553. posx = xmin + 0.70 * (xmax - xmin)
  554. posy = ymin + 0.01 * (ymax - ymin)
  555. plot.text(posx, posy, f"$R^2={r ** 2:1.4f}$")
  556. if fit:
  557. return (osm, osr), (slope, intercept, r)
  558. else:
  559. return osm, osr
  560. @xp_capabilities(np_only=True)
  561. def ppcc_max(x, brack=(0.0, 1.0), dist='tukeylambda'):
  562. """Calculate the shape parameter that maximizes the PPCC.
  563. The probability plot correlation coefficient (PPCC) plot can be used
  564. to determine the optimal shape parameter for a one-parameter family
  565. of distributions. ``ppcc_max`` returns the shape parameter that would
  566. maximize the probability plot correlation coefficient for the given
  567. data to a one-parameter family of distributions.
  568. Parameters
  569. ----------
  570. x : array_like
  571. Input array.
  572. brack : tuple, optional
  573. Triple (a,b,c) where (a<b<c). If bracket consists of two numbers (a, c)
  574. then they are assumed to be a starting interval for a downhill bracket
  575. search (see `scipy.optimize.brent`).
  576. dist : str or stats.distributions instance, optional
  577. Distribution or distribution function name. Objects that look enough
  578. like a stats.distributions instance (i.e. they have a ``ppf`` method)
  579. are also accepted. The default is ``'tukeylambda'``.
  580. Returns
  581. -------
  582. shape_value : float
  583. The shape parameter at which the probability plot correlation
  584. coefficient reaches its max value.
  585. See Also
  586. --------
  587. ppcc_plot, probplot, boxcox
  588. Notes
  589. -----
  590. The brack keyword serves as a starting point which is useful in corner
  591. cases. One can use a plot to obtain a rough visual estimate of the location
  592. for the maximum to start the search near it.
  593. References
  594. ----------
  595. .. [1] J.J. Filliben, "The Probability Plot Correlation Coefficient Test
  596. for Normality", Technometrics, Vol. 17, pp. 111-117, 1975.
  597. .. [2] Engineering Statistics Handbook, NIST/SEMATEC,
  598. https://www.itl.nist.gov/div898/handbook/eda/section3/ppccplot.htm
  599. Examples
  600. --------
  601. First we generate some random data from a Weibull distribution
  602. with shape parameter 2.5:
  603. >>> import numpy as np
  604. >>> from scipy import stats
  605. >>> import matplotlib.pyplot as plt
  606. >>> rng = np.random.default_rng()
  607. >>> c = 2.5
  608. >>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng)
  609. Generate the PPCC plot for this data with the Weibull distribution.
  610. >>> fig, ax = plt.subplots(figsize=(8, 6))
  611. >>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax)
  612. We calculate the value where the shape should reach its maximum and a
  613. red line is drawn there. The line should coincide with the highest
  614. point in the PPCC graph.
  615. >>> cmax = stats.ppcc_max(x, brack=(c/2, 2*c), dist='weibull_min')
  616. >>> ax.axvline(cmax, color='r')
  617. >>> plt.show()
  618. """
  619. dist = _parse_dist_kw(dist)
  620. osm_uniform = _calc_uniform_order_statistic_medians(len(x))
  621. osr = sort(x)
  622. # this function computes the x-axis values of the probability plot
  623. # and computes a linear regression (including the correlation)
  624. # and returns 1-r so that a minimization function maximizes the
  625. # correlation
  626. def tempfunc(shape, mi, yvals, func):
  627. xvals = func(mi, shape)
  628. r, prob = _stats_py.pearsonr(xvals, yvals)
  629. return 1 - r
  630. return optimize.brent(tempfunc, brack=brack,
  631. args=(osm_uniform, osr, dist.ppf))
  632. @xp_capabilities(np_only=True)
  633. def ppcc_plot(x, a, b, dist='tukeylambda', plot=None, N=80):
  634. """Calculate and optionally plot probability plot correlation coefficient.
  635. The probability plot correlation coefficient (PPCC) plot can be used to
  636. determine the optimal shape parameter for a one-parameter family of
  637. distributions. It cannot be used for distributions without shape
  638. parameters
  639. (like the normal distribution) or with multiple shape parameters.
  640. By default a Tukey-Lambda distribution (`stats.tukeylambda`) is used. A
  641. Tukey-Lambda PPCC plot interpolates from long-tailed to short-tailed
  642. distributions via an approximately normal one, and is therefore
  643. particularly useful in practice.
  644. Parameters
  645. ----------
  646. x : array_like
  647. Input array.
  648. a, b : scalar
  649. Lower and upper bounds of the shape parameter to use.
  650. dist : str or stats.distributions instance, optional
  651. Distribution or distribution function name. Objects that look enough
  652. like a stats.distributions instance (i.e. they have a ``ppf`` method)
  653. are also accepted. The default is ``'tukeylambda'``.
  654. plot : object, optional
  655. If given, plots PPCC against the shape parameter.
  656. `plot` is an object that has to have methods "plot" and "text".
  657. The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
  658. or a custom object with the same methods.
  659. Default is None, which means that no plot is created.
  660. N : int, optional
  661. Number of points on the horizontal axis (equally distributed from
  662. `a` to `b`).
  663. Returns
  664. -------
  665. svals : ndarray
  666. The shape values for which `ppcc` was calculated.
  667. ppcc : ndarray
  668. The calculated probability plot correlation coefficient values.
  669. See Also
  670. --------
  671. ppcc_max, probplot, boxcox_normplot, tukeylambda
  672. References
  673. ----------
  674. J.J. Filliben, "The Probability Plot Correlation Coefficient Test for
  675. Normality", Technometrics, Vol. 17, pp. 111-117, 1975.
  676. Examples
  677. --------
  678. First we generate some random data from a Weibull distribution
  679. with shape parameter 2.5, and plot the histogram of the data:
  680. >>> import numpy as np
  681. >>> from scipy import stats
  682. >>> import matplotlib.pyplot as plt
  683. >>> rng = np.random.default_rng()
  684. >>> c = 2.5
  685. >>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng)
  686. Take a look at the histogram of the data.
  687. >>> fig1, ax = plt.subplots(figsize=(9, 4))
  688. >>> ax.hist(x, bins=50)
  689. >>> ax.set_title('Histogram of x')
  690. >>> plt.show()
  691. Now we explore this data with a PPCC plot as well as the related
  692. probability plot and Box-Cox normplot. A red line is drawn where we
  693. expect the PPCC value to be maximal (at the shape parameter ``c``
  694. used above):
  695. >>> fig2 = plt.figure(figsize=(12, 4))
  696. >>> ax1 = fig2.add_subplot(1, 3, 1)
  697. >>> ax2 = fig2.add_subplot(1, 3, 2)
  698. >>> ax3 = fig2.add_subplot(1, 3, 3)
  699. >>> res = stats.probplot(x, plot=ax1)
  700. >>> res = stats.boxcox_normplot(x, -4, 4, plot=ax2)
  701. >>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax3)
  702. >>> ax3.axvline(c, color='r')
  703. >>> plt.show()
  704. """
  705. if b <= a:
  706. raise ValueError("`b` has to be larger than `a`.")
  707. svals = np.linspace(a, b, num=N)
  708. ppcc = np.empty_like(svals)
  709. for k, sval in enumerate(svals):
  710. _, r2 = probplot(x, sval, dist=dist, fit=True)
  711. ppcc[k] = r2[-1]
  712. if plot is not None:
  713. plot.plot(svals, ppcc, 'x')
  714. _add_axis_labels_title(plot, xlabel='Shape Values',
  715. ylabel='Prob Plot Corr. Coef.',
  716. title=f'({dist}) PPCC Plot')
  717. return svals, ppcc
  718. def _log_mean(logx, axis):
  719. # compute log of mean of x from log(x)
  720. return (
  721. special.logsumexp(logx, axis=axis, keepdims=True)
  722. - math.log(logx.shape[axis])
  723. )
  724. def _log_var(logx, xp, axis):
  725. # compute log of variance of x from log(x)
  726. logmean = xp.broadcast_to(_log_mean(logx, axis=axis), logx.shape)
  727. ones = xp.ones_like(logx)
  728. logxmu, _ = special.logsumexp(xp.stack((logx, logmean), axis=0), axis=0,
  729. b=xp.stack((ones, -ones), axis=0), return_sign=True)
  730. return special.logsumexp(2 * logxmu, axis=axis) - math.log(logx.shape[axis])
  731. @xp_capabilities()
  732. def boxcox_llf(lmb, data, *, axis=0, keepdims=False, nan_policy='propagate'):
  733. r"""The boxcox log-likelihood function.
  734. Parameters
  735. ----------
  736. lmb : scalar
  737. Parameter for Box-Cox transformation. See `boxcox` for details.
  738. data : array_like
  739. Data to calculate Box-Cox log-likelihood for. If `data` is
  740. multi-dimensional, the log-likelihood is calculated along the first
  741. axis.
  742. axis : int, default: 0
  743. If an int, the axis of the input along which to compute the statistic.
  744. The statistic of each axis-slice (e.g. row) of the input will appear in a
  745. corresponding element of the output.
  746. If ``None``, the input will be raveled before computing the statistic.
  747. nan_policy : {'propagate', 'omit', 'raise'
  748. Defines how to handle input NaNs.
  749. - ``propagate``: if a NaN is present in the axis slice (e.g. row) along
  750. which the statistic is computed, the corresponding entry of the output
  751. will be NaN.
  752. - ``omit``: NaNs will be omitted when performing the calculation.
  753. If insufficient data remains in the axis slice along which the
  754. statistic is computed, the corresponding entry of the output will be
  755. NaN.
  756. - ``raise``: if a NaN is present, a ``ValueError`` will be raised.
  757. keepdims : bool, default: False
  758. If this is set to True, the axes which are reduced are left
  759. in the result as dimensions with size one. With this option,
  760. the result will broadcast correctly against the input array.
  761. Returns
  762. -------
  763. llf : float or ndarray
  764. Box-Cox log-likelihood of `data` given `lmb`. A float for 1-D `data`,
  765. an array otherwise.
  766. See Also
  767. --------
  768. boxcox, probplot, boxcox_normplot, boxcox_normmax
  769. Notes
  770. -----
  771. The Box-Cox log-likelihood function :math:`l` is defined here as
  772. .. math::
  773. l = (\lambda - 1) \sum_i^N \log(x_i) -
  774. \frac{N}{2} \log\left(\sum_i^N (y_i - \bar{y})^2 / N\right),
  775. where :math:`N` is the number of data points ``data`` and :math:`y` is the Box-Cox
  776. transformed input data.
  777. This corresponds to the *profile log-likelihood* of the original data :math:`x`
  778. with some constant terms dropped.
  779. Examples
  780. --------
  781. >>> import numpy as np
  782. >>> from scipy import stats
  783. >>> import matplotlib.pyplot as plt
  784. >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes
  785. Generate some random variates and calculate Box-Cox log-likelihood values
  786. for them for a range of ``lmbda`` values:
  787. >>> rng = np.random.default_rng()
  788. >>> x = stats.loggamma.rvs(5, loc=10, size=1000, random_state=rng)
  789. >>> lmbdas = np.linspace(-2, 10)
  790. >>> llf = np.zeros(lmbdas.shape, dtype=float)
  791. >>> for ii, lmbda in enumerate(lmbdas):
  792. ... llf[ii] = stats.boxcox_llf(lmbda, x)
  793. Also find the optimal lmbda value with `boxcox`:
  794. >>> x_most_normal, lmbda_optimal = stats.boxcox(x)
  795. Plot the log-likelihood as function of lmbda. Add the optimal lmbda as a
  796. horizontal line to check that that's really the optimum:
  797. >>> fig = plt.figure()
  798. >>> ax = fig.add_subplot(111)
  799. >>> ax.plot(lmbdas, llf, 'b.-')
  800. >>> ax.axhline(stats.boxcox_llf(lmbda_optimal, x), color='r')
  801. >>> ax.set_xlabel('lmbda parameter')
  802. >>> ax.set_ylabel('Box-Cox log-likelihood')
  803. Now add some probability plots to show that where the log-likelihood is
  804. maximized the data transformed with `boxcox` looks closest to normal:
  805. >>> locs = [3, 10, 4] # 'lower left', 'center', 'lower right'
  806. >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs):
  807. ... xt = stats.boxcox(x, lmbda=lmbda)
  808. ... (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt)
  809. ... ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc)
  810. ... ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-')
  811. ... ax_inset.set_xticklabels([])
  812. ... ax_inset.set_yticklabels([])
  813. ... ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda)
  814. >>> plt.show()
  815. """
  816. # _axis_nan_policy decorator does not currently support these for lazy arrays.
  817. # We want to run tests with lazy backends, so don't pass the arguments explicitly
  818. # unless necessary.
  819. kwargs = {}
  820. if keepdims is not False:
  821. kwargs['keepdims'] = keepdims
  822. if nan_policy != 'propagate':
  823. kwargs['nan_policy'] = nan_policy
  824. return _boxcox_llf(data, lmb=lmb, axis=axis, **kwargs)
  825. @_axis_nan_policy_factory(lambda x: x, n_outputs=1, default_axis=0,
  826. result_to_tuple=lambda x, _: (x,))
  827. def _boxcox_llf(data, axis=0, *, lmb):
  828. xp = array_namespace(data)
  829. dtype = xp_result_type(lmb, data, force_floating=True, xp=xp)
  830. data = xp.asarray(data, dtype=dtype)
  831. N = data.shape[axis]
  832. if N == 0:
  833. return _get_nan(data, xp=xp)
  834. logdata = xp.log(data)
  835. # Compute the variance of the transformed data.
  836. if lmb == 0:
  837. logvar = xp.log(xp.var(logdata, axis=axis))
  838. else:
  839. # Transform without the constant offset 1/lmb. The offset does
  840. # not affect the variance, and the subtraction of the offset can
  841. # lead to loss of precision.
  842. # Division by lmb can be factored out to enhance numerical stability.
  843. logx = lmb * logdata
  844. logvar = _log_var(logx, xp, axis) - 2 * math.log(abs(lmb))
  845. res = (lmb - 1) * xp.sum(logdata, axis=axis) - N/2 * logvar
  846. res = xp.astype(res, data.dtype, copy=False) # compensate for NumPy <2.0
  847. res = res[()] if res.ndim == 0 else res
  848. return res
  849. def _boxcox_conf_interval(x, lmax, alpha):
  850. # Need to find the lambda for which
  851. # f(x,lmbda) >= f(x,lmax) - 0.5*chi^2_alpha;1
  852. fac = 0.5 * distributions.chi2.ppf(1 - alpha, 1)
  853. target = boxcox_llf(lmax, x) - fac
  854. def rootfunc(lmbda, data, target):
  855. return boxcox_llf(lmbda, data) - target
  856. # Find positive endpoint of interval in which answer is to be found
  857. newlm = lmax + 0.5
  858. N = 0
  859. while (rootfunc(newlm, x, target) > 0.0) and (N < 500):
  860. newlm += 0.1
  861. N += 1
  862. if N == 500:
  863. raise RuntimeError("Could not find endpoint.")
  864. lmplus = optimize.brentq(rootfunc, lmax, newlm, args=(x, target))
  865. # Now find negative interval in the same way
  866. newlm = lmax - 0.5
  867. N = 0
  868. while (rootfunc(newlm, x, target) > 0.0) and (N < 500):
  869. newlm -= 0.1
  870. N += 1
  871. if N == 500:
  872. raise RuntimeError("Could not find endpoint.")
  873. lmminus = optimize.brentq(rootfunc, newlm, lmax, args=(x, target))
  874. return lmminus, lmplus
  875. @xp_capabilities(np_only=True)
  876. def boxcox(x, lmbda=None, alpha=None, optimizer=None):
  877. r"""Return a dataset transformed by a Box-Cox power transformation.
  878. Parameters
  879. ----------
  880. x : ndarray
  881. Input array to be transformed.
  882. If `lmbda` is not None, this is an alias of
  883. `scipy.special.boxcox`.
  884. Returns nan if ``x < 0``; returns -inf if ``x == 0 and lmbda < 0``.
  885. If `lmbda` is None, array must be positive, 1-dimensional, and
  886. non-constant.
  887. lmbda : scalar, optional
  888. If `lmbda` is None (default), find the value of `lmbda` that maximizes
  889. the log-likelihood function and return it as the second output
  890. argument.
  891. If `lmbda` is not None, do the transformation for that value.
  892. alpha : float, optional
  893. If `lmbda` is None and `alpha` is not None (default), return the
  894. ``100 * (1-alpha)%`` confidence interval for `lmbda` as the third
  895. output argument. Must be between 0.0 and 1.0.
  896. If `lmbda` is not None, `alpha` is ignored.
  897. optimizer : callable, optional
  898. If `lmbda` is None, `optimizer` is the scalar optimizer used to find
  899. the value of `lmbda` that minimizes the negative log-likelihood
  900. function. `optimizer` is a callable that accepts one argument:
  901. fun : callable
  902. The objective function, which evaluates the negative
  903. log-likelihood function at a provided value of `lmbda`
  904. and returns an object, such as an instance of
  905. `scipy.optimize.OptimizeResult`, which holds the optimal value of
  906. `lmbda` in an attribute `x`.
  907. See the example in `boxcox_normmax` or the documentation of
  908. `scipy.optimize.minimize_scalar` for more information.
  909. If `lmbda` is not None, `optimizer` is ignored.
  910. Returns
  911. -------
  912. boxcox : ndarray
  913. Box-Cox power transformed array.
  914. maxlog : float, optional
  915. If the `lmbda` parameter is None, the second returned argument is
  916. the `lmbda` that maximizes the log-likelihood function.
  917. (min_ci, max_ci) : tuple of float, optional
  918. If `lmbda` parameter is None and `alpha` is not None, this returned
  919. tuple of floats represents the minimum and maximum confidence limits
  920. given `alpha`.
  921. See Also
  922. --------
  923. probplot, boxcox_normplot, boxcox_normmax, boxcox_llf
  924. Notes
  925. -----
  926. The Box-Cox transform is given by:
  927. .. math::
  928. y =
  929. \begin{cases}
  930. \frac{x^\lambda - 1}{\lambda}, &\text{for } \lambda \neq 0 \\
  931. \log(x), &\text{for } \lambda = 0
  932. \end{cases}
  933. `boxcox` requires the input data to be positive. Sometimes a Box-Cox
  934. transformation provides a shift parameter to achieve this; `boxcox` does
  935. not. Such a shift parameter is equivalent to adding a positive constant to
  936. `x` before calling `boxcox`.
  937. The confidence limits returned when `alpha` is provided give the interval
  938. where:
  939. .. math::
  940. l(\hat{\lambda}) - l(\lambda) < \frac{1}{2}\chi^2(1 - \alpha, 1),
  941. with :math:`l` the log-likelihood function and :math:`\chi^2` the chi-squared
  942. function.
  943. References
  944. ----------
  945. G.E.P. Box and D.R. Cox, "An Analysis of Transformations", Journal of the
  946. Royal Statistical Society B, 26, 211-252 (1964).
  947. Examples
  948. --------
  949. >>> from scipy import stats
  950. >>> import matplotlib.pyplot as plt
  951. We generate some random variates from a non-normal distribution and make a
  952. probability plot for it, to show it is non-normal in the tails:
  953. >>> fig = plt.figure()
  954. >>> ax1 = fig.add_subplot(211)
  955. >>> x = stats.loggamma.rvs(5, size=500) + 5
  956. >>> prob = stats.probplot(x, dist=stats.norm, plot=ax1)
  957. >>> ax1.set_xlabel('')
  958. >>> ax1.set_title('Probplot against normal distribution')
  959. We now use `boxcox` to transform the data so it's closest to normal:
  960. >>> ax2 = fig.add_subplot(212)
  961. >>> xt, _ = stats.boxcox(x)
  962. >>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2)
  963. >>> ax2.set_title('Probplot after Box-Cox transformation')
  964. >>> plt.show()
  965. """
  966. x = np.asarray(x)
  967. if lmbda is not None: # single transformation
  968. return special.boxcox(x, lmbda)
  969. if x.ndim != 1:
  970. raise ValueError("Data must be 1-dimensional.")
  971. if x.size == 0:
  972. return x
  973. if np.all(x == x[0]):
  974. raise ValueError("Data must not be constant.")
  975. if np.any(x <= 0):
  976. raise ValueError("Data must be positive.")
  977. # If lmbda=None, find the lmbda that maximizes the log-likelihood function.
  978. lmax = boxcox_normmax(x, method='mle', optimizer=optimizer)
  979. y = boxcox(x, lmax)
  980. if alpha is None:
  981. return y, lmax
  982. else:
  983. # Find confidence interval
  984. interval = _boxcox_conf_interval(x, lmax, alpha)
  985. return y, lmax, interval
  986. def _boxcox_inv_lmbda(x, y):
  987. # compute lmbda given x and y for Box-Cox transformation
  988. num = special.lambertw(-(x ** (-1 / y)) * np.log(x) / y, k=-1)
  989. return np.real(-num / np.log(x) - 1 / y)
  990. class _BigFloat:
  991. def __repr__(self):
  992. return "BIG_FLOAT"
  993. _BigFloat_singleton = _BigFloat()
  994. @xp_capabilities(np_only=True)
  995. def boxcox_normmax(
  996. x, brack=None, method='pearsonr', optimizer=None, *, ymax=_BigFloat_singleton
  997. ):
  998. """Compute optimal Box-Cox transform parameter for input data.
  999. Parameters
  1000. ----------
  1001. x : array_like
  1002. Input array. All entries must be positive, finite, real numbers.
  1003. brack : 2-tuple, optional, default (-2.0, 2.0)
  1004. The starting interval for a downhill bracket search for the default
  1005. `optimize.brent` solver. Note that this is in most cases not
  1006. critical; the final result is allowed to be outside this bracket.
  1007. If `optimizer` is passed, `brack` must be None.
  1008. method : str, optional
  1009. The method to determine the optimal transform parameter (`boxcox`
  1010. ``lmbda`` parameter). Options are:
  1011. 'pearsonr' (default)
  1012. Maximizes the Pearson correlation coefficient between
  1013. ``y = boxcox(x)`` and the expected values for ``y`` if `x` would be
  1014. normally-distributed.
  1015. 'mle'
  1016. Maximizes the log-likelihood `boxcox_llf`. This is the method used
  1017. in `boxcox`.
  1018. 'all'
  1019. Use all optimization methods available, and return all results.
  1020. Useful to compare different methods.
  1021. optimizer : callable, optional
  1022. `optimizer` is a callable that accepts one argument:
  1023. fun : callable
  1024. The objective function to be minimized. `fun` accepts one argument,
  1025. the Box-Cox transform parameter `lmbda`, and returns the value of
  1026. the function (e.g., the negative log-likelihood) at the provided
  1027. argument. The job of `optimizer` is to find the value of `lmbda`
  1028. that *minimizes* `fun`.
  1029. and returns an object, such as an instance of
  1030. `scipy.optimize.OptimizeResult`, which holds the optimal value of
  1031. `lmbda` in an attribute `x`.
  1032. See the example below or the documentation of
  1033. `scipy.optimize.minimize_scalar` for more information.
  1034. ymax : float, optional
  1035. The unconstrained optimal transform parameter may cause Box-Cox
  1036. transformed data to have extreme magnitude or even overflow.
  1037. This parameter constrains MLE optimization such that the magnitude
  1038. of the transformed `x` does not exceed `ymax`. The default is
  1039. the maximum value of the input dtype. If set to infinity,
  1040. `boxcox_normmax` returns the unconstrained optimal lambda.
  1041. Ignored when ``method='pearsonr'``.
  1042. Returns
  1043. -------
  1044. maxlog : float or ndarray
  1045. The optimal transform parameter found. An array instead of a scalar
  1046. for ``method='all'``.
  1047. See Also
  1048. --------
  1049. boxcox, boxcox_llf, boxcox_normplot, scipy.optimize.minimize_scalar
  1050. Examples
  1051. --------
  1052. >>> import numpy as np
  1053. >>> from scipy import stats
  1054. >>> import matplotlib.pyplot as plt
  1055. We can generate some data and determine the optimal ``lmbda`` in various
  1056. ways:
  1057. >>> rng = np.random.default_rng()
  1058. >>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5
  1059. >>> y, lmax_mle = stats.boxcox(x)
  1060. >>> lmax_pearsonr = stats.boxcox_normmax(x)
  1061. >>> lmax_mle
  1062. 2.217563431465757
  1063. >>> lmax_pearsonr
  1064. 2.238318660200961
  1065. >>> stats.boxcox_normmax(x, method='all')
  1066. array([2.23831866, 2.21756343])
  1067. >>> fig = plt.figure()
  1068. >>> ax = fig.add_subplot(111)
  1069. >>> prob = stats.boxcox_normplot(x, -10, 10, plot=ax)
  1070. >>> ax.axvline(lmax_mle, color='r')
  1071. >>> ax.axvline(lmax_pearsonr, color='g', ls='--')
  1072. >>> plt.show()
  1073. Alternatively, we can define our own `optimizer` function. Suppose we
  1074. are only interested in values of `lmbda` on the interval [6, 7], we
  1075. want to use `scipy.optimize.minimize_scalar` with ``method='bounded'``,
  1076. and we want to use tighter tolerances when optimizing the log-likelihood
  1077. function. To do this, we define a function that accepts positional argument
  1078. `fun` and uses `scipy.optimize.minimize_scalar` to minimize `fun` subject
  1079. to the provided bounds and tolerances:
  1080. >>> from scipy import optimize
  1081. >>> options = {'xatol': 1e-12} # absolute tolerance on `x`
  1082. >>> def optimizer(fun):
  1083. ... return optimize.minimize_scalar(fun, bounds=(6, 7),
  1084. ... method="bounded", options=options)
  1085. >>> stats.boxcox_normmax(x, optimizer=optimizer)
  1086. 6.000000000
  1087. """
  1088. x = np.asarray(x)
  1089. if not np.all(np.isfinite(x) & (x >= 0)):
  1090. message = ("The `x` argument of `boxcox_normmax` must contain "
  1091. "only positive, finite, real numbers.")
  1092. raise ValueError(message)
  1093. end_msg = "exceed specified `ymax`."
  1094. if ymax is _BigFloat_singleton:
  1095. dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64
  1096. # 10000 is a safety factor because `special.boxcox` overflows prematurely.
  1097. ymax = np.finfo(dtype).max / 10000
  1098. end_msg = f"overflow in {dtype}."
  1099. elif ymax <= 0:
  1100. raise ValueError("`ymax` must be strictly positive")
  1101. # If optimizer is not given, define default 'brent' optimizer.
  1102. if optimizer is None:
  1103. # Set default value for `brack`.
  1104. if brack is None:
  1105. brack = (-2.0, 2.0)
  1106. def _optimizer(func, args):
  1107. return optimize.brent(func, args=args, brack=brack)
  1108. # Otherwise check optimizer.
  1109. else:
  1110. if not callable(optimizer):
  1111. raise ValueError("`optimizer` must be a callable")
  1112. if brack is not None:
  1113. raise ValueError("`brack` must be None if `optimizer` is given")
  1114. # `optimizer` is expected to return a `OptimizeResult` object, we here
  1115. # get the solution to the optimization problem.
  1116. def _optimizer(func, args):
  1117. def func_wrapped(x):
  1118. return func(x, *args)
  1119. return getattr(optimizer(func_wrapped), 'x', None)
  1120. def _pearsonr(x):
  1121. osm_uniform = _calc_uniform_order_statistic_medians(len(x))
  1122. xvals = distributions.norm.ppf(osm_uniform)
  1123. def _eval_pearsonr(lmbda, xvals, samps):
  1124. # This function computes the x-axis values of the probability plot
  1125. # and computes a linear regression (including the correlation) and
  1126. # returns ``1 - r`` so that a minimization function maximizes the
  1127. # correlation.
  1128. y = boxcox(samps, lmbda)
  1129. yvals = np.sort(y)
  1130. r, prob = _stats_py.pearsonr(xvals, yvals)
  1131. return 1 - r
  1132. return _optimizer(_eval_pearsonr, args=(xvals, x))
  1133. def _mle(x):
  1134. def _eval_mle(lmb, data):
  1135. # function to minimize
  1136. return -boxcox_llf(lmb, data)
  1137. return _optimizer(_eval_mle, args=(x,))
  1138. def _all(x):
  1139. maxlog = np.empty(2, dtype=float)
  1140. maxlog[0] = _pearsonr(x)
  1141. maxlog[1] = _mle(x)
  1142. return maxlog
  1143. methods = {'pearsonr': _pearsonr,
  1144. 'mle': _mle,
  1145. 'all': _all}
  1146. if method not in methods.keys():
  1147. raise ValueError(f"Method {method} not recognized.")
  1148. optimfunc = methods[method]
  1149. res = optimfunc(x)
  1150. if res is None:
  1151. message = ("The `optimizer` argument of `boxcox_normmax` must return "
  1152. "an object containing the optimal `lmbda` in attribute `x`.")
  1153. raise ValueError(message)
  1154. elif not np.isinf(ymax): # adjust the final lambda
  1155. # x > 1, boxcox(x) > 0; x < 1, boxcox(x) < 0
  1156. xmax, xmin = np.max(x), np.min(x)
  1157. if xmin >= 1:
  1158. x_treme = xmax
  1159. elif xmax <= 1:
  1160. x_treme = xmin
  1161. else: # xmin < 1 < xmax
  1162. indicator = special.boxcox(xmax, res) > abs(special.boxcox(xmin, res))
  1163. if isinstance(res, np.ndarray):
  1164. indicator = indicator[1] # select corresponds with 'mle'
  1165. x_treme = xmax if indicator else xmin
  1166. mask = abs(special.boxcox(x_treme, res)) > ymax
  1167. if np.any(mask):
  1168. message = (
  1169. f"The optimal lambda is {res}, but the returned lambda is the "
  1170. f"constrained optimum to ensure that the maximum or the minimum "
  1171. f"of the transformed data does not " + end_msg
  1172. )
  1173. warnings.warn(message, stacklevel=2)
  1174. # Return the constrained lambda to ensure the transformation
  1175. # does not cause overflow or exceed specified `ymax`
  1176. constrained_res = _boxcox_inv_lmbda(x_treme, ymax * np.sign(x_treme - 1))
  1177. if isinstance(res, np.ndarray):
  1178. res[mask] = constrained_res
  1179. else:
  1180. res = constrained_res
  1181. return res
  1182. def _normplot(method, x, la, lb, plot=None, N=80):
  1183. """Compute parameters for a Box-Cox or Yeo-Johnson normality plot,
  1184. optionally show it.
  1185. See `boxcox_normplot` or `yeojohnson_normplot` for details.
  1186. """
  1187. if method == 'boxcox':
  1188. title = 'Box-Cox Normality Plot'
  1189. transform_func = boxcox
  1190. else:
  1191. title = 'Yeo-Johnson Normality Plot'
  1192. transform_func = yeojohnson
  1193. x = np.asarray(x)
  1194. if x.size == 0:
  1195. return x
  1196. if lb <= la:
  1197. raise ValueError("`lb` has to be larger than `la`.")
  1198. if method == 'boxcox' and np.any(x <= 0):
  1199. raise ValueError("Data must be positive.")
  1200. lmbdas = np.linspace(la, lb, num=N)
  1201. ppcc = lmbdas * 0.0
  1202. for i, val in enumerate(lmbdas):
  1203. # Determine for each lmbda the square root of correlation coefficient
  1204. # of transformed x
  1205. z = transform_func(x, lmbda=val)
  1206. _, (_, _, r) = probplot(z, dist='norm', fit=True)
  1207. ppcc[i] = r
  1208. if plot is not None:
  1209. plot.plot(lmbdas, ppcc, 'x')
  1210. _add_axis_labels_title(plot, xlabel='$\\lambda$',
  1211. ylabel='Prob Plot Corr. Coef.',
  1212. title=title)
  1213. return lmbdas, ppcc
  1214. @xp_capabilities(np_only=True)
  1215. def boxcox_normplot(x, la, lb, plot=None, N=80):
  1216. """Compute parameters for a Box-Cox normality plot, optionally show it.
  1217. A Box-Cox normality plot shows graphically what the best transformation
  1218. parameter is to use in `boxcox` to obtain a distribution that is close
  1219. to normal.
  1220. Parameters
  1221. ----------
  1222. x : array_like
  1223. Input array.
  1224. la, lb : scalar
  1225. The lower and upper bounds for the ``lmbda`` values to pass to `boxcox`
  1226. for Box-Cox transformations. These are also the limits of the
  1227. horizontal axis of the plot if that is generated.
  1228. plot : object, optional
  1229. If given, plots the quantiles and least squares fit.
  1230. `plot` is an object that has to have methods "plot" and "text".
  1231. The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
  1232. or a custom object with the same methods.
  1233. Default is None, which means that no plot is created.
  1234. N : int, optional
  1235. Number of points on the horizontal axis (equally distributed from
  1236. `la` to `lb`).
  1237. Returns
  1238. -------
  1239. lmbdas : ndarray
  1240. The ``lmbda`` values for which a Box-Cox transform was done.
  1241. ppcc : ndarray
  1242. Probability Plot Correlation Coefficient, as obtained from `probplot`
  1243. when fitting the Box-Cox transformed input `x` against a normal
  1244. distribution.
  1245. See Also
  1246. --------
  1247. probplot, boxcox, boxcox_normmax, boxcox_llf, ppcc_max
  1248. Notes
  1249. -----
  1250. Even if `plot` is given, the figure is not shown or saved by
  1251. `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')``
  1252. should be used after calling `probplot`.
  1253. Examples
  1254. --------
  1255. >>> from scipy import stats
  1256. >>> import matplotlib.pyplot as plt
  1257. Generate some non-normally distributed data, and create a Box-Cox plot:
  1258. >>> x = stats.loggamma.rvs(5, size=500) + 5
  1259. >>> fig = plt.figure()
  1260. >>> ax = fig.add_subplot(111)
  1261. >>> prob = stats.boxcox_normplot(x, -20, 20, plot=ax)
  1262. Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in
  1263. the same plot:
  1264. >>> _, maxlog = stats.boxcox(x)
  1265. >>> ax.axvline(maxlog, color='r')
  1266. >>> plt.show()
  1267. """
  1268. return _normplot('boxcox', x, la, lb, plot, N)
  1269. @xp_capabilities(np_only=True)
  1270. def yeojohnson(x, lmbda=None):
  1271. r"""Return a dataset transformed by a Yeo-Johnson power transformation.
  1272. Parameters
  1273. ----------
  1274. x : ndarray
  1275. Input array. Should be 1-dimensional.
  1276. lmbda : float, optional
  1277. If ``lmbda`` is ``None``, find the lambda that maximizes the
  1278. log-likelihood function and return it as the second output argument.
  1279. Otherwise the transformation is done for the given value.
  1280. Returns
  1281. -------
  1282. yeojohnson: ndarray
  1283. Yeo-Johnson power transformed array.
  1284. maxlog : float, optional
  1285. If the `lmbda` parameter is None, the second returned argument is
  1286. the lambda that maximizes the log-likelihood function.
  1287. See Also
  1288. --------
  1289. probplot, yeojohnson_normplot, yeojohnson_normmax, yeojohnson_llf, boxcox
  1290. Notes
  1291. -----
  1292. The Yeo-Johnson transform is given by:
  1293. .. math::
  1294. y =
  1295. \begin{cases}
  1296. \frac{(x + 1)^\lambda - 1}{\lambda},
  1297. &\text{for } x \geq 0, \lambda \neq 0
  1298. \\
  1299. \log(x + 1),
  1300. &\text{for } x \geq 0, \lambda = 0
  1301. \\
  1302. -\frac{(-x + 1)^{2 - \lambda} - 1}{2 - \lambda},
  1303. &\text{for } x < 0, \lambda \neq 2
  1304. \\
  1305. -\log(-x + 1),
  1306. &\text{for } x < 0, \lambda = 2
  1307. \end{cases}
  1308. Unlike `boxcox`, `yeojohnson` does not require the input data to be
  1309. positive.
  1310. .. versionadded:: 1.2.0
  1311. References
  1312. ----------
  1313. I. Yeo and R.A. Johnson, "A New Family of Power Transformations to
  1314. Improve Normality or Symmetry", Biometrika 87.4 (2000):
  1315. Examples
  1316. --------
  1317. >>> from scipy import stats
  1318. >>> import matplotlib.pyplot as plt
  1319. We generate some random variates from a non-normal distribution and make a
  1320. probability plot for it, to show it is non-normal in the tails:
  1321. >>> fig = plt.figure()
  1322. >>> ax1 = fig.add_subplot(211)
  1323. >>> x = stats.loggamma.rvs(5, size=500) + 5
  1324. >>> prob = stats.probplot(x, dist=stats.norm, plot=ax1)
  1325. >>> ax1.set_xlabel('')
  1326. >>> ax1.set_title('Probplot against normal distribution')
  1327. We now use `yeojohnson` to transform the data so it's closest to normal:
  1328. >>> ax2 = fig.add_subplot(212)
  1329. >>> xt, lmbda = stats.yeojohnson(x)
  1330. >>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2)
  1331. >>> ax2.set_title('Probplot after Yeo-Johnson transformation')
  1332. >>> plt.show()
  1333. """
  1334. x = np.asarray(x)
  1335. if x.size == 0:
  1336. return x
  1337. if np.issubdtype(x.dtype, np.complexfloating):
  1338. raise ValueError('Yeo-Johnson transformation is not defined for '
  1339. 'complex numbers.')
  1340. if np.issubdtype(x.dtype, np.integer):
  1341. x = x.astype(np.float64, copy=False)
  1342. if lmbda is not None:
  1343. return _yeojohnson_transform(x, lmbda)
  1344. # if lmbda=None, find the lmbda that maximizes the log-likelihood function.
  1345. lmax = yeojohnson_normmax(x)
  1346. y = _yeojohnson_transform(x, lmax)
  1347. return y, lmax
  1348. def _yeojohnson_transform(x, lmbda, xp=None):
  1349. """Returns `x` transformed by the Yeo-Johnson power transform with given
  1350. parameter `lmbda`.
  1351. """
  1352. xp = array_namespace(x) if xp is None else xp
  1353. dtype = xp_result_type(x, lmbda, force_floating=True, xp=xp)
  1354. eps = xp.finfo(dtype).eps
  1355. out = xp.zeros_like(x, dtype=dtype)
  1356. pos = x >= 0 # binary mask
  1357. # when x >= 0
  1358. if abs(lmbda) < eps:
  1359. out = xpx.at(out)[pos].set(xp.log1p(x[pos]))
  1360. else: # lmbda != 0
  1361. # more stable version of: ((x + 1) ** lmbda - 1) / lmbda
  1362. out = xpx.at(out)[pos].set(xp.expm1(lmbda * xp.log1p(x[pos])) / lmbda)
  1363. # when x < 0
  1364. if abs(lmbda - 2) > eps:
  1365. out = xpx.at(out)[~pos].set(
  1366. -xp.expm1((2 - lmbda) * xp.log1p(-x[~pos])) / (2 - lmbda))
  1367. else: # lmbda == 2
  1368. out = xpx.at(out)[~pos].set(-xp.log1p(-x[~pos]))
  1369. return out
  1370. @xp_capabilities(skip_backends=[("dask.array", "Dask can't broadcast nan shapes")])
  1371. def yeojohnson_llf(lmb, data, *, axis=0, nan_policy='propagate', keepdims=False):
  1372. r"""The Yeo-Johnson log-likelihood function.
  1373. Parameters
  1374. ----------
  1375. lmb : scalar
  1376. Parameter for Yeo-Johnson transformation. See `yeojohnson` for
  1377. details.
  1378. data : array_like
  1379. Data to calculate Yeo-Johnson log-likelihood for.
  1380. axis : int, default: 0
  1381. If an int, the axis of the input along which to compute the statistic.
  1382. The statistic of each axis-slice (e.g. row) of the input will appear in a
  1383. corresponding element of the output.
  1384. If ``None``, the input will be raveled before computing the statistic.
  1385. nan_policy : {'propagate', 'omit', 'raise'
  1386. Defines how to handle input NaNs.
  1387. - ``propagate``: if a NaN is present in the axis slice (e.g. row) along
  1388. which the statistic is computed, the corresponding entry of the output
  1389. will be NaN.
  1390. - ``omit``: NaNs will be omitted when performing the calculation.
  1391. If insufficient data remains in the axis slice along which the
  1392. statistic is computed, the corresponding entry of the output will be
  1393. NaN.
  1394. - ``raise``: if a NaN is present, a ``ValueError`` will be raised.
  1395. keepdims : bool, default: False
  1396. If this is set to True, the axes which are reduced are left
  1397. in the result as dimensions with size one. With this option,
  1398. the result will broadcast correctly against the input array.
  1399. Returns
  1400. -------
  1401. llf : float
  1402. Yeo-Johnson log-likelihood of `data` given `lmb`.
  1403. See Also
  1404. --------
  1405. yeojohnson, probplot, yeojohnson_normplot, yeojohnson_normmax
  1406. Notes
  1407. -----
  1408. The Yeo-Johnson log-likelihood function :math:`l` is defined here as
  1409. .. math::
  1410. l = -\frac{N}{2} \log(\hat{\sigma}^2) + (\lambda - 1)
  1411. \sum_i^N \text{sign}(x_i) \log(|x_i| + 1)
  1412. where :math:`N` is the number of data points :math:`x`=``data`` and
  1413. :math:`\hat{\sigma}^2` is the estimated variance of the Yeo-Johnson transformed
  1414. input data :math:`x`.
  1415. This corresponds to the *profile log-likelihood* of the original data :math:`x`
  1416. with some constant terms dropped.
  1417. .. versionadded:: 1.2.0
  1418. Examples
  1419. --------
  1420. >>> import numpy as np
  1421. >>> from scipy import stats
  1422. >>> import matplotlib.pyplot as plt
  1423. >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes
  1424. Generate some random variates and calculate Yeo-Johnson log-likelihood
  1425. values for them for a range of ``lmbda`` values:
  1426. >>> x = stats.loggamma.rvs(5, loc=10, size=1000)
  1427. >>> lmbdas = np.linspace(-2, 10)
  1428. >>> llf = np.zeros(lmbdas.shape, dtype=float)
  1429. >>> for ii, lmbda in enumerate(lmbdas):
  1430. ... llf[ii] = stats.yeojohnson_llf(lmbda, x)
  1431. Also find the optimal lmbda value with `yeojohnson`:
  1432. >>> x_most_normal, lmbda_optimal = stats.yeojohnson(x)
  1433. Plot the log-likelihood as function of lmbda. Add the optimal lmbda as a
  1434. horizontal line to check that that's really the optimum:
  1435. >>> fig = plt.figure()
  1436. >>> ax = fig.add_subplot(111)
  1437. >>> ax.plot(lmbdas, llf, 'b.-')
  1438. >>> ax.axhline(stats.yeojohnson_llf(lmbda_optimal, x), color='r')
  1439. >>> ax.set_xlabel('lmbda parameter')
  1440. >>> ax.set_ylabel('Yeo-Johnson log-likelihood')
  1441. Now add some probability plots to show that where the log-likelihood is
  1442. maximized the data transformed with `yeojohnson` looks closest to normal:
  1443. >>> locs = [3, 10, 4] # 'lower left', 'center', 'lower right'
  1444. >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs):
  1445. ... xt = stats.yeojohnson(x, lmbda=lmbda)
  1446. ... (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt)
  1447. ... ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc)
  1448. ... ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-')
  1449. ... ax_inset.set_xticklabels([])
  1450. ... ax_inset.set_yticklabels([])
  1451. ... ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda)
  1452. >>> plt.show()
  1453. """
  1454. # _axis_nan_policy decorator does not currently support these for lazy arrays.
  1455. # We want to run tests with lazy backends, so don't pass the arguments explicitly
  1456. # unless necessary.
  1457. kwargs = {}
  1458. if keepdims is not False:
  1459. kwargs['keepdims'] = keepdims
  1460. if nan_policy != 'propagate':
  1461. kwargs['nan_policy'] = nan_policy
  1462. res = _yeojohnson_llf(data, lmb=lmb, axis=axis, **kwargs)
  1463. return res[()] if res.ndim == 0 else res
  1464. @_axis_nan_policy_factory(lambda x: x, n_outputs=1, default_axis=0,
  1465. result_to_tuple=lambda x, _: (x,))
  1466. def _yeojohnson_llf(data, *, lmb, axis=0):
  1467. xp = array_namespace(data)
  1468. y = _yeojohnson_transform(data, lmb, xp=xp)
  1469. sigma = xp.var(y, axis=axis)
  1470. # Suppress RuntimeWarning raised by np.log when the variance is too low
  1471. finite_variance = sigma >= xp.finfo(sigma.dtype).smallest_normal
  1472. log_sigma = xpx.apply_where(finite_variance, (sigma,), xp.log, fill_value=-xp.inf)
  1473. n = data.shape[axis]
  1474. loglike = (-n / 2 * log_sigma
  1475. + (lmb - 1) * xp.sum(xp.sign(data) * xp.log1p(xp.abs(data)), axis=axis))
  1476. return loglike
  1477. @xp_capabilities(np_only=True)
  1478. def yeojohnson_normmax(x, brack=None):
  1479. """Compute optimal Yeo-Johnson transform parameter.
  1480. Compute optimal Yeo-Johnson transform parameter for input data, using
  1481. maximum likelihood estimation.
  1482. Parameters
  1483. ----------
  1484. x : array_like
  1485. Input array.
  1486. brack : 2-tuple, optional
  1487. The starting interval for a downhill bracket search with
  1488. `optimize.brent`. Note that this is in most cases not critical; the
  1489. final result is allowed to be outside this bracket. If None,
  1490. `optimize.fminbound` is used with bounds that avoid overflow.
  1491. Returns
  1492. -------
  1493. maxlog : float
  1494. The optimal transform parameter found.
  1495. See Also
  1496. --------
  1497. yeojohnson, yeojohnson_llf, yeojohnson_normplot
  1498. Notes
  1499. -----
  1500. .. versionadded:: 1.2.0
  1501. Examples
  1502. --------
  1503. >>> import numpy as np
  1504. >>> from scipy import stats
  1505. >>> import matplotlib.pyplot as plt
  1506. Generate some data and determine optimal ``lmbda``
  1507. >>> rng = np.random.default_rng()
  1508. >>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5
  1509. >>> lmax = stats.yeojohnson_normmax(x)
  1510. >>> fig = plt.figure()
  1511. >>> ax = fig.add_subplot(111)
  1512. >>> prob = stats.yeojohnson_normplot(x, -10, 10, plot=ax)
  1513. >>> ax.axvline(lmax, color='r')
  1514. >>> plt.show()
  1515. """
  1516. def _neg_llf(lmbda, data):
  1517. llf = np.asarray(yeojohnson_llf(lmbda, data))
  1518. # reject likelihoods that are inf which are likely due to small
  1519. # variance in the transformed space
  1520. llf[np.isinf(llf)] = -np.inf
  1521. return -llf
  1522. with np.errstate(invalid='ignore'):
  1523. if not np.all(np.isfinite(x)):
  1524. raise ValueError('Yeo-Johnson input must be finite.')
  1525. if np.all(x == 0):
  1526. return 1.0
  1527. if brack is not None:
  1528. return optimize.brent(_neg_llf, brack=brack, args=(x,))
  1529. x = np.asarray(x)
  1530. dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64
  1531. # Allow values up to 20 times the maximum observed value to be safely
  1532. # transformed without over- or underflow.
  1533. log1p_max_x = np.log1p(20 * np.max(np.abs(x)))
  1534. # Use half of floating point's exponent range to allow safe computation
  1535. # of the variance of the transformed data.
  1536. log_eps = np.log(np.finfo(dtype).eps)
  1537. log_tiny_float = (np.log(np.finfo(dtype).tiny) - log_eps) / 2
  1538. log_max_float = (np.log(np.finfo(dtype).max) + log_eps) / 2
  1539. # Compute the bounds by approximating the inverse of the Yeo-Johnson
  1540. # transform on the smallest and largest floating point exponents, given
  1541. # the largest data we expect to observe. See [1] for further details.
  1542. # [1] https://github.com/scipy/scipy/pull/18852#issuecomment-1630286174
  1543. lb = log_tiny_float / log1p_max_x
  1544. ub = log_max_float / log1p_max_x
  1545. # Convert the bounds if all or some of the data is negative.
  1546. if np.all(x < 0):
  1547. lb, ub = 2 - ub, 2 - lb
  1548. elif np.any(x < 0):
  1549. lb, ub = max(2 - ub, lb), min(2 - lb, ub)
  1550. # Match `optimize.brent`'s tolerance.
  1551. tol_brent = 1.48e-08
  1552. return optimize.fminbound(_neg_llf, lb, ub, args=(x,), xtol=tol_brent)
  1553. @xp_capabilities(np_only=True)
  1554. def yeojohnson_normplot(x, la, lb, plot=None, N=80):
  1555. """Compute parameters for a Yeo-Johnson normality plot, optionally show it.
  1556. A Yeo-Johnson normality plot shows graphically what the best
  1557. transformation parameter is to use in `yeojohnson` to obtain a
  1558. distribution that is close to normal.
  1559. Parameters
  1560. ----------
  1561. x : array_like
  1562. Input array.
  1563. la, lb : scalar
  1564. The lower and upper bounds for the ``lmbda`` values to pass to
  1565. `yeojohnson` for Yeo-Johnson transformations. These are also the
  1566. limits of the horizontal axis of the plot if that is generated.
  1567. plot : object, optional
  1568. If given, plots the quantiles and least squares fit.
  1569. `plot` is an object that has to have methods "plot" and "text".
  1570. The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
  1571. or a custom object with the same methods.
  1572. Default is None, which means that no plot is created.
  1573. N : int, optional
  1574. Number of points on the horizontal axis (equally distributed from
  1575. `la` to `lb`).
  1576. Returns
  1577. -------
  1578. lmbdas : ndarray
  1579. The ``lmbda`` values for which a Yeo-Johnson transform was done.
  1580. ppcc : ndarray
  1581. Probability Plot Correlation Coefficient, as obtained from `probplot`
  1582. when fitting the Box-Cox transformed input `x` against a normal
  1583. distribution.
  1584. See Also
  1585. --------
  1586. probplot, yeojohnson, yeojohnson_normmax, yeojohnson_llf, ppcc_max
  1587. Notes
  1588. -----
  1589. Even if `plot` is given, the figure is not shown or saved by
  1590. `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')``
  1591. should be used after calling `probplot`.
  1592. .. versionadded:: 1.2.0
  1593. Examples
  1594. --------
  1595. >>> from scipy import stats
  1596. >>> import matplotlib.pyplot as plt
  1597. Generate some non-normally distributed data, and create a Yeo-Johnson plot:
  1598. >>> x = stats.loggamma.rvs(5, size=500) + 5
  1599. >>> fig = plt.figure()
  1600. >>> ax = fig.add_subplot(111)
  1601. >>> prob = stats.yeojohnson_normplot(x, -20, 20, plot=ax)
  1602. Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in
  1603. the same plot:
  1604. >>> _, maxlog = stats.yeojohnson(x)
  1605. >>> ax.axvline(maxlog, color='r')
  1606. >>> plt.show()
  1607. """
  1608. return _normplot('yeojohnson', x, la, lb, plot, N)
  1609. ShapiroResult = namedtuple('ShapiroResult', ('statistic', 'pvalue'))
  1610. @xp_capabilities(np_only=True)
  1611. @_axis_nan_policy_factory(ShapiroResult, n_samples=1, too_small=2, default_axis=None)
  1612. def shapiro(x):
  1613. r"""Perform the Shapiro-Wilk test for normality.
  1614. The Shapiro-Wilk test tests the null hypothesis that the
  1615. data was drawn from a normal distribution.
  1616. Parameters
  1617. ----------
  1618. x : array_like
  1619. Array of sample data. Must contain at least three observations.
  1620. Returns
  1621. -------
  1622. statistic : float
  1623. The test statistic.
  1624. p-value : float
  1625. The p-value for the hypothesis test.
  1626. See Also
  1627. --------
  1628. anderson : The Anderson-Darling test for normality
  1629. kstest : The Kolmogorov-Smirnov test for goodness of fit.
  1630. :ref:`hypothesis_shapiro` : Extended example
  1631. Notes
  1632. -----
  1633. The algorithm used is described in [4]_ but censoring parameters as
  1634. described are not implemented. For N > 5000 the W test statistic is
  1635. accurate, but the p-value may not be.
  1636. References
  1637. ----------
  1638. .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
  1639. :doi:`10.18434/M32189`
  1640. .. [2] Shapiro, S. S. & Wilk, M.B, "An analysis of variance test for
  1641. normality (complete samples)", Biometrika, 1965, Vol. 52,
  1642. pp. 591-611, :doi:`10.2307/2333709`
  1643. .. [3] Razali, N. M. & Wah, Y. B., "Power comparisons of Shapiro-Wilk,
  1644. Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests", Journal
  1645. of Statistical Modeling and Analytics, 2011, Vol. 2, pp. 21-33.
  1646. .. [4] Royston P., "Remark AS R94: A Remark on Algorithm AS 181: The
  1647. W-test for Normality", 1995, Applied Statistics, Vol. 44,
  1648. :doi:`10.2307/2986146`
  1649. Examples
  1650. --------
  1651. >>> import numpy as np
  1652. >>> from scipy import stats
  1653. >>> rng = np.random.default_rng()
  1654. >>> x = stats.norm.rvs(loc=5, scale=3, size=100, random_state=rng)
  1655. >>> shapiro_test = stats.shapiro(x)
  1656. >>> shapiro_test
  1657. ShapiroResult(statistic=0.9813305735588074, pvalue=0.16855233907699585)
  1658. >>> shapiro_test.statistic
  1659. 0.9813305735588074
  1660. >>> shapiro_test.pvalue
  1661. 0.16855233907699585
  1662. For a more detailed example, see :ref:`hypothesis_shapiro`.
  1663. """
  1664. x = np.ravel(x).astype(np.float64)
  1665. N = len(x)
  1666. if N < 3:
  1667. raise ValueError("Data must be at least length 3.")
  1668. a = zeros(N//2, dtype=np.float64)
  1669. init = 0
  1670. y = sort(x)
  1671. y -= x[N//2] # subtract the median (or a nearby value); see gh-15777
  1672. w, pw, ifault = swilk(y, a, init)
  1673. if ifault not in [0, 2]:
  1674. warnings.warn("scipy.stats.shapiro: Input data has range zero. The"
  1675. " results may not be accurate.", stacklevel=2)
  1676. if N > 5000:
  1677. warnings.warn("scipy.stats.shapiro: For N > 5000, computed p-value "
  1678. f"may not be accurate. Current N is {N}.",
  1679. stacklevel=2)
  1680. # `w` and `pw` are always Python floats, which are double precision.
  1681. # We want to ensure that they are NumPy floats, so until dtypes are
  1682. # respected, we can explicitly convert each to float64 (faster than
  1683. # `np.array([w, pw])`).
  1684. return ShapiroResult(np.float64(w), np.float64(pw))
  1685. # Values from [8]
  1686. _Avals_norm = array([0.561, 0.631, 0.752, 0.873, 1.035])
  1687. _Avals_expon = array([0.916, 1.062, 1.321, 1.591, 1.959])
  1688. # From Stephens, M A, "Goodness of Fit for the Extreme Value Distribution",
  1689. # Biometrika, Vol. 64, Issue 3, Dec. 1977, pp 583-588.
  1690. _Avals_gumbel = array([0.474, 0.637, 0.757, 0.877, 1.038])
  1691. # From Stephens, M A, "Tests of Fit for the Logistic Distribution Based
  1692. # on the Empirical Distribution Function.", Biometrika,
  1693. # Vol. 66, Issue 3, Dec. 1979, pp 591-595.
  1694. _Avals_logistic = array([0.426, 0.563, 0.660, 0.769, 0.906, 1.010])
  1695. # From Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of
  1696. # Fit for the Three-Parameter Weibull Distribution"
  1697. # Journal of the Royal Statistical Society.Series B(Methodological)
  1698. # Vol. 56, No. 3 (1994), pp. 491-500, table 1. Keys are c*100
  1699. _Avals_weibull = [[0.292, 0.395, 0.467, 0.522, 0.617, 0.711, 0.836, 0.931],
  1700. [0.295, 0.399, 0.471, 0.527, 0.623, 0.719, 0.845, 0.941],
  1701. [0.298, 0.403, 0.476, 0.534, 0.631, 0.728, 0.856, 0.954],
  1702. [0.301, 0.408, 0.483, 0.541, 0.640, 0.738, 0.869, 0.969],
  1703. [0.305, 0.414, 0.490, 0.549, 0.650, 0.751, 0.885, 0.986],
  1704. [0.309, 0.421, 0.498, 0.559, 0.662, 0.765, 0.902, 1.007],
  1705. [0.314, 0.429, 0.508, 0.570, 0.676, 0.782, 0.923, 1.030],
  1706. [0.320, 0.438, 0.519, 0.583, 0.692, 0.802, 0.947, 1.057],
  1707. [0.327, 0.448, 0.532, 0.598, 0.711, 0.824, 0.974, 1.089],
  1708. [0.334, 0.469, 0.547, 0.615, 0.732, 0.850, 1.006, 1.125],
  1709. [0.342, 0.472, 0.563, 0.636, 0.757, 0.879, 1.043, 1.167]]
  1710. _Avals_weibull = np.array(_Avals_weibull)
  1711. _cvals_weibull = np.linspace(0, 0.5, 11)
  1712. _get_As_weibull = interpolate.interp1d(_cvals_weibull, _Avals_weibull.T,
  1713. kind='linear', bounds_error=False,
  1714. fill_value=_Avals_weibull[-1])
  1715. def _weibull_fit_check(params, x):
  1716. # Refine the fit returned by `weibull_min.fit` to ensure that the first
  1717. # order necessary conditions are satisfied. If not, raise an error.
  1718. # Here, use `m` for the shape parameter to be consistent with [7]
  1719. # and avoid confusion with `c` as defined in [7].
  1720. n = len(x)
  1721. m, u, s = params
  1722. def dnllf_dm(m, u):
  1723. # Partial w.r.t. shape w/ optimal scale. See [7] Equation 5.
  1724. xu = x-u
  1725. return (1/m - (xu**m*np.log(xu)).sum()/(xu**m).sum()
  1726. + np.log(xu).sum()/n)
  1727. def dnllf_du(m, u):
  1728. # Partial w.r.t. loc w/ optimal scale. See [7] Equation 6.
  1729. xu = x-u
  1730. return (m-1)/m*(xu**-1).sum() - n*(xu**(m-1)).sum()/(xu**m).sum()
  1731. def get_scale(m, u):
  1732. # Partial w.r.t. scale solved in terms of shape and location.
  1733. # See [7] Equation 7.
  1734. return ((x-u)**m/n).sum()**(1/m)
  1735. def dnllf(params):
  1736. # Partial derivatives of the NLLF w.r.t. parameters, i.e.
  1737. # first order necessary conditions for MLE fit.
  1738. return [dnllf_dm(*params), dnllf_du(*params)]
  1739. suggestion = ("Maximum likelihood estimation is known to be challenging "
  1740. "for the three-parameter Weibull distribution. Consider "
  1741. "performing a custom goodness-of-fit test using "
  1742. "`scipy.stats.monte_carlo_test`.")
  1743. if np.allclose(u, np.min(x)) or m < 1:
  1744. # The critical values provided by [7] don't seem to control the
  1745. # Type I error rate in this case. Error out.
  1746. message = ("Maximum likelihood estimation has converged to "
  1747. "a solution in which the location is equal to the minimum "
  1748. "of the data, the shape parameter is less than 2, or both. "
  1749. "The table of critical values in [7] does not "
  1750. "include this case. " + suggestion)
  1751. raise ValueError(message)
  1752. try:
  1753. # Refine the MLE / verify that first-order necessary conditions are
  1754. # satisfied. If so, the critical values provided in [7] seem reliable.
  1755. with np.errstate(over='raise', invalid='raise'):
  1756. res = optimize.root(dnllf, params[:-1])
  1757. message = ("Solution of MLE first-order conditions failed: "
  1758. f"{res.message}. `anderson` cannot continue. " + suggestion)
  1759. if not res.success:
  1760. raise ValueError(message)
  1761. except (FloatingPointError, ValueError) as e:
  1762. message = ("An error occurred while fitting the Weibull distribution "
  1763. "to the data, so `anderson` cannot continue. " + suggestion)
  1764. raise ValueError(message) from e
  1765. m, u = res.x
  1766. s = get_scale(m, u)
  1767. return m, u, s
  1768. AndersonResult = _make_tuple_bunch('AndersonResult',
  1769. ['statistic', 'critical_values',
  1770. 'significance_level'], ['fit_result'])
  1771. _anderson_warning_message = (
  1772. """As of SciPy 1.17, users must choose a p-value calculation method by providing the
  1773. `method` parameter. `method='interpolate'` interpolates the p-value from pre-calculated
  1774. tables; `method` may also be an instance of `MonteCarloMethod` to approximate the
  1775. p-value via Monte Carlo simulation. When `method` is specified, the result object will
  1776. include a `pvalue` attribute and not attributes `critical_value`, `significance_level`,
  1777. or `fit_result`. Beginning in 1.19.0, these other attributes will no longer be
  1778. available, and a p-value will always be computed according to one of the available
  1779. `method` options.""".replace('\n', ' '))
  1780. @xp_capabilities(np_only=True)
  1781. def anderson(x, dist='norm', *, method=None):
  1782. """Anderson-Darling test for data coming from a particular distribution.
  1783. The Anderson-Darling test tests the null hypothesis that a sample is
  1784. drawn from a population that follows a particular distribution.
  1785. For the Anderson-Darling test, the critical values depend on
  1786. which distribution is being tested against. This function works
  1787. for normal, exponential, logistic, weibull_min, or Gumbel (Extreme Value
  1788. Type I) distributions.
  1789. Parameters
  1790. ----------
  1791. x : array_like
  1792. Array of sample data.
  1793. dist : {'norm', 'expon', 'logistic', 'gumbel', 'gumbel_l', 'gumbel_r', 'extreme1', 'weibull_min'}, optional
  1794. The type of distribution to test against. The default is 'norm'.
  1795. The names 'extreme1', 'gumbel_l' and 'gumbel' are synonyms for the
  1796. same distribution.
  1797. method : str or instance of `MonteCarloMethod`
  1798. Defines the method used to compute the p-value.
  1799. If `method` is ``"interpolated"``, the p-value is interpolated from
  1800. pre-calculated tables.
  1801. If `method` is an instance of `MonteCarloMethod`, the p-value is computed using
  1802. `scipy.stats.monte_carlo_test` with the provided configuration options and other
  1803. appropriate settings.
  1804. .. versionadded:: 1.17.0
  1805. If `method` is not specified, `anderson` will emit a ``FutureWarning``
  1806. specifying that the user must opt into a p-value calculation method.
  1807. When `method` is specified, the object returned will include a ``pvalue``
  1808. attribute, but no ``critical_value``, ``significance_level``, or
  1809. ``fit_result`` attributes. Beginning in 1.19.0, these other attributes will
  1810. no longer be available, and a p-value will always be computed according to
  1811. one of the available `method` options.
  1812. Returns
  1813. -------
  1814. result : AndersonResult
  1815. If `method` is provided, this is an object with the following attributes:
  1816. statistic : float
  1817. The Anderson-Darling test statistic.
  1818. pvalue: float
  1819. The p-value corresponding with the test statistic, calculated according to
  1820. the specified `method`.
  1821. If `method` is unspecified, this is an object with the following attributes:
  1822. statistic : float
  1823. The Anderson-Darling test statistic.
  1824. critical_values : list
  1825. The critical values for this distribution.
  1826. significance_level : list
  1827. The significance levels for the corresponding critical values
  1828. in percents. The function returns critical values for a
  1829. differing set of significance levels depending on the
  1830. distribution that is being tested against.
  1831. fit_result : `~scipy.stats._result_classes.FitResult`
  1832. An object containing the results of fitting the distribution to
  1833. the data.
  1834. .. deprecated :: 1.17.0
  1835. The tuple-unpacking behavior of the return object and attributes
  1836. ``critical_values``, ``significance_level``, and ``fit_result`` are
  1837. deprecated. Beginning in SciPy 1.19.0, these features will no longer be
  1838. available, and the object returned will have attributes ``statistic`` and
  1839. ``pvalue``.
  1840. See Also
  1841. --------
  1842. kstest : The Kolmogorov-Smirnov test for goodness-of-fit.
  1843. Notes
  1844. -----
  1845. Critical values provided when `method` is unspecified are for the following
  1846. significance levels:
  1847. normal/exponential
  1848. 15%, 10%, 5%, 2.5%, 1%
  1849. logistic
  1850. 25%, 10%, 5%, 2.5%, 1%, 0.5%
  1851. gumbel_l / gumbel_r
  1852. 25%, 10%, 5%, 2.5%, 1%
  1853. weibull_min
  1854. 50%, 25%, 15%, 10%, 5%, 2.5%, 1%, 0.5%
  1855. If the returned statistic is larger than these critical values then
  1856. for the corresponding significance level, the null hypothesis that
  1857. the data come from the chosen distribution can be rejected.
  1858. The returned statistic is referred to as 'A2' in the references.
  1859. For `weibull_min`, maximum likelihood estimation is known to be
  1860. challenging. If the test returns successfully, then the first order
  1861. conditions for a maximum likelihood estimate have been verified and
  1862. the critical values correspond relatively well to the significance levels,
  1863. provided that the sample is sufficiently large (>10 observations [7]).
  1864. However, for some data - especially data with no left tail - `anderson`
  1865. is likely to result in an error message. In this case, consider
  1866. performing a custom goodness of fit test using
  1867. `scipy.stats.monte_carlo_test`.
  1868. References
  1869. ----------
  1870. .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
  1871. .. [2] Stephens, M. A. (1974). EDF Statistics for Goodness of Fit and
  1872. Some Comparisons, Journal of the American Statistical Association,
  1873. Vol. 69, pp. 730-737.
  1874. .. [3] Stephens, M. A. (1976). Asymptotic Results for Goodness-of-Fit
  1875. Statistics with Unknown Parameters, Annals of Statistics, Vol. 4,
  1876. pp. 357-369.
  1877. .. [4] Stephens, M. A. (1977). Goodness of Fit for the Extreme Value
  1878. Distribution, Biometrika, Vol. 64, pp. 583-588.
  1879. .. [5] Stephens, M. A. (1977). Goodness of Fit with Special Reference
  1880. to Tests for Exponentiality , Technical Report No. 262,
  1881. Department of Statistics, Stanford University, Stanford, CA.
  1882. .. [6] Stephens, M. A. (1979). Tests of Fit for the Logistic Distribution
  1883. Based on the Empirical Distribution Function, Biometrika, Vol. 66,
  1884. pp. 591-595.
  1885. .. [7] Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of
  1886. Fit for the Three-Parameter Weibull Distribution"
  1887. Journal of the Royal Statistical Society.Series B(Methodological)
  1888. Vol. 56, No. 3 (1994), pp. 491-500, Table 0.
  1889. .. [8] D'Agostino, Ralph B. (1986). "Tests for the Normal Distribution".
  1890. In: Goodness-of-Fit Techniques. Ed. by Ralph B. D'Agostino and
  1891. Michael A. Stephens. New York: Marcel Dekker, pp. 122-141. ISBN:
  1892. 0-8247-7487-6.
  1893. Examples
  1894. --------
  1895. Test the null hypothesis that a random sample was drawn from a normal
  1896. distribution (with unspecified mean and standard deviation).
  1897. >>> import numpy as np
  1898. >>> from scipy.stats import anderson
  1899. >>> rng = np.random.default_rng(9781234521)
  1900. >>> data = rng.random(size=35)
  1901. >>> res = anderson(data, dist='norm', method='interpolate')
  1902. >>> res.statistic
  1903. np.float64(0.9887620209957291)
  1904. >>> res.pvalue
  1905. np.float64(0.012111200538380142)
  1906. The p-value is approximately 0.012,, so the null hypothesis may be rejected
  1907. at a significance level of 2.5%, but not at a significance level of 1%.
  1908. """ # numpy/numpydoc#87 # noqa: E501
  1909. dist = dist.lower()
  1910. if dist in {'extreme1', 'gumbel'}:
  1911. dist = 'gumbel_l'
  1912. dists = {'norm', 'expon', 'gumbel_l',
  1913. 'gumbel_r', 'logistic', 'weibull_min'}
  1914. if dist not in dists:
  1915. raise ValueError(f"Invalid distribution; dist must be in {dists}.")
  1916. y = sort(x)
  1917. xbar = np.mean(x, axis=0)
  1918. N = len(y)
  1919. if dist == 'norm':
  1920. s = np.std(x, ddof=1, axis=0)
  1921. w = (y - xbar) / s
  1922. fit_params = xbar, s
  1923. logcdf = distributions.norm.logcdf(w)
  1924. logsf = distributions.norm.logsf(w)
  1925. sig = array([15, 10, 5, 2.5, 1])
  1926. critical = around(_Avals_norm / (1.0 + 0.75/N + 2.25/N/N), 3)
  1927. elif dist == 'expon':
  1928. w = y / xbar
  1929. fit_params = 0, xbar
  1930. logcdf = distributions.expon.logcdf(w)
  1931. logsf = distributions.expon.logsf(w)
  1932. sig = array([15, 10, 5, 2.5, 1])
  1933. critical = around(_Avals_expon / (1.0 + 0.6/N), 3)
  1934. elif dist == 'logistic':
  1935. def rootfunc(ab, xj, N):
  1936. a, b = ab
  1937. tmp = (xj - a) / b
  1938. tmp2 = exp(tmp)
  1939. val = [np.sum(1.0/(1+tmp2), axis=0) - 0.5*N,
  1940. np.sum(tmp*(1.0-tmp2)/(1+tmp2), axis=0) + N]
  1941. return array(val)
  1942. sol0 = array([xbar, np.std(x, ddof=1, axis=0)])
  1943. sol = optimize.fsolve(rootfunc, sol0, args=(x, N), xtol=1e-5)
  1944. w = (y - sol[0]) / sol[1]
  1945. fit_params = sol
  1946. logcdf = distributions.logistic.logcdf(w)
  1947. logsf = distributions.logistic.logsf(w)
  1948. sig = array([25, 10, 5, 2.5, 1, 0.5])
  1949. critical = around(_Avals_logistic / (1.0 + 0.25/N), 3)
  1950. elif dist == 'gumbel_r':
  1951. xbar, s = distributions.gumbel_r.fit(x)
  1952. w = (y - xbar) / s
  1953. fit_params = xbar, s
  1954. logcdf = distributions.gumbel_r.logcdf(w)
  1955. logsf = distributions.gumbel_r.logsf(w)
  1956. sig = array([25, 10, 5, 2.5, 1])
  1957. critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)), 3)
  1958. elif dist == 'gumbel_l':
  1959. xbar, s = distributions.gumbel_l.fit(x)
  1960. w = (y - xbar) / s
  1961. fit_params = xbar, s
  1962. logcdf = distributions.gumbel_l.logcdf(w)
  1963. logsf = distributions.gumbel_l.logsf(w)
  1964. sig = array([25, 10, 5, 2.5, 1])
  1965. critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)), 3)
  1966. elif dist == 'weibull_min':
  1967. message = ("Critical values of the test statistic are given for the "
  1968. "asymptotic distribution. These may not be accurate for "
  1969. "samples with fewer than 10 observations. Consider using "
  1970. "`scipy.stats.monte_carlo_test`.")
  1971. if N < 10:
  1972. warnings.warn(message, stacklevel=2)
  1973. # [7] writes our 'c' as 'm', and they write `c = 1/m`. Use their names.
  1974. m, loc, scale = distributions.weibull_min.fit(y)
  1975. m, loc, scale = _weibull_fit_check((m, loc, scale), y)
  1976. fit_params = m, loc, scale
  1977. logcdf = stats.weibull_min(*fit_params).logcdf(y)
  1978. logsf = stats.weibull_min(*fit_params).logsf(y)
  1979. c = 1 / m # m and c are as used in [7]
  1980. sig = array([0.5, 0.75, 0.85, 0.9, 0.95, 0.975, 0.99, 0.995])
  1981. critical = _get_As_weibull(c)
  1982. # Goodness-of-fit tests should only be used to provide evidence
  1983. # _against_ the null hypothesis. Be conservative and round up.
  1984. critical = np.round(critical + 0.0005, decimals=3)
  1985. i = arange(1, N + 1)
  1986. A2 = -N - np.sum((2*i - 1.0) / N * (logcdf + logsf[::-1]), axis=0)
  1987. # FitResult initializer expects an optimize result, so let's work with it
  1988. message = '`anderson` successfully fit the distribution to the data.'
  1989. res = optimize.OptimizeResult(success=True, message=message)
  1990. res.x = np.array(fit_params)
  1991. fit_result = FitResult(getattr(distributions, dist), y,
  1992. discrete=False, res=res)
  1993. if method is None:
  1994. warnings.warn(_anderson_warning_message, FutureWarning, stacklevel=2)
  1995. return AndersonResult(A2, critical, sig, fit_result=fit_result)
  1996. if method == 'interpolate':
  1997. sig = 1 - sig if dist == 'weibull_min' else sig / 100
  1998. pvalue = np.interp(A2, critical, sig)
  1999. elif isinstance(method, stats.MonteCarloMethod):
  2000. pvalue = _anderson_simulate_pvalue(x, dist, method)
  2001. else:
  2002. message = ("`method` must be either 'interpolate' or "
  2003. "an instance of `MonteCarloMethod`.")
  2004. raise ValueError(message)
  2005. return SignificanceResult(statistic=A2, pvalue=pvalue)
  2006. def _anderson_simulate_pvalue(x, dist, method):
  2007. message = ("The `___` attribute of a `MonteCarloMethod` object passed as the "
  2008. "`method` parameter of `scipy.stats.anderson` is ignored.")
  2009. method = method._asdict()
  2010. if method.pop('rvs', False):
  2011. warnings.warn(message.replace('___', 'rvs'), UserWarning, stacklevel=3)
  2012. if method.pop('batch', False):
  2013. warnings.warn(message.replace('___', 'batch'), UserWarning, stacklevel=3)
  2014. method['n_mc_samples'] = method.pop('n_resamples')
  2015. kwargs= {'known_params': {'loc': 0}} if dist == 'expon' else {}
  2016. dist = getattr(stats, dist)
  2017. res = stats.goodness_of_fit(dist, x, statistic='ad', **kwargs, **method)
  2018. return res.pvalue
  2019. def _anderson_ksamp_continuous(samples, Z, Zstar, k, n, N):
  2020. """Compute A2akN equation 3 of Scholz & Stephens.
  2021. Parameters
  2022. ----------
  2023. samples : sequence of 1-D array_like
  2024. Array of sample arrays.
  2025. Z : array_like
  2026. Sorted array of all observations.
  2027. Zstar : array_like
  2028. Sorted array of unique observations. Unused.
  2029. k : int
  2030. Number of samples.
  2031. n : array_like
  2032. Number of observations in each sample.
  2033. N : int
  2034. Total number of observations.
  2035. Returns
  2036. -------
  2037. A2KN : float
  2038. The A2KN statistics of Scholz and Stephens 1987.
  2039. """
  2040. A2kN = 0.
  2041. j = np.arange(1, N)
  2042. for i in arange(0, k):
  2043. s = np.sort(samples[i])
  2044. Mij = s.searchsorted(Z[:-1], side='right')
  2045. inner = (N*Mij - j*n[i])**2 / (j * (N - j))
  2046. A2kN += inner.sum() / n[i]
  2047. return A2kN / N
  2048. def _anderson_ksamp_midrank(samples, Z, Zstar, k, n, N):
  2049. """Compute A2akN equation 7 of Scholz and Stephens.
  2050. Parameters
  2051. ----------
  2052. samples : sequence of 1-D array_like
  2053. Array of sample arrays.
  2054. Z : array_like
  2055. Sorted array of all observations.
  2056. Zstar : array_like
  2057. Sorted array of unique observations.
  2058. k : int
  2059. Number of samples.
  2060. n : array_like
  2061. Number of observations in each sample.
  2062. N : int
  2063. Total number of observations.
  2064. Returns
  2065. -------
  2066. A2aKN : float
  2067. The A2aKN statistics of Scholz and Stephens 1987.
  2068. """
  2069. A2akN = 0.
  2070. Z_ssorted_left = Z.searchsorted(Zstar, 'left')
  2071. if N == Zstar.size:
  2072. lj = 1.
  2073. else:
  2074. lj = Z.searchsorted(Zstar, 'right') - Z_ssorted_left
  2075. Bj = Z_ssorted_left + lj / 2.
  2076. for i in arange(0, k):
  2077. s = np.sort(samples[i])
  2078. s_ssorted_right = s.searchsorted(Zstar, side='right')
  2079. Mij = s_ssorted_right.astype(float)
  2080. fij = s_ssorted_right - s.searchsorted(Zstar, 'left')
  2081. Mij -= fij / 2.
  2082. inner = lj / float(N) * (N*Mij - Bj*n[i])**2 / (Bj*(N - Bj) - N*lj/4.)
  2083. A2akN += inner.sum() / n[i]
  2084. A2akN *= (N - 1.) / N
  2085. return A2akN
  2086. def _anderson_ksamp_right(samples, Z, Zstar, k, n, N):
  2087. """Compute A2akN equation 6 of Scholz & Stephens.
  2088. Parameters
  2089. ----------
  2090. samples : sequence of 1-D array_like
  2091. Array of sample arrays.
  2092. Z : array_like
  2093. Sorted array of all observations.
  2094. Zstar : array_like
  2095. Sorted array of unique observations.
  2096. k : int
  2097. Number of samples.
  2098. n : array_like
  2099. Number of observations in each sample.
  2100. N : int
  2101. Total number of observations.
  2102. Returns
  2103. -------
  2104. A2KN : float
  2105. The A2KN statistics of Scholz and Stephens 1987.
  2106. """
  2107. A2kN = 0.
  2108. lj = Z.searchsorted(Zstar[:-1], 'right') - Z.searchsorted(Zstar[:-1],
  2109. 'left')
  2110. Bj = lj.cumsum()
  2111. for i in arange(0, k):
  2112. s = np.sort(samples[i])
  2113. Mij = s.searchsorted(Zstar[:-1], side='right')
  2114. inner = lj / float(N) * (N * Mij - Bj * n[i])**2 / (Bj * (N - Bj))
  2115. A2kN += inner.sum() / n[i]
  2116. return A2kN
  2117. Anderson_ksampResult = _make_tuple_bunch(
  2118. 'Anderson_ksampResult',
  2119. ['statistic', 'critical_values', 'pvalue'], []
  2120. )
  2121. @xp_capabilities(np_only=True)
  2122. def anderson_ksamp(samples, midrank=_NoValue, *, variant=_NoValue, method=None):
  2123. """The Anderson-Darling test for k-samples.
  2124. The k-sample Anderson-Darling test is a modification of the
  2125. one-sample Anderson-Darling test. It tests the null hypothesis
  2126. that k-samples are drawn from the same population without having
  2127. to specify the distribution function of that population. The
  2128. critical values depend on the number of samples.
  2129. Parameters
  2130. ----------
  2131. samples : sequence of 1-D array_like
  2132. Array of sample data in arrays.
  2133. midrank : bool, optional
  2134. Variant of Anderson-Darling test which is computed. Default
  2135. (True) is the midrank test applicable to continuous and
  2136. discrete populations. If False, the right side empirical
  2137. distribution is used.
  2138. .. deprecated::1.17.0
  2139. Use parameter `variant` instead.
  2140. variant : {'midrank', 'right', 'continuous'}
  2141. Variant of Anderson-Darling test to be computed. ``'midrank'`` is applicable
  2142. to both continuous and discrete populations. ``'discrete'`` and ``'continuous'``
  2143. perform alternative versions of the test for discrete and continuous
  2144. populations, respectively.
  2145. When `variant` is specified, the return object will not be unpackable as a
  2146. tuple, and only attributes ``statistic`` and ``pvalue`` will be present.
  2147. method : PermutationMethod, optional
  2148. Defines the method used to compute the p-value. If `method` is an
  2149. instance of `PermutationMethod`, the p-value is computed using
  2150. `scipy.stats.permutation_test` with the provided configuration options
  2151. and other appropriate settings. Otherwise, the p-value is interpolated
  2152. from tabulated values.
  2153. Returns
  2154. -------
  2155. res : Anderson_ksampResult
  2156. An object containing attributes:
  2157. statistic : float
  2158. Normalized k-sample Anderson-Darling test statistic.
  2159. critical_values : array
  2160. The critical values for significance levels 25%, 10%, 5%, 2.5%, 1%,
  2161. 0.5%, 0.1%.
  2162. .. deprecated::1.17.0
  2163. Present only when `variant` is unspecified.
  2164. pvalue : float
  2165. The approximate p-value of the test. If `method` is not
  2166. provided, the value is floored / capped at 0.1% / 25%.
  2167. Raises
  2168. ------
  2169. ValueError
  2170. If fewer than 2 samples are provided, a sample is empty, or no
  2171. distinct observations are in the samples.
  2172. See Also
  2173. --------
  2174. ks_2samp : 2 sample Kolmogorov-Smirnov test
  2175. anderson : 1 sample Anderson-Darling test
  2176. Notes
  2177. -----
  2178. [1]_ defines three versions of the k-sample Anderson-Darling test:
  2179. one for continuous distributions and two for discrete
  2180. distributions, in which ties between samples may occur. The
  2181. default of this routine is to compute the version based on the
  2182. midrank empirical distribution function. This test is applicable
  2183. to continuous and discrete data. If `variant` is set to ``'discrete'``, the
  2184. right side empirical distribution is used for a test for discrete
  2185. data; if `variant` is ``'continuous'``, the same test statistic and p-value are
  2186. computed for data with no ties, but with less computation. According to [1]_,
  2187. the two discrete test statistics differ only slightly if a few collisions due
  2188. to round-off errors occur in the test not adjusted for ties between samples.
  2189. The critical values corresponding to the significance levels from 0.01
  2190. to 0.25 are taken from [1]_. p-values are floored / capped
  2191. at 0.1% / 25%. Since the range of critical values might be extended in
  2192. future releases, it is recommended not to test ``p == 0.25``, but rather
  2193. ``p >= 0.25`` (analogously for the lower bound).
  2194. .. versionadded:: 0.14.0
  2195. References
  2196. ----------
  2197. .. [1] Scholz, F. W and Stephens, M. A. (1987), K-Sample
  2198. Anderson-Darling Tests, Journal of the American Statistical
  2199. Association, Vol. 82, pp. 918-924.
  2200. Examples
  2201. --------
  2202. >>> import numpy as np
  2203. >>> from scipy import stats
  2204. >>> rng = np.random.default_rng(44925884305279435)
  2205. >>> res = stats.anderson_ksamp([rng.normal(size=50), rng.normal(loc=0.5, size=30)],
  2206. ... variant='midrank')
  2207. >>> res.statistic, res.pvalue
  2208. (3.4444310693448936, 0.013106682406720973)
  2209. The null hypothesis that the two random samples come from the same
  2210. distribution can be rejected at the 5% level because the returned
  2211. p-value is less than 0.05, but not at the 1% level.
  2212. >>> samples = [rng.normal(size=50), rng.normal(size=30),
  2213. ... rng.normal(size=20)]
  2214. >>> res = stats.anderson_ksamp(samples, variant='continuous')
  2215. >>> res.statistic, res.pvalue
  2216. (-0.6309662273193832, 0.25)
  2217. As we might expect, the null hypothesis cannot be rejected here for three samples
  2218. from an identical distribution. The reported p-value (25%) has been capped at the
  2219. maximum value for which pre-computed p-values are available.
  2220. In such cases where the p-value is capped or when sample sizes are
  2221. small, a permutation test may be more accurate.
  2222. >>> method = stats.PermutationMethod(n_resamples=9999, random_state=rng)
  2223. >>> res = stats.anderson_ksamp(samples, variant='continuous', method=method)
  2224. >>> res.pvalue
  2225. 0.699
  2226. """
  2227. k = len(samples)
  2228. if (k < 2):
  2229. raise ValueError("anderson_ksamp needs at least two samples")
  2230. samples = list(map(np.asarray, samples))
  2231. Z = np.sort(np.hstack(samples))
  2232. N = Z.size
  2233. Zstar = np.unique(Z)
  2234. if Zstar.size < 2:
  2235. raise ValueError("anderson_ksamp needs more than one distinct "
  2236. "observation")
  2237. n = np.array([sample.size for sample in samples])
  2238. if np.any(n == 0):
  2239. raise ValueError("anderson_ksamp encountered sample without "
  2240. "observations")
  2241. if variant == _NoValue or midrank != _NoValue:
  2242. message = ("Parameter `variant` has been introduced to replace `midrank`; "
  2243. "`midrank` will be removed in SciPy 1.19.0. Specify `variant` to "
  2244. "silence this warning. Note that the returned object will no longer "
  2245. "be unpackable as a tuple, and `critical_values` will be omitted.")
  2246. warnings.warn(message, category=UserWarning, stacklevel=2)
  2247. return_critical_values = False
  2248. if variant == _NoValue:
  2249. return_critical_values = True
  2250. variant = 'midrank' if midrank else 'right'
  2251. if variant == 'midrank':
  2252. A2kN_fun = _anderson_ksamp_midrank
  2253. elif variant == 'right':
  2254. A2kN_fun = _anderson_ksamp_right
  2255. elif variant == 'continuous':
  2256. A2kN_fun = _anderson_ksamp_continuous
  2257. else:
  2258. message = "`variant` must be one of 'midrank', 'right', or 'continuous'."
  2259. raise ValueError(message)
  2260. A2kN = A2kN_fun(samples, Z, Zstar, k, n, N)
  2261. def statistic(*samples):
  2262. return A2kN_fun(samples, Z, Zstar, k, n, N)
  2263. if method is not None:
  2264. res = stats.permutation_test(samples, statistic, **method._asdict(),
  2265. alternative='greater')
  2266. H = (1. / n).sum()
  2267. hs_cs = (1. / arange(N - 1, 1, -1)).cumsum()
  2268. h = hs_cs[-1] + 1
  2269. g = (hs_cs / arange(2, N)).sum()
  2270. a = (4*g - 6) * (k - 1) + (10 - 6*g)*H
  2271. b = (2*g - 4)*k**2 + 8*h*k + (2*g - 14*h - 4)*H - 8*h + 4*g - 6
  2272. c = (6*h + 2*g - 2)*k**2 + (4*h - 4*g + 6)*k + (2*h - 6)*H + 4*h
  2273. d = (2*h + 6)*k**2 - 4*h*k
  2274. sigmasq = (a*N**3 + b*N**2 + c*N + d) / ((N - 1.) * (N - 2.) * (N - 3.))
  2275. m = k - 1
  2276. A2 = (A2kN - m) / math.sqrt(sigmasq)
  2277. # The b_i values are the interpolation coefficients from Table 2
  2278. # of Scholz and Stephens 1987
  2279. b0 = np.array([0.675, 1.281, 1.645, 1.96, 2.326, 2.573, 3.085])
  2280. b1 = np.array([-0.245, 0.25, 0.678, 1.149, 1.822, 2.364, 3.615])
  2281. b2 = np.array([-0.105, -0.305, -0.362, -0.391, -0.396, -0.345, -0.154])
  2282. critical = b0 + b1 / math.sqrt(m) + b2 / m
  2283. sig = np.array([0.25, 0.1, 0.05, 0.025, 0.01, 0.005, 0.001])
  2284. if A2 < critical.min() and method is None:
  2285. p = sig.max()
  2286. msg = (f"p-value capped: true value larger than {p}. Consider "
  2287. "specifying `method` "
  2288. "(e.g. `method=stats.PermutationMethod()`.)")
  2289. warnings.warn(msg, stacklevel=2)
  2290. elif A2 > critical.max() and method is None:
  2291. p = sig.min()
  2292. msg = (f"p-value floored: true value smaller than {p}. Consider "
  2293. "specifying `method` "
  2294. "(e.g. `method=stats.PermutationMethod()`.)")
  2295. warnings.warn(msg, stacklevel=2)
  2296. elif method is None:
  2297. # interpolation of probit of significance level
  2298. pf = np.polyfit(critical, log(sig), 2)
  2299. p = math.exp(np.polyval(pf, A2))
  2300. else:
  2301. p = res.pvalue if method is not None else p
  2302. if return_critical_values:
  2303. # create result object with alias for backward compatibility
  2304. res = Anderson_ksampResult(A2, critical, p)
  2305. res.significance_level = p
  2306. else:
  2307. res = SignificanceResult(statistic=A2, pvalue=p)
  2308. return res
  2309. AnsariResult = namedtuple('AnsariResult', ('statistic', 'pvalue'))
  2310. class _ABW:
  2311. """Distribution of Ansari-Bradley W-statistic under the null hypothesis."""
  2312. # TODO: calculate exact distribution considering ties
  2313. # We could avoid summing over more than half the frequencies,
  2314. # but initially it doesn't seem worth the extra complexity
  2315. def __init__(self):
  2316. """Minimal initializer."""
  2317. self.m = None
  2318. self.n = None
  2319. self.astart = None
  2320. self.total = None
  2321. self.freqs = None
  2322. def _recalc(self, n, m):
  2323. """When necessary, recalculate exact distribution."""
  2324. if n != self.n or m != self.m:
  2325. self.n, self.m = n, m
  2326. # distribution is NOT symmetric when m + n is odd
  2327. # n is len(x), m is len(y), and ratio of scales is defined x/y
  2328. astart, a1, _ = gscale(n, m)
  2329. self.astart = astart # minimum value of statistic
  2330. # Exact distribution of test statistic under null hypothesis
  2331. # expressed as frequencies/counts/integers to maintain precision.
  2332. # Stored as floats to avoid overflow of sums.
  2333. self.freqs = a1.astype(np.float64)
  2334. self.total = self.freqs.sum() # could calculate from m and n
  2335. # probability mass is self.freqs / self.total;
  2336. def pmf(self, k, n, m):
  2337. """Probability mass function."""
  2338. self._recalc(n, m)
  2339. # The convention here is that PMF at k = 12.5 is the same as at k = 12,
  2340. # -> use `floor` in case of ties.
  2341. ind = np.floor(k - self.astart).astype(int)
  2342. return self.freqs[ind] / self.total
  2343. def cdf(self, k, n, m):
  2344. """Cumulative distribution function."""
  2345. self._recalc(n, m)
  2346. # Null distribution derived without considering ties is
  2347. # approximate. Round down to avoid Type I error.
  2348. ind = np.ceil(k - self.astart).astype(int)
  2349. return self.freqs[:ind+1].sum() / self.total
  2350. def sf(self, k, n, m):
  2351. """Survival function."""
  2352. self._recalc(n, m)
  2353. # Null distribution derived without considering ties is
  2354. # approximate. Round down to avoid Type I error.
  2355. ind = np.floor(k - self.astart).astype(int)
  2356. return self.freqs[ind:].sum() / self.total
  2357. # Maintain state for faster repeat calls to ansari w/ method='exact'
  2358. # _ABW() is calculated once per thread and stored as an attribute on
  2359. # this thread-local variable inside ansari().
  2360. _abw_state = threading.local()
  2361. @xp_capabilities(cpu_only=True, jax_jit=False, # p-value is Cython
  2362. skip_backends=[('dask.array', 'no rankdata')])
  2363. @_axis_nan_policy_factory(AnsariResult, n_samples=2)
  2364. def ansari(x, y, alternative='two-sided', *, axis=0):
  2365. """Perform the Ansari-Bradley test for equal scale parameters.
  2366. The Ansari-Bradley test ([1]_, [2]_) is a non-parametric test
  2367. for the equality of the scale parameter of the distributions
  2368. from which two samples were drawn. The null hypothesis states that
  2369. the ratio of the scale of the distribution underlying `x` to the scale
  2370. of the distribution underlying `y` is 1.
  2371. Parameters
  2372. ----------
  2373. x, y : array_like
  2374. Arrays of sample data.
  2375. alternative : {'two-sided', 'less', 'greater'}, optional
  2376. Defines the alternative hypothesis. Default is 'two-sided'.
  2377. The following options are available:
  2378. * 'two-sided': the ratio of scales is not equal to 1.
  2379. * 'less': the ratio of scales is less than 1.
  2380. * 'greater': the ratio of scales is greater than 1.
  2381. .. versionadded:: 1.7.0
  2382. axis : int or tuple of ints, default: 0
  2383. If an int or tuple of ints, the axis or axes of the input along which
  2384. to compute the statistic. The statistic of each axis-slice (e.g. row)
  2385. of the input will appear in a corresponding element of the output.
  2386. If ``None``, the input will be raveled before computing the statistic.
  2387. Returns
  2388. -------
  2389. statistic : float
  2390. The Ansari-Bradley test statistic.
  2391. pvalue : float
  2392. The p-value of the hypothesis test.
  2393. See Also
  2394. --------
  2395. fligner : A non-parametric test for the equality of k variances
  2396. mood : A non-parametric test for the equality of two scale parameters
  2397. Notes
  2398. -----
  2399. The p-value given is exact when the sample sizes are both less than
  2400. 55 and there are no ties, otherwise a normal approximation for the
  2401. p-value is used.
  2402. References
  2403. ----------
  2404. .. [1] Ansari, A. R. and Bradley, R. A. (1960) Rank-sum tests for
  2405. dispersions, Annals of Mathematical Statistics, 31, 1174-1189.
  2406. .. [2] Sprent, Peter and N.C. Smeeton. Applied nonparametric
  2407. statistical methods. 3rd ed. Chapman and Hall/CRC. 2001.
  2408. Section 5.8.2.
  2409. .. [3] Nathaniel E. Helwig "Nonparametric Dispersion and Equality
  2410. Tests" at http://users.stat.umn.edu/~helwig/notes/npde-Notes.pdf
  2411. Examples
  2412. --------
  2413. >>> import numpy as np
  2414. >>> from scipy.stats import ansari
  2415. >>> rng = np.random.default_rng()
  2416. For these examples, we'll create three random data sets. The first
  2417. two, with sizes 35 and 25, are drawn from a normal distribution with
  2418. mean 0 and standard deviation 2. The third data set has size 25 and
  2419. is drawn from a normal distribution with standard deviation 1.25.
  2420. >>> x1 = rng.normal(loc=0, scale=2, size=35)
  2421. >>> x2 = rng.normal(loc=0, scale=2, size=25)
  2422. >>> x3 = rng.normal(loc=0, scale=1.25, size=25)
  2423. First we apply `ansari` to `x1` and `x2`. These samples are drawn
  2424. from the same distribution, so we expect the Ansari-Bradley test
  2425. should not lead us to conclude that the scales of the distributions
  2426. are different.
  2427. >>> ansari(x1, x2)
  2428. AnsariResult(statistic=541.0, pvalue=0.9762532927399098)
  2429. With a p-value close to 1, we cannot conclude that there is a
  2430. significant difference in the scales (as expected).
  2431. Now apply the test to `x1` and `x3`:
  2432. >>> ansari(x1, x3)
  2433. AnsariResult(statistic=425.0, pvalue=0.0003087020407974518)
  2434. The probability of observing such an extreme value of the statistic
  2435. under the null hypothesis of equal scales is only 0.03087%. We take this
  2436. as evidence against the null hypothesis in favor of the alternative:
  2437. the scales of the distributions from which the samples were drawn
  2438. are not equal.
  2439. We can use the `alternative` parameter to perform a one-tailed test.
  2440. In the above example, the scale of `x1` is greater than `x3` and so
  2441. the ratio of scales of `x1` and `x3` is greater than 1. This means
  2442. that the p-value when ``alternative='greater'`` should be near 0 and
  2443. hence we should be able to reject the null hypothesis:
  2444. >>> ansari(x1, x3, alternative='greater')
  2445. AnsariResult(statistic=425.0, pvalue=0.0001543510203987259)
  2446. As we can see, the p-value is indeed quite low. Use of
  2447. ``alternative='less'`` should thus yield a large p-value:
  2448. >>> ansari(x1, x3, alternative='less')
  2449. AnsariResult(statistic=425.0, pvalue=0.9998643258449039)
  2450. """
  2451. xp = array_namespace(x, y)
  2452. dtype = xp_result_type(x, y, force_floating=True, xp=xp)
  2453. if alternative not in {'two-sided', 'greater', 'less'}:
  2454. raise ValueError("'alternative' must be 'two-sided',"
  2455. " 'greater', or 'less'.")
  2456. if not hasattr(_abw_state, 'a'):
  2457. _abw_state.a = _ABW()
  2458. # _axis_nan_policy decorator guarantees that axis=-1
  2459. n = x.shape[-1]
  2460. m = y.shape[-1]
  2461. if m < 1: # needed by test_axis_nan_policy; not user-facing
  2462. raise ValueError("Not enough other observations.")
  2463. if n < 1:
  2464. raise ValueError("Not enough test observations.")
  2465. N = m + n
  2466. xy = xp.concat([x, y], axis=-1) # combine
  2467. rank, t = _stats_py._rankdata(xy, method='average', return_ties=True)
  2468. rank, t = xp.astype(rank, dtype), xp.astype(t, dtype)
  2469. symrank = xp.minimum(rank, N - rank + 1)
  2470. AB = xp.sum(symrank[..., :n], axis=-1)
  2471. repeats = xp.any(t > 1) # in theory we could branch for each slice separately
  2472. exact = ((m < 55) and (n < 55) and not repeats)
  2473. if exact:
  2474. # np.vectorize converts to NumPy here, and we convert back to the result
  2475. # type before returning
  2476. cdf = np.vectorize(_abw_state.a.cdf, otypes=[np.float64])
  2477. sf = np.vectorize(_abw_state.a.sf, otypes=[np.float64])
  2478. if alternative == 'two-sided':
  2479. pval = 2.0 * np.minimum(cdf(AB, n, m),
  2480. sf(AB, n, m))
  2481. elif alternative == 'greater':
  2482. # AB statistic is _smaller_ when ratio of scales is larger,
  2483. # so this is the opposite of the usual calculation
  2484. pval = cdf(AB, n, m)
  2485. else:
  2486. pval = sf(AB, n, m)
  2487. pval = xp.clip(xp.asarray(pval, dtype=dtype), max=1.0)
  2488. AB = AB[()] if AB.ndim == 0 else AB
  2489. pval = pval[()] if pval.ndim == 0 else pval
  2490. return AnsariResult(AB, pval)
  2491. mnAB = (n * (N + 1.0) ** 2 / 4.0 / N) if N % 2 else (n * (N + 2.0) / 4.0)
  2492. if repeats: # adjust variance estimates
  2493. # compute np.sum(tj * rj**2,axis=0)
  2494. fac = xp.sum(symrank**2, axis=-1)
  2495. if N % 2: # N odd
  2496. varAB = m * n * (16*N*fac - (N+1)**4) / (16.0 * N**2 * (N-1))
  2497. else: # N even
  2498. varAB = m * n * (16*fac - N*(N+2)**2) / (16.0 * N * (N-1))
  2499. else:
  2500. # otherwise compute normal approximation
  2501. if N % 2: # N odd
  2502. varAB = n * m * (N + 1.0) * (3 + N ** 2) / (48.0 * N ** 2)
  2503. else:
  2504. varAB = m * n * (N + 2) * (N - 2.0) / 48 / (N - 1.0)
  2505. varAB = xp.asarray(varAB, dtype=dtype)
  2506. # Small values of AB indicate larger dispersion for the x sample.
  2507. # Large values of AB indicate larger dispersion for the y sample.
  2508. # This is opposite to the way we define the ratio of scales. see [1]_.
  2509. z = (mnAB - AB) / xp.sqrt(varAB)
  2510. pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=xp)
  2511. AB = AB[()] if AB.ndim == 0 else AB
  2512. pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
  2513. return AnsariResult(AB, pvalue)
  2514. BartlettResult = namedtuple('BartlettResult', ('statistic', 'pvalue'))
  2515. @xp_capabilities()
  2516. @_axis_nan_policy_factory(BartlettResult, n_samples=None)
  2517. def bartlett(*samples, axis=0):
  2518. r"""Perform Bartlett's test for equal variances.
  2519. Bartlett's test tests the null hypothesis that all input samples
  2520. are from populations with equal variances. For samples
  2521. from significantly non-normal populations, Levene's test
  2522. `levene` is more robust.
  2523. Parameters
  2524. ----------
  2525. sample1, sample2, ... : array_like
  2526. arrays of sample data. Only 1d arrays are accepted, they may have
  2527. different lengths.
  2528. Returns
  2529. -------
  2530. statistic : float
  2531. The test statistic.
  2532. pvalue : float
  2533. The p-value of the test.
  2534. See Also
  2535. --------
  2536. fligner : A non-parametric test for the equality of k variances
  2537. levene : A robust parametric test for equality of k variances
  2538. :ref:`hypothesis_bartlett` : Extended example
  2539. Notes
  2540. -----
  2541. Conover et al. (1981) examine many of the existing parametric and
  2542. nonparametric tests by extensive simulations and they conclude that the
  2543. tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be
  2544. superior in terms of robustness of departures from normality and power
  2545. ([3]_).
  2546. References
  2547. ----------
  2548. .. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm
  2549. .. [2] Snedecor, George W. and Cochran, William G. (1989), Statistical
  2550. Methods, Eighth Edition, Iowa State University Press.
  2551. .. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
  2552. Hypothesis Testing based on Quadratic Inference Function. Technical
  2553. Report #99-03, Center for Likelihood Studies, Pennsylvania State
  2554. University.
  2555. .. [4] Bartlett, M. S. (1937). Properties of Sufficiency and Statistical
  2556. Tests. Proceedings of the Royal Society of London. Series A,
  2557. Mathematical and Physical Sciences, Vol. 160, No.901, pp. 268-282.
  2558. Examples
  2559. --------
  2560. Test whether the lists `a`, `b` and `c` come from populations
  2561. with equal variances.
  2562. >>> import numpy as np
  2563. >>> from scipy import stats
  2564. >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
  2565. >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
  2566. >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
  2567. >>> stat, p = stats.bartlett(a, b, c)
  2568. >>> p
  2569. 1.1254782518834628e-05
  2570. The very small p-value suggests that the populations do not have equal
  2571. variances.
  2572. This is not surprising, given that the sample variance of `b` is much
  2573. larger than that of `a` and `c`:
  2574. >>> [np.var(x, ddof=1) for x in [a, b, c]]
  2575. [0.007054444444444413, 0.13073888888888888, 0.008890000000000002]
  2576. For a more detailed example, see :ref:`hypothesis_bartlett`.
  2577. """
  2578. xp = array_namespace(*samples)
  2579. k = len(samples)
  2580. if k < 2:
  2581. raise ValueError("Must enter at least two input sample vectors.")
  2582. if axis is None:
  2583. samples = [xp_ravel(sample) for sample in samples]
  2584. else:
  2585. samples = _broadcast_arrays(samples, axis=axis, xp=xp)
  2586. samples = [xp.moveaxis(sample, axis, -1) for sample in samples]
  2587. Ni = [xp.asarray(_length_nonmasked(sample, axis=-1, xp=xp),
  2588. dtype=sample.dtype, device=xp_device(sample))
  2589. for sample in samples]
  2590. Ni = [xp.broadcast_to(N, samples[0].shape[:-1]) for N in Ni]
  2591. ssq = [xp.var(sample, correction=1, axis=-1) for sample in samples]
  2592. Ni = [arr[xp.newaxis, ...] for arr in Ni]
  2593. ssq = [arr[xp.newaxis, ...] for arr in ssq]
  2594. Ni = xp.concat(Ni, axis=0)
  2595. Ni = xpx.at(Ni)[Ni == 0].set(xp.nan)
  2596. ssq = xp.concat(ssq, axis=0)
  2597. dtype = Ni.dtype
  2598. Ntot = xp.sum(Ni, axis=0)
  2599. spsq = xp.sum((Ni - 1)*ssq, axis=0, dtype=dtype) / (Ntot - k)
  2600. numer = ((Ntot - k) * xp.log(spsq)
  2601. - xp.sum((Ni - 1)*xp.log(ssq), axis=0, dtype=dtype))
  2602. denom = (1 + 1/(3*(k - 1))
  2603. * ((xp.sum(1/(Ni - 1), axis=0)) - 1/(Ntot - k)))
  2604. T = numer / denom
  2605. chi2 = _SimpleChi2(xp.asarray(k-1, dtype=dtype, device=xp_device(T)))
  2606. pvalue = _get_pvalue(T, chi2, alternative='greater', symmetric=False, xp=xp)
  2607. T = xp.clip(T, min=0., max=xp.inf)
  2608. T = T[()] if T.ndim == 0 else T
  2609. pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
  2610. return BartlettResult(T, pvalue)
  2611. LeveneResult = namedtuple('LeveneResult', ('statistic', 'pvalue'))
  2612. @xp_capabilities(cpu_only=True, exceptions=['cupy'])
  2613. @_axis_nan_policy_factory(LeveneResult, n_samples=None)
  2614. def levene(*samples, center='median', proportiontocut=0.05, axis=0):
  2615. r"""Perform Levene test for equal variances.
  2616. The Levene test tests the null hypothesis that all input samples
  2617. are from populations with equal variances. Levene's test is an
  2618. alternative to Bartlett's test `bartlett` in the case where
  2619. there are significant deviations from normality.
  2620. Parameters
  2621. ----------
  2622. sample1, sample2, ... : array_like
  2623. The sample data, possibly with different lengths.
  2624. center : {'mean', 'median', 'trimmed'}, optional
  2625. Which statistics to use to center data points within each sample. Default
  2626. is 'median'.
  2627. proportiontocut : float, optional
  2628. When `center` is 'trimmed', this gives the proportion of data points
  2629. to cut from each end. (See `scipy.stats.trim_mean`.)
  2630. Default is 0.05.
  2631. axis : int or tuple of ints, default: 0
  2632. If an int or tuple of ints, the axis or axes of the input along which
  2633. to compute the statistic. The statistic of each axis-slice (e.g. row)
  2634. of the input will appear in a corresponding element of the output.
  2635. If ``None``, the input will be raveled before computing the statistic.
  2636. Returns
  2637. -------
  2638. statistic : float
  2639. The test statistic.
  2640. pvalue : float
  2641. The p-value for the test.
  2642. See Also
  2643. --------
  2644. fligner : A non-parametric test for the equality of k variances
  2645. bartlett : A parametric test for equality of k variances in normal samples
  2646. :ref:`hypothesis_levene` : Extended example
  2647. Notes
  2648. -----
  2649. Three variations of Levene's test are possible. The possibilities
  2650. and their recommended usages are:
  2651. * 'median' : Recommended for skewed (non-normal) distributions>
  2652. * 'mean' : Recommended for symmetric, moderate-tailed distributions.
  2653. * 'trimmed' : Recommended for heavy-tailed distributions.
  2654. The test version using the mean was proposed in the original article
  2655. of Levene ([2]_) while the median and trimmed mean have been studied by
  2656. Brown and Forsythe ([3]_), sometimes also referred to as Brown-Forsythe
  2657. test.
  2658. References
  2659. ----------
  2660. .. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm
  2661. .. [2] Levene, H. (1960). In Contributions to Probability and Statistics:
  2662. Essays in Honor of Harold Hotelling, I. Olkin et al. eds.,
  2663. Stanford University Press, pp. 278-292.
  2664. .. [3] Brown, M. B. and Forsythe, A. B. (1974), Journal of the American
  2665. Statistical Association, 69, 364-367
  2666. Examples
  2667. --------
  2668. Test whether the lists `a`, `b` and `c` come from populations
  2669. with equal variances.
  2670. >>> import numpy as np
  2671. >>> from scipy import stats
  2672. >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
  2673. >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
  2674. >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
  2675. >>> stat, p = stats.levene(a, b, c)
  2676. >>> p
  2677. 0.002431505967249681
  2678. The small p-value suggests that the populations do not have equal
  2679. variances.
  2680. This is not surprising, given that the sample variance of `b` is much
  2681. larger than that of `a` and `c`:
  2682. >>> [np.var(x, ddof=1) for x in [a, b, c]]
  2683. [0.007054444444444413, 0.13073888888888888, 0.008890000000000002]
  2684. For a more detailed example, see :ref:`hypothesis_levene`.
  2685. """
  2686. xp = array_namespace(*samples)
  2687. if center not in ['mean', 'median', 'trimmed']:
  2688. raise ValueError("center must be 'mean', 'median' or 'trimmed'.")
  2689. k = len(samples)
  2690. if k < 2:
  2691. raise ValueError("Must provide at least two samples.")
  2692. if center == 'median':
  2693. def func(x):
  2694. return (xp.median(x, axis=-1, keepdims=True)
  2695. if (is_numpy(xp) or is_dask(xp))
  2696. else stats.quantile(x, 0.5, axis=-1, keepdims=True))
  2697. elif center == 'mean':
  2698. def func(x):
  2699. return xp.mean(x, axis=-1, keepdims=True)
  2700. else: # center == 'trimmed'
  2701. def func(x):
  2702. # keepdims=True doesn't currently work for lazy arrays
  2703. return _stats_py.trim_mean(x, proportiontocut, axis=-1)[..., xp.newaxis]
  2704. Nis = [sample.shape[-1] for sample in samples]
  2705. Ycis = [func(sample) for sample in samples]
  2706. Ntot = sum(Nis)
  2707. # compute Zij's
  2708. Zijs = [xp.abs(sample - Yc) for sample, Yc in zip(samples, Ycis)]
  2709. # compute Zbari
  2710. Zbaris = [xp.mean(Zij, axis=-1, keepdims=True) for Zij in Zijs]
  2711. Zbar = sum(Ni*Zbari for Ni, Zbari in zip(Nis, Zbaris)) / Ntot
  2712. # compute numerator and denominator
  2713. dfd = (Ntot - k)
  2714. numer = dfd * sum(Ni * (Zbari - Zbar)**2
  2715. for Ni, Zbari in zip(Nis, Zbaris))
  2716. dfn = (k - 1.0)
  2717. denom = dfn * sum(xp.sum((Zij - Zbari)**2, axis=-1, keepdims=True)
  2718. for Zij, Zbari in zip(Zijs, Zbaris))
  2719. W = numer / denom
  2720. W = xp.squeeze(W, axis=-1)
  2721. dfn, dfd = xp.asarray(dfn, dtype=W.dtype), xp.asarray(dfd, dtype=W.dtype)
  2722. pval = _get_pvalue(W, _SimpleF(dfn, dfd), 'greater', xp=xp)
  2723. return LeveneResult(W[()], pval[()])
  2724. FlignerResult = namedtuple('FlignerResult', ('statistic', 'pvalue'))
  2725. @xp_capabilities(skip_backends=[('dask.array', 'no rankdata'),
  2726. ('cupy', 'no rankdata')], jax_jit=False)
  2727. @_axis_nan_policy_factory(FlignerResult, n_samples=None)
  2728. def fligner(*samples, center='median', proportiontocut=0.05, axis=0):
  2729. r"""Perform Fligner-Killeen test for equality of variance.
  2730. Fligner's test tests the null hypothesis that all input samples
  2731. are from populations with equal variances. Fligner-Killeen's test is
  2732. distribution free when populations are identical [2]_.
  2733. Parameters
  2734. ----------
  2735. sample1, sample2, ... : array_like
  2736. Arrays of sample data. Need not be the same length.
  2737. center : {'mean', 'median', 'trimmed'}, optional
  2738. Which statistics to use to center data points within each sample. Default
  2739. is 'median'.
  2740. proportiontocut : float, optional
  2741. When `center` is 'trimmed', this gives the proportion of data points
  2742. to cut from each end. (See `scipy.stats.trim_mean`.)
  2743. Default is 0.05.
  2744. axis : int or tuple of ints, default: 0
  2745. If an int or tuple of ints, the axis or axes of the input along which
  2746. to compute the statistic. The statistic of each axis-slice (e.g. row)
  2747. of the input will appear in a corresponding element of the output.
  2748. If ``None``, the input will be raveled before computing the statistic.
  2749. Returns
  2750. -------
  2751. statistic : float
  2752. The test statistic.
  2753. pvalue : float
  2754. The p-value for the hypothesis test.
  2755. See Also
  2756. --------
  2757. bartlett : A parametric test for equality of k variances in normal samples
  2758. levene : A robust parametric test for equality of k variances
  2759. :ref:`hypothesis_fligner` : Extended example
  2760. Notes
  2761. -----
  2762. As with Levene's test there are three variants of Fligner's test that
  2763. differ by the measure of central tendency used in the test. See `levene`
  2764. for more information.
  2765. Conover et al. (1981) examine many of the existing parametric and
  2766. nonparametric tests by extensive simulations and they conclude that the
  2767. tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be
  2768. superior in terms of robustness of departures from normality and power
  2769. [3]_.
  2770. References
  2771. ----------
  2772. .. [1] Qu, A., Lindsay, B. G., and Li, B. (2000). Improving generalized
  2773. estimating equations using quadratic inference functions.
  2774. Biometrika, 87(4), 823-836.
  2775. :doi:`10.1093/biomet/87.4.823`
  2776. .. [2] Fligner, M.A. and Killeen, T.J. (1976). Distribution-free two-sample
  2777. tests for scale. Journal of the American Statistical Association.
  2778. 71(353), 210-213.
  2779. .. [3] Conover, W. J., Johnson, M. E. and Johnson M. M. (1981). A
  2780. comparative study of tests for homogeneity of variances, with
  2781. applications to the outer continental shelf bidding data.
  2782. Technometrics, 23(4), 351-361.
  2783. Examples
  2784. --------
  2785. >>> import numpy as np
  2786. >>> from scipy import stats
  2787. Test whether the lists `a`, `b` and `c` come from populations
  2788. with equal variances.
  2789. >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
  2790. >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
  2791. >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
  2792. >>> stat, p = stats.fligner(a, b, c)
  2793. >>> p
  2794. 0.00450826080004775
  2795. The small p-value suggests that the populations do not have equal
  2796. variances.
  2797. This is not surprising, given that the sample variance of `b` is much
  2798. larger than that of `a` and `c`:
  2799. >>> [np.var(x, ddof=1) for x in [a, b, c]]
  2800. [0.007054444444444413, 0.13073888888888888, 0.008890000000000002]
  2801. For a more detailed example, see :ref:`hypothesis_fligner`.
  2802. """
  2803. xp = array_namespace(*samples)
  2804. if center not in ['mean', 'median', 'trimmed']:
  2805. raise ValueError("center must be 'mean', 'median' or 'trimmed'.")
  2806. k = len(samples)
  2807. if k < 2:
  2808. raise ValueError("Must provide at least two samples.")
  2809. samples = xp_promote(*samples, force_floating=True, xp=xp)
  2810. dtype = samples[0].dtype
  2811. # Handle empty input
  2812. for sample in samples:
  2813. if sample.size == 0:
  2814. NaN = _get_nan(*samples, xp=xp)
  2815. return FlignerResult(NaN, NaN)
  2816. if center == 'median':
  2817. def func(x):
  2818. return (xp.median(x, axis=-1, keepdims=True)
  2819. if (is_numpy(xp) or is_dask(xp))
  2820. else stats.quantile(x, 0.5, axis=-1, keepdims=True))
  2821. elif center == 'mean':
  2822. def func(x):
  2823. return xp.mean(x, axis=-1, keepdims=True)
  2824. else: # center == 'trimmed'
  2825. def func(x):
  2826. # keepdims=True doesn't currently work for lazy arrays
  2827. return _stats_py.trim_mean(x, proportiontocut, axis=-1)[..., xp.newaxis]
  2828. ni = [sample.shape[-1] for sample in samples]
  2829. N = sum(ni)
  2830. # Implementation follows [3] pg 355 F-K.
  2831. Xibar = [func(sample) for sample in samples]
  2832. Xij_Xibar = [xp.abs(sample - Xibar_) for sample, Xibar_ in zip(samples, Xibar)]
  2833. Xij_Xibar = xp.concat(Xij_Xibar, axis=-1)
  2834. ranks = _stats_py._rankdata(Xij_Xibar, method='average', xp=xp)
  2835. ranks = xp.astype(ranks, dtype)
  2836. a_Ni = special.ndtri(ranks / (2*(N + 1.0)) + 0.5)
  2837. # [3] Equation 2.1
  2838. splits = list(itertools.accumulate(ni, initial=0))
  2839. Ai = [a_Ni[..., i:j] for i, j in zip(splits[:-1], splits[1:])]
  2840. Aibar = [xp.mean(Ai_, axis=-1) for Ai_ in Ai]
  2841. abar = xp.mean(a_Ni, axis=-1)
  2842. V2 = xp.var(a_Ni, axis=-1, correction=1)
  2843. statistic = sum(ni_ * (Aibar_ - abar)**2 for ni_, Aibar_ in zip(ni, Aibar)) / V2
  2844. chi2 = _SimpleChi2(xp.asarray(k-1, dtype=dtype))
  2845. pval = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp)
  2846. return FlignerResult(statistic, pval)
  2847. def _mood_statistic_with_ties(x, y, t, m, n, N, xp):
  2848. # First equation of "Mood's Squared Rank Test", Mielke pg 313
  2849. E_0_T = m * (N * N - 1) / 12
  2850. # m, n, N, t, and S are defined in the second paragraph of Mielke pg 312
  2851. # The only difference is that our `t` has zeros interspersed with the relevant
  2852. # numbers to keep the array rectangular, but these terms add nothing to the sum.
  2853. S = xp.cumulative_sum(t, include_initial=True, axis=-1)
  2854. S_i, S_i_m1 = S[..., 1:], S[..., :-1]
  2855. # Second equation of "Mood's Squared Rank Test", Mielke pg 313
  2856. varM = (m * n * (N + 1.0) * (N**2 - 4) / 180
  2857. - m * n / (180 * N * (N - 1))
  2858. * xp.sum(t * (t ** 2 - 1) * (t ** 2 - 4 + (15 * (N - S_i - S_i_m1) ** 2)),
  2859. axis=-1))
  2860. # There is a formula for Phi (`phi` in code) in terms of t, S, and Psi(I) at the
  2861. # bottom of Mielke pg 312. Psi(I) = [I - (N+1)/2]^2 is defined (with a mistake in
  2862. # the location of the ^2) at the beginning of "Mood's Squared Rank Test" (pg 313).
  2863. # To vectorize this calculation, let c = (N + 1) / 2, so Psi(I) = I^2 - 2*c*I + c^2.
  2864. # We sum each of these three parts of Psi separately using formulas for sums from a
  2865. # to b (inclusive) of terms I^2, I, and 1 where I takes on successive integers.
  2866. def sum_I2(a, b=None):
  2867. return (a * (a + 1) * (2 * a + 1) / 6 if b is None
  2868. else sum_I2(b) - sum_I2(a) + a**2)
  2869. def sum_I(a, b=None):
  2870. return (a * (a + 1) / 2 if b is None
  2871. else sum_I(b) - sum_I(a) + a)
  2872. def sum_1(a, b):
  2873. return (b - a) + 1
  2874. with np.errstate(invalid='ignore', divide='ignore'):
  2875. sum_I2 = sum_I2(S_i_m1 + 1, S_i)
  2876. sum_I = sum_I(S_i_m1 + 1, S_i)
  2877. sum_1 = sum_1(S_i_m1 + 1, S_i)
  2878. c = (N + 1) / 2
  2879. phi = (sum_I2 - 2*c*sum_I + sum_1*c**2) / t
  2880. phi = xpx.at(phi)[t == 0].set(0.) # where t = 0 we get NaNs; eliminate them
  2881. # Mielke pg 312 defines `a` as the count of elements in sample `x` for each of the
  2882. # unique values in the combined sample. The tricky thing is getting these to line
  2883. # up with the locations of nonzero elements in `t`/`phi`.
  2884. x = xp.sort(x, axis=-1)
  2885. xy = xp.concat((x, y), axis=-1)
  2886. i = xp.argsort(xy, stable=True, axis=-1)
  2887. _, a = _stats_py._rankdata(x, method='average', return_ties=True)
  2888. a = xp.astype(a, phi.dtype)
  2889. zeros = xp.zeros(a.shape[:-1] + (n,), dtype=a.dtype)
  2890. a = xp.concat((a, zeros), axis=-1)
  2891. a = xp.take_along_axis(a, i, axis=-1)
  2892. # Mielke pg 312 defines test statistic `T` as the inner product `a` and `phi`
  2893. T = xp.vecdot(a, phi, axis=-1)
  2894. return (T - E_0_T) / xp.sqrt(varM)
  2895. def _mood_statistic_no_ties(r, m, n, N, xp):
  2896. rx = r[..., :m]
  2897. M = xp.sum((rx - (N + 1.0) / 2) ** 2, axis=-1)
  2898. E_0_T = m * (N * N - 1.0) / 12
  2899. varM = m * n * (N + 1.0) * (N + 2) * (N - 2) / 180
  2900. return (M - E_0_T) / math.sqrt(varM)
  2901. def _mood_too_small(samples, kwargs, axis=-1):
  2902. x, y = samples
  2903. m = x.shape[axis]
  2904. n = y.shape[axis]
  2905. N = m + n
  2906. return N < 3
  2907. @xp_capabilities(skip_backends=[('cupy', 'no rankdata'), ('dask.array', 'no rankdata')])
  2908. @_axis_nan_policy_factory(SignificanceResult, n_samples=2, too_small=_mood_too_small)
  2909. def mood(x, y, axis=0, alternative="two-sided"):
  2910. """Perform Mood's test for equal scale parameters.
  2911. Mood's two-sample test for scale parameters is a non-parametric
  2912. test for the null hypothesis that two samples are drawn from the
  2913. same distribution with the same scale parameter.
  2914. Parameters
  2915. ----------
  2916. x, y : array_like
  2917. Arrays of sample data. There must be at least three observations
  2918. total.
  2919. axis : int, optional
  2920. The axis along which the samples are tested. `x` and `y` can be of
  2921. different length along `axis`.
  2922. If `axis` is None, `x` and `y` are flattened and the test is done on
  2923. all values in the flattened arrays.
  2924. alternative : {'two-sided', 'less', 'greater'}, optional
  2925. Defines the alternative hypothesis. Default is 'two-sided'.
  2926. The following options are available:
  2927. * 'two-sided': the scales of the distributions underlying `x` and `y`
  2928. are different.
  2929. * 'less': the scale of the distribution underlying `x` is less than
  2930. the scale of the distribution underlying `y`.
  2931. * 'greater': the scale of the distribution underlying `x` is greater
  2932. than the scale of the distribution underlying `y`.
  2933. .. versionadded:: 1.7.0
  2934. Returns
  2935. -------
  2936. res : SignificanceResult
  2937. An object containing attributes:
  2938. statistic : scalar or ndarray
  2939. The z-score for the hypothesis test. For 1-D inputs a scalar is
  2940. returned.
  2941. pvalue : scalar ndarray
  2942. The p-value for the hypothesis test.
  2943. See Also
  2944. --------
  2945. fligner : A non-parametric test for the equality of k variances
  2946. ansari : A non-parametric test for the equality of 2 variances
  2947. bartlett : A parametric test for equality of k variances in normal samples
  2948. levene : A parametric test for equality of k variances
  2949. Notes
  2950. -----
  2951. The data are assumed to be drawn from probability distributions ``f(x)``
  2952. and ``f(x/s) / s`` respectively, for some probability density function f.
  2953. The null hypothesis is that ``s == 1``.
  2954. For multi-dimensional arrays, if the inputs are of shapes
  2955. ``(n0, n1, n2, n3)`` and ``(n0, m1, n2, n3)``, then if ``axis=1``, the
  2956. resulting z and p values will have shape ``(n0, n2, n3)``. Note that
  2957. ``n1`` and ``m1`` don't have to be equal, but the other dimensions do.
  2958. References
  2959. ----------
  2960. [1] Mielke, Paul W. "Note on Some Squared Rank Tests with Existing Ties."
  2961. Technometrics, vol. 9, no. 2, 1967, pp. 312-14. JSTOR,
  2962. https://doi.org/10.2307/1266427. Accessed 18 May 2022.
  2963. Examples
  2964. --------
  2965. >>> import numpy as np
  2966. >>> from scipy import stats
  2967. >>> rng = np.random.default_rng()
  2968. >>> x2 = rng.standard_normal((2, 45, 6, 7))
  2969. >>> x1 = rng.standard_normal((2, 30, 6, 7))
  2970. >>> res = stats.mood(x1, x2, axis=1)
  2971. >>> res.pvalue.shape
  2972. (2, 6, 7)
  2973. Find the number of points where the difference in scale is not significant:
  2974. >>> (res.pvalue > 0.1).sum()
  2975. 78
  2976. Perform the test with different scales:
  2977. >>> x1 = rng.standard_normal((2, 30))
  2978. >>> x2 = rng.standard_normal((2, 35)) * 10.0
  2979. >>> stats.mood(x1, x2, axis=1)
  2980. SignificanceResult(statistic=array([-5.76174136, -6.12650783]),
  2981. pvalue=array([8.32505043e-09, 8.98287869e-10]))
  2982. """
  2983. xp = array_namespace(x, y)
  2984. x, y = xp_promote(x, y, force_floating=True, xp=xp)
  2985. dtype = x.dtype
  2986. # _axis_nan_policy decorator ensures axis=-1
  2987. xy = xp.concat((x, y), axis=-1)
  2988. m = x.shape[-1]
  2989. n = y.shape[-1]
  2990. N = m + n
  2991. if m == 0 or n == 0 or N < 3: # only needed for test_axis_nan_policy
  2992. NaN = _get_nan(x, y, xp=xp)
  2993. return SignificanceResult(NaN, NaN)
  2994. # determine if any of the samples contain ties
  2995. # `a` represents ties within `x`; `t` represents ties within `xy`
  2996. r, t = _stats_py._rankdata(xy, method='average', return_ties=True)
  2997. r, t = xp.asarray(r, dtype=dtype), xp.asarray(t, dtype=dtype)
  2998. if xp.any(t > 1):
  2999. z = _mood_statistic_with_ties(x, y, t, m, n, N, xp=xp)
  3000. else:
  3001. z = _mood_statistic_no_ties(r, m, n, N, xp=xp)
  3002. pval = _get_pvalue(z, _SimpleNormal(), alternative, xp=xp)
  3003. z = z[()] if z.ndim == 0 else z
  3004. pval = pval[()] if pval.ndim == 0 else pval
  3005. return SignificanceResult(z, pval)
  3006. WilcoxonResult = _make_tuple_bunch('WilcoxonResult', ['statistic', 'pvalue'])
  3007. def wilcoxon_result_unpacker(res, _):
  3008. if hasattr(res, 'zstatistic'):
  3009. return res.statistic, res.pvalue, res.zstatistic
  3010. else:
  3011. return res.statistic, res.pvalue
  3012. def wilcoxon_result_object(statistic, pvalue, zstatistic=None):
  3013. res = WilcoxonResult(statistic, pvalue)
  3014. if zstatistic is not None:
  3015. res.zstatistic = zstatistic
  3016. return res
  3017. def wilcoxon_outputs(kwds):
  3018. method = kwds.get('method', 'auto')
  3019. if method == 'asymptotic':
  3020. return 3
  3021. return 2
  3022. @xp_capabilities(skip_backends=[("dask.array", "no rankdata"),
  3023. ("cupy", "no rankdata")],
  3024. jax_jit=False, cpu_only=True) # null distribution is CPU only
  3025. @_rename_parameter("mode", "method")
  3026. @_axis_nan_policy_factory(
  3027. wilcoxon_result_object, paired=True,
  3028. n_samples=lambda kwds: 2 if kwds.get('y', None) is not None else 1,
  3029. result_to_tuple=wilcoxon_result_unpacker, n_outputs=wilcoxon_outputs,
  3030. )
  3031. def wilcoxon(x, y=None, zero_method="wilcox", correction=False,
  3032. alternative="two-sided", method='auto', *, axis=0):
  3033. """Calculate the Wilcoxon signed-rank test.
  3034. The Wilcoxon signed-rank test tests the null hypothesis that two
  3035. related paired samples come from the same distribution. In particular,
  3036. it tests whether the distribution of the differences ``x - y`` is symmetric
  3037. about zero. It is a non-parametric version of the paired T-test.
  3038. Parameters
  3039. ----------
  3040. x : array_like
  3041. Either the first set of measurements (in which case ``y`` is the second
  3042. set of measurements), or the differences between two sets of
  3043. measurements (in which case ``y`` is not to be specified.) Must be
  3044. one-dimensional.
  3045. y : array_like, optional
  3046. Either the second set of measurements (if ``x`` is the first set of
  3047. measurements), or not specified (if ``x`` is the differences between
  3048. two sets of measurements.) Must be one-dimensional.
  3049. .. warning::
  3050. When `y` is provided, `wilcoxon` calculates the test statistic
  3051. based on the ranks of the absolute values of ``d = x - y``.
  3052. Roundoff error in the subtraction can result in elements of ``d``
  3053. being assigned different ranks even when they would be tied with
  3054. exact arithmetic. Rather than passing `x` and `y` separately,
  3055. consider computing the difference ``x - y``, rounding as needed to
  3056. ensure that only truly unique elements are numerically distinct,
  3057. and passing the result as `x`, leaving `y` at the default (None).
  3058. zero_method : {"wilcox", "pratt", "zsplit"}, optional
  3059. There are different conventions for handling pairs of observations
  3060. with equal values ("zero-differences", or "zeros").
  3061. * "wilcox": Discards all zero-differences (default); see [4]_.
  3062. * "pratt": Includes zero-differences in the ranking process,
  3063. but drops the ranks of the zeros (more conservative); see [3]_.
  3064. In this case, the normal approximation is adjusted as in [5]_.
  3065. * "zsplit": Includes zero-differences in the ranking process and
  3066. splits the zero rank between positive and negative ones.
  3067. correction : bool, optional
  3068. If True, apply continuity correction by adjusting the Wilcoxon rank
  3069. statistic by 0.5 towards the mean value when computing the
  3070. z-statistic if a normal approximation is used. Default is False.
  3071. alternative : {"two-sided", "greater", "less"}, optional
  3072. Defines the alternative hypothesis. Default is 'two-sided'.
  3073. In the following, let ``d`` represent the difference between the paired
  3074. samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or
  3075. ``d = x`` otherwise.
  3076. * 'two-sided': the distribution underlying ``d`` is not symmetric
  3077. about zero.
  3078. * 'less': the distribution underlying ``d`` is stochastically less
  3079. than a distribution symmetric about zero.
  3080. * 'greater': the distribution underlying ``d`` is stochastically
  3081. greater than a distribution symmetric about zero.
  3082. method : {"auto", "exact", "asymptotic"} or `PermutationMethod` instance, optional
  3083. Method to calculate the p-value, see Notes. Default is "auto".
  3084. axis : int or None, default: 0
  3085. If an int, the axis of the input along which to compute the statistic.
  3086. The statistic of each axis-slice (e.g. row) of the input will appear
  3087. in a corresponding element of the output. If ``None``, the input will
  3088. be raveled before computing the statistic.
  3089. Returns
  3090. -------
  3091. An object with the following attributes.
  3092. statistic : array_like
  3093. If `alternative` is "two-sided", the sum of the ranks of the
  3094. differences above or below zero, whichever is smaller.
  3095. Otherwise the sum of the ranks of the differences above zero.
  3096. pvalue : array_like
  3097. The p-value for the test depending on `alternative` and `method`.
  3098. zstatistic : array_like
  3099. When ``method = 'asymptotic'``, this is the normalized z-statistic::
  3100. z = (T - mn - d) / se
  3101. where ``T`` is `statistic` as defined above, ``mn`` is the mean of the
  3102. distribution under the null hypothesis, ``d`` is a continuity
  3103. correction, and ``se`` is the standard error.
  3104. When ``method != 'asymptotic'``, this attribute is not available.
  3105. See Also
  3106. --------
  3107. kruskal, mannwhitneyu
  3108. Notes
  3109. -----
  3110. In the following, let ``d`` represent the difference between the paired
  3111. samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or ``d = x``
  3112. otherwise. Assume that all elements of ``d`` are independent and
  3113. identically distributed observations, and all are distinct and nonzero.
  3114. - When ``len(d)`` is sufficiently large, the null distribution of the
  3115. normalized test statistic (`zstatistic` above) is approximately normal,
  3116. and ``method = 'asymptotic'`` can be used to compute the p-value.
  3117. - When ``len(d)`` is small, the normal approximation may not be accurate,
  3118. and ``method='exact'`` is preferred (at the cost of additional
  3119. execution time).
  3120. - The default, ``method='auto'``, selects between the two:
  3121. ``method='exact'`` is used when ``len(d) <= 50``, and
  3122. ``method='asymptotic'`` is used otherwise.
  3123. The presence of "ties" (i.e. not all elements of ``d`` are unique) or
  3124. "zeros" (i.e. elements of ``d`` are zero) changes the null distribution
  3125. of the test statistic, and ``method='exact'`` no longer calculates
  3126. the exact p-value. If ``method='asymptotic'``, the z-statistic is adjusted
  3127. for more accurate comparison against the standard normal, but still,
  3128. for finite sample sizes, the standard normal is only an approximation of
  3129. the true null distribution of the z-statistic. For such situations, the
  3130. `method` parameter also accepts instances of `PermutationMethod`. In this
  3131. case, the p-value is computed using `permutation_test` with the provided
  3132. configuration options and other appropriate settings.
  3133. The presence of ties and zeros affects the resolution of ``method='auto'``
  3134. accordingly: exhasutive permutations are performed when ``len(d) <= 13``,
  3135. and the asymptotic method is used otherwise. Note that they asymptotic
  3136. method may not be very accurate even for ``len(d) > 14``; the threshold
  3137. was chosen as a compromise between execution time and accuracy under the
  3138. constraint that the results must be deterministic. Consider providing an
  3139. instance of `PermutationMethod` method manually, choosing the
  3140. ``n_resamples`` parameter to balance time constraints and accuracy
  3141. requirements.
  3142. Please also note that in the edge case that all elements of ``d`` are zero,
  3143. the p-value relying on the normal approximaton cannot be computed (NaN)
  3144. if ``zero_method='wilcox'`` or ``zero_method='pratt'``.
  3145. References
  3146. ----------
  3147. .. [1] https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test
  3148. .. [2] Conover, W.J., Practical Nonparametric Statistics, 1971.
  3149. .. [3] Pratt, J.W., Remarks on Zeros and Ties in the Wilcoxon Signed
  3150. Rank Procedures, Journal of the American Statistical Association,
  3151. Vol. 54, 1959, pp. 655-667. :doi:`10.1080/01621459.1959.10501526`
  3152. .. [4] Wilcoxon, F., Individual Comparisons by Ranking Methods,
  3153. Biometrics Bulletin, Vol. 1, 1945, pp. 80-83. :doi:`10.2307/3001968`
  3154. .. [5] Cureton, E.E., The Normal Approximation to the Signed-Rank
  3155. Sampling Distribution When Zero Differences are Present,
  3156. Journal of the American Statistical Association, Vol. 62, 1967,
  3157. pp. 1068-1069. :doi:`10.1080/01621459.1967.10500917`
  3158. Examples
  3159. --------
  3160. In [4]_, the differences in height between cross- and self-fertilized
  3161. corn plants is given as follows:
  3162. >>> d = [6, 8, 14, 16, 23, 24, 28, 29, 41, -48, 49, 56, 60, -67, 75]
  3163. Cross-fertilized plants appear to be higher. To test the null
  3164. hypothesis that there is no height difference, we can apply the
  3165. two-sided test:
  3166. >>> from scipy.stats import wilcoxon
  3167. >>> res = wilcoxon(d)
  3168. >>> res.statistic, res.pvalue
  3169. (24.0, 0.041259765625)
  3170. Hence, we would reject the null hypothesis at a confidence level of 5%,
  3171. concluding that there is a difference in height between the groups.
  3172. To confirm that the median of the differences can be assumed to be
  3173. positive, we use:
  3174. >>> res = wilcoxon(d, alternative='greater')
  3175. >>> res.statistic, res.pvalue
  3176. (96.0, 0.0206298828125)
  3177. This shows that the null hypothesis that the median is negative can be
  3178. rejected at a confidence level of 5% in favor of the alternative that
  3179. the median is greater than zero. The p-values above are exact. Using the
  3180. normal approximation gives very similar values:
  3181. >>> res = wilcoxon(d, method='asymptotic')
  3182. >>> res.statistic, res.pvalue
  3183. (24.0, 0.04088813291185591)
  3184. Note that the statistic changed to 96 in the one-sided case (the sum
  3185. of ranks of positive differences) whereas it is 24 in the two-sided
  3186. case (the minimum of sum of ranks above and below zero).
  3187. In the example above, the differences in height between paired plants are
  3188. provided to `wilcoxon` directly. Alternatively, `wilcoxon` accepts two
  3189. samples of equal length, calculates the differences between paired
  3190. elements, then performs the test. Consider the samples ``x`` and ``y``:
  3191. >>> import numpy as np
  3192. >>> x = np.array([0.5, 0.825, 0.375, 0.5])
  3193. >>> y = np.array([0.525, 0.775, 0.325, 0.55])
  3194. >>> res = wilcoxon(x, y, alternative='greater')
  3195. >>> res
  3196. WilcoxonResult(statistic=5.0, pvalue=0.5625)
  3197. Note that had we calculated the differences by hand, the test would have
  3198. produced different results:
  3199. >>> d = [-0.025, 0.05, 0.05, -0.05]
  3200. >>> ref = wilcoxon(d, alternative='greater')
  3201. >>> ref
  3202. WilcoxonResult(statistic=6.0, pvalue=0.5)
  3203. The substantial difference is due to roundoff error in the results of
  3204. ``x-y``:
  3205. >>> d - (x-y)
  3206. array([2.08166817e-17, 6.93889390e-17, 1.38777878e-17, 4.16333634e-17])
  3207. Even though we expected all the elements of ``(x-y)[1:]`` to have the same
  3208. magnitude ``0.05``, they have slightly different magnitudes in practice,
  3209. and therefore are assigned different ranks in the test. Before performing
  3210. the test, consider calculating ``d`` and adjusting it as necessary to
  3211. ensure that theoretically identically values are not numerically distinct.
  3212. For example:
  3213. >>> d2 = np.around(x - y, decimals=3)
  3214. >>> wilcoxon(d2, alternative='greater')
  3215. WilcoxonResult(statistic=6.0, pvalue=0.5)
  3216. """
  3217. # replace approx by asymptotic to ensure backwards compatability
  3218. if method == "approx":
  3219. method = "asymptotic"
  3220. return _wilcoxon._wilcoxon_nd(x, y, zero_method, correction, alternative,
  3221. method, axis)
  3222. MedianTestResult = _make_tuple_bunch(
  3223. 'MedianTestResult',
  3224. ['statistic', 'pvalue', 'median', 'table'], []
  3225. )
  3226. @xp_capabilities(np_only=True)
  3227. def median_test(*samples, ties='below', correction=True, lambda_=1,
  3228. nan_policy='propagate'):
  3229. """Perform a Mood's median test.
  3230. Test that two or more samples come from populations with the same median.
  3231. Let ``n = len(samples)`` be the number of samples. The "grand median" of
  3232. all the data is computed, and a contingency table is formed by
  3233. classifying the values in each sample as being above or below the grand
  3234. median. The contingency table, along with `correction` and `lambda_`,
  3235. are passed to `scipy.stats.chi2_contingency` to compute the test statistic
  3236. and p-value.
  3237. Parameters
  3238. ----------
  3239. sample1, sample2, ... : array_like
  3240. The set of samples. There must be at least two samples.
  3241. Each sample must be a one-dimensional sequence containing at least
  3242. one value. The samples are not required to have the same length.
  3243. ties : str, optional
  3244. Determines how values equal to the grand median are classified in
  3245. the contingency table. The string must be one of::
  3246. "below":
  3247. Values equal to the grand median are counted as "below".
  3248. "above":
  3249. Values equal to the grand median are counted as "above".
  3250. "ignore":
  3251. Values equal to the grand median are not counted.
  3252. The default is "below".
  3253. correction : bool, optional
  3254. If True, *and* there are just two samples, apply Yates' correction
  3255. for continuity when computing the test statistic associated with
  3256. the contingency table. Default is True.
  3257. lambda_ : float or str, optional
  3258. By default, the statistic computed in this test is Pearson's
  3259. chi-squared statistic. `lambda_` allows a statistic from the
  3260. Cressie-Read power divergence family to be used instead. See
  3261. `power_divergence` for details.
  3262. Default is 1 (Pearson's chi-squared statistic).
  3263. nan_policy : {'propagate', 'raise', 'omit'}, optional
  3264. Defines how to handle when input contains nan. 'propagate' returns nan,
  3265. 'raise' throws an error, 'omit' performs the calculations ignoring nan
  3266. values. Default is 'propagate'.
  3267. Returns
  3268. -------
  3269. res : MedianTestResult
  3270. An object containing attributes:
  3271. statistic : float
  3272. The test statistic. The statistic that is returned is determined
  3273. by `lambda_`. The default is Pearson's chi-squared statistic.
  3274. pvalue : float
  3275. The p-value of the test.
  3276. median : float
  3277. The grand median.
  3278. table : ndarray
  3279. The contingency table. The shape of the table is (2, n), where
  3280. n is the number of samples. The first row holds the counts of the
  3281. values above the grand median, and the second row holds the counts
  3282. of the values below the grand median. The table allows further
  3283. analysis with, for example, `scipy.stats.chi2_contingency`, or with
  3284. `scipy.stats.fisher_exact` if there are two samples, without having
  3285. to recompute the table. If ``nan_policy`` is "propagate" and there
  3286. are nans in the input, the return value for ``table`` is ``None``.
  3287. See Also
  3288. --------
  3289. kruskal : Compute the Kruskal-Wallis H-test for independent samples.
  3290. mannwhitneyu : Computes the Mann-Whitney rank test on samples x and y.
  3291. Notes
  3292. -----
  3293. .. versionadded:: 0.15.0
  3294. References
  3295. ----------
  3296. .. [1] Mood, A. M., Introduction to the Theory of Statistics. McGraw-Hill
  3297. (1950), pp. 394-399.
  3298. .. [2] Zar, J. H., Biostatistical Analysis, 5th ed. Prentice Hall (2010).
  3299. See Sections 8.12 and 10.15.
  3300. Examples
  3301. --------
  3302. A biologist runs an experiment in which there are three groups of plants.
  3303. Group 1 has 16 plants, group 2 has 15 plants, and group 3 has 17 plants.
  3304. Each plant produces a number of seeds. The seed counts for each group
  3305. are::
  3306. Group 1: 10 14 14 18 20 22 24 25 31 31 32 39 43 43 48 49
  3307. Group 2: 28 30 31 33 34 35 36 40 44 55 57 61 91 92 99
  3308. Group 3: 0 3 9 22 23 25 25 33 34 34 40 45 46 48 62 67 84
  3309. The following code applies Mood's median test to these samples.
  3310. >>> g1 = [10, 14, 14, 18, 20, 22, 24, 25, 31, 31, 32, 39, 43, 43, 48, 49]
  3311. >>> g2 = [28, 30, 31, 33, 34, 35, 36, 40, 44, 55, 57, 61, 91, 92, 99]
  3312. >>> g3 = [0, 3, 9, 22, 23, 25, 25, 33, 34, 34, 40, 45, 46, 48, 62, 67, 84]
  3313. >>> from scipy.stats import median_test
  3314. >>> res = median_test(g1, g2, g3)
  3315. The median is
  3316. >>> res.median
  3317. 34.0
  3318. and the contingency table is
  3319. >>> res.table
  3320. array([[ 5, 10, 7],
  3321. [11, 5, 10]])
  3322. `p` is too large to conclude that the medians are not the same:
  3323. >>> res.pvalue
  3324. 0.12609082774093244
  3325. The "G-test" can be performed by passing ``lambda_="log-likelihood"`` to
  3326. `median_test`.
  3327. >>> res = median_test(g1, g2, g3, lambda_="log-likelihood")
  3328. >>> res.pvalue
  3329. 0.12224779737117837
  3330. The median occurs several times in the data, so we'll get a different
  3331. result if, for example, ``ties="above"`` is used:
  3332. >>> res = median_test(g1, g2, g3, ties="above")
  3333. >>> res.pvalue
  3334. 0.063873276069553273
  3335. >>> res.table
  3336. array([[ 5, 11, 9],
  3337. [11, 4, 8]])
  3338. This example demonstrates that if the data set is not large and there
  3339. are values equal to the median, the p-value can be sensitive to the
  3340. choice of `ties`.
  3341. """
  3342. if len(samples) < 2:
  3343. raise ValueError('median_test requires two or more samples.')
  3344. ties_options = ['below', 'above', 'ignore']
  3345. if ties not in ties_options:
  3346. raise ValueError(f"invalid 'ties' option '{ties}'; 'ties' must be one "
  3347. f"of: {str(ties_options)[1:-1]}")
  3348. data = [np.asarray(sample) for sample in samples]
  3349. # Validate the sizes and shapes of the arguments.
  3350. for k, d in enumerate(data):
  3351. if d.size == 0:
  3352. raise ValueError(f"Sample {k + 1} is empty. All samples must "
  3353. f"contain at least one value.")
  3354. if d.ndim != 1:
  3355. raise ValueError(f"Sample {k + 1} has {d.ndim} dimensions. "
  3356. f"All samples must be one-dimensional sequences.")
  3357. cdata = np.concatenate(data)
  3358. contains_nan = _contains_nan(cdata, nan_policy)
  3359. if nan_policy == 'propagate' and contains_nan:
  3360. return MedianTestResult(np.nan, np.nan, np.nan, None)
  3361. if contains_nan:
  3362. grand_median = np.median(cdata[~np.isnan(cdata)])
  3363. else:
  3364. grand_median = np.median(cdata)
  3365. # When the minimum version of numpy supported by scipy is 1.9.0,
  3366. # the above if/else statement can be replaced by the single line:
  3367. # grand_median = np.nanmedian(cdata)
  3368. # Create the contingency table.
  3369. table = np.zeros((2, len(data)), dtype=np.int64)
  3370. for k, sample in enumerate(data):
  3371. sample = sample[~np.isnan(sample)]
  3372. nabove = count_nonzero(sample > grand_median)
  3373. nbelow = count_nonzero(sample < grand_median)
  3374. nequal = sample.size - (nabove + nbelow)
  3375. table[0, k] += nabove
  3376. table[1, k] += nbelow
  3377. if ties == "below":
  3378. table[1, k] += nequal
  3379. elif ties == "above":
  3380. table[0, k] += nequal
  3381. # Check that no row or column of the table is all zero.
  3382. # Such a table can not be given to chi2_contingency, because it would have
  3383. # a zero in the table of expected frequencies.
  3384. rowsums = table.sum(axis=1)
  3385. if rowsums[0] == 0:
  3386. raise ValueError(f"All values are below the grand median ({grand_median}).")
  3387. if rowsums[1] == 0:
  3388. raise ValueError(f"All values are above the grand median ({grand_median}).")
  3389. if ties == "ignore":
  3390. # We already checked that each sample has at least one value, but it
  3391. # is possible that all those values equal the grand median. If `ties`
  3392. # is "ignore", that would result in a column of zeros in `table`. We
  3393. # check for that case here.
  3394. zero_cols = np.nonzero((table == 0).all(axis=0))[0]
  3395. if len(zero_cols) > 0:
  3396. raise ValueError(
  3397. f"All values in sample {zero_cols[0] + 1} are equal to the grand "
  3398. f"median ({grand_median!r}), so they are ignored, resulting in an "
  3399. f"empty sample."
  3400. )
  3401. stat, p, dof, expected = chi2_contingency(table, lambda_=lambda_,
  3402. correction=correction)
  3403. return MedianTestResult(stat, p, grand_median, table)
  3404. def _circfuncs_common(samples, period, xp=None):
  3405. xp = array_namespace(samples) if xp is None else xp
  3406. samples = xp_promote(samples, force_floating=True, xp=xp)
  3407. # Recast samples as radians that range between 0 and 2 pi and calculate
  3408. # the sine and cosine
  3409. scaled_samples = samples * ((2.0 * pi) / period)
  3410. sin_samp = xp.sin(scaled_samples)
  3411. cos_samp = xp.cos(scaled_samples)
  3412. return samples, sin_samp, cos_samp
  3413. @xp_capabilities()
  3414. @_axis_nan_policy_factory(
  3415. lambda x: x, n_outputs=1, default_axis=None,
  3416. result_to_tuple=lambda x, _: (x,)
  3417. )
  3418. def circmean(samples, high=2*pi, low=0, axis=None, nan_policy='propagate'):
  3419. r"""Compute the circular mean of a sample of angle observations.
  3420. Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
  3421. radians, their *circular mean* is defined by ([1]_, Eq. 2.2.4)
  3422. .. math::
  3423. \mathrm{Arg} \left( \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right)
  3424. where :math:`i` is the imaginary unit and :math:`\mathop{\mathrm{Arg}} z`
  3425. gives the principal value of the argument of complex number :math:`z`,
  3426. restricted to the range :math:`[0,2\pi]` by default. :math:`z` in the
  3427. above expression is known as the `mean resultant vector`.
  3428. Parameters
  3429. ----------
  3430. samples : array_like
  3431. Input array of angle observations. The value of a full angle is
  3432. equal to ``(high - low)``.
  3433. high : float, optional
  3434. Upper boundary of the principal value of an angle. Default is ``2*pi``.
  3435. low : float, optional
  3436. Lower boundary of the principal value of an angle. Default is ``0``.
  3437. Returns
  3438. -------
  3439. circmean : float
  3440. Circular mean, restricted to the range ``[low, high]``.
  3441. If the mean resultant vector is zero, an input-dependent,
  3442. implementation-defined number between ``[low, high]`` is returned.
  3443. If the input array is empty, ``np.nan`` is returned.
  3444. See Also
  3445. --------
  3446. circstd : Circular standard deviation.
  3447. circvar : Circular variance.
  3448. References
  3449. ----------
  3450. .. [1] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
  3451. John Wiley & Sons, 1999.
  3452. Examples
  3453. --------
  3454. For readability, all angles are printed out in degrees.
  3455. >>> import numpy as np
  3456. >>> from scipy.stats import circmean
  3457. >>> import matplotlib.pyplot as plt
  3458. >>> angles = np.deg2rad(np.array([20, 30, 330]))
  3459. >>> circmean = circmean(angles)
  3460. >>> np.rad2deg(circmean)
  3461. 7.294976657784009
  3462. >>> mean = angles.mean()
  3463. >>> np.rad2deg(mean)
  3464. 126.66666666666666
  3465. Plot and compare the circular mean against the arithmetic mean.
  3466. >>> plt.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
  3467. ... np.sin(np.linspace(0, 2*np.pi, 500)),
  3468. ... c='k')
  3469. >>> plt.scatter(np.cos(angles), np.sin(angles), c='k')
  3470. >>> plt.scatter(np.cos(circmean), np.sin(circmean), c='b',
  3471. ... label='circmean')
  3472. >>> plt.scatter(np.cos(mean), np.sin(mean), c='r', label='mean')
  3473. >>> plt.legend()
  3474. >>> plt.axis('equal')
  3475. >>> plt.show()
  3476. """
  3477. xp = array_namespace(samples)
  3478. # Needed for non-NumPy arrays to get appropriate NaN result
  3479. # Apparently atan2(0, 0) is 0, even though it is mathematically undefined
  3480. if xp_size(samples) == 0:
  3481. return xp.mean(samples, axis=axis)
  3482. period = high - low
  3483. samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp)
  3484. sin_sum = xp.sum(sin_samp, axis=axis)
  3485. cos_sum = xp.sum(cos_samp, axis=axis)
  3486. res = xp.atan2(sin_sum, cos_sum)
  3487. res = res[()] if res.ndim == 0 else res
  3488. return (res * (period / (2.0 * pi)) - low) % period + low
  3489. @xp_capabilities()
  3490. @_axis_nan_policy_factory(
  3491. lambda x: x, n_outputs=1, default_axis=None,
  3492. result_to_tuple=lambda x, _: (x,)
  3493. )
  3494. def circvar(samples, high=2*pi, low=0, axis=None, nan_policy='propagate'):
  3495. r"""Compute the circular variance of a sample of angle observations.
  3496. Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
  3497. radians, their *circular variance* is defined by ([2]_, Eq. 2.3.3)
  3498. .. math::
  3499. 1 - \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right|
  3500. where :math:`i` is the imaginary unit and :math:`|z|` gives the length
  3501. of the complex number :math:`z`. :math:`|z|` in the above expression
  3502. is known as the `mean resultant length`.
  3503. Parameters
  3504. ----------
  3505. samples : array_like
  3506. Input array of angle observations. The value of a full angle is
  3507. equal to ``(high - low)``.
  3508. high : float, optional
  3509. Upper boundary of the principal value of an angle. Default is ``2*pi``.
  3510. low : float, optional
  3511. Lower boundary of the principal value of an angle. Default is ``0``.
  3512. Returns
  3513. -------
  3514. circvar : float
  3515. Circular variance. The returned value is in the range ``[0, 1]``,
  3516. where ``0`` indicates no variance and ``1`` indicates large variance.
  3517. If the input array is empty, ``np.nan`` is returned.
  3518. See Also
  3519. --------
  3520. circmean : Circular mean.
  3521. circstd : Circular standard deviation.
  3522. Notes
  3523. -----
  3524. In the limit of small angles, the circular variance is close to
  3525. half the 'linear' variance if measured in radians.
  3526. References
  3527. ----------
  3528. .. [1] Fisher, N.I. *Statistical analysis of circular data*. Cambridge
  3529. University Press, 1993.
  3530. .. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
  3531. John Wiley & Sons, 1999.
  3532. Examples
  3533. --------
  3534. >>> import numpy as np
  3535. >>> from scipy.stats import circvar
  3536. >>> import matplotlib.pyplot as plt
  3537. >>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286,
  3538. ... 0.133, -0.473, -0.001, -0.348, 0.131])
  3539. >>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421,
  3540. ... 0.104, -0.136, -0.867, 0.012, 0.105])
  3541. >>> circvar_1 = circvar(samples_1)
  3542. >>> circvar_2 = circvar(samples_2)
  3543. Plot the samples.
  3544. >>> fig, (left, right) = plt.subplots(ncols=2)
  3545. >>> for image in (left, right):
  3546. ... image.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
  3547. ... np.sin(np.linspace(0, 2*np.pi, 500)),
  3548. ... c='k')
  3549. ... image.axis('equal')
  3550. ... image.axis('off')
  3551. >>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15)
  3552. >>> left.set_title(f"circular variance: {np.round(circvar_1, 2)!r}")
  3553. >>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15)
  3554. >>> right.set_title(f"circular variance: {np.round(circvar_2, 2)!r}")
  3555. >>> plt.show()
  3556. """
  3557. xp = array_namespace(samples)
  3558. period = high - low
  3559. samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp)
  3560. sin_mean = xp.mean(sin_samp, axis=axis)
  3561. cos_mean = xp.mean(cos_samp, axis=axis)
  3562. hypotenuse = (sin_mean**2. + cos_mean**2.)**0.5
  3563. # hypotenuse can go slightly above 1 due to rounding errors
  3564. R = xp.clip(hypotenuse, max=1.)
  3565. res = 1. - R
  3566. return res
  3567. @xp_capabilities()
  3568. @_axis_nan_policy_factory(
  3569. lambda x: x, n_outputs=1, default_axis=None,
  3570. result_to_tuple=lambda x, _: (x,)
  3571. )
  3572. def circstd(samples, high=2*pi, low=0, axis=None, nan_policy='propagate', *,
  3573. normalize=False):
  3574. r"""
  3575. Compute the circular standard deviation of a sample of angle observations.
  3576. Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
  3577. radians, their `circular standard deviation` is defined by
  3578. ([2]_, Eq. 2.3.11)
  3579. .. math::
  3580. \sqrt{ -2 \log \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right| }
  3581. where :math:`i` is the imaginary unit and :math:`|z|` gives the length
  3582. of the complex number :math:`z`. :math:`|z|` in the above expression
  3583. is known as the `mean resultant length`.
  3584. Parameters
  3585. ----------
  3586. samples : array_like
  3587. Input array of angle observations. The value of a full angle is
  3588. equal to ``(high - low)``.
  3589. high : float, optional
  3590. Upper boundary of the principal value of an angle. Default is ``2*pi``.
  3591. low : float, optional
  3592. Lower boundary of the principal value of an angle. Default is ``0``.
  3593. normalize : boolean, optional
  3594. If ``False`` (the default), the return value is computed from the
  3595. above formula with the input scaled by ``(2*pi)/(high-low)`` and
  3596. the output scaled (back) by ``(high-low)/(2*pi)``. If ``True``,
  3597. the output is not scaled and is returned directly.
  3598. Returns
  3599. -------
  3600. circstd : float
  3601. Circular standard deviation, optionally normalized.
  3602. If the input array is empty, ``np.nan`` is returned.
  3603. See Also
  3604. --------
  3605. circmean : Circular mean.
  3606. circvar : Circular variance.
  3607. Notes
  3608. -----
  3609. In the limit of small angles, the circular standard deviation is close
  3610. to the 'linear' standard deviation if ``normalize`` is ``False``.
  3611. References
  3612. ----------
  3613. .. [1] Mardia, K. V. (1972). 2. In *Statistics of Directional Data*
  3614. (pp. 18-24). Academic Press. :doi:`10.1016/C2013-0-07425-7`.
  3615. .. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
  3616. John Wiley & Sons, 1999.
  3617. Examples
  3618. --------
  3619. >>> import numpy as np
  3620. >>> from scipy.stats import circstd
  3621. >>> import matplotlib.pyplot as plt
  3622. >>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286,
  3623. ... 0.133, -0.473, -0.001, -0.348, 0.131])
  3624. >>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421,
  3625. ... 0.104, -0.136, -0.867, 0.012, 0.105])
  3626. >>> circstd_1 = circstd(samples_1)
  3627. >>> circstd_2 = circstd(samples_2)
  3628. Plot the samples.
  3629. >>> fig, (left, right) = plt.subplots(ncols=2)
  3630. >>> for image in (left, right):
  3631. ... image.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
  3632. ... np.sin(np.linspace(0, 2*np.pi, 500)),
  3633. ... c='k')
  3634. ... image.axis('equal')
  3635. ... image.axis('off')
  3636. >>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15)
  3637. >>> left.set_title(f"circular std: {np.round(circstd_1, 2)!r}")
  3638. >>> right.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
  3639. ... np.sin(np.linspace(0, 2*np.pi, 500)),
  3640. ... c='k')
  3641. >>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15)
  3642. >>> right.set_title(f"circular std: {np.round(circstd_2, 2)!r}")
  3643. >>> plt.show()
  3644. """
  3645. xp = array_namespace(samples)
  3646. period = high - low
  3647. samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp)
  3648. sin_mean = xp.mean(sin_samp, axis=axis) # [1] (2.2.3)
  3649. cos_mean = xp.mean(cos_samp, axis=axis) # [1] (2.2.3)
  3650. hypotenuse = (sin_mean**2. + cos_mean**2.)**0.5
  3651. # hypotenuse can go slightly above 1 due to rounding errors
  3652. R = xp.clip(hypotenuse, max=1.) # [1] (2.2.4)
  3653. res = (-2*xp.log(R))**0.5+0.0 # torch.pow returns -0.0 if R==1
  3654. if not normalize:
  3655. res *= (high-low)/(2.*pi) # [1] (2.3.14) w/ (2.3.7)
  3656. return res
  3657. class DirectionalStats:
  3658. def __init__(self, mean_direction, mean_resultant_length):
  3659. self.mean_direction = mean_direction
  3660. self.mean_resultant_length = mean_resultant_length
  3661. def __repr__(self):
  3662. return (f"DirectionalStats(mean_direction={self.mean_direction},"
  3663. f" mean_resultant_length={self.mean_resultant_length})")
  3664. @xp_capabilities()
  3665. def directional_stats(samples, *, axis=0, normalize=True):
  3666. """
  3667. Computes sample statistics for directional data.
  3668. Computes the directional mean (also called the mean direction vector) and
  3669. mean resultant length of a sample of vectors.
  3670. The directional mean is a measure of "preferred direction" of vector data.
  3671. It is analogous to the sample mean, but it is for use when the length of
  3672. the data is irrelevant (e.g. unit vectors).
  3673. The mean resultant length is a value between 0 and 1 used to quantify the
  3674. dispersion of directional data: the smaller the mean resultant length, the
  3675. greater the dispersion. Several definitions of directional variance
  3676. involving the mean resultant length are given in [1]_ and [2]_.
  3677. Parameters
  3678. ----------
  3679. samples : array_like
  3680. Input array. Must be at least two-dimensional, and the last axis of the
  3681. input must correspond with the dimensionality of the vector space.
  3682. When the input is exactly two dimensional, this means that each row
  3683. of the data is a vector observation.
  3684. axis : int, default: 0
  3685. Axis along which the directional mean is computed.
  3686. normalize: boolean, default: True
  3687. If True, normalize the input to ensure that each observation is a
  3688. unit vector. It the observations are already unit vectors, consider
  3689. setting this to False to avoid unnecessary computation.
  3690. Returns
  3691. -------
  3692. res : DirectionalStats
  3693. An object containing attributes:
  3694. mean_direction : ndarray
  3695. Directional mean.
  3696. mean_resultant_length : ndarray
  3697. The mean resultant length [1]_.
  3698. See Also
  3699. --------
  3700. circmean: circular mean; i.e. directional mean for 2D *angles*
  3701. circvar: circular variance; i.e. directional variance for 2D *angles*
  3702. Notes
  3703. -----
  3704. This uses a definition of directional mean from [1]_.
  3705. Assuming the observations are unit vectors, the calculation is as follows.
  3706. .. code-block:: python
  3707. mean = samples.mean(axis=0)
  3708. mean_resultant_length = np.linalg.norm(mean)
  3709. mean_direction = mean / mean_resultant_length
  3710. This definition is appropriate for *directional* data (i.e. vector data
  3711. for which the magnitude of each observation is irrelevant) but not
  3712. for *axial* data (i.e. vector data for which the magnitude and *sign* of
  3713. each observation is irrelevant).
  3714. Several definitions of directional variance involving the mean resultant
  3715. length ``R`` have been proposed, including ``1 - R`` [1]_, ``1 - R**2``
  3716. [2]_, and ``2 * (1 - R)`` [2]_. Rather than choosing one, this function
  3717. returns ``R`` as attribute `mean_resultant_length` so the user can compute
  3718. their preferred measure of dispersion.
  3719. References
  3720. ----------
  3721. .. [1] Mardia, Jupp. (2000). *Directional Statistics*
  3722. (p. 163). Wiley.
  3723. .. [2] https://en.wikipedia.org/wiki/Directional_statistics
  3724. Examples
  3725. --------
  3726. >>> import numpy as np
  3727. >>> from scipy.stats import directional_stats
  3728. >>> data = np.array([[3, 4], # first observation, 2D vector space
  3729. ... [6, -8]]) # second observation
  3730. >>> dirstats = directional_stats(data)
  3731. >>> dirstats.mean_direction
  3732. array([1., 0.])
  3733. In contrast, the regular sample mean of the vectors would be influenced
  3734. by the magnitude of each observation. Furthermore, the result would not be
  3735. a unit vector.
  3736. >>> data.mean(axis=0)
  3737. array([4.5, -2.])
  3738. An exemplary use case for `directional_stats` is to find a *meaningful*
  3739. center for a set of observations on a sphere, e.g. geographical locations.
  3740. >>> data = np.array([[0.8660254, 0.5, 0.],
  3741. ... [0.8660254, -0.5, 0.]])
  3742. >>> dirstats = directional_stats(data)
  3743. >>> dirstats.mean_direction
  3744. array([1., 0., 0.])
  3745. The regular sample mean on the other hand yields a result which does not
  3746. lie on the surface of the sphere.
  3747. >>> data.mean(axis=0)
  3748. array([0.8660254, 0., 0.])
  3749. The function also returns the mean resultant length, which
  3750. can be used to calculate a directional variance. For example, using the
  3751. definition ``Var(z) = 1 - R`` from [2]_ where ``R`` is the
  3752. mean resultant length, we can calculate the directional variance of the
  3753. vectors in the above example as:
  3754. >>> 1 - dirstats.mean_resultant_length
  3755. 0.13397459716167093
  3756. """
  3757. xp = array_namespace(samples)
  3758. samples = xp.asarray(samples)
  3759. if samples.ndim < 2:
  3760. raise ValueError("samples must at least be two-dimensional. "
  3761. f"Instead samples has shape: {tuple(samples.shape)}")
  3762. samples = xp.moveaxis(samples, axis, 0)
  3763. if is_marray(xp):
  3764. _xp = array_namespace(samples.mask)
  3765. mask = _xp.any(samples.mask, axis=-1, keepdims=True)
  3766. samples = xp.asarray(samples.data, mask=mask)
  3767. if normalize:
  3768. vectornorms = xp_vector_norm(samples, axis=-1, keepdims=True, xp=xp)
  3769. samples = samples/vectornorms
  3770. mean = xp.mean(samples, axis=0)
  3771. mean_resultant_length = xp_vector_norm(mean, axis=-1, keepdims=True, xp=xp)
  3772. mean_direction = mean / mean_resultant_length
  3773. mrl = xp.squeeze(mean_resultant_length, axis=-1)
  3774. mean_resultant_length = mrl[()] if mrl.ndim == 0 else mrl
  3775. return DirectionalStats(mean_direction, mean_resultant_length)
  3776. @xp_capabilities(skip_backends=[('dask.array', "no take_along_axis")], jax_jit=False)
  3777. def false_discovery_control(ps, *, axis=0, method='bh'):
  3778. """Adjust p-values to control the false discovery rate.
  3779. The false discovery rate (FDR) is the expected proportion of rejected null
  3780. hypotheses that are actually true.
  3781. If the null hypothesis is rejected when the *adjusted* p-value falls below
  3782. a specified level, the false discovery rate is controlled at that level.
  3783. Parameters
  3784. ----------
  3785. ps : 1D array_like
  3786. The p-values to adjust. Elements must be real numbers between 0 and 1.
  3787. axis : int
  3788. The axis along which to perform the adjustment. The adjustment is
  3789. performed independently along each axis-slice. If `axis` is None, `ps`
  3790. is raveled before performing the adjustment.
  3791. method : {'bh', 'by'}
  3792. The false discovery rate control procedure to apply: ``'bh'`` is for
  3793. Benjamini-Hochberg [1]_ (Eq. 1), ``'by'`` is for Benjaminini-Yekutieli
  3794. [2]_ (Theorem 1.3). The latter is more conservative, but it is
  3795. guaranteed to control the FDR even when the p-values are not from
  3796. independent tests.
  3797. Returns
  3798. -------
  3799. ps_adusted : array_like
  3800. The adjusted p-values. If the null hypothesis is rejected where these
  3801. fall below a specified level, the false discovery rate is controlled
  3802. at that level.
  3803. See Also
  3804. --------
  3805. combine_pvalues
  3806. statsmodels.stats.multitest.multipletests
  3807. Notes
  3808. -----
  3809. In multiple hypothesis testing, false discovery control procedures tend to
  3810. offer higher power than familywise error rate control procedures (e.g.
  3811. Bonferroni correction [1]_).
  3812. If the p-values correspond with independent tests (or tests with
  3813. "positive regression dependencies" [2]_), rejecting null hypotheses
  3814. corresponding with Benjamini-Hochberg-adjusted p-values below :math:`q`
  3815. controls the false discovery rate at a level less than or equal to
  3816. :math:`q m_0 / m`, where :math:`m_0` is the number of true null hypotheses
  3817. and :math:`m` is the total number of null hypotheses tested. The same is
  3818. true even for dependent tests when the p-values are adjusted accorded to
  3819. the more conservative Benjaminini-Yekutieli procedure.
  3820. The adjusted p-values produced by this function are comparable to those
  3821. produced by the R function ``p.adjust`` and the statsmodels function
  3822. `statsmodels.stats.multitest.multipletests`. Please consider the latter
  3823. for more advanced methods of multiple comparison correction.
  3824. References
  3825. ----------
  3826. .. [1] Benjamini, Yoav, and Yosef Hochberg. "Controlling the false
  3827. discovery rate: a practical and powerful approach to multiple
  3828. testing." Journal of the Royal statistical society: series B
  3829. (Methodological) 57.1 (1995): 289-300.
  3830. .. [2] Benjamini, Yoav, and Daniel Yekutieli. "The control of the false
  3831. discovery rate in multiple testing under dependency." Annals of
  3832. statistics (2001): 1165-1188.
  3833. .. [3] TileStats. FDR - Benjamini-Hochberg explained - Youtube.
  3834. https://www.youtube.com/watch?v=rZKa4tW2NKs.
  3835. .. [4] Neuhaus, Karl-Ludwig, et al. "Improved thrombolysis in acute
  3836. myocardial infarction with front-loaded administration of alteplase:
  3837. results of the rt-PA-APSAC patency study (TAPS)." Journal of the
  3838. American College of Cardiology 19.5 (1992): 885-891.
  3839. Examples
  3840. --------
  3841. We follow the example from [1]_.
  3842. Thrombolysis with recombinant tissue-type plasminogen activator (rt-PA)
  3843. and anisoylated plasminogen streptokinase activator (APSAC) in
  3844. myocardial infarction has been proved to reduce mortality. [4]_
  3845. investigated the effects of a new front-loaded administration of rt-PA
  3846. versus those obtained with a standard regimen of APSAC, in a randomized
  3847. multicentre trial in 421 patients with acute myocardial infarction.
  3848. There were four families of hypotheses tested in the study, the last of
  3849. which was "cardiac and other events after the start of thrombolitic
  3850. treatment". FDR control may be desired in this family of hypotheses
  3851. because it would not be appropriate to conclude that the front-loaded
  3852. treatment is better if it is merely equivalent to the previous treatment.
  3853. The p-values corresponding with the 15 hypotheses in this family were
  3854. >>> ps = [0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344,
  3855. ... 0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590, 1.000]
  3856. If the chosen significance level is 0.05, we may be tempted to reject the
  3857. null hypotheses for the tests corresponding with the first nine p-values,
  3858. as the first nine p-values fall below the chosen significance level.
  3859. However, this would ignore the problem of "multiplicity": if we fail to
  3860. correct for the fact that multiple comparisons are being performed, we
  3861. are more likely to incorrectly reject true null hypotheses.
  3862. One approach to the multiplicity problem is to control the family-wise
  3863. error rate (FWER), that is, the rate at which the null hypothesis is
  3864. rejected when it is actually true. A common procedure of this kind is the
  3865. Bonferroni correction [1]_. We begin by multiplying the p-values by the
  3866. number of hypotheses tested.
  3867. >>> import numpy as np
  3868. >>> np.array(ps) * len(ps)
  3869. array([1.5000e-03, 6.0000e-03, 2.8500e-02, 1.4250e-01, 3.0150e-01,
  3870. 4.1700e-01, 4.4700e-01, 5.1600e-01, 6.8850e-01, 4.8600e+00,
  3871. 6.3930e+00, 8.5785e+00, 9.7920e+00, 1.1385e+01, 1.5000e+01])
  3872. To control the FWER at 5%, we reject only the hypotheses corresponding
  3873. with adjusted p-values less than 0.05. In this case, only the hypotheses
  3874. corresponding with the first three p-values can be rejected. According to
  3875. [1]_, these three hypotheses concerned "allergic reaction" and "two
  3876. different aspects of bleeding."
  3877. An alternative approach is to control the false discovery rate: the
  3878. expected fraction of rejected null hypotheses that are actually true. The
  3879. advantage of this approach is that it typically affords greater power: an
  3880. increased rate of rejecting the null hypothesis when it is indeed false. To
  3881. control the false discovery rate at 5%, we apply the Benjamini-Hochberg
  3882. p-value adjustment.
  3883. >>> from scipy import stats
  3884. >>> stats.false_discovery_control(ps)
  3885. array([0.0015 , 0.003 , 0.0095 , 0.035625 , 0.0603 ,
  3886. 0.06385714, 0.06385714, 0.0645 , 0.0765 , 0.486 ,
  3887. 0.58118182, 0.714875 , 0.75323077, 0.81321429, 1. ])
  3888. Now, the first *four* adjusted p-values fall below 0.05, so we would reject
  3889. the null hypotheses corresponding with these *four* p-values. Rejection
  3890. of the fourth null hypothesis was particularly important to the original
  3891. study as it led to the conclusion that the new treatment had a
  3892. "substantially lower in-hospital mortality rate."
  3893. For simplicity of exposition, the p-values in the example above were given in
  3894. sorted order, but this is not required; `false_discovery_control` returns
  3895. adjusted p-values in order corresponding with the input `ps`.
  3896. >>> stats.false_discovery_control([0.5, 0.6, 0.1, 0.001])
  3897. array([0.6 , 0.6 , 0.2 , 0.004])
  3898. """
  3899. xp = array_namespace(ps)
  3900. # Input Validation and Special Cases
  3901. ps = xp.asarray(ps)
  3902. ps_in_range = (xp.isdtype(ps.dtype, ("integral", "real floating"))
  3903. and xp.all(ps == xp.clip(ps, 0., 1.)))
  3904. if not ps_in_range:
  3905. raise ValueError("`ps` must include only numbers between 0 and 1.")
  3906. methods = {'bh', 'by'}
  3907. if method.lower() not in methods:
  3908. raise ValueError(f"Unrecognized `method` '{method}'."
  3909. f"Method must be one of {methods}.")
  3910. method = method.lower()
  3911. if axis is None:
  3912. axis = 0
  3913. ps = xp_ravel(ps)
  3914. axis = np.asarray(axis)[()] # use of NumPy for input validation is OK
  3915. if not np.issubdtype(axis.dtype, np.integer) or axis.size != 1:
  3916. raise ValueError("`axis` must be an integer or `None`")
  3917. axis = int(axis)
  3918. if xp_size(ps) <= 1 or ps.shape[axis] <= 1:
  3919. return ps[()] if ps.ndim == 0 else ps
  3920. ps = xp.moveaxis(ps, axis, -1)
  3921. m = ps.shape[-1]
  3922. # Main Algorithm
  3923. # Equivalent to the ideas of [1] and [2], except that this adjusts the
  3924. # p-values as described in [3]. The results are similar to those produced
  3925. # by R's p.adjust.
  3926. # "Let [ps] be the ordered observed p-values..."
  3927. order = xp.argsort(ps, axis=-1)
  3928. ps = xp.take_along_axis(ps, order, axis=-1) # this copies ps
  3929. # Equation 1 of [1] rearranged to reject when p is less than specified q
  3930. i = xp.arange(1, m+1, dtype=ps.dtype, device=xp_device(ps))
  3931. # ps *= m / i
  3932. ps = xpx.at(ps)[...].multiply(m / i)
  3933. # Theorem 1.3 of [2]
  3934. if method == 'by':
  3935. # ps *= np.sum(1 / i)
  3936. ps = xpx.at(ps)[...].multiply(xp.sum(1 / i))
  3937. # accounts for rejecting all null hypotheses i for i < k, where k is
  3938. # defined in Eq. 1 of either [1] or [2]. See [3]. Starting with the index j
  3939. # of the second to last element, we replace element j with element j+1 if
  3940. # the latter is smaller.
  3941. if is_numpy(xp):
  3942. np.minimum.accumulate(ps[..., ::-1], out=ps[..., ::-1], axis=-1)
  3943. else:
  3944. n = ps.shape[-1]
  3945. for j in range(n-2, -1, -1):
  3946. # ps[..., j] = xp.minimum(ps[..., j], ps[..., j+1])
  3947. ps = xpx.at(ps)[..., j].set(xp.minimum(ps[..., j], ps[..., j+1]))
  3948. # Restore original order of axes and data
  3949. ps = _reorder_along_axis(ps, order, axis=-1, xp=xp)
  3950. ps = xp.moveaxis(ps, -1, axis)
  3951. return xp.clip(ps, 0., 1.)
  3952. def _reorder_along_axis(x, i, *, axis, xp):
  3953. if is_jax(xp):
  3954. return xp.put_along_axis(x, i, values=x, axis=axis, inplace=False)
  3955. if hasattr(xp, 'put_along_axis'):
  3956. xp.put_along_axis(x, i, values=x.copy(), axis=axis)
  3957. return x
  3958. else:
  3959. return xp.take_along_axis(x, xp.argsort(i, axis=-1), axis=-1)