_resampling.py 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417
  1. import warnings
  2. import numpy as np
  3. from itertools import combinations, permutations, product, accumulate
  4. from collections.abc import Sequence
  5. from dataclasses import dataclass, field
  6. import inspect
  7. import math
  8. from scipy._lib._util import (check_random_state, _rename_parameter, rng_integers,
  9. _transition_to_rng)
  10. from scipy._lib._array_api import (
  11. array_namespace,
  12. is_numpy,
  13. is_array_api_strict,
  14. xp_capabilities,
  15. xp_result_type,
  16. xp_size,
  17. xp_device,
  18. xp_swapaxes
  19. )
  20. from scipy._lib import array_api_extra as xpx
  21. from scipy.special import ndtr, ndtri
  22. from scipy import stats
  23. from ._common import ConfidenceInterval
  24. from ._axis_nan_policy import _broadcast_concatenate, _broadcast_arrays
  25. from ._warnings_errors import DegenerateDataWarning
  26. __all__ = ['bootstrap', 'monte_carlo_test', 'permutation_test']
  27. def _vectorize_statistic(statistic):
  28. """Vectorize an n-sample statistic"""
  29. # This is a little cleaner than np.nditer at the expense of some data
  30. # copying: concatenate samples together, then use np.apply_along_axis
  31. def stat_nd(*data, axis=0):
  32. lengths = [sample.shape[axis] for sample in data]
  33. split_indices = np.cumsum(lengths)[:-1]
  34. z = _broadcast_concatenate(data, axis)
  35. # move working axis to position 0 so that new dimensions in the output
  36. # of `statistic` are _prepended_. ("This axis is removed, and replaced
  37. # with new dimensions...")
  38. z = np.moveaxis(z, axis, 0)
  39. def stat_1d(z):
  40. data = np.split(z, split_indices)
  41. return statistic(*data)
  42. return np.apply_along_axis(stat_1d, 0, z)[()]
  43. return stat_nd
  44. def _jackknife_resample(sample, batch=None, *, xp):
  45. """Jackknife resample the sample. Only one-sample stats for now."""
  46. n = sample.shape[-1]
  47. batch_nominal = batch or n
  48. for k in range(0, n, batch_nominal):
  49. # col_start:col_end are the observations to remove
  50. batch_actual = min(batch_nominal, n-k)
  51. # jackknife - each row leaves out one observation
  52. j = np.ones((batch_actual, n), dtype=bool)
  53. np.fill_diagonal(j[:, k:k+batch_actual], False)
  54. i = np.arange(n)
  55. i = np.broadcast_to(i, (batch_actual, n))
  56. i = i[j].reshape((batch_actual, n-1))
  57. i = xp.asarray(i, device=xp_device(sample))
  58. yield _get_from_last_axis(sample, i, xp=xp)
  59. def _bootstrap_resample(sample, n_resamples=None, rng=None, *, xp):
  60. """Bootstrap resample the sample."""
  61. n = sample.shape[-1]
  62. # bootstrap - each row is a random resample of original observations
  63. i = rng_integers(rng, 0, n, (n_resamples, n))
  64. i = xp.asarray(i, device=xp_device(sample))
  65. return _get_from_last_axis(sample, i, xp=xp)
  66. def _get_from_last_axis(sample, i, xp):
  67. if not is_array_api_strict(xp):
  68. return sample[..., i]
  69. # Equivalent to `sample[..., i]` as used in `bootstrap`. Assumes i.ndim <=2.
  70. if i.ndim == 2:
  71. sample = xp.expand_dims(sample, axis=-2)
  72. sample, i = _broadcast_arrays((sample, i), axis=-1, xp=xp)
  73. return xp.take_along_axis(sample, i, axis=-1)
  74. def _percentile_of_score(a, score, axis, xp):
  75. """Vectorized, simplified `scipy.stats.percentileofscore`.
  76. Uses logic of the 'mean' value of percentileofscore's kind parameter.
  77. Unlike `stats.percentileofscore`, the percentile returned is a fraction
  78. in [0, 1].
  79. """
  80. B = a.shape[axis]
  81. nonzeros = (xp.count_nonzero(a < score, axis=axis)
  82. + xp.count_nonzero(a <= score, axis=axis))
  83. return xp.astype(nonzeros, score.dtype) / (2 * B)
  84. def _bca_interval(data, statistic, axis, alpha, theta_hat_b, batch, xp):
  85. """Bias-corrected and accelerated interval."""
  86. # closely follows [1] 14.3 and 15.4 (Eq. 15.36)
  87. # calculate z0_hat
  88. theta_hat = xp.expand_dims(statistic(*data, axis=axis), axis=-1)
  89. percentile = _percentile_of_score(theta_hat_b, theta_hat, axis=-1, xp=xp)
  90. percentile = xp.asarray(percentile, dtype=theta_hat.dtype,
  91. device=xp_device(theta_hat))
  92. z0_hat = ndtri(percentile)
  93. # calculate a_hat
  94. theta_hat_ji = [] # j is for sample of data, i is for jackknife resample
  95. for j, sample in enumerate(data):
  96. # _jackknife_resample will add an axis prior to the last axis that
  97. # corresponds with the different jackknife resamples. Do the same for
  98. # each sample of the data to ensure broadcastability. We need to
  99. # create a copy of the list containing the samples anyway, so do this
  100. # in the loop to simplify the code. This is not the bottleneck...
  101. samples = [xp.expand_dims(sample, axis=-2) for sample in data]
  102. theta_hat_i = []
  103. for jackknife_sample in _jackknife_resample(sample, batch, xp=xp):
  104. samples[j] = jackknife_sample
  105. broadcasted = _broadcast_arrays(samples, axis=-1, xp=xp)
  106. theta_hat_i.append(statistic(*broadcasted, axis=-1))
  107. theta_hat_ji.append(theta_hat_i)
  108. theta_hat_ji = [xp.concat(theta_hat_i, axis=-1)
  109. for theta_hat_i in theta_hat_ji]
  110. # CuPy array dtype is unstable in 1.13.6 when divided by large Python int:
  111. # (cp.ones(1, dtype=cp.float32)/10000).dtype # float32
  112. # (cp.ones(1, dtype=cp.float32)/100000).dtype # float64
  113. # Solution for now is to make the divisor a Python float
  114. # Looks like this will be fixed in 1.14.0
  115. n_j = [float(theta_hat_i.shape[-1]) for theta_hat_i in theta_hat_ji]
  116. theta_hat_j_dot = [xp.mean(theta_hat_i, axis=-1, keepdims=True)
  117. for theta_hat_i in theta_hat_ji]
  118. U_ji = [(n - 1) * (theta_hat_dot - theta_hat_i)
  119. for theta_hat_dot, theta_hat_i, n
  120. in zip(theta_hat_j_dot, theta_hat_ji, n_j)]
  121. nums = [xp.sum(U_i**3, axis=-1)/n**3 for U_i, n in zip(U_ji, n_j)]
  122. dens = [xp.sum(U_i**2, axis=-1)/n**2 for U_i, n in zip(U_ji, n_j)]
  123. a_hat = 1/6 * sum(nums) / sum(dens)**(3/2)
  124. # calculate alpha_1, alpha_2
  125. # `float` because dtype of ndtri output (float64) should not promote other vals
  126. z_alpha = float(ndtri(alpha))
  127. z_1alpha = -z_alpha
  128. num1 = z0_hat + z_alpha
  129. alpha_1 = ndtr(z0_hat + num1/(1 - a_hat*num1))
  130. num2 = z0_hat + z_1alpha
  131. alpha_2 = ndtr(z0_hat + num2/(1 - a_hat*num2))
  132. return alpha_1, alpha_2, a_hat # return a_hat for testing
  133. def _bootstrap_iv(data, statistic, vectorized, paired, axis, confidence_level,
  134. alternative, n_resamples, batch, method, bootstrap_result,
  135. rng):
  136. """Input validation and standardization for `bootstrap`."""
  137. xp = array_namespace(*data)
  138. if vectorized not in {True, False, None}:
  139. raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
  140. if vectorized is None:
  141. vectorized = 'axis' in inspect.signature(statistic).parameters
  142. if not vectorized:
  143. if not is_numpy(xp):
  144. message = (f"When using array library {xp.__name__}, `func` must be "
  145. "vectorized and accept argument `axis`.")
  146. raise TypeError(message)
  147. statistic = _vectorize_statistic(statistic)
  148. axis_int = int(axis)
  149. if axis != axis_int:
  150. raise ValueError("`axis` must be an integer.")
  151. n_samples = 0
  152. try:
  153. n_samples = len(data)
  154. except TypeError:
  155. raise ValueError("`data` must be a sequence of samples.")
  156. if n_samples == 0:
  157. raise ValueError("`data` must contain at least one sample.")
  158. data = _broadcast_arrays(data, axis_int, xp=xp)
  159. data_iv = []
  160. for sample in data:
  161. if sample.shape[axis_int] <= 1:
  162. raise ValueError("each sample in `data` must contain two or more "
  163. "observations along `axis`.")
  164. sample = xp.moveaxis(sample, axis_int, -1)
  165. data_iv.append(sample)
  166. if paired not in {True, False}:
  167. raise ValueError("`paired` must be `True` or `False`.")
  168. if paired:
  169. n = data_iv[0].shape[-1]
  170. for sample in data_iv[1:]:
  171. if sample.shape[-1] != n:
  172. message = ("When `paired is True`, all samples must have the "
  173. "same length along `axis`")
  174. raise ValueError(message)
  175. # to generate the bootstrap distribution for paired-sample statistics,
  176. # resample the indices of the observations
  177. def statistic(i, axis=-1, data=data_iv, unpaired_statistic=statistic):
  178. # data = [sample[..., i] for sample in data]
  179. data = [_get_from_last_axis(sample, i, xp=xp) for sample in data]
  180. return unpaired_statistic(*data, axis=axis)
  181. data_iv = [xp.arange(n)]
  182. confidence_level_float = float(confidence_level)
  183. alternative = alternative.lower()
  184. alternatives = {'two-sided', 'less', 'greater'}
  185. if alternative not in alternatives:
  186. raise ValueError(f"`alternative` must be one of {alternatives}")
  187. n_resamples_int = int(n_resamples)
  188. if n_resamples != n_resamples_int or n_resamples_int < 0:
  189. raise ValueError("`n_resamples` must be a non-negative integer.")
  190. if batch is None:
  191. batch_iv = batch
  192. else:
  193. batch_iv = int(batch)
  194. if batch != batch_iv or batch_iv <= 0:
  195. raise ValueError("`batch` must be a positive integer or None.")
  196. methods = {'percentile', 'basic', 'bca'}
  197. method = method.lower()
  198. if method not in methods:
  199. raise ValueError(f"`method` must be in {methods}")
  200. message = "`bootstrap_result` must have attribute `bootstrap_distribution'"
  201. if (bootstrap_result is not None
  202. and not hasattr(bootstrap_result, "bootstrap_distribution")):
  203. raise ValueError(message)
  204. message = ("Either `bootstrap_result.bootstrap_distribution.size` or "
  205. "`n_resamples` must be positive.")
  206. if ((not bootstrap_result or
  207. not xp_size(bootstrap_result.bootstrap_distribution))
  208. and n_resamples_int == 0):
  209. raise ValueError(message)
  210. rng = check_random_state(rng)
  211. return (data_iv, statistic, vectorized, paired, axis_int,
  212. confidence_level_float, alternative, n_resamples_int, batch_iv,
  213. method, bootstrap_result, rng, xp)
  214. @dataclass
  215. class BootstrapResult:
  216. """Result object returned by `scipy.stats.bootstrap`.
  217. Attributes
  218. ----------
  219. confidence_interval : ConfidenceInterval
  220. The bootstrap confidence interval as an instance of
  221. `collections.namedtuple` with attributes `low` and `high`.
  222. bootstrap_distribution : ndarray
  223. The bootstrap distribution, that is, the value of `statistic` for
  224. each resample. The last dimension corresponds with the resamples
  225. (e.g. ``res.bootstrap_distribution.shape[-1] == n_resamples``).
  226. standard_error : float or ndarray
  227. The bootstrap standard error, that is, the sample standard
  228. deviation of the bootstrap distribution.
  229. """
  230. confidence_interval: ConfidenceInterval
  231. bootstrap_distribution: np.ndarray
  232. standard_error: float | np.ndarray
  233. @xp_capabilities(skip_backends=[("jax.numpy", "Incompatible with `quantile`."),
  234. ("dask.array", "Dask doesn't have take_along_axis.")])
  235. @_transition_to_rng('random_state')
  236. def bootstrap(data, statistic, *, n_resamples=9999, batch=None,
  237. vectorized=None, paired=False, axis=0, confidence_level=0.95,
  238. alternative='two-sided', method='BCa', bootstrap_result=None,
  239. rng=None):
  240. r"""
  241. Compute a two-sided bootstrap confidence interval of a statistic.
  242. When `method` is ``'percentile'`` and `alternative` is ``'two-sided'``,
  243. a bootstrap confidence interval is computed according to the following
  244. procedure.
  245. 1. Resample the data: for each sample in `data` and for each of
  246. `n_resamples`, take a random sample of the original sample
  247. (with replacement) of the same size as the original sample.
  248. 2. Compute the bootstrap distribution of the statistic: for each set of
  249. resamples, compute the test statistic.
  250. 3. Determine the confidence interval: find the interval of the bootstrap
  251. distribution that is
  252. - symmetric about the median and
  253. - contains `confidence_level` of the resampled statistic values.
  254. While the ``'percentile'`` method is the most intuitive, it is rarely
  255. used in practice. Two more common methods are available, ``'basic'``
  256. ('reverse percentile') and ``'BCa'`` ('bias-corrected and accelerated');
  257. they differ in how step 3 is performed.
  258. If the samples in `data` are taken at random from their respective
  259. distributions :math:`n` times, the confidence interval returned by
  260. `bootstrap` will contain the true value of the statistic for those
  261. distributions approximately `confidence_level`:math:`\, \times \, n` times.
  262. Parameters
  263. ----------
  264. data : sequence of array-like
  265. Each element of `data` is a sample containing scalar observations from an
  266. underlying distribution. Elements of `data` must be broadcastable to the
  267. same shape (with the possible exception of the dimension specified by `axis`).
  268. statistic : callable
  269. Statistic for which the confidence interval is to be calculated.
  270. `statistic` must be a callable that accepts ``len(data)`` samples
  271. as separate arguments and returns the resulting statistic.
  272. If `vectorized` is set ``True``,
  273. `statistic` must also accept a keyword argument `axis` and be
  274. vectorized to compute the statistic along the provided `axis`.
  275. n_resamples : int, default: ``9999``
  276. The number of resamples performed to form the bootstrap distribution
  277. of the statistic.
  278. batch : int, optional
  279. The number of resamples to process in each vectorized call to
  280. `statistic`. Memory usage is O( `batch` * ``n`` ), where ``n`` is the
  281. sample size. Default is ``None``, in which case ``batch = n_resamples``
  282. (or ``batch = max(n_resamples, n)`` for ``method='BCa'``).
  283. vectorized : bool, optional
  284. If `vectorized` is set ``False``, `statistic` will not be passed
  285. keyword argument `axis` and is expected to calculate the statistic
  286. only for 1D samples. If ``True``, `statistic` will be passed keyword
  287. argument `axis` and is expected to calculate the statistic along `axis`
  288. when passed an ND sample array. If ``None`` (default), `vectorized`
  289. will be set ``True`` if ``axis`` is a parameter of `statistic`. Use of
  290. a vectorized statistic typically reduces computation time.
  291. paired : bool, default: ``False``
  292. Whether the statistic treats corresponding elements of the samples
  293. in `data` as paired. If True, `bootstrap` resamples an array of
  294. *indices* and uses the same indices for all arrays in `data`; otherwise,
  295. `bootstrap` independently resamples the elements of each array.
  296. axis : int, default: ``0``
  297. The axis of the samples in `data` along which the `statistic` is
  298. calculated.
  299. confidence_level : float, default: ``0.95``
  300. The confidence level of the confidence interval.
  301. alternative : {'two-sided', 'less', 'greater'}, default: ``'two-sided'``
  302. Choose ``'two-sided'`` (default) for a two-sided confidence interval,
  303. ``'less'`` for a one-sided confidence interval with the lower bound
  304. at ``-np.inf``, and ``'greater'`` for a one-sided confidence interval
  305. with the upper bound at ``np.inf``. The other bound of the one-sided
  306. confidence intervals is the same as that of a two-sided confidence
  307. interval with `confidence_level` twice as far from 1.0; e.g. the upper
  308. bound of a 95% ``'less'`` confidence interval is the same as the upper
  309. bound of a 90% ``'two-sided'`` confidence interval.
  310. method : {'percentile', 'basic', 'bca'}, default: ``'BCa'``
  311. Whether to return the 'percentile' bootstrap confidence interval
  312. (``'percentile'``), the 'basic' (AKA 'reverse') bootstrap confidence
  313. interval (``'basic'``), or the bias-corrected and accelerated bootstrap
  314. confidence interval (``'BCa'``).
  315. bootstrap_result : BootstrapResult, optional
  316. Provide the result object returned by a previous call to `bootstrap`
  317. to include the previous bootstrap distribution in the new bootstrap
  318. distribution. This can be used, for example, to change
  319. `confidence_level`, change `method`, or see the effect of performing
  320. additional resampling without repeating computations.
  321. rng : `numpy.random.Generator`, optional
  322. Pseudorandom number generator state. When `rng` is None, a new
  323. `numpy.random.Generator` is created using entropy from the
  324. operating system. Types other than `numpy.random.Generator` are
  325. passed to `numpy.random.default_rng` to instantiate a ``Generator``.
  326. Returns
  327. -------
  328. res : BootstrapResult
  329. An object with attributes:
  330. confidence_interval : ConfidenceInterval
  331. The bootstrap confidence interval as an instance of
  332. `collections.namedtuple` with attributes `low` and `high`.
  333. bootstrap_distribution : ndarray
  334. The bootstrap distribution, that is, the value of `statistic` for
  335. each resample. The last dimension corresponds with the resamples
  336. (e.g. ``res.bootstrap_distribution.shape[-1] == n_resamples``).
  337. standard_error : float or ndarray
  338. The bootstrap standard error, that is, the sample standard
  339. deviation of the bootstrap distribution.
  340. Warns
  341. -----
  342. `~scipy.stats.DegenerateDataWarning`
  343. Generated when ``method='BCa'`` and the bootstrap distribution is
  344. degenerate (e.g. all elements are identical).
  345. Notes
  346. -----
  347. Elements of the confidence interval may be NaN for ``method='BCa'`` if
  348. the bootstrap distribution is degenerate (e.g. all elements are identical).
  349. In this case, consider using another `method` or inspecting `data` for
  350. indications that other analysis may be more appropriate (e.g. all
  351. observations are identical).
  352. References
  353. ----------
  354. .. [1] B. Efron and R. J. Tibshirani, An Introduction to the Bootstrap,
  355. Chapman & Hall/CRC, Boca Raton, FL, USA (1993)
  356. .. [2] Nathaniel E. Helwig, "Bootstrap Confidence Intervals",
  357. http://users.stat.umn.edu/~helwig/notes/bootci-Notes.pdf
  358. .. [3] Bootstrapping (statistics), Wikipedia,
  359. https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29
  360. Examples
  361. --------
  362. Suppose we have sampled data from an unknown distribution.
  363. >>> import numpy as np
  364. >>> rng = np.random.default_rng()
  365. >>> from scipy.stats import norm
  366. >>> dist = norm(loc=2, scale=4) # our "unknown" distribution
  367. >>> data = dist.rvs(size=100, random_state=rng)
  368. We are interested in the standard deviation of the distribution.
  369. >>> std_true = dist.std() # the true value of the statistic
  370. >>> print(std_true)
  371. 4.0
  372. >>> std_sample = np.std(data) # the sample statistic
  373. >>> print(std_sample)
  374. 3.9460644295563863
  375. The bootstrap is used to approximate the variability we would expect if we
  376. were to repeatedly sample from the unknown distribution and calculate the
  377. statistic of the sample each time. It does this by repeatedly resampling
  378. values *from the original sample* with replacement and calculating the
  379. statistic of each resample. This results in a "bootstrap distribution" of
  380. the statistic.
  381. >>> import matplotlib.pyplot as plt
  382. >>> from scipy.stats import bootstrap
  383. >>> data = (data,) # samples must be in a sequence
  384. >>> res = bootstrap(data, np.std, confidence_level=0.9, rng=rng)
  385. >>> fig, ax = plt.subplots()
  386. >>> ax.hist(res.bootstrap_distribution, bins=25)
  387. >>> ax.set_title('Bootstrap Distribution')
  388. >>> ax.set_xlabel('statistic value')
  389. >>> ax.set_ylabel('frequency')
  390. >>> plt.show()
  391. The standard error quantifies this variability. It is calculated as the
  392. standard deviation of the bootstrap distribution.
  393. >>> res.standard_error
  394. 0.24427002125829136
  395. >>> res.standard_error == np.std(res.bootstrap_distribution, ddof=1)
  396. True
  397. The bootstrap distribution of the statistic is often approximately normal
  398. with scale equal to the standard error.
  399. >>> x = np.linspace(3, 5)
  400. >>> pdf = norm.pdf(x, loc=std_sample, scale=res.standard_error)
  401. >>> fig, ax = plt.subplots()
  402. >>> ax.hist(res.bootstrap_distribution, bins=25, density=True)
  403. >>> ax.plot(x, pdf)
  404. >>> ax.set_title('Normal Approximation of the Bootstrap Distribution')
  405. >>> ax.set_xlabel('statistic value')
  406. >>> ax.set_ylabel('pdf')
  407. >>> plt.show()
  408. This suggests that we could construct a 90% confidence interval on the
  409. statistic based on quantiles of this normal distribution.
  410. >>> norm.interval(0.9, loc=std_sample, scale=res.standard_error)
  411. (3.5442759991341726, 4.3478528599786)
  412. Due to central limit theorem, this normal approximation is accurate for a
  413. variety of statistics and distributions underlying the samples; however,
  414. the approximation is not reliable in all cases. Because `bootstrap` is
  415. designed to work with arbitrary underlying distributions and statistics,
  416. it uses more advanced techniques to generate an accurate confidence
  417. interval.
  418. >>> print(res.confidence_interval)
  419. ConfidenceInterval(low=3.57655333533867, high=4.382043696342881)
  420. If we sample from the original distribution 100 times and form a bootstrap
  421. confidence interval for each sample, the confidence interval
  422. contains the true value of the statistic approximately 90% of the time.
  423. >>> n_trials = 100
  424. >>> ci_contains_true_std = 0
  425. >>> for i in range(n_trials):
  426. ... data = (dist.rvs(size=100, random_state=rng),)
  427. ... res = bootstrap(data, np.std, confidence_level=0.9,
  428. ... n_resamples=999, rng=rng)
  429. ... ci = res.confidence_interval
  430. ... if ci[0] < std_true < ci[1]:
  431. ... ci_contains_true_std += 1
  432. >>> print(ci_contains_true_std)
  433. 88
  434. Rather than writing a loop, we can also determine the confidence intervals
  435. for all 100 samples at once.
  436. >>> data = (dist.rvs(size=(n_trials, 100), random_state=rng),)
  437. >>> res = bootstrap(data, np.std, axis=-1, confidence_level=0.9,
  438. ... n_resamples=999, rng=rng)
  439. >>> ci_l, ci_u = res.confidence_interval
  440. Here, `ci_l` and `ci_u` contain the confidence interval for each of the
  441. ``n_trials = 100`` samples.
  442. >>> print(ci_l[:5])
  443. [3.86401283 3.33304394 3.52474647 3.54160981 3.80569252]
  444. >>> print(ci_u[:5])
  445. [4.80217409 4.18143252 4.39734707 4.37549713 4.72843584]
  446. And again, approximately 90% contain the true value, ``std_true = 4``.
  447. >>> print(np.sum((ci_l < std_true) & (std_true < ci_u)))
  448. 93
  449. `bootstrap` can also be used to estimate confidence intervals of
  450. multi-sample statistics. For example, to get a confidence interval
  451. for the difference between means, we write a function that accepts
  452. two sample arguments and returns only the statistic. The use of the
  453. ``axis`` argument ensures that all mean calculations are perform in
  454. a single vectorized call, which is faster than looping over pairs
  455. of resamples in Python.
  456. >>> def my_statistic(sample1, sample2, axis=-1):
  457. ... mean1 = np.mean(sample1, axis=axis)
  458. ... mean2 = np.mean(sample2, axis=axis)
  459. ... return mean1 - mean2
  460. Here, we use the 'percentile' method with the default 95% confidence level.
  461. >>> sample1 = norm.rvs(scale=1, size=100, random_state=rng)
  462. >>> sample2 = norm.rvs(scale=2, size=100, random_state=rng)
  463. >>> data = (sample1, sample2)
  464. >>> res = bootstrap(data, my_statistic, method='basic', rng=rng)
  465. >>> print(my_statistic(sample1, sample2))
  466. 0.16661030792089523
  467. >>> print(res.confidence_interval)
  468. ConfidenceInterval(low=-0.29087973240818693, high=0.6371338699912273)
  469. The bootstrap estimate of the standard error is also available.
  470. >>> print(res.standard_error)
  471. 0.238323948262459
  472. Paired-sample statistics work, too. For example, consider the Pearson
  473. correlation coefficient.
  474. >>> from scipy.stats import pearsonr
  475. >>> n = 100
  476. >>> x = np.linspace(0, 10, n)
  477. >>> y = x + rng.uniform(size=n)
  478. >>> print(pearsonr(x, y)[0]) # element 0 is the statistic
  479. 0.9954306665125647
  480. We wrap `pearsonr` so that it returns only the statistic, ensuring
  481. that we use the `axis` argument because it is available.
  482. >>> def my_statistic(x, y, axis=-1):
  483. ... return pearsonr(x, y, axis=axis)[0]
  484. We call `bootstrap` using ``paired=True``.
  485. >>> res = bootstrap((x, y), my_statistic, paired=True, rng=rng)
  486. >>> print(res.confidence_interval)
  487. ConfidenceInterval(low=0.9941504301315878, high=0.996377412215445)
  488. The result object can be passed back into `bootstrap` to perform additional
  489. resampling:
  490. >>> len(res.bootstrap_distribution)
  491. 9999
  492. >>> res = bootstrap((x, y), my_statistic, paired=True,
  493. ... n_resamples=1000, rng=rng,
  494. ... bootstrap_result=res)
  495. >>> len(res.bootstrap_distribution)
  496. 10999
  497. or to change the confidence interval options:
  498. >>> res2 = bootstrap((x, y), my_statistic, paired=True,
  499. ... n_resamples=0, rng=rng, bootstrap_result=res,
  500. ... method='percentile', confidence_level=0.9)
  501. >>> np.testing.assert_equal(res2.bootstrap_distribution,
  502. ... res.bootstrap_distribution)
  503. >>> res.confidence_interval
  504. ConfidenceInterval(low=0.9941574828235082, high=0.9963781698210212)
  505. without repeating computation of the original bootstrap distribution.
  506. """
  507. # Input validation
  508. args = _bootstrap_iv(data, statistic, vectorized, paired, axis,
  509. confidence_level, alternative, n_resamples, batch,
  510. method, bootstrap_result, rng)
  511. (data, statistic, vectorized, paired, axis, confidence_level,
  512. alternative, n_resamples, batch, method, bootstrap_result,
  513. rng, xp) = args
  514. theta_hat_b = ([] if bootstrap_result is None
  515. else [bootstrap_result.bootstrap_distribution])
  516. batch_nominal = batch or n_resamples or 1
  517. for k in range(0, n_resamples, batch_nominal):
  518. batch_actual = min(batch_nominal, n_resamples-k)
  519. # Generate resamples
  520. resampled_data = []
  521. for sample in data:
  522. resample = _bootstrap_resample(sample, n_resamples=batch_actual,
  523. rng=rng, xp=xp)
  524. resampled_data.append(resample)
  525. # Compute bootstrap distribution of statistic
  526. theta_hat_b.append(statistic(*resampled_data, axis=-1))
  527. theta_hat_b = xp.concat(theta_hat_b, axis=-1)
  528. # Calculate percentile interval
  529. alpha = ((1 - confidence_level)/2 if alternative == 'two-sided'
  530. else (1 - confidence_level))
  531. if method == 'bca':
  532. interval = _bca_interval(data, statistic, axis=-1, alpha=alpha,
  533. theta_hat_b=theta_hat_b, batch=batch, xp=xp)[:2]
  534. else:
  535. alpha = xp.asarray(alpha, dtype=theta_hat_b.dtype,
  536. device=xp_device(theta_hat_b))
  537. interval = alpha, 1 - alpha
  538. # Calculate confidence interval of statistic
  539. interval = xp.stack(interval, axis=-1)
  540. ci = stats.quantile(theta_hat_b, interval, axis=-1)
  541. if xp.any(xp.isnan(ci)):
  542. msg = (
  543. "The BCa confidence interval cannot be calculated. "
  544. "This problem is known to occur when the distribution "
  545. "is degenerate or the statistic is np.min."
  546. )
  547. warnings.warn(DegenerateDataWarning(msg), stacklevel=2)
  548. ci_l = ci[..., 0]
  549. ci_u = ci[..., 1]
  550. if method == 'basic': # see [3]
  551. theta_hat = statistic(*data, axis=-1)
  552. ci_l, ci_u = 2*theta_hat - ci_u, 2*theta_hat - ci_l
  553. if alternative == 'less':
  554. ci_l = xp.full_like(ci_l, -xp.inf)
  555. elif alternative == 'greater':
  556. ci_u = xp.full_like(ci_u, xp.inf)
  557. standard_error = xp.std(theta_hat_b, correction=1, axis=-1)
  558. ci_l = ci_l[()] if ci_l.ndim == 0 else ci_l
  559. ci_u = ci_u[()] if ci_u.ndim == 0 else ci_u
  560. standard_error = standard_error[()] if standard_error.ndim == 0 else standard_error
  561. return BootstrapResult(confidence_interval=ConfidenceInterval(ci_l, ci_u),
  562. bootstrap_distribution=theta_hat_b,
  563. standard_error=standard_error)
  564. def _monte_carlo_test_iv(data, rvs, statistic, vectorized, n_resamples,
  565. batch, alternative, axis):
  566. """Input validation for `monte_carlo_test`."""
  567. axis_int = int(axis)
  568. if axis != axis_int:
  569. raise ValueError("`axis` must be an integer.")
  570. if vectorized not in {True, False, None}:
  571. raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
  572. if not isinstance(rvs, Sequence):
  573. rvs = (rvs,)
  574. data = (data,)
  575. for rvs_i in rvs:
  576. if not callable(rvs_i):
  577. raise TypeError("`rvs` must be callable or sequence of callables.")
  578. # At this point, `data` should be a sequence
  579. # If it isn't, the user passed a sequence for `rvs` but not `data`
  580. message = "If `rvs` is a sequence, `len(rvs)` must equal `len(data)`."
  581. try:
  582. len(data)
  583. except TypeError as e:
  584. raise ValueError(message) from e
  585. if not len(rvs) == len(data):
  586. raise ValueError(message)
  587. if not callable(statistic):
  588. raise TypeError("`statistic` must be callable.")
  589. if vectorized is None:
  590. try:
  591. signature = inspect.signature(statistic).parameters
  592. except ValueError as e:
  593. message = (f"Signature inspection of {statistic=} failed; "
  594. "pass `vectorize` explicitly.")
  595. raise ValueError(message) from e
  596. vectorized = 'axis' in signature
  597. xp = array_namespace(*data)
  598. dtype = xp_result_type(*data, force_floating=True, xp=xp)
  599. if not vectorized:
  600. if is_numpy(xp):
  601. statistic_vectorized = _vectorize_statistic(statistic)
  602. else:
  603. message = ("`statistic` must be vectorized (i.e. support an `axis` "
  604. f"argument) when `data` contains {xp.__name__} arrays.")
  605. raise ValueError(message)
  606. else:
  607. statistic_vectorized = statistic
  608. data = _broadcast_arrays(data, axis, xp=xp)
  609. data_iv = []
  610. for sample in data:
  611. sample = xp.broadcast_to(sample, (1,)) if sample.ndim == 0 else sample
  612. sample = xp.moveaxis(sample, axis_int, -1)
  613. data_iv.append(sample)
  614. n_resamples_int = int(n_resamples)
  615. if n_resamples != n_resamples_int or n_resamples_int <= 0:
  616. raise ValueError("`n_resamples` must be a positive integer.")
  617. if batch is None:
  618. batch_iv = batch
  619. else:
  620. batch_iv = int(batch)
  621. if batch != batch_iv or batch_iv <= 0:
  622. raise ValueError("`batch` must be a positive integer or None.")
  623. alternatives = {'two-sided', 'greater', 'less'}
  624. alternative = alternative.lower()
  625. if alternative not in alternatives:
  626. raise ValueError(f"`alternative` must be in {alternatives}")
  627. return (data_iv, rvs, statistic_vectorized, vectorized, n_resamples_int,
  628. batch_iv, alternative, axis_int, dtype, xp)
  629. @dataclass
  630. class MonteCarloTestResult:
  631. """Result object returned by `scipy.stats.monte_carlo_test`.
  632. Attributes
  633. ----------
  634. statistic : float or ndarray
  635. The observed test statistic of the sample.
  636. pvalue : float or ndarray
  637. The p-value for the given alternative.
  638. null_distribution : ndarray
  639. The values of the test statistic generated under the null
  640. hypothesis.
  641. """
  642. statistic: float | np.ndarray
  643. pvalue: float | np.ndarray
  644. null_distribution: np.ndarray
  645. @xp_capabilities()
  646. @_rename_parameter('sample', 'data')
  647. def monte_carlo_test(data, rvs, statistic, *, vectorized=None,
  648. n_resamples=9999, batch=None, alternative="two-sided",
  649. axis=0):
  650. r"""Perform a Monte Carlo hypothesis test.
  651. `data` contains a sample or a sequence of one or more samples. `rvs`
  652. specifies the distribution(s) of the sample(s) in `data` under the null
  653. hypothesis. The value of `statistic` for the given `data` is compared
  654. against a Monte Carlo null distribution: the value of the statistic for
  655. each of `n_resamples` sets of samples generated using `rvs`. This gives
  656. the p-value, the probability of observing such an extreme value of the
  657. test statistic under the null hypothesis.
  658. Parameters
  659. ----------
  660. data : array-like or sequence of array-like
  661. An array or sequence of arrays of observations.
  662. rvs : callable or tuple of callables
  663. A callable or sequence of callables that generates random variates
  664. under the null hypothesis. Each element of `rvs` must be a callable
  665. that accepts keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and
  666. returns an N-d array sample of that shape. If `rvs` is a sequence, the
  667. number of callables in `rvs` must match the number of samples in
  668. `data`, i.e. ``len(rvs) == len(data)``. If `rvs` is a single callable,
  669. `data` is treated as a single sample.
  670. statistic : callable
  671. Statistic for which the p-value of the hypothesis test is to be
  672. calculated. `statistic` must be a callable that accepts a sample
  673. (e.g. ``statistic(sample)``) or ``len(rvs)`` separate samples (e.g.
  674. ``statistic(samples1, sample2)`` if `rvs` contains two callables and
  675. `data` contains two samples) and returns the resulting statistic.
  676. If `vectorized` is set ``True``, `statistic` must also accept a keyword
  677. argument `axis` and be vectorized to compute the statistic along the
  678. provided `axis` of the samples in `data`.
  679. vectorized : bool, optional
  680. If `vectorized` is set ``False``, `statistic` will not be passed
  681. keyword argument `axis` and is expected to calculate the statistic
  682. only for 1D samples. If ``True``, `statistic` will be passed keyword
  683. argument `axis` and is expected to calculate the statistic along `axis`
  684. when passed ND sample arrays. If ``None`` (default), `vectorized`
  685. will be set ``True`` if ``axis`` is a parameter of `statistic`. Use of
  686. a vectorized statistic typically reduces computation time.
  687. n_resamples : int, default: 9999
  688. Number of samples drawn from each of the callables of `rvs`.
  689. Equivalently, the number statistic values under the null hypothesis
  690. used as the Monte Carlo null distribution.
  691. batch : int, optional
  692. The number of Monte Carlo samples to process in each call to
  693. `statistic`. Memory usage is O( `batch` * ``sample.size[axis]`` ). Default
  694. is ``None``, in which case `batch` equals `n_resamples`.
  695. alternative : {'two-sided', 'less', 'greater'}
  696. The alternative hypothesis for which the p-value is calculated.
  697. For each alternative, the p-value is defined as follows.
  698. - ``'greater'`` : the percentage of the null distribution that is
  699. greater than or equal to the observed value of the test statistic.
  700. - ``'less'`` : the percentage of the null distribution that is
  701. less than or equal to the observed value of the test statistic.
  702. - ``'two-sided'`` : twice the smaller of the p-values above.
  703. axis : int, default: 0
  704. The axis of `data` (or each sample within `data`) over which to
  705. calculate the statistic.
  706. Returns
  707. -------
  708. res : MonteCarloTestResult
  709. An object with attributes:
  710. statistic : float or ndarray
  711. The test statistic of the observed `data`.
  712. pvalue : float or ndarray
  713. The p-value for the given alternative.
  714. null_distribution : ndarray
  715. The values of the test statistic generated under the null
  716. hypothesis.
  717. .. warning::
  718. The p-value is calculated by counting the elements of the null
  719. distribution that are as extreme or more extreme than the observed
  720. value of the statistic. Due to the use of finite precision arithmetic,
  721. some statistic functions return numerically distinct values when the
  722. theoretical values would be exactly equal. In some cases, this could
  723. lead to a large error in the calculated p-value. `monte_carlo_test`
  724. guards against this by considering elements in the null distribution
  725. that are "close" (within a relative tolerance of 100 times the
  726. floating point epsilon of inexact dtypes) to the observed
  727. value of the test statistic as equal to the observed value of the
  728. test statistic. However, the user is advised to inspect the null
  729. distribution to assess whether this method of comparison is
  730. appropriate, and if not, calculate the p-value manually.
  731. References
  732. ----------
  733. .. [1] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be
  734. Zero: Calculating Exact P-values When Permutations Are Randomly Drawn."
  735. Statistical Applications in Genetics and Molecular Biology 9.1 (2010).
  736. Examples
  737. --------
  738. Suppose we wish to test whether a small sample has been drawn from a normal
  739. distribution. We decide that we will use the skew of the sample as a
  740. test statistic, and we will consider a p-value of 0.05 to be statistically
  741. significant.
  742. >>> import numpy as np
  743. >>> from scipy import stats
  744. >>> def statistic(x, axis):
  745. ... return stats.skew(x, axis)
  746. After collecting our data, we calculate the observed value of the test
  747. statistic.
  748. >>> rng = np.random.default_rng()
  749. >>> x = stats.skewnorm.rvs(a=1, size=50, random_state=rng)
  750. >>> statistic(x, axis=0)
  751. 0.12457412450240658
  752. To determine the probability of observing such an extreme value of the
  753. skewness by chance if the sample were drawn from the normal distribution,
  754. we can perform a Monte Carlo hypothesis test. The test will draw many
  755. samples at random from their normal distribution, calculate the skewness
  756. of each sample, and compare our original skewness against this
  757. distribution to determine an approximate p-value.
  758. >>> from scipy.stats import monte_carlo_test
  759. >>> # because our statistic is vectorized, we pass `vectorized=True`
  760. >>> rvs = lambda size: stats.norm.rvs(size=size, random_state=rng)
  761. >>> res = monte_carlo_test(x, rvs, statistic, vectorized=True)
  762. >>> print(res.statistic)
  763. 0.12457412450240658
  764. >>> print(res.pvalue)
  765. 0.7012
  766. The probability of obtaining a test statistic less than or equal to the
  767. observed value under the null hypothesis is ~70%. This is greater than
  768. our chosen threshold of 5%, so we cannot consider this to be significant
  769. evidence against the null hypothesis.
  770. Note that this p-value essentially matches that of
  771. `scipy.stats.skewtest`, which relies on an asymptotic distribution of a
  772. test statistic based on the sample skewness.
  773. >>> stats.skewtest(x).pvalue
  774. 0.6892046027110614
  775. This asymptotic approximation is not valid for small sample sizes, but
  776. `monte_carlo_test` can be used with samples of any size.
  777. >>> x = stats.skewnorm.rvs(a=1, size=7, random_state=rng)
  778. >>> # stats.skewtest(x) would produce an error due to small sample
  779. >>> res = monte_carlo_test(x, rvs, statistic, vectorized=True)
  780. The Monte Carlo distribution of the test statistic is provided for
  781. further investigation.
  782. >>> import matplotlib.pyplot as plt
  783. >>> fig, ax = plt.subplots()
  784. >>> ax.hist(res.null_distribution, bins=50)
  785. >>> ax.set_title("Monte Carlo distribution of test statistic")
  786. >>> ax.set_xlabel("Value of Statistic")
  787. >>> ax.set_ylabel("Frequency")
  788. >>> plt.show()
  789. """
  790. args = _monte_carlo_test_iv(data, rvs, statistic, vectorized,
  791. n_resamples, batch, alternative, axis)
  792. (data, rvs, statistic, vectorized, n_resamples,
  793. batch, alternative, axis, dtype, xp) = args
  794. # Some statistics return plain floats; ensure they're at least a NumPy float
  795. observed = xp.asarray(statistic(*data, axis=-1))
  796. observed = observed[()] if observed.ndim == 0 else observed
  797. n_observations = [sample.shape[-1] for sample in data]
  798. batch_nominal = batch or n_resamples
  799. null_distribution = []
  800. for k in range(0, n_resamples, batch_nominal):
  801. batch_actual = min(batch_nominal, n_resamples - k)
  802. resamples = [rvs_i(size=(batch_actual, n_observations_i))
  803. for rvs_i, n_observations_i in zip(rvs, n_observations)]
  804. null_distribution.append(statistic(*resamples, axis=-1))
  805. null_distribution = xp.concat(null_distribution)
  806. null_distribution = xp.reshape(null_distribution, (-1,) + (1,)*observed.ndim)
  807. # relative tolerance for detecting numerically distinct but
  808. # theoretically equal values in the null distribution
  809. eps = (0 if not xp.isdtype(observed.dtype, ('real floating'))
  810. else xp.finfo(observed.dtype).eps*100)
  811. gamma = xp.abs(eps * observed)
  812. def less(null_distribution, observed):
  813. cmps = null_distribution <= observed + gamma
  814. cmps = xp.asarray(cmps, dtype=dtype)
  815. pvalues = (xp.sum(cmps, axis=0, dtype=dtype) + 1.) / (n_resamples + 1.)
  816. return pvalues
  817. def greater(null_distribution, observed):
  818. cmps = null_distribution >= observed - gamma
  819. cmps = xp.asarray(cmps, dtype=dtype)
  820. pvalues = (xp.sum(cmps, axis=0, dtype=dtype) + 1.) / (n_resamples + 1.)
  821. return pvalues
  822. def two_sided(null_distribution, observed):
  823. pvalues_less = less(null_distribution, observed)
  824. pvalues_greater = greater(null_distribution, observed)
  825. pvalues = xp.minimum(pvalues_less, pvalues_greater) * 2
  826. return pvalues
  827. compare = {"less": less,
  828. "greater": greater,
  829. "two-sided": two_sided}
  830. pvalues = compare[alternative](null_distribution, observed)
  831. pvalues = xp.clip(pvalues, 0., 1.)
  832. return MonteCarloTestResult(observed, pvalues, null_distribution)
  833. @dataclass
  834. class PowerResult:
  835. """Result object returned by `scipy.stats.power`.
  836. Attributes
  837. ----------
  838. power : float or ndarray
  839. The estimated power.
  840. pvalues : float or ndarray
  841. The simulated p-values.
  842. """
  843. power: float | np.ndarray
  844. pvalues: float | np.ndarray
  845. def _wrap_kwargs(fun):
  846. """Wrap callable to accept arbitrary kwargs and ignore unused ones"""
  847. try:
  848. keys = set(inspect.signature(fun).parameters.keys())
  849. except ValueError:
  850. # NumPy Generator methods can't be inspected
  851. keys = {'size'}
  852. # Set keys=keys/fun=fun to avoid late binding gotcha
  853. def wrapped_rvs_i(*args, keys=keys, fun=fun, **all_kwargs):
  854. kwargs = {key: val for key, val in all_kwargs.items()
  855. if key in keys}
  856. return fun(*args, **kwargs)
  857. return wrapped_rvs_i
  858. def _power_iv(rvs, test, n_observations, significance, vectorized,
  859. n_resamples, batch, kwargs):
  860. """Input validation for `monte_carlo_test`."""
  861. if vectorized not in {True, False, None}:
  862. raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
  863. if not isinstance(rvs, Sequence):
  864. rvs = (rvs,)
  865. n_observations = (n_observations,)
  866. for rvs_i in rvs:
  867. if not callable(rvs_i):
  868. raise TypeError("`rvs` must be callable or sequence of callables.")
  869. if not len(rvs) == len(n_observations):
  870. message = ("If `rvs` is a sequence, `len(rvs)` "
  871. "must equal `len(n_observations)`.")
  872. raise ValueError(message)
  873. kwargs = dict() if kwargs is None else kwargs
  874. if not isinstance(kwargs, dict):
  875. raise TypeError("`kwargs` must be a dictionary that maps keywords to arrays.")
  876. vals = kwargs.values()
  877. keys = kwargs.keys()
  878. xp = array_namespace(*n_observations, significance, *vals)
  879. significance = xp.asarray(significance)
  880. if (not xp.isdtype(significance.dtype, "real floating")
  881. or xp.min(significance) < 0 or xp.max(significance) > 1):
  882. raise ValueError("`significance` must contain floats between 0 and 1.")
  883. # Wrap callables to ignore unused keyword arguments
  884. wrapped_rvs = [_wrap_kwargs(rvs_i) for rvs_i in rvs]
  885. # Broadcast, then ravel nobs/kwarg combinations. In the end,
  886. # `nobs` and `vals` have shape (# of combinations, number of variables)
  887. # todo: find a better way to do this without combining arrays
  888. tmp = xp.stack(xp.broadcast_arrays(*n_observations, *vals))
  889. shape = tmp.shape
  890. if tmp.ndim == 1:
  891. tmp = xp.expand_dims(tmp, axis=0)
  892. else:
  893. tmp = xp.reshape(tmp, (shape[0], -1)).T
  894. nobs, vals = tmp[:, :len(rvs)], tmp[:, len(rvs):]
  895. integer_dtype = xp_result_type(*n_observations, xp=xp)
  896. nobs = xp.astype(nobs, integer_dtype)
  897. if not callable(test):
  898. raise TypeError("`test` must be callable.")
  899. if vectorized is None:
  900. vectorized = 'axis' in inspect.signature(test).parameters
  901. test_vectorized = test
  902. if not vectorized:
  903. if not is_numpy(xp):
  904. message = (f"When using array library {xp.__name__}, `test` must be "
  905. "be vectorized and accept argument `axis`.")
  906. raise TypeError(message)
  907. test_vectorized = _vectorize_statistic(test)
  908. # Wrap `test` function to ignore unused kwargs
  909. test_vectorized = _wrap_kwargs(test_vectorized)
  910. n_resamples_int = int(n_resamples)
  911. if n_resamples != n_resamples_int or n_resamples_int <= 0:
  912. raise ValueError("`n_resamples` must be a positive integer.")
  913. if batch is None:
  914. batch_iv = batch
  915. else:
  916. batch_iv = int(batch)
  917. if batch != batch_iv or batch_iv <= 0:
  918. raise ValueError("`batch` must be a positive integer or None.")
  919. return (wrapped_rvs, test_vectorized, nobs, significance, vectorized,
  920. n_resamples_int, batch_iv, vals, keys, shape[1:], xp)
  921. @xp_capabilities(allow_dask_compute=True, jax_jit=False)
  922. def power(test, rvs, n_observations, *, significance=0.01, vectorized=None,
  923. n_resamples=10000, batch=None, kwargs=None):
  924. r"""Simulate the power of a hypothesis test under an alternative hypothesis.
  925. Parameters
  926. ----------
  927. test : callable
  928. Hypothesis test for which the power is to be simulated.
  929. `test` must be a callable that accepts a sample (e.g. ``test(sample)``)
  930. or ``len(rvs)`` separate samples (e.g. ``test(samples1, sample2)`` if
  931. `rvs` contains two callables and `n_observations` contains two values)
  932. and returns the p-value of the test.
  933. If `vectorized` is set to ``True``, `test` must also accept a keyword
  934. argument `axis` and be vectorized to perform the test along the
  935. provided `axis` of the samples.
  936. Any callable from `scipy.stats` with an `axis` argument that returns an
  937. object with a `pvalue` attribute is also acceptable.
  938. rvs : callable or tuple of callables
  939. A callable or sequence of callables that generate(s) random variates
  940. under the alternative hypothesis. Each element of `rvs` must accept
  941. keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and return an
  942. N-d array of that shape. If `rvs` is a sequence, the number of callables
  943. in `rvs` must match the number of elements of `n_observations`, i.e.
  944. ``len(rvs) == len(n_observations)``. If `rvs` is a single callable,
  945. `n_observations` is treated as a single element.
  946. n_observations : tuple of ints or tuple of integer arrays
  947. If a sequence of ints, each is the sizes of a sample to be passed to `test`.
  948. If a sequence of integer arrays, the power is simulated for each
  949. set of corresponding sample sizes. See Examples.
  950. significance : float or array_like of floats, default: 0.01
  951. The threshold for significance; i.e., the p-value below which the
  952. hypothesis test results will be considered as evidence against the null
  953. hypothesis. Equivalently, the acceptable rate of Type I error under
  954. the null hypothesis. If an array, the power is simulated for each
  955. significance threshold.
  956. kwargs : dict, optional
  957. Keyword arguments to be passed to `rvs` and/or `test` callables.
  958. Introspection is used to determine which keyword arguments may be
  959. passed to each callable.
  960. The value corresponding with each keyword must be an array.
  961. Arrays must be broadcastable with one another and with each array in
  962. `n_observations`. The power is simulated for each set of corresponding
  963. sample sizes and arguments. See Examples.
  964. vectorized : bool, optional
  965. If `vectorized` is set to ``False``, `test` will not be passed keyword
  966. argument `axis` and is expected to perform the test only for 1D samples.
  967. If ``True``, `test` will be passed keyword argument `axis` and is
  968. expected to perform the test along `axis` when passed N-D sample arrays.
  969. If ``None`` (default), `vectorized` will be set ``True`` if ``axis`` is
  970. a parameter of `test`. Use of a vectorized test typically reduces
  971. computation time.
  972. n_resamples : int, default: 10000
  973. Number of samples drawn from each of the callables of `rvs`.
  974. Equivalently, the number tests performed under the alternative
  975. hypothesis to approximate the power.
  976. batch : int, optional
  977. The number of samples to process in each call to `test`. Memory usage is
  978. proportional to the product of `batch` and the largest sample size. Default
  979. is ``None``, in which case `batch` equals `n_resamples`.
  980. Returns
  981. -------
  982. res : PowerResult
  983. An object with attributes:
  984. power : float or ndarray
  985. The estimated power against the alternative.
  986. pvalues : ndarray
  987. The p-values observed under the alternative hypothesis.
  988. Notes
  989. -----
  990. The power is simulated as follows:
  991. - Draw many random samples (or sets of samples), each of the size(s)
  992. specified by `n_observations`, under the alternative specified by
  993. `rvs`.
  994. - For each sample (or set of samples), compute the p-value according to
  995. `test`. These p-values are recorded in the ``pvalues`` attribute of
  996. the result object.
  997. - Compute the proportion of p-values that are less than the `significance`
  998. level. This is the power recorded in the ``power`` attribute of the
  999. result object.
  1000. Suppose that `significance` is an array with shape ``shape1``, the elements
  1001. of `kwargs` and `n_observations` are mutually broadcastable to shape ``shape2``,
  1002. and `test` returns an array of p-values of shape ``shape3``. Then the result
  1003. object ``power`` attribute will be of shape ``shape1 + shape2 + shape3``, and
  1004. the ``pvalues`` attribute will be of shape ``shape2 + shape3 + (n_resamples,)``.
  1005. Examples
  1006. --------
  1007. Suppose we wish to simulate the power of the independent sample t-test
  1008. under the following conditions:
  1009. - The first sample has 10 observations drawn from a normal distribution
  1010. with mean 0.
  1011. - The second sample has 12 observations drawn from a normal distribution
  1012. with mean 1.0.
  1013. - The threshold on p-values for significance is 0.05.
  1014. >>> import numpy as np
  1015. >>> from scipy import stats
  1016. >>> rng = np.random.default_rng(2549598345528)
  1017. >>>
  1018. >>> test = stats.ttest_ind
  1019. >>> n_observations = (10, 12)
  1020. >>> rvs1 = rng.normal
  1021. >>> rvs2 = lambda size: rng.normal(loc=1, size=size)
  1022. >>> rvs = (rvs1, rvs2)
  1023. >>> res = stats.power(test, rvs, n_observations, significance=0.05)
  1024. >>> res.power
  1025. 0.6116
  1026. With samples of size 10 and 12, respectively, the power of the t-test
  1027. with a significance threshold of 0.05 is approximately 60% under the chosen
  1028. alternative. We can investigate the effect of sample size on the power
  1029. by passing sample size arrays.
  1030. >>> import matplotlib.pyplot as plt
  1031. >>> nobs_x = np.arange(5, 21)
  1032. >>> nobs_y = nobs_x
  1033. >>> n_observations = (nobs_x, nobs_y)
  1034. >>> res = stats.power(test, rvs, n_observations, significance=0.05)
  1035. >>> ax = plt.subplot()
  1036. >>> ax.plot(nobs_x, res.power)
  1037. >>> ax.set_xlabel('Sample Size')
  1038. >>> ax.set_ylabel('Simulated Power')
  1039. >>> ax.set_title('Simulated Power of `ttest_ind` with Equal Sample Sizes')
  1040. >>> plt.show()
  1041. Alternatively, we can investigate the impact that effect size has on the power.
  1042. In this case, the effect size is the location of the distribution underlying
  1043. the second sample.
  1044. >>> n_observations = (10, 12)
  1045. >>> loc = np.linspace(0, 1, 20)
  1046. >>> rvs2 = lambda size, loc: rng.normal(loc=loc, size=size)
  1047. >>> rvs = (rvs1, rvs2)
  1048. >>> res = stats.power(test, rvs, n_observations, significance=0.05,
  1049. ... kwargs={'loc': loc})
  1050. >>> ax = plt.subplot()
  1051. >>> ax.plot(loc, res.power)
  1052. >>> ax.set_xlabel('Effect Size')
  1053. >>> ax.set_ylabel('Simulated Power')
  1054. >>> ax.set_title('Simulated Power of `ttest_ind`, Varying Effect Size')
  1055. >>> plt.show()
  1056. We can also use `power` to estimate the Type I error rate (also referred to by the
  1057. ambiguous term "size") of a test and assess whether it matches the nominal level.
  1058. For example, the null hypothesis of `jarque_bera` is that the sample was drawn from
  1059. a distribution with the same skewness and kurtosis as the normal distribution. To
  1060. estimate the Type I error rate, we can consider the null hypothesis to be a true
  1061. *alternative* hypothesis and calculate the power.
  1062. >>> test = stats.jarque_bera
  1063. >>> n_observations = 10
  1064. >>> rvs = rng.normal
  1065. >>> significance = np.linspace(0.0001, 0.1, 1000)
  1066. >>> res = stats.power(test, rvs, n_observations, significance=significance)
  1067. >>> size = res.power
  1068. As shown below, the Type I error rate of the test is far below the nominal level
  1069. for such a small sample, as mentioned in its documentation.
  1070. >>> ax = plt.subplot()
  1071. >>> ax.plot(significance, size)
  1072. >>> ax.plot([0, 0.1], [0, 0.1], '--')
  1073. >>> ax.set_xlabel('nominal significance level')
  1074. >>> ax.set_ylabel('estimated test size (Type I error rate)')
  1075. >>> ax.set_title('Estimated test size vs nominal significance level')
  1076. >>> ax.set_aspect('equal', 'box')
  1077. >>> ax.legend(('`ttest_1samp`', 'ideal test'))
  1078. >>> plt.show()
  1079. As one might expect from such a conservative test, the power is quite low with
  1080. respect to some alternatives. For example, the power of the test under the
  1081. alternative that the sample was drawn from the Laplace distribution may not
  1082. be much greater than the Type I error rate.
  1083. >>> rvs = rng.laplace
  1084. >>> significance = np.linspace(0.0001, 0.1, 1000)
  1085. >>> res = stats.power(test, rvs, n_observations, significance=0.05)
  1086. >>> print(res.power)
  1087. 0.0587
  1088. This is not a mistake in SciPy's implementation; it is simply due to the fact
  1089. that the null distribution of the test statistic is derived under the assumption
  1090. that the sample size is large (i.e. approaches infinity), and this asymptotic
  1091. approximation is not accurate for small samples. In such cases, resampling
  1092. and Monte Carlo methods (e.g. `permutation_test`, `goodness_of_fit`,
  1093. `monte_carlo_test`) may be more appropriate.
  1094. """
  1095. tmp = _power_iv(rvs, test, n_observations, significance,
  1096. vectorized, n_resamples, batch, kwargs)
  1097. (rvs, test, nobs, significance,
  1098. vectorized, n_resamples, batch, args, kwds, shape, xp) = tmp
  1099. batch_nominal = batch or n_resamples
  1100. pvalues = [] # results of various nobs/kwargs combinations
  1101. for i in range(nobs.shape[0]):
  1102. nobs_i, args_i = nobs[i, ...], args[i, ...]
  1103. kwargs_i = dict(zip(kwds, args_i))
  1104. pvalues_i = [] # results of batches; fixed nobs/kwargs combination
  1105. for k in range(0, n_resamples, batch_nominal):
  1106. batch_actual = min(batch_nominal, n_resamples - k)
  1107. resamples = [rvs_j(size=(batch_actual, int(nobs_ij)), **kwargs_i)
  1108. for rvs_j, nobs_ij in zip(rvs, nobs_i)]
  1109. res = test(*resamples, **kwargs_i, axis=-1)
  1110. p = getattr(res, 'pvalue', res)
  1111. pvalues_i.append(p)
  1112. # Concatenate results from batches
  1113. pvalues_i = xp.concat(pvalues_i, axis=-1)
  1114. pvalues.append(pvalues_i)
  1115. # `test` can return result with array of p-values
  1116. shape += pvalues_i.shape[:-1]
  1117. # Concatenate results from various nobs/kwargs combinations
  1118. pvalues = xp.concat(pvalues, axis=0)
  1119. # nobs/kwargs arrays were raveled to single axis; unravel
  1120. pvalues = xp.reshape(pvalues, shape + (-1,))
  1121. if significance.ndim > 0:
  1122. newdims = tuple(range(significance.ndim, pvalues.ndim + significance.ndim))
  1123. significance = xpx.expand_dims(significance, axis=newdims)
  1124. float_dtype = xp_result_type(significance, pvalues, xp=xp)
  1125. powers = xp.mean(xp.astype(pvalues < significance, float_dtype), axis=-1)
  1126. return PowerResult(power=powers, pvalues=pvalues)
  1127. @dataclass
  1128. class PermutationTestResult:
  1129. """Result object returned by `scipy.stats.permutation_test`.
  1130. Attributes
  1131. ----------
  1132. statistic : float or ndarray
  1133. The observed test statistic of the data.
  1134. pvalue : float or ndarray
  1135. The p-value for the given alternative.
  1136. null_distribution : ndarray
  1137. The values of the test statistic generated under the null
  1138. hypothesis.
  1139. """
  1140. statistic: float | np.ndarray
  1141. pvalue: float | np.ndarray
  1142. null_distribution: np.ndarray
  1143. def _all_partitions_concatenated(ns):
  1144. """
  1145. Generate all partitions of indices of groups of given sizes, concatenated
  1146. `ns` is an iterable of ints.
  1147. """
  1148. def all_partitions(z, n):
  1149. for c in combinations(z, n):
  1150. x0 = set(c)
  1151. x1 = z - x0
  1152. yield [x0, x1]
  1153. def all_partitions_n(z, ns):
  1154. if len(ns) == 0:
  1155. yield [z]
  1156. return
  1157. for c in all_partitions(z, ns[0]):
  1158. for d in all_partitions_n(c[1], ns[1:]):
  1159. yield c[0:1] + d
  1160. z = set(range(np.sum(ns)))
  1161. for partitioning in all_partitions_n(z, ns[:]):
  1162. x = np.concatenate([list(partition)
  1163. for partition in partitioning]).astype(int)
  1164. yield x
  1165. def _batch_generator(iterable, batch):
  1166. """A generator that yields batches of elements from an iterable"""
  1167. iterator = iter(iterable)
  1168. if batch <= 0:
  1169. raise ValueError("`batch` must be positive.")
  1170. z = [item for i, item in zip(range(batch), iterator)]
  1171. while z: # we don't want StopIteration without yielding an empty list
  1172. yield z
  1173. z = [item for i, item in zip(range(batch), iterator)]
  1174. def _pairings_permutations_gen(n_permutations, n_samples, n_obs_sample, batch,
  1175. rng):
  1176. # Returns a generator that yields arrays of size
  1177. # `(batch, n_samples, n_obs_sample)`.
  1178. # Each row is an independent permutation of indices 0 to `n_obs_sample`.
  1179. batch = min(batch, n_permutations)
  1180. if hasattr(rng, 'permuted'):
  1181. def batched_perm_generator():
  1182. indices = np.arange(n_obs_sample)
  1183. indices = np.tile(indices, (batch, n_samples, 1))
  1184. for k in range(0, n_permutations, batch):
  1185. batch_actual = min(batch, n_permutations-k)
  1186. # Don't permute in place, otherwise results depend on `batch`
  1187. permuted_indices = rng.permuted(indices, axis=-1)
  1188. yield permuted_indices[:batch_actual]
  1189. else: # RandomState and early Generators don't have `permuted`
  1190. def batched_perm_generator():
  1191. for k in range(0, n_permutations, batch):
  1192. batch_actual = min(batch, n_permutations-k)
  1193. size = (batch_actual, n_samples, n_obs_sample)
  1194. x = rng.random(size=size)
  1195. yield np.argsort(x, axis=-1)[:batch_actual]
  1196. return batched_perm_generator()
  1197. def _calculate_null_both(data, statistic, n_permutations, batch,
  1198. rng=None, *, xp):
  1199. """
  1200. Calculate null distribution for independent sample tests.
  1201. """
  1202. # compute number of permutations
  1203. # (distinct partitions of data into samples of these sizes)
  1204. n_obs_i = [sample.shape[-1] for sample in data] # observations per sample
  1205. n_obs_ic = list(accumulate(n_obs_i, initial=0))
  1206. n_obs = n_obs_ic[-1] # total number of observations
  1207. n_max = math.prod([math.comb(n, k) for n, k in zip(n_obs_ic[1:], n_obs_ic[:-1])])
  1208. # perm_generator is an iterator that produces permutations of indices
  1209. # from 0 to n_obs. We'll concatenate the samples, use these indices to
  1210. # permute the data, then split the samples apart again.
  1211. if n_permutations >= n_max:
  1212. exact_test = True
  1213. n_permutations = n_max
  1214. perm_generator = _all_partitions_concatenated(n_obs_i)
  1215. else:
  1216. exact_test = False
  1217. # Neither RandomState.permutation nor Generator.permutation
  1218. # can permute axis-slices independently. If this feature is
  1219. # added in the future, batches of the desired size should be
  1220. # generated in a single call.
  1221. perm_generator = (rng.permutation(n_obs)
  1222. for i in range(n_permutations))
  1223. batch = batch or int(n_permutations)
  1224. null_distribution = []
  1225. # First, concatenate all the samples. In batches, permute samples with
  1226. # indices produced by the `perm_generator`, split them into new samples of
  1227. # the original sizes, compute the statistic for each batch, and add these
  1228. # statistic values to the null distribution.
  1229. data = xp.concat(data, axis=-1)
  1230. for indices in _batch_generator(perm_generator, batch=batch):
  1231. # Creating a tensor from a list of numpy.ndarrays is extremely slow...
  1232. indices = np.asarray(indices)
  1233. indices = xp.asarray(indices)
  1234. # `indices` is 2D: each row is a permutation of the indices.
  1235. # We use it to index `data` along its last axis, which corresponds
  1236. # with observations.
  1237. # After indexing, the second to last axis of `data_batch` corresponds
  1238. # with permutations, and the last axis corresponds with observations.
  1239. # data_batch = data[..., indices]
  1240. data_batch = _get_from_last_axis(data, indices, xp=xp)
  1241. # Move the permutation axis to the front: we'll concatenate a list
  1242. # of batched statistic values along this zeroth axis to form the
  1243. # null distribution.
  1244. data_batch = xp.moveaxis(data_batch, -2, 0)
  1245. # data_batch = np.split(data_batch, n_obs_ic[:-1], axis=-1)
  1246. data_batch = [data_batch[..., i:j] for i, j in zip(n_obs_ic[:-1], n_obs_ic[1:])]
  1247. null_distribution.append(statistic(*data_batch, axis=-1))
  1248. null_distribution = xp.concat(null_distribution, axis=0)
  1249. return null_distribution, n_permutations, exact_test
  1250. def _calculate_null_pairings(data, statistic, n_permutations, batch,
  1251. rng=None, *, xp):
  1252. """
  1253. Calculate null distribution for association tests.
  1254. """
  1255. n_samples = len(data)
  1256. # compute number of permutations (factorial(n) permutations of each sample)
  1257. n_obs_sample = data[0].shape[-1] # observations per sample; same for each
  1258. n_max = math.factorial(n_obs_sample)**n_samples
  1259. # `perm_generator` is an iterator that produces a list of permutations of
  1260. # indices from 0 to n_obs_sample, one for each sample.
  1261. if n_permutations >= n_max:
  1262. exact_test = True
  1263. n_permutations = n_max
  1264. batch = batch or int(n_permutations)
  1265. # Cartesian product of the sets of all permutations of indices
  1266. perm_generator = product(*(permutations(range(n_obs_sample))
  1267. for i in range(n_samples)))
  1268. batched_perm_generator = _batch_generator(perm_generator, batch=batch)
  1269. else:
  1270. exact_test = False
  1271. batch = batch or int(n_permutations)
  1272. # Separate random permutations of indices for each sample.
  1273. # Again, it would be nice if RandomState/Generator.permutation
  1274. # could permute each axis-slice separately.
  1275. args = n_permutations, n_samples, n_obs_sample, batch, rng
  1276. batched_perm_generator = _pairings_permutations_gen(*args)
  1277. null_distribution = []
  1278. for indices in batched_perm_generator:
  1279. indices = xp.asarray(indices)
  1280. # `indices` is 3D: the zeroth axis is for permutations, the next is
  1281. # for samples, and the last is for observations. Swap the first two
  1282. # to make the zeroth axis correspond with samples, as it does for
  1283. # `data`.
  1284. indices = xp_swapaxes(indices, 0, 1, xp=xp)
  1285. # When we're done, `data_batch` will be a list of length `n_samples`.
  1286. # Each element will be a batch of random permutations of one sample.
  1287. # The zeroth axis of each batch will correspond with permutations,
  1288. # and the last will correspond with observations. (This makes it
  1289. # easy to pass into `statistic`.)
  1290. data_batch = [None]*n_samples
  1291. for i in range(n_samples):
  1292. # data_batch[i] = data[i][..., indices[i]]
  1293. data_batch[i] = _get_from_last_axis(data[i], indices[i, ...], xp=xp)
  1294. data_batch[i] = xp.moveaxis(data_batch[i], -2, 0)
  1295. null_distribution.append(statistic(*data_batch, axis=-1))
  1296. null_distribution = xp.concat(null_distribution, axis=0)
  1297. return null_distribution, n_permutations, exact_test
  1298. def _calculate_null_samples(data, statistic, n_permutations, batch,
  1299. rng=None, *, xp):
  1300. """
  1301. Calculate null distribution for paired-sample tests.
  1302. """
  1303. n_samples = len(data)
  1304. # By convention, the meaning of the "samples" permutations type for
  1305. # data with only one sample is to flip the sign of the observations.
  1306. # Achieve this by adding a second sample - the negative of the original.
  1307. if n_samples == 1:
  1308. data = [data[0], -data[0]]
  1309. # The "samples" permutation strategy is the same as the "pairings"
  1310. # strategy except the roles of samples and observations are flipped.
  1311. # So swap these axes, then we'll use the function for the "pairings"
  1312. # strategy to do all the work!
  1313. data = xp.stack(data, axis=0)
  1314. data = xp_swapaxes(data, 0, -1, xp=xp)
  1315. # (Of course, the user's statistic doesn't know what we've done here,
  1316. # so we need to pass it what it's expecting.)
  1317. def statistic_wrapped(*data, axis):
  1318. # can we do this without converting back and forth between
  1319. # array and list?
  1320. data = xp.stack(data, axis=0)
  1321. data = xp_swapaxes(data, 0, -1, xp=xp)
  1322. if n_samples == 1:
  1323. data = data[0:1, ...]
  1324. data = [data[i, ...] for i in range(data.shape[0])]
  1325. return statistic(*data, axis=axis)
  1326. data = [data[i, ...] for i in range(data.shape[0])]
  1327. return _calculate_null_pairings(data, statistic_wrapped, n_permutations,
  1328. batch, rng, xp=xp)
  1329. def _permutation_test_iv(data, statistic, permutation_type, vectorized,
  1330. n_resamples, batch, alternative, axis, rng):
  1331. """Input validation for `permutation_test`."""
  1332. axis_int = int(axis)
  1333. if axis != axis_int:
  1334. raise ValueError("`axis` must be an integer.")
  1335. permutation_types = {'samples', 'pairings', 'independent'}
  1336. permutation_type = permutation_type.lower()
  1337. if permutation_type not in permutation_types:
  1338. raise ValueError(f"`permutation_type` must be in {permutation_types}.")
  1339. if vectorized not in {True, False, None}:
  1340. raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
  1341. if vectorized is None:
  1342. vectorized = 'axis' in inspect.signature(statistic).parameters
  1343. message = "`data` must be a tuple containing at least two samples"
  1344. try:
  1345. if len(data) < 2 and permutation_type == 'independent':
  1346. raise ValueError(message)
  1347. except TypeError:
  1348. raise TypeError(message)
  1349. xp = array_namespace(*data)
  1350. if not vectorized:
  1351. if not is_numpy(xp):
  1352. message = (f"When using array library {xp.__name__}, `func` must be "
  1353. "vectorized and accept argument `axis`.")
  1354. raise TypeError(message)
  1355. statistic = _vectorize_statistic(statistic)
  1356. data = _broadcast_arrays(data, axis, xp=xp)
  1357. data_iv = []
  1358. for sample in data:
  1359. sample = xpx.atleast_nd(sample, ndim=1)
  1360. if sample.shape[axis] <= 1:
  1361. raise ValueError("each sample in `data` must contain two or more "
  1362. "observations along `axis`.")
  1363. sample = xp.moveaxis(sample, axis_int, -1)
  1364. data_iv.append(sample)
  1365. n_resamples_int = (int(n_resamples) if not math.isinf(n_resamples)
  1366. else xp.inf)
  1367. if n_resamples != n_resamples_int or n_resamples_int <= 0:
  1368. raise ValueError("`n_resamples` must be a positive integer.")
  1369. if batch is None:
  1370. batch_iv = batch
  1371. else:
  1372. batch_iv = int(batch)
  1373. if batch != batch_iv or batch_iv <= 0:
  1374. raise ValueError("`batch` must be a positive integer or None.")
  1375. alternatives = {'two-sided', 'greater', 'less'}
  1376. alternative = alternative.lower()
  1377. if alternative not in alternatives:
  1378. raise ValueError(f"`alternative` must be in {alternatives}")
  1379. rng = check_random_state(rng)
  1380. float_dtype = xp_result_type(*data_iv, force_floating=True, xp=xp)
  1381. return (data_iv, statistic, permutation_type, vectorized, n_resamples_int,
  1382. batch_iv, alternative, axis_int, rng, float_dtype, xp)
  1383. @xp_capabilities(skip_backends=[('dask.array', "lacks required indexing capabilities")])
  1384. @_transition_to_rng('random_state')
  1385. def permutation_test(data, statistic, *, permutation_type='independent',
  1386. vectorized=None, n_resamples=9999, batch=None,
  1387. alternative="two-sided", axis=0, rng=None):
  1388. r"""
  1389. Performs a permutation test of a given statistic on provided data.
  1390. For independent sample statistics, the null hypothesis is that the data are
  1391. randomly sampled from the same distribution.
  1392. For paired sample statistics, two null hypothesis can be tested:
  1393. that the data are paired at random or that the data are assigned to samples
  1394. at random.
  1395. Parameters
  1396. ----------
  1397. data : iterable of array-like
  1398. Contains the samples, each of which is an array of observations.
  1399. Dimensions of sample arrays must be compatible for broadcasting except
  1400. along `axis`.
  1401. statistic : callable
  1402. Statistic for which the p-value of the hypothesis test is to be
  1403. calculated. `statistic` must be a callable that accepts samples
  1404. as separate arguments (e.g. ``statistic(*data)``) and returns the
  1405. resulting statistic.
  1406. If `vectorized` is set ``True``, `statistic` must also accept a keyword
  1407. argument `axis` and be vectorized to compute the statistic along the
  1408. provided `axis` of the sample arrays.
  1409. permutation_type : {'independent', 'samples', 'pairings'}, optional
  1410. The type of permutations to be performed, in accordance with the
  1411. null hypothesis. The first two permutation types are for paired sample
  1412. statistics, in which all samples contain the same number of
  1413. observations and observations with corresponding indices along `axis`
  1414. are considered to be paired; the third is for independent sample
  1415. statistics.
  1416. - ``'samples'`` : observations are assigned to different samples
  1417. but remain paired with the same observations from other samples.
  1418. This permutation type is appropriate for paired sample hypothesis
  1419. tests such as the Wilcoxon signed-rank test and the paired t-test.
  1420. - ``'pairings'`` : observations are paired with different observations,
  1421. but they remain within the same sample. This permutation type is
  1422. appropriate for association/correlation tests with statistics such
  1423. as Spearman's :math:`\rho`, Kendall's :math:`\tau`, and Pearson's
  1424. :math:`r`.
  1425. - ``'independent'`` (default) : observations are assigned to different
  1426. samples. Samples may contain different numbers of observations. This
  1427. permutation type is appropriate for independent sample hypothesis
  1428. tests such as the Mann-Whitney :math:`U` test and the independent
  1429. sample t-test.
  1430. Please see the Notes section below for more detailed descriptions
  1431. of the permutation types.
  1432. vectorized : bool, optional
  1433. If `vectorized` is set ``False``, `statistic` will not be passed
  1434. keyword argument `axis` and is expected to calculate the statistic
  1435. only for 1D samples. If ``True``, `statistic` will be passed keyword
  1436. argument `axis` and is expected to calculate the statistic along `axis`
  1437. when passed an ND sample array. If ``None`` (default), `vectorized`
  1438. will be set ``True`` if ``axis`` is a parameter of `statistic`. Use
  1439. of a vectorized statistic typically reduces computation time.
  1440. n_resamples : int or np.inf, default: 9999
  1441. Number of random permutations (resamples) used to approximate the null
  1442. distribution. If greater than or equal to the number of distinct
  1443. permutations, the exact null distribution will be computed.
  1444. Note that the number of distinct permutations grows very rapidly with
  1445. the sizes of samples, so exact tests are feasible only for very small
  1446. data sets.
  1447. batch : int, optional
  1448. The number of permutations to process in each call to `statistic`.
  1449. Memory usage is O( `batch` * ``n`` ), where ``n`` is the total size
  1450. of all samples, regardless of the value of `vectorized`. Default is
  1451. ``None``, in which case ``batch`` is the number of permutations.
  1452. alternative : {'two-sided', 'less', 'greater'}, optional
  1453. The alternative hypothesis for which the p-value is calculated.
  1454. For each alternative, the p-value is defined for exact tests as
  1455. follows.
  1456. - ``'greater'`` : the percentage of the null distribution that is
  1457. greater than or equal to the observed value of the test statistic.
  1458. - ``'less'`` : the percentage of the null distribution that is
  1459. less than or equal to the observed value of the test statistic.
  1460. - ``'two-sided'`` (default) : twice the smaller of the p-values above.
  1461. Note that p-values for randomized tests are calculated according to the
  1462. conservative (over-estimated) approximation suggested in [2]_ and [3]_
  1463. rather than the unbiased estimator suggested in [4]_. That is, when
  1464. calculating the proportion of the randomized null distribution that is
  1465. as extreme as the observed value of the test statistic, the values in
  1466. the numerator and denominator are both increased by one. An
  1467. interpretation of this adjustment is that the observed value of the
  1468. test statistic is always included as an element of the randomized
  1469. null distribution.
  1470. The convention used for two-sided p-values is not universal;
  1471. the observed test statistic and null distribution are returned in
  1472. case a different definition is preferred.
  1473. axis : int, default: 0
  1474. The axis of the (broadcasted) samples over which to calculate the
  1475. statistic. If samples have a different number of dimensions,
  1476. singleton dimensions are prepended to samples with fewer dimensions
  1477. before `axis` is considered.
  1478. rng : `numpy.random.Generator`, optional
  1479. Pseudorandom number generator state. When `rng` is None, a new
  1480. `numpy.random.Generator` is created using entropy from the
  1481. operating system. Types other than `numpy.random.Generator` are
  1482. passed to `numpy.random.default_rng` to instantiate a ``Generator``.
  1483. Returns
  1484. -------
  1485. res : PermutationTestResult
  1486. An object with attributes:
  1487. statistic : float or ndarray
  1488. The observed test statistic of the data.
  1489. pvalue : float or ndarray
  1490. The p-value for the given alternative.
  1491. null_distribution : ndarray
  1492. The values of the test statistic generated under the null
  1493. hypothesis.
  1494. Notes
  1495. -----
  1496. The three types of permutation tests supported by this function are
  1497. described below.
  1498. **Unpaired statistics** (``permutation_type='independent'``):
  1499. The null hypothesis associated with this permutation type is that all
  1500. observations are sampled from the same underlying distribution and that
  1501. they have been assigned to one of the samples at random.
  1502. Suppose ``data`` contains two samples; e.g. ``a, b = data``.
  1503. When ``1 < n_resamples < binom(n, k)``, where
  1504. * ``k`` is the number of observations in ``a``,
  1505. * ``n`` is the total number of observations in ``a`` and ``b``, and
  1506. * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``),
  1507. the data are pooled (concatenated), randomly assigned to either the first
  1508. or second sample, and the statistic is calculated. This process is
  1509. performed repeatedly, `permutation` times, generating a distribution of the
  1510. statistic under the null hypothesis. The statistic of the original
  1511. data is compared to this distribution to determine the p-value.
  1512. When ``n_resamples >= binom(n, k)``, an exact test is performed: the data
  1513. are *partitioned* between the samples in each distinct way exactly once,
  1514. and the exact null distribution is formed.
  1515. Note that for a given partitioning of the data between the samples,
  1516. only one ordering/permutation of the data *within* each sample is
  1517. considered. For statistics that do not depend on the order of the data
  1518. within samples, this dramatically reduces computational cost without
  1519. affecting the shape of the null distribution (because the frequency/count
  1520. of each value is affected by the same factor).
  1521. For ``a = [a1, a2, a3, a4]`` and ``b = [b1, b2, b3]``, an example of this
  1522. permutation type is ``x = [b3, a1, a2, b2]`` and ``y = [a4, b1, a3]``.
  1523. Because only one ordering/permutation of the data *within* each sample
  1524. is considered in an exact test, a resampling like ``x = [b3, a1, b2, a2]``
  1525. and ``y = [a4, a3, b1]`` would *not* be considered distinct from the
  1526. example above.
  1527. ``permutation_type='independent'`` does not support one-sample statistics,
  1528. but it can be applied to statistics with more than two samples. In this
  1529. case, if ``n`` is an array of the number of observations within each
  1530. sample, the number of distinct partitions is::
  1531. np.prod([binom(sum(n[i:]), sum(n[i+1:])) for i in range(len(n)-1)])
  1532. **Paired statistics, permute pairings** (``permutation_type='pairings'``):
  1533. The null hypothesis associated with this permutation type is that
  1534. observations within each sample are drawn from the same underlying
  1535. distribution and that pairings with elements of other samples are
  1536. assigned at random.
  1537. Suppose ``data`` contains only one sample; e.g. ``a, = data``, and we
  1538. wish to consider all possible pairings of elements of ``a`` with elements
  1539. of a second sample, ``b``. Let ``n`` be the number of observations in
  1540. ``a``, which must also equal the number of observations in ``b``.
  1541. When ``1 < n_resamples < factorial(n)``, the elements of ``a`` are
  1542. randomly permuted. The user-supplied statistic accepts one data argument,
  1543. say ``a_perm``, and calculates the statistic considering ``a_perm`` and
  1544. ``b``. This process is performed repeatedly, `permutation` times,
  1545. generating a distribution of the statistic under the null hypothesis.
  1546. The statistic of the original data is compared to this distribution to
  1547. determine the p-value.
  1548. When ``n_resamples >= factorial(n)``, an exact test is performed:
  1549. ``a`` is permuted in each distinct way exactly once. Therefore, the
  1550. `statistic` is computed for each unique pairing of samples between ``a``
  1551. and ``b`` exactly once.
  1552. For ``a = [a1, a2, a3]`` and ``b = [b1, b2, b3]``, an example of this
  1553. permutation type is ``a_perm = [a3, a1, a2]`` while ``b`` is left
  1554. in its original order.
  1555. ``permutation_type='pairings'`` supports ``data`` containing any number
  1556. of samples, each of which must contain the same number of observations.
  1557. All samples provided in ``data`` are permuted *independently*. Therefore,
  1558. if ``m`` is the number of samples and ``n`` is the number of observations
  1559. within each sample, then the number of permutations in an exact test is::
  1560. factorial(n)**m
  1561. Note that if a two-sample statistic, for example, does not inherently
  1562. depend on the order in which observations are provided - only on the
  1563. *pairings* of observations - then only one of the two samples should be
  1564. provided in ``data``. This dramatically reduces computational cost without
  1565. affecting the shape of the null distribution (because the frequency/count
  1566. of each value is affected by the same factor).
  1567. **Paired statistics, permute samples** (``permutation_type='samples'``):
  1568. The null hypothesis associated with this permutation type is that
  1569. observations within each pair are drawn from the same underlying
  1570. distribution and that the sample to which they are assigned is random.
  1571. Suppose ``data`` contains two samples; e.g. ``a, b = data``.
  1572. Let ``n`` be the number of observations in ``a``, which must also equal
  1573. the number of observations in ``b``.
  1574. When ``1 < n_resamples < 2**n``, the elements of ``a`` are ``b`` are
  1575. randomly swapped between samples (maintaining their pairings) and the
  1576. statistic is calculated. This process is performed repeatedly,
  1577. `permutation` times, generating a distribution of the statistic under the
  1578. null hypothesis. The statistic of the original data is compared to this
  1579. distribution to determine the p-value.
  1580. When ``n_resamples >= 2**n``, an exact test is performed: the observations
  1581. are assigned to the two samples in each distinct way (while maintaining
  1582. pairings) exactly once.
  1583. For ``a = [a1, a2, a3]`` and ``b = [b1, b2, b3]``, an example of this
  1584. permutation type is ``x = [b1, a2, b3]`` and ``y = [a1, b2, a3]``.
  1585. ``permutation_type='samples'`` supports ``data`` containing any number
  1586. of samples, each of which must contain the same number of observations.
  1587. If ``data`` contains more than one sample, paired observations within
  1588. ``data`` are exchanged between samples *independently*. Therefore, if ``m``
  1589. is the number of samples and ``n`` is the number of observations within
  1590. each sample, then the number of permutations in an exact test is::
  1591. factorial(m)**n
  1592. Several paired-sample statistical tests, such as the Wilcoxon signed rank
  1593. test and paired-sample t-test, can be performed considering only the
  1594. *difference* between two paired elements. Accordingly, if ``data`` contains
  1595. only one sample, then the null distribution is formed by independently
  1596. changing the *sign* of each observation.
  1597. .. warning::
  1598. The p-value is calculated by counting the elements of the null
  1599. distribution that are as extreme or more extreme than the observed
  1600. value of the statistic. Due to the use of finite precision arithmetic,
  1601. some statistic functions return numerically distinct values when the
  1602. theoretical values would be exactly equal. In some cases, this could
  1603. lead to a large error in the calculated p-value. `permutation_test`
  1604. guards against this by considering elements in the null distribution
  1605. that are "close" (within a relative tolerance of 100 times the
  1606. floating point epsilon of inexact dtypes) to the observed
  1607. value of the test statistic as equal to the observed value of the
  1608. test statistic. However, the user is advised to inspect the null
  1609. distribution to assess whether this method of comparison is
  1610. appropriate, and if not, calculate the p-value manually. See example
  1611. below.
  1612. References
  1613. ----------
  1614. .. [1] R. A. Fisher. The Design of Experiments, 6th Ed (1951).
  1615. .. [2] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be
  1616. Zero: Calculating Exact P-values When Permutations Are Randomly Drawn."
  1617. Statistical Applications in Genetics and Molecular Biology 9.1 (2010).
  1618. .. [3] M. D. Ernst. "Permutation Methods: A Basis for Exact Inference".
  1619. Statistical Science (2004).
  1620. .. [4] B. Efron and R. J. Tibshirani. An Introduction to the Bootstrap
  1621. (1993).
  1622. Examples
  1623. --------
  1624. Suppose we wish to test whether two samples are drawn from the same
  1625. distribution. Assume that the underlying distributions are unknown to us,
  1626. and that before observing the data, we hypothesized that the mean of the
  1627. first sample would be less than that of the second sample. We decide that
  1628. we will use the difference between the sample means as a test statistic,
  1629. and we will consider a p-value of 0.05 to be statistically significant.
  1630. For efficiency, we write the function defining the test statistic in a
  1631. vectorized fashion: the samples ``x`` and ``y`` can be ND arrays, and the
  1632. statistic will be calculated for each axis-slice along `axis`.
  1633. >>> import numpy as np
  1634. >>> def statistic(x, y, axis):
  1635. ... return np.mean(x, axis=axis) - np.mean(y, axis=axis)
  1636. After collecting our data, we calculate the observed value of the test
  1637. statistic.
  1638. >>> from scipy.stats import norm
  1639. >>> rng = np.random.default_rng()
  1640. >>> x = norm.rvs(size=5, random_state=rng)
  1641. >>> y = norm.rvs(size=6, loc = 3, random_state=rng)
  1642. >>> statistic(x, y, 0)
  1643. -3.5411688580987266
  1644. Indeed, the test statistic is negative, suggesting that the true mean of
  1645. the distribution underlying ``x`` is less than that of the distribution
  1646. underlying ``y``. To determine the probability of this occurring by chance
  1647. if the two samples were drawn from the same distribution, we perform
  1648. a permutation test.
  1649. >>> from scipy.stats import permutation_test
  1650. >>> # because our statistic is vectorized, we pass `vectorized=True`
  1651. >>> # `n_resamples=np.inf` indicates that an exact test is to be performed
  1652. >>> res = permutation_test((x, y), statistic, vectorized=True,
  1653. ... n_resamples=np.inf, alternative='less')
  1654. >>> print(res.statistic)
  1655. -3.5411688580987266
  1656. >>> print(res.pvalue)
  1657. 0.004329004329004329
  1658. The probability of obtaining a test statistic less than or equal to the
  1659. observed value under the null hypothesis is 0.4329%. This is less than our
  1660. chosen threshold of 5%, so we consider this to be significant evidence
  1661. against the null hypothesis in favor of the alternative.
  1662. Because the size of the samples above was small, `permutation_test` could
  1663. perform an exact test. For larger samples, we resort to a randomized
  1664. permutation test.
  1665. >>> x = norm.rvs(size=100, random_state=rng)
  1666. >>> y = norm.rvs(size=120, loc=0.2, random_state=rng)
  1667. >>> res = permutation_test((x, y), statistic, n_resamples=9999,
  1668. ... vectorized=True, alternative='less',
  1669. ... rng=rng)
  1670. >>> print(res.statistic)
  1671. -0.4230459671240913
  1672. >>> print(res.pvalue)
  1673. 0.0015
  1674. The approximate probability of obtaining a test statistic less than or
  1675. equal to the observed value under the null hypothesis is 0.0225%. This is
  1676. again less than our chosen threshold of 5%, so again we have significant
  1677. evidence to reject the null hypothesis in favor of the alternative.
  1678. For large samples and number of permutations, the result is comparable to
  1679. that of the corresponding asymptotic test, the independent sample t-test.
  1680. >>> from scipy.stats import ttest_ind
  1681. >>> res_asymptotic = ttest_ind(x, y, alternative='less')
  1682. >>> print(res_asymptotic.pvalue)
  1683. 0.0014669545224902675
  1684. The permutation distribution of the test statistic is provided for
  1685. further investigation.
  1686. >>> import matplotlib.pyplot as plt
  1687. >>> plt.hist(res.null_distribution, bins=50)
  1688. >>> plt.title("Permutation distribution of test statistic")
  1689. >>> plt.xlabel("Value of Statistic")
  1690. >>> plt.ylabel("Frequency")
  1691. >>> plt.show()
  1692. Inspection of the null distribution is essential if the statistic suffers
  1693. from inaccuracy due to limited machine precision. Consider the following
  1694. case:
  1695. >>> from scipy.stats import pearsonr
  1696. >>> x = [1, 2, 4, 3]
  1697. >>> y = [2, 4, 6, 8]
  1698. >>> def statistic(x, y, axis=-1):
  1699. ... return pearsonr(x, y, axis=axis).statistic
  1700. >>> res = permutation_test((x, y), statistic, vectorized=True,
  1701. ... permutation_type='pairings',
  1702. ... alternative='greater')
  1703. >>> r, pvalue, null = res.statistic, res.pvalue, res.null_distribution
  1704. In this case, some elements of the null distribution differ from the
  1705. observed value of the correlation coefficient ``r`` due to numerical noise.
  1706. We manually inspect the elements of the null distribution that are nearly
  1707. the same as the observed value of the test statistic.
  1708. >>> r
  1709. 0.7999999999999999
  1710. >>> unique = np.unique(null)
  1711. >>> unique
  1712. array([-1. , -1. , -0.8, -0.8, -0.8, -0.6, -0.4, -0.4, -0.2, -0.2, -0.2,
  1713. 0. , 0.2, 0.2, 0.2, 0.4, 0.4, 0.6, 0.8, 0.8, 0.8, 1. ,
  1714. 1. ]) # may vary
  1715. >>> unique[np.isclose(r, unique)].tolist()
  1716. [0.7999999999999998, 0.7999999999999999, 0.8] # may vary
  1717. If `permutation_test` were to perform the comparison naively, the
  1718. elements of the null distribution with value ``0.7999999999999998`` would
  1719. not be considered as extreme or more extreme as the observed value of the
  1720. statistic, so the calculated p-value would be too small.
  1721. >>> incorrect_pvalue = np.count_nonzero(null >= r) / len(null)
  1722. >>> incorrect_pvalue
  1723. 0.14583333333333334 # may vary
  1724. Instead, `permutation_test` treats elements of the null distribution that
  1725. are within ``max(1e-14, abs(r)*1e-14)`` of the observed value of the
  1726. statistic ``r`` to be equal to ``r``.
  1727. >>> correct_pvalue = np.count_nonzero(null >= r - 1e-14) / len(null)
  1728. >>> correct_pvalue
  1729. 0.16666666666666666
  1730. >>> res.pvalue == correct_pvalue
  1731. True
  1732. This method of comparison is expected to be accurate in most practical
  1733. situations, but the user is advised to assess this by inspecting the
  1734. elements of the null distribution that are close to the observed value
  1735. of the statistic. Also, consider the use of statistics that can be
  1736. calculated using exact arithmetic (e.g. integer statistics).
  1737. """
  1738. args = _permutation_test_iv(data, statistic, permutation_type, vectorized,
  1739. n_resamples, batch, alternative, axis,
  1740. rng)
  1741. (data, statistic, permutation_type, vectorized, n_resamples, batch,
  1742. alternative, axis, rng, float_dtype, xp) = args
  1743. observed = statistic(*data, axis=-1)
  1744. null_calculators = {"pairings": _calculate_null_pairings,
  1745. "samples": _calculate_null_samples,
  1746. "independent": _calculate_null_both}
  1747. null_calculator_args = (data, statistic, n_resamples,
  1748. batch, rng)
  1749. calculate_null = null_calculators[permutation_type]
  1750. null_distribution, n_resamples, exact_test = (
  1751. calculate_null(*null_calculator_args, xp=xp))
  1752. # See References [2] and [3]
  1753. adjustment = 0 if exact_test else 1
  1754. # relative tolerance for detecting numerically distinct but
  1755. # theoretically equal values in the null distribution
  1756. eps = (0 if not xp.isdtype(observed.dtype, 'real floating')
  1757. else xp.finfo(observed.dtype).eps*100)
  1758. gamma = xp.abs(eps * observed)
  1759. def less(null_distribution, observed):
  1760. cmps = null_distribution <= observed + gamma
  1761. count = xp.count_nonzero(cmps, axis=0) + adjustment
  1762. pvalues = xp.astype(count, float_dtype) / (n_resamples + adjustment)
  1763. return pvalues
  1764. def greater(null_distribution, observed):
  1765. cmps = null_distribution >= observed - gamma
  1766. count = xp.count_nonzero(cmps, axis=0) + adjustment
  1767. pvalues = xp.astype(count, float_dtype) / (n_resamples + adjustment)
  1768. return pvalues
  1769. def two_sided(null_distribution, observed):
  1770. pvalues_less = less(null_distribution, observed)
  1771. pvalues_greater = greater(null_distribution, observed)
  1772. pvalues = xp.minimum(pvalues_less, pvalues_greater) * 2
  1773. return pvalues
  1774. compare = {"less": less,
  1775. "greater": greater,
  1776. "two-sided": two_sided}
  1777. pvalues = compare[alternative](null_distribution, observed)
  1778. pvalues = xp.clip(pvalues, 0., 1.)
  1779. return PermutationTestResult(observed, pvalues, null_distribution)
  1780. @dataclass
  1781. class ResamplingMethod:
  1782. """Configuration information for a statistical resampling method.
  1783. Instances of this class can be passed into the `method` parameter of some
  1784. hypothesis test functions to perform a resampling or Monte Carlo version
  1785. of the hypothesis test.
  1786. Attributes
  1787. ----------
  1788. n_resamples : int
  1789. The number of resamples to perform or Monte Carlo samples to draw.
  1790. batch : int, optional
  1791. The number of resamples to process in each vectorized call to
  1792. the statistic. Batch sizes >>1 tend to be faster when the statistic
  1793. is vectorized, but memory usage scales linearly with the batch size.
  1794. Default is ``None``, which processes all resamples in a single batch.
  1795. """
  1796. n_resamples: int = 9999
  1797. batch: int = None # type: ignore[assignment]
  1798. @dataclass
  1799. class MonteCarloMethod(ResamplingMethod):
  1800. """Configuration information for a Monte Carlo hypothesis test.
  1801. Instances of this class can be passed into the `method` parameter of some
  1802. hypothesis test functions to perform a Monte Carlo version of the
  1803. hypothesis tests.
  1804. Attributes
  1805. ----------
  1806. n_resamples : int, optional
  1807. The number of Monte Carlo samples to draw. Default is 9999.
  1808. batch : int, optional
  1809. The number of Monte Carlo samples to process in each vectorized call to
  1810. the statistic. Batch sizes >>1 tend to be faster when the statistic
  1811. is vectorized, but memory usage scales linearly with the batch size.
  1812. Default is ``None``, which processes all samples in a single batch.
  1813. rvs : callable or tuple of callables, optional
  1814. A callable or sequence of callables that generates random variates
  1815. under the null hypothesis. Each element of `rvs` must be a callable
  1816. that accepts keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and
  1817. returns an N-d array sample of that shape. If `rvs` is a sequence, the
  1818. number of callables in `rvs` must match the number of samples passed
  1819. to the hypothesis test in which the `MonteCarloMethod` is used. Default
  1820. is ``None``, in which case the hypothesis test function chooses values
  1821. to match the standard version of the hypothesis test. For example,
  1822. the null hypothesis of `scipy.stats.pearsonr` is typically that the
  1823. samples are drawn from the standard normal distribution, so
  1824. ``rvs = (rng.normal, rng.normal)`` where
  1825. ``rng = np.random.default_rng()``.
  1826. rng : `numpy.random.Generator`, optional
  1827. Pseudorandom number generator state. When `rng` is None, a new
  1828. `numpy.random.Generator` is created using entropy from the
  1829. operating system. Types other than `numpy.random.Generator` are
  1830. passed to `numpy.random.default_rng` to instantiate a ``Generator``.
  1831. """
  1832. rvs: object = None
  1833. rng: object = None
  1834. def __init__(self, n_resamples=9999, batch=None, rvs=None, rng=None):
  1835. if (rvs is not None) and (rng is not None):
  1836. message = 'Use of `rvs` and `rng` are mutually exclusive.'
  1837. raise ValueError(message)
  1838. self.n_resamples = n_resamples
  1839. self.batch = batch
  1840. self.rvs = rvs
  1841. self.rng = rng
  1842. def _asdict(self):
  1843. # `dataclasses.asdict` deepcopies; we don't want that.
  1844. return dict(n_resamples=self.n_resamples, batch=self.batch,
  1845. rvs=self.rvs, rng=self.rng)
  1846. _rs_deprecation = ("Use of attribute `random_state` is deprecated and replaced by "
  1847. "`rng`. Support for `random_state` will be removed in SciPy 1.19.0. "
  1848. "To silence this warning and ensure consistent behavior in SciPy "
  1849. "1.19.0, control the RNG using attribute `rng`. Values set using "
  1850. "attribute `rng` will be validated by `np.random.default_rng`, so "
  1851. "the behavior corresponding with a given value may change compared "
  1852. "to use of `random_state`. For example, 1) `None` will result in "
  1853. "unpredictable random numbers, 2) an integer will result in a "
  1854. "different stream of random numbers, (with the same distribution), "
  1855. "and 3) `np.random` or `RandomState` instances will result in an "
  1856. "error. See the documentation of `default_rng` for more "
  1857. "information.")
  1858. @dataclass
  1859. class PermutationMethod(ResamplingMethod):
  1860. """Configuration information for a permutation hypothesis test.
  1861. Instances of this class can be passed into the `method` parameter of some
  1862. hypothesis test functions to perform a permutation version of the
  1863. hypothesis tests.
  1864. Attributes
  1865. ----------
  1866. n_resamples : int, optional
  1867. The number of resamples to perform. Default is 9999.
  1868. batch : int, optional
  1869. The number of resamples to process in each vectorized call to
  1870. the statistic. Batch sizes >>1 tend to be faster when the statistic
  1871. is vectorized, but memory usage scales linearly with the batch size.
  1872. Default is ``None``, which processes all resamples in a single batch.
  1873. rng : `numpy.random.Generator`, optional
  1874. Pseudorandom number generator used to perform resampling.
  1875. If `rng` is passed by keyword to the initializer or the `rng` attribute is used
  1876. directly, types other than `numpy.random.Generator` are passed to
  1877. `numpy.random.default_rng` to instantiate a ``Generator`` before use.
  1878. If `rng` is already a ``Generator`` instance, then the provided instance is
  1879. used. Specify `rng` for repeatable behavior.
  1880. If this argument is passed by position, if `random_state` is passed by keyword
  1881. into the initializer, or if the `random_state` attribute is used directly,
  1882. legacy behavior for `random_state` applies:
  1883. - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
  1884. singleton is used.
  1885. - If `random_state` is an int, a new ``RandomState`` instance is used,
  1886. seeded with `random_state`.
  1887. - If `random_state` is already a ``Generator`` or ``RandomState`` instance then
  1888. that instance is used.
  1889. .. versionchanged:: 1.15.0
  1890. As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
  1891. transition from use of `numpy.random.RandomState` to
  1892. `numpy.random.Generator`, this attribute name was changed from
  1893. `random_state` to `rng`. For an interim period, both names will continue to
  1894. work, although only one may be specified at a time. After the interim
  1895. period, uses of `random_state` will emit warnings. The behavior of both
  1896. `random_state` and `rng` are outlined above, but only `rng` should be used
  1897. in new code.
  1898. """
  1899. rng: object # type: ignore[misc]
  1900. _rng: object = field(init=False, repr=False, default=None) # type: ignore[assignment]
  1901. @property
  1902. def random_state(self):
  1903. # Uncomment in SciPy 1.17.0
  1904. # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
  1905. return self._random_state
  1906. @random_state.setter
  1907. def random_state(self, val):
  1908. # Uncomment in SciPy 1.17.0
  1909. # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
  1910. self._random_state = val
  1911. @property # type: ignore[no-redef]
  1912. def rng(self): # noqa: F811
  1913. return self._rng
  1914. def __init__(self, n_resamples=9999, batch=None, random_state=None, *, rng=None):
  1915. # Uncomment in SciPy 1.17.0
  1916. # warnings.warn(_rs_deprecation.replace('attribute', 'argument'),
  1917. # DeprecationWarning, stacklevel=2)
  1918. self._rng = rng
  1919. self._random_state = random_state
  1920. super().__init__(n_resamples=n_resamples, batch=batch)
  1921. def _asdict(self):
  1922. # `dataclasses.asdict` deepcopies; we don't want that.
  1923. d = dict(n_resamples=self.n_resamples, batch=self.batch)
  1924. if self.rng is not None:
  1925. d['rng'] = self.rng
  1926. if self.random_state is not None:
  1927. d['random_state'] = self.random_state
  1928. return d
  1929. @dataclass
  1930. class BootstrapMethod(ResamplingMethod):
  1931. """Configuration information for a bootstrap confidence interval.
  1932. Instances of this class can be passed into the `method` parameter of some
  1933. confidence interval methods to generate a bootstrap confidence interval.
  1934. Attributes
  1935. ----------
  1936. n_resamples : int, optional
  1937. The number of resamples to perform. Default is 9999.
  1938. batch : int, optional
  1939. The number of resamples to process in each vectorized call to
  1940. the statistic. Batch sizes >>1 tend to be faster when the statistic
  1941. is vectorized, but memory usage scales linearly with the batch size.
  1942. Default is ``None``, which processes all resamples in a single batch.
  1943. rng : `numpy.random.Generator`, optional
  1944. Pseudorandom number generator used to perform resampling.
  1945. If `rng` is passed by keyword to the initializer or the `rng` attribute is used
  1946. directly, types other than `numpy.random.Generator` are passed to
  1947. `numpy.random.default_rng` to instantiate a ``Generator`` before use.
  1948. If `rng` is already a ``Generator`` instance, then the provided instance is
  1949. used. Specify `rng` for repeatable behavior.
  1950. If this argument is passed by position, if `random_state` is passed by keyword
  1951. into the initializer, or if the `random_state` attribute is used directly,
  1952. legacy behavior for `random_state` applies:
  1953. - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
  1954. singleton is used.
  1955. - If `random_state` is an int, a new ``RandomState`` instance is used,
  1956. seeded with `random_state`.
  1957. - If `random_state` is already a ``Generator`` or ``RandomState`` instance then
  1958. that instance is used.
  1959. .. versionchanged:: 1.15.0
  1960. As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
  1961. transition from use of `numpy.random.RandomState` to
  1962. `numpy.random.Generator`, this attribute name was changed from
  1963. `random_state` to `rng`. For an interim period, both names will continue to
  1964. work, although only one may be specified at a time. After the interim
  1965. period, uses of `random_state` will emit warnings. The behavior of both
  1966. `random_state` and `rng` are outlined above, but only `rng` should be used
  1967. in new code.
  1968. method : {'BCa', 'percentile', 'basic'}
  1969. Whether to use the 'percentile' bootstrap ('percentile'), the 'basic'
  1970. (AKA 'reverse') bootstrap ('basic'), or the bias-corrected and
  1971. accelerated bootstrap ('BCa', default).
  1972. """
  1973. rng: object # type: ignore[misc]
  1974. _rng: object = field(init=False, repr=False, default=None) # type: ignore[assignment]
  1975. method: str = 'BCa'
  1976. @property
  1977. def random_state(self):
  1978. # Uncomment in SciPy 1.17.0
  1979. # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
  1980. return self._random_state
  1981. @random_state.setter
  1982. def random_state(self, val):
  1983. # Uncomment in SciPy 1.17.0
  1984. # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
  1985. self._random_state = val
  1986. @property # type: ignore[no-redef]
  1987. def rng(self): # noqa: F811
  1988. return self._rng
  1989. def __init__(self, n_resamples=9999, batch=None, random_state=None,
  1990. method='BCa', *, rng=None):
  1991. # Uncomment in SciPy 1.17.0
  1992. # warnings.warn(_rs_deprecation.replace('attribute', 'argument'),
  1993. # DeprecationWarning, stacklevel=2)
  1994. self._rng = rng # don't validate with `default_rng`
  1995. self._random_state = random_state
  1996. self.method = method
  1997. super().__init__(n_resamples=n_resamples, batch=batch)
  1998. def _asdict(self):
  1999. # `dataclasses.asdict` deepcopies; we don't want that.
  2000. d = dict(n_resamples=self.n_resamples, batch=self.batch,
  2001. method=self.method)
  2002. if self.rng is not None:
  2003. d['rng'] = self.rng
  2004. if self.random_state is not None:
  2005. d['random_state'] = self.random_state
  2006. return d