L i:dZgdZddlZddlmZddlmZddlmZmZddl Z ddl Z ddl Z ddl m Z ddlmZdd lmZmZdd lmZddlmZddlZddlmcmZdd lmZmZmZ d Z!d Z"dZ#dZ$dZ%dZ&dedZ'dfdZ(e ddZ)dgdZ*dhdZ+dZ,dZ-dZ. didZ/djdZ0 dkdZ1dZ2e dd Z3d!Z4dld"Z5dmd#Zdnd$Zed%d&d'gZ6d(Z7e d)d*Z8dod+Z9e9Z:e d,d*Z;dpd-Z<e d.d*Z=dod/Z>e d0d*Z?dqd1Z@e d2d*ZAd3ZBeBZCed4d5drd6ZDed4d5dsd7ZEeEZFed4d5drd8ZGdtd9ZHdud:ZId;ZJdvd<ZKeKjreKjeJzeK_dwd=ZL dxd>ZMeMZN dyd?ZOeOjreOjeJzeO_ dzd@ZPePjrePjeJzeP_ dzdAZQeQjreQjeJzeQ_d{dBZRdCZSdudDZTd|dEZUd}dFZVd}dGZWd|dHZX d~dIZYddJZZddKdLZ[ddMZ\dhdNZ]ddOZ^e dPdQZ_ddRZ`dldSZae dTd*ZbdodUZce dVd*ZddodWZee dXd*ZfdgdYZg ddZZhdd[Zidd\ZjejZkd]Zldd^Zme d_d*Znd`Zoe dad*ZpdbZqe dcd*ZrdddZsy)zA An extension of scipy.stats._stats_py to support masked arrays ): argstoarraycount_tied_groupsdescribef_oneway find_repeatsfriedmanchisquare kendalltaukendalltau_seasonalkruskal kruskalwallis ks_twosampks_2sampkurtosis kurtosistestks_1sampkstest linregress mannwhitneyumeppfmodemoment mquantilesmsign normaltestobrientransformpearsonrplotting_positionspointbiserialrrankdatascoreatpercentilesemsen_seasonal_slopesskewskewtest spearmanr siegelslopes theilslopestmaxtmeantmintrimtrimbothtrimtailtrimatrimr trimmed_mean trimmed_std trimmed_stde trimmed_vartsem ttest_1samp ttest_onesamp ttest_ind ttest_reltvar variation winsorize brunnermunzelN)ndarray)maskednomask) namedtuple) distributions)_rename_parameter _contains_nan)_make_tuple_bunch) _find_repeatsr&r%crtj|}|tj|}d}||fS|}||fSNr<ma asanyarrayravel)aaxisoutaxiss _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/stats/_mstats_basic.py _chk_asarrayrQ9sD aA | HHQK g: g:ctj|}tj|}|-tj|}tj|}d}n|}|||fSrHrI)rMbrNrOs rP _chk2_asarrayrUDsS aA aA | HHQK HHQK a=rRctj|}tj|}|j|j}}||k7rtd|d|d|||fS)Nz+The size of the input array should match! (z <> ))rJrKsize ValueError)rMrTnanbs rP _chk_sizer\Psf aA aAR Rx TbT,- - q":rRc|dk(r!tjj||}no|dk(r"tjj|| }nH|dk(r8tjj|tj| dz}n t d|j dk(r|d}|j dk(r|d}||fS)z+Common code between all 3 t-test functions.lessgreater two-sidedz4alternative must be 'less', 'greater' or 'two-sided'r<)special_ufuncsstdtrnpabsrYndim)dft alternativepvals rP _ttest_finishrmZsf$$R+  !$$R!,  #$$R"&&)4Q6<= = vv{ bE yyA~Bx d7NrRc0t|dk(rEt|dts2tj|d}|j dk7rt dt|}t|Dcgc] }t|c}}tjtj||ftd}t|D]\}}|||dt|f<t|tjtj|j <|Scc}w) a Constructs a 2D array from a group of sequences. Sequences are filled with missing values to match the length of the longest sequence. Parameters ---------- *args : sequences Group of sequences. Returns ------- argstoarray : MaskedArray A ( `m` x `n` ) masked array, where `m` is the number of arguments and `n` the length of the longest argument. Notes ----- `numpy.ma.vstack` has identical behavior, but is called with a sequence of sequences. Examples -------- A 2D masked array constructed from a group of sequences is returned. >>> from scipy.stats.mstats import argstoarray >>> argstoarray([1, 2, 3], [4, 5, 6]) masked_array( data=[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], mask=[[False, False, False], [False, False, False]], fill_value=1e+20) The returned masked array filled with missing values when the lengths of sequences are different. >>> argstoarray([1, 3], [4, 5, 6]) masked_array( data=[[1.0, 3.0, --], [4.0, 5.0, 6.0]], mask=[[False, False, True], [False, False, False]], fill_value=1e+20) rAr<razThe input should be 2DdtypeTmaskN)len isinstancer=rJasarrayrhrYmaxarrayrfemptyfloat enumerater> logical_notisfinite_data)argsoutputnkmvs rPrrps` 4yA~ja':DG$ ;;! 56 6 I &AQ& '"((Aa56TBt_ "EQq !F1Wc!fW9  "9?F2>>"++fll3 45 M 's(Dctjtj|tj} tj ||}|r|j}t|S#t $rd}Y*wxYw)aFind repeats in arr and return a tuple (repeats, repeat_count). The input is cast to float64. Masked values are discarded. Parameters ---------- arr : sequence Input array. The array is flattened if it is not 1D. Returns ------- repeats : ndarray Array of repeated values. counts : ndarray Array of counts. Examples -------- >>> from scipy.stats import mstats >>> mstats.find_repeats([2, 1, 2, 3, 2, 2, 5]) (array([2.]), array([4])) In the above example, 2 repeats 4 times. >>> mstats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]]) (array([4., 5.]), array([2, 2])) In the above example, both 4 and 5 repeat 2 times. roF) rfrurJ compressedfloat64may_share_memoryAttributeErrorcopyrF)arrcompr need_copys rPrrslB JJr}}S) >> from scipy.stats import mstats >>> import numpy as np >>> z = [0, 0, 0, 2, 2, 2, 3, 3, 4, 5, 6] >>> mstats.count_tied_groups(z) {2: 1, 3: 2} In the above example, the ties were 0 (3x), 2 (3x) and 3 (2x). >>> z = np.ma.array([0, 0, 1, 2, 2, 2, 3, 3, 4, 5, 6]) >>> mstats.count_tied_groups(z) {2: 2, 3: 1} >>> z[[1,-1]] = np.ma.masked >>> mstats.count_tied_groups(z, use_missing=True) {2: 2, 3: 1} rA)rJgetmasksumrrrrsdictziprfunique itertoolsrepeatupdateKeyError)x use_missingnmaskeddatatiescountsntiess rPrrsDjjm!G ==  "D!$'NT6 E 4yS6*I,<,._rank1d%s JJL XXdiiu -llnii!A#&3r7 Q3(Bs12wKBs12wKtyy{+ 1A**51IyM..0ByM 1 rRrrAF) rJrwrhrLreshapeshapeapply_along_axisviewr=)rrNrrs rPrrsz*" 88Du %D | 99q=4::<5==djjI I4- -""74[AFFwOOrR ModeResult)rrct||dS)aA Returns an array of the modal (most common) value in the passed array. Parameters ---------- a : array_like n-dimensional array of which to find mode(s). axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. Returns ------- mode : ndarray Array of modal values. count : ndarray Array of counts for each mode. Notes ----- For more details, see `scipy.stats.mode`. Examples -------- >>> import numpy as np >>> from scipy import stats >>> from scipy.stats import mstats >>> m_arr = np.ma.array([1, 1, 0, 0, 0, 0], mask=[0, 0, 1, 1, 1, 0]) >>> mstats.mode(m_arr) # note that most zeros are masked ModeResult(mode=array([1.]), count=array([2.])) T)rNkeepdims)_mode)rMrNs rPrrCsB  --rRcJt||\}}d}|S|tj|}tj|dtj|df}t|Stj|||}||rt |j }d||<tdg|jz}d||<|t|j|}d||<|t|j|}||f}t|Stj||d}t|S)Nct|\}}|jsy|jr#||j|j fS|j dfS)Nr<r<rA)rrhrXargmaxrvmin)rMrepcnts rP_mode1Dz_mode.._mode1DksL O Sxx XX %swwy1 1EEGQ< rRr<rA)rQrJrLrwrlistrslicerhtuplerrfmoveaxisr) rMrNrrrnewshapeslicesmodesrs rPrrgs"1d#GAt  |!%((6!9%rxxq ':; v $$WdA6  xAGG}HHTNDk]V[[0FF4L5=)11(;EF4LE&M*228>> import numpy as np >>> from scipy import stats >>> from scipy.stats import mstats >>> mstats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4]) (-0.7426106572325057, 0.1505558088534455) There is a linear dependence between x and y if y = a + b*x + e, where a,b are constants and e is a random error term, assumed to be independent of x. For simplicity, assume that x is standard normal, a=0, b=1 and let e follow a normal distribution with mean zero and standard deviation s>0. >>> s = 0.5 >>> x = stats.norm.rvs(size=500) >>> e = stats.norm.rvs(scale=s, size=500) >>> y = x + e >>> mstats.pearsonr(x, y) (0.9029601878969703, 8.428978827629898e-185) # may vary This should be close to the exact value given by >>> 1/np.sqrt(1 + s**2) 0.8944271909999159 For s=0.5, we observe a high level of correlation. In general, a large variance of the noise reduces the correlation, while the correlation approaches one as the variance of the error goes to zero. It is important to keep in mind that no correlation does not imply independence unless (x, y) is jointly normal. Correlation can even be zero when there is a very simple dependence structure: if X follows a standard normal distribution, let y = abs(x). Note that the correlation between x and y is zero. Indeed, since the expectation of x is zero, cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero by symmetry. The following lines of code illustrate this observation: >>> y = np.abs(x) >>> mstats.pearsonr(x, y) (-0.016172891856853524, 0.7182823678751942) # may vary A non-zero correlation coefficient can be misleading. For example, if X has a standard normal distribution, define y = x if x < 0 and y = 0 otherwise. A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797..., implying a high level of correlation: >>> y = np.where(x < 0, x, 0) >>> mstats.pearsonr(x, y) (0.8537091583771509, 3.183461621422181e-143) # may vary This is unintuitive since there is no dependence of x and y if x is larger than zero which happens in about half of the cases if we sample x and y. rar<rq) r\rLrJmask_orrrr>scipystats _stats_pyr masked_arrayr)ryrrris rPrrs|!QIQ1ggiQ 2::a="**Q-0ALA 1B Av ;; ) )*557*557 99rRc0|s tdt||\}}|Ct||\}}|dk(rtj||f}ntj||f}|dk(r |j }|dk(rtj |}fd}|jd} | dk(r||Stj| | ft} tj| | ft} t| dz D]k} t| dz| D]W} ||dd| | gf}|j| | | f<|j| | | f<|j| | | f<|j| | | f<Ymtj j"j%| | }| |_ |S) a Calculates a Spearman rank-order correlation coefficient and the p-value to test for non-correlation. The Spearman correlation is a nonparametric measure of the linear relationship between two datasets. Unlike the Pearson correlation, the Spearman correlation does not assume that both datasets are normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply a monotonic relationship. Positive correlations imply that as `x` increases, so does `y`. Negative correlations imply that as `x` increases, `y` decreases. Missing values are discarded pair-wise: if a value is missing in `x`, the corresponding value in `y` is masked. The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Spearman correlation at least as extreme as the one computed from these datasets. The p-values are not entirely reliable but are probably reasonable for datasets larger than 500 or so. Parameters ---------- x, y : 1D or 2D array_like, y is optional One or two 1-D or 2-D arrays containing multiple variables and observations. When these are 1-D, each represents a vector of observations of a single variable. For the behavior in the 2-D case, see under ``axis``, below. use_ties : bool, optional DO NOT USE. Does not do anything, keyword is only left in place for backwards compatibility reasons. axis : int or None, optional If axis=0 (default), then each column represents a variable, with observations in the rows. If axis=1, the relationship is transposed: each row represents a variable, while the columns contain observations. If axis=None, then both arrays will be raveled. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. 'propagate' returns nan, 'raise' throws an error, 'omit' performs the calculations ignoring nan values. Default is 'propagate'. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. Default is 'two-sided'. The following options are available: * 'two-sided': the correlation is nonzero * 'less': the correlation is negative (less than zero) * 'greater': the correlation is positive (greater than zero) .. versionadded:: 1.7.0 Returns ------- res : SignificanceResult An object containing attributes: statistic : float or ndarray (2-D square) Spearman correlation matrix or correlation coefficient (if only 2 variables are given as parameters). Correlation matrix is square with length equal to total number of variables (columns or rows) in ``a`` and ``b`` combined. pvalue : float The p-value for a hypothesis test whose null hypothesis is that two sets of data are linearly uncorrelated. See `alternative` above for alternative hypotheses. `pvalue` has the same shape as `statistic`. References ---------- [CRCProbStat2000] section 14.7 z3`use_ties=False` is not supported in SciPy >= 1.2.0Nr<rAomitcVtj|d}||jjdddf}t j|j s]t jjjtjtj}tj|_ |Stj|}|jd}|dz t|jddz }|dkr t!dt#|d}tj$|dj }t j&d 5|t j(||d zd |z zz j+dz}dddt-| \}}|jd k(r._spearmanr_2colss OOAA & qvvzzqz!!1$ %vvaff~++''::266266JC ffCOJ JJqM ai#aeeemA.// 7FG GAA& [[% 0 5 5[[ ) DRWWcbfR%89??BCCA D  Q 44 88v ++''::2d8;?:GC hCOJ++''::2tDC COJ! D Ds 4HH(raro)rYrQrJ column_stackvstackTmasked_invalidrrfonesryzerosrangerpvaluerrrr)rruse_tiesrN nan_policyrkaxisout_rn_varsrrvar1var2resultrs ` rPr$r$?sR NOOa&JAw}At$1 a<A'A 1a&!A!| CCV   a 'VWWQZF {"" WWff%U 3xx(6&1*% 1Dd1ff- 1)!Ad|O*<=!'!3!34:!'!3!34:#)==T4Z #)==T4Z  1 1kk##66r4@ rRc |||dz zdz|z k\}|dk(}tt|||dz zdz|z }|dkrtd|d|dksd|z||dz zkDrtd|d ||dz zd |dk(rd }d}n|dk(rd }d }n|dk(r&|d krdtj|z nd}|dz }n|dk(r?|dkrdtj|dz z nd}|dz tj|z }nLd|z||dz zk(r |dk(rd }n5|d krt j |dz}d |ddtd|dzD]4}t j|}||ks||dxxx|d|dz|z zccc6dt j|ztj|z }|dtj|z }nt j |dz}d |ddtd|dzD]7}t j||z }||ks!||dxxx|d|dz|z zccc9t j|}|ddz }|dk7r||k(r|dz}n d|dz z z}t j|dd}|S)NrArar_r<zn (z) must be positivezc (z#) must satisfy 0 <= 4c <= n(n-1) = .r?rr`) rrrYmath factorialrfrrcumsumrr) rcrk in_right_tailalternative_greaterr p_mass_at_cnewjs rP_kendall_p_exactrs1ac7Q,**M&)3 CAqsGa>!$$S1f a*+c's4>>!A#&&ssDNN1-- 11Q3K;6 ShhqsmAaq1 'A))C.CAvAB3v!A;& '266#;t~~a00"gdnnQ// hhqsmAaq!A# 'A))C."CAvAB3v!A;& 'vvc{"gai k! / / AIDtAv: +D 774A D KrRc B t||\}}}|j|j}}tjtj|tj|}|t urLtj ||d}tj ||d}|t|jz}|dkr]tjjjtjtj}tj|_|Stj t#||d} tj t#||d} | j%} | | | | } } tjt't)| dz D cgc]<} | | dzd| | kD| | dzd| | kDzj+dj>c} t,} tjt't)| dz D cgc]<} | | dzd| | k| | dzd| | kDzj+dj>c} t,}t/|}t/|}|rtj|j1Dcgc]\}}||z|dz zc}}t,}tj|j1Dcgc]\}}||z|dz zc}}t,}tj2||dz z|z d z ||dz z|z zd z }n ||dz zd z }| |z |z }|d k(r|s|r t5d |d k(r)|s%|s#|d kst7| ||dz zd z | z dkrd }nd}|s|s|d k(rt9|| |}n|dk(rc||dz zd|zdzz}|r|tj|j1Dcgc]\}}||z|dz zd|zdzzdzc}}z}|tj|j1Dcgc]\}}||z|dz zd|zdzzdzc}}z}tj|j1Dcgc]\}}||z|dz zc}}t,tj|j1Dcgc]\}}||z|dz zc}}t,z}|d |z|dz zz}|dkDrtj|j1Dcgc]\}}||z|dz z|dz zc}}t,tj|j1Dcgc]\}}||z|dz z|dz zc}}t,z}|d|z|dz z|dz zz}nd}ndx}}|dz}|||zz }| |z tj2|z }tjjj;|t<j>|}nt5dtA|zdztjjj|d|d}||_|Scc} wcc} wcc}}wcc}}wcc}}wcc}}wcc}}wcc}}wcc}}wcc}}w)a Computes Kendall's rank correlation tau on two variables *x* and *y*. Parameters ---------- x : sequence First data list (for example, time). y : sequence Second data list. use_ties : {True, False}, optional Whether ties correction should be performed. use_missing : {False, True}, optional Whether missing data should be allocated a rank of 0 (False) or the average rank (True) method : {'auto', 'asymptotic', 'exact'}, optional Defines which method is used to calculate the p-value [1]_. 'asymptotic' uses a normal approximation valid for large samples. 'exact' computes the exact p-value, but can only be used if no ties are present. As the sample size increases, the 'exact' computation time may grow and the result may lose some precision. 'auto' is the default and selects the appropriate method based on a trade-off between speed and accuracy. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. Default is 'two-sided'. The following options are available: * 'two-sided': the rank correlation is nonzero * 'less': the rank correlation is negative (less than zero) * 'greater': the rank correlation is positive (greater than zero) Returns ------- res : SignificanceResult An object containing attributes: statistic : float The tau statistic. pvalue : float The p-value for a hypothesis test whose null hypothesis is an absence of association, tau = 0. References ---------- .. [1] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition), Charles Griffin & Co., 1970. T)rrrrarr<rANrorexactz(Ties found, exact method cannot be used.auto! asymptoticr"@g2@zUnknown method z1 specified, please use auto, exact or asymptotic.rb)!r\flattenrJrrr?rwrrrrrrrfrr masked_equalrrrrsrryritemsrrYrr _get_pvaluerBnormstr)rrrrmethodrkrrrrxryriCDxtiesytiesrrcorr_xcorr_ydenomtaurvar_sv1v2zs rPrrsb!QIQ1iik199;Q 2::a="**Q-0A HHQQT * HHQQT * S\1ukk##66rvvrvvF&& !=q AB !=q AB **,C3CR s2wqy)+QqST(RU"r!A#$x"Q%'78@@CGGI+27 9A s2wqy)+QqST(RU"R!X1%56>>qAEEG+27 9A a E a E >u!1ac>eL >u!1ac>eLAaC+q!A#wv~>rAB1Q3  Q3%-C euCDD e!r'SAqsGCKM5Ja5OF!F 6W#41k2 < 1Q31Q  RVVu{{}MeqQqS!A#Y!A.r1MN NE RVVu{{}MeqQqS!A#Y!A.r1MN NE&&%++-@A!A#qs)@N&&%++-@A!A#qs)@NOB "Q$!* B1uVV%++-H!AQqS!A#Y!_H"')VV%++-H!AQqS!A#Y!_H"'))bdAaCj!A#&&KB   "r' qS"''%. {{$$00M4F4F T*3v;68::; ; ++   2 23r7DH ECCO Jo++ ?>*NM@@IHs>'AY'AY,%Y1 *Y7 (!Y= 6!Z Z Z !Z +Z c tjdddj\}}jd}t fdt |D}|j }j}t j}t d|jD}tjd|z|d z z||d z z|z zd z } tdd } tj||ft } tj||ft } tj|t } t |D] t d d fj}t d|jD}||d z z}t |d D]t fdt |D| f<| fd| d d f| d d fzj zz||d zz|d zzz dz | f<| f| f<| f| f<tj|||z zd z | < | j}t|t!|d z ztj|z }t|t!|d z ztj|j z }t|t!|d z ztj| j z }t#j$t!|j&t)jdz }t#j$t!|t)jdz }t#j$t!|t)jdz }||zj }||j+dzz}|| z || z || j z |||||d}|S)z Computes a multivariate Kendall's rank correlation tau, for seasonal data. Parameters ---------- x : 2-D ndarray Array of seasonal data, with seasons in columns. TFrasubokrndminr<c3dK|]'}t|d|z jd)ywrHrr).0r rs rP z&kendalltau_seasonal..s/;QaeAaDj!%%a(;s-0c38K|]\}}||z|dz zywrANrbr3rrs rPr4z&kendalltau_seasonal..s 8%1QAaC1I8rrAr)rNrroNc38K|]\}}||z|dz zywr6rbr7s rPr4z&kendalltau_seasonal..s ;5AaQqS!A#Y;r8c3K|]>}t|df|fz |df|fz zj@ywNr2)r3r r rrs rPr4z&kendalltau_seasonal..sX,!"Q$!A#12a41Q3@AEEG,sAAr@)z seasonal tauz global tauzglobal tau (alt)zseasonal p-valuezglobal p-value (indep)zglobal p-value (dep)z chi2 totalz chi2 trend)rJrwrrrrrrrrrrxrrydiagonalrrgrcerfcrrfr)rrrn_pS_sznS_totn_totr corr_ties denom_totRKcovmat denom_sznties_jcorr_jcmbvar_sznz_szn z_tot_ind z_tot_depprob_szn prob_tot_ind prob_tot_depchi2_totchi2_trdrr rs` @@rPr r s $U!4A GGEQq ''!*C ;%(; ;E IIKE GGIE Q\\^ ,D84::<88I5%'*E57OI,EFGJI-A !Ac"A XXqe5 )F%(I 1X 6"1QqS6#4#4#67;FLLN;;!fc!fQhq1 &A,"'(,,AacFQqS6Aq1va!f}&9&9&;$;;c!fQh<Q23467F1Q3KqsVAacF 1+F1Q3K  &wwsCJ/025 !  6ooG %LCJqL )BGGG,< >> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import stats >>> rng = np.random.default_rng() Generate some data: >>> x = rng.random(10) >>> y = 1.6*x + rng.random(10) Perform the linear regression: >>> res = stats.mstats.linregress(x, y) Coefficient of determination (R-squared): >>> print(f"R-squared: {res.rvalue**2:.6f}") R-squared: 0.717533 Plot the data along with the fitted line: >>> plt.plot(x, y, 'o', label='original data') >>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line') >>> plt.legend() >>> plt.show() Calculate 95% confidence interval on slope and intercept: >>> # Two-sided inverse Students t-distribution >>> # p - probability, df - degrees of freedom >>> from scipy.stats import t >>> tinv = lambda p, df: abs(t.ppf(p/2, df)) >>> ts = tinv(0.05, len(x)-2) >>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}") slope (95%): 1.453392 +/- 0.743465 >>> print(f"intercept (95%): {res.intercept:.6f}" ... f" +/- {ts*res.intercept_stderr:.6f}") intercept (95%): 0.616950 +/- 0.544475 Nr<rarAzZIf only `x` is given as input, it has to be of shape (2, N) or (N, 2), provided shape was zBCannot calculate a linear regression if all x values are identicalF)shrinkrq)slope interceptrvaluerstderrintercept_stderr)rJrwrrrYrrfamaxaminrsrrr?rrrrLinregressResult)rrrrs rPrrsV y HHQK 771:?DAq WWQZ1_33DAq33477)=> > HHQK HHQK A A wwqzRWWQZCFQJ9: : 2::a="**Q->A HHQQ  HHQQ  661":))!&&!*affaRjAF M//dd7;D7;AEGF M%%affaff5 MrRcjtj|j}|%tjt |t }n^tj|j}t |t |k7r$t dt |dt |dtjtj|tj|}|x|_ |_ |j}|jjt }t||||S)am Computes the Theil-Sen estimator for a set of points (x, y). `theilslopes` implements a method for robust linear regression. It computes the slope as the median of all slopes between paired values. Parameters ---------- y : array_like Dependent variable. x : array_like or None, optional Independent variable. If None, use ``arange(len(y))`` instead. alpha : float, optional Confidence degree between 0 and 1. Default is 95% confidence. Note that `alpha` is symmetric around 0.5, i.e. both 0.1 and 0.9 are interpreted as "find the 90% confidence interval". method : {'joint', 'separate'}, optional Method to be used for computing estimate for intercept. Following methods are supported, * 'joint': Uses np.median(y - slope * x) as intercept. * 'separate': Uses np.median(y) - slope * np.median(x) as intercept. The default is 'separate'. .. versionadded:: 1.8.0 Returns ------- result : ``TheilslopesResult`` instance The return value is an object with the following attributes: slope : float Theil slope. intercept : float Intercept of the Theil line. low_slope : float Lower bound of the confidence interval on `slope`. high_slope : float Upper bound of the confidence interval on `slope`. See Also -------- siegelslopes : a similar technique using repeated medians Notes ----- For more details on `theilslopes`, see `scipy.stats.theilslopes`. roIncompatible lengths ! (<>rW)alphar) rJrurrrsryrYrr_maskrrXstats_theilslopes)rrrorrs rPr&r&sj 1 Ay IIc!fE * JJqM ! ! # q6SV 7Axr#a&KL L 2::a="**Q-0AAGag A e$A Qv >>rRchtj|j}|%tjt |t }n^tj|j}t |t |k7r$t dt |dt |dtjtj|tj|}|x|_ |_ |j}|jjt }t|||S)a Computes the Siegel estimator for a set of points (x, y). `siegelslopes` implements a method for robust linear regression using repeated medians to fit a line to the points (x, y). The method is robust to outliers with an asymptotic breakdown point of 50%. Parameters ---------- y : array_like Dependent variable. x : array_like or None, optional Independent variable. If None, use ``arange(len(y))`` instead. method : {'hierarchical', 'separate'} If 'hierarchical', estimate the intercept using the estimated slope ``slope`` (default option). If 'separate', estimate the intercept independent of the estimated slope. See Notes for details. Returns ------- result : ``SiegelslopesResult`` instance The return value is an object with the following attributes: slope : float Estimate of the slope of the regression line. intercept : float Estimate of the intercept of the regression line. See Also -------- theilslopes : a similar technique without repeated medians Notes ----- For more details on `siegelslopes`, see `scipy.stats.siegelslopes`. rormrnrW)r) rJrurLrrsryrYrrrprrXstats_siegelslopes)rrrrs rPr%r%sP 1 Ay IIc!fE * JJqM   ! q6SV 7Axr#a&KL L 2::a="**Q-0AAGag A e$A a6 22rRSenSeasonalSlopesResult intra_slope inter_slopec tj|ddd}|j\}}tjt |Dcgc]1}||dzd||z t j d||z dddfz 3c}}tj|d}tj|d}t||Scc}w) a) Computes seasonal Theil-Sen and Kendall slope estimators. The seasonal generalization of Sen's slope computes the slopes between all pairs of values within a "season" (column) of a 2D array. It returns an array containing the median of these "within-season" slopes for each season (the Theil-Sen slope estimator of each season), and it returns the median of the within-season slopes across all seasons (the seasonal Kendall slope estimator). Parameters ---------- x : 2D array_like Each column of `x` contains measurements of the dependent variable within a season. The independent variable (usually time) of each season is assumed to be ``np.arange(x.shape[0])``. Returns ------- result : ``SenSeasonalSlopesResult`` instance The return value is an object with the following attributes: intra_slope : ndarray For each season, the Theil-Sen slope estimator: the median of within-season slopes. inter_slope : float The seasonal Kendall slope estimator: the median of within-season slopes *across all* seasons. See Also -------- theilslopes : the analogous function for non-seasonal data scipy.stats.theilslopes : non-seasonal slopes for non-masked arrays Notes ----- The slopes :math:`d_{ijk}` within season :math:`i` are: .. math:: d_{ijk} = \frac{x_{ij} - x_{ik}} {j - k} for pairs of distinct integer indices :math:`j, k` of :math:`x`. Element :math:`i` of the returned `intra_slope` array is the median of the :math:`d_{ijk}` over all :math:`j < k`; this is the Theil-Sen slope estimator of season :math:`i`. The returned `inter_slope` value, better known as the seasonal Kendall slope estimator, is the median of the :math:`d_{ijk}` over all :math:`i, j, k`. References ---------- .. [1] Hirsch, Robert M., James R. Slack, and Richard A. Smith. "Techniques of trend analysis for monthly water quality data." *Water Resources Research* 18.1 (1982): 107-121. Examples -------- Suppose we have 100 observations of a dependent variable for each of four seasons: >>> import numpy as np >>> rng = np.random.default_rng() >>> x = rng.random(size=(100, 4)) We compute the seasonal slopes as: >>> from scipy import stats >>> intra_slope, inter_slope = stats.mstats.sen_seasonal_slopes(x) If we define a function to compute all slopes between observations within a season: >>> def dijk(yi): ... n = len(yi) ... x = np.arange(n) ... dy = yi - yi[:, np.newaxis] ... dx = x - x[:, np.newaxis] ... # we only want unique pairs of distinct indices ... mask = np.triu(np.ones((n, n), dtype=bool), k=1) ... return dy[mask]/dx[mask] then element ``i`` of ``intra_slope`` is the median of ``dijk[x[:, i]]``: >>> i = 2 >>> np.allclose(np.median(dijk(x[:, i])), intra_slope[i]) True and ``inter_slope`` is the median of the values returned by ``dijk`` for all seasons: >>> all_slopes = np.concatenate([dijk(x[:, i]) for i in range(x.shape[1])]) >>> np.allclose(np.median(all_slopes), inter_slope) True Because the data are randomly generated, we would expect the median slopes to be nearly zero both within and across all seasons, and indeed they are: >>> intra_slope.data array([ 0.00124504, -0.00277761, -0.00221245, -0.00036338]) >>> inter_slope -0.0010511779872922058 TFrar.rANr<r) rJrwrrrrfrmedianrt)rrrr  szn_slopes szn_medslopesmedslopes rPr!r!(sT $U!4A GGEQq%*1X/ !qstWQqT\299Qqs+;AdF+CC/0JIIjq1Myy$/H "=( ;; /s6B<Ttest_1sampResult) statisticrct||\}}|jdk(r tjtjfS|j |}|j |d}|j |}tj|dz }|dz |z|z }tjdd5||z tj||z z } dddt| |\} } t| | S#1swY%xYw) a Calculates the T-test for the mean of ONE group of scores. Parameters ---------- a : array_like sample observation popmean : float or array_like expected value in null hypothesis, if array_like than it must have the same shape as `a` excluding the axis dimension axis : int or None, optional Axis along which to compute test. If None, compute over the whole array `a`. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided': the mean of the underlying distribution of the sample is different than the given population mean (`popmean`) * 'less': the mean of the underlying distribution of the sample is less than the given population mean (`popmean`) * 'greater': the mean of the underlying distribution of the sample is greater than the given population mean (`popmean`) .. versionadded:: 1.7.0 Returns ------- statistic : float or array t-statistic pvalue : float or array The p-value Notes ----- For more details on `ttest_1samp`, see `scipy.stats.ttest_1samp`. r<rrArNddofrrrinvalidN) rQrXrfrrvarrrJrKrrrmr|) rMpopmeanrNrkrrrrisvarrjrs rPr4r4sN1d#GAtvv{ DA 4a A TA q3w B WMR D Hh 7. [BGGD1H- -.B;/GAt Q %% ..s 0C33C<Ttest_indResultct|||\}}}|jdk(s|jdk(r(ttjtjS|j ||j |}}|j |d|j |d}}|j||j|} } |rQtj| | zdz } | dz |z| dz |zz| z } tj| d| z d| z zz} n|| z }|| z }tjdd5||zdz|dz| dz z |dz| dz z zz } d d d tjtj d| } tj||z} tjdd5||z | z }d d d t| |\}}t||S#1swYxYw#1swY1xYw) a Calculates the T-test for the means of TWO INDEPENDENT samples of scores. Parameters ---------- a, b : array_like The arrays must have the same shape, except in the dimension corresponding to `axis` (the first, by default). axis : int or None, optional Axis along which to compute test. If None, compute over the whole arrays, `a`, and `b`. equal_var : bool, optional If True, perform a standard independent 2 sample test that assumes equal population variances. If False, perform Welch's t-test, which does not assume equal population variance. .. versionadded:: 0.17.0 alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided': the means of the distributions underlying the samples are unequal. * 'less': the mean of the distribution underlying the first sample is less than the mean of the distribution underlying the second sample. * 'greater': the mean of the distribution underlying the first sample is greater than the mean of the distribution underlying the second sample. .. versionadded:: 1.7.0 Returns ------- statistic : float or array The calculated t-statistic. pvalue : float or array The p-value. Notes ----- For more details on `ttest_ind`, see `scipy.stats.ttest_ind`. r<rArrrrrraN)rUrXrrfrrrrrJrKrrrisnanrm)rMrTrN equal_varrkx1x2r*r+n1n2rirr'vn1vn2rjrs rPr6r6s\q!T*JAq$vv{affkrvvrvv..t affTlR4a(!%%T%*BR qwwt}R ]]27S= )Ar 2a4)#r)c"fs2vo./ee [[( ; J)a36R!V#4sAva7H#HIB J XXbhhrlAr *c " Hh 7 UeOB;/GAt 1d ## J Js6!G%8 G1%G.1G:Ttest_relResultct|||\}}}t|t|k7r td|jdk(s|jdk(r(t t j t j S|j|}tj|dz }||z jd}|j|}|j|d}tj||z } t jdd5|| z } d d d t| |\} } t | | S#1swY%xYw) a Calculates the T-test on TWO RELATED samples of scores, a and b. Parameters ---------- a, b : array_like The arrays must have the same shape. axis : int or None, optional Axis along which to compute test. If None, compute over the whole arrays, `a`, and `b`. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided': the means of the distributions underlying the samples are unequal. * 'less': the mean of the distribution underlying the first sample is less than the mean of the distribution underlying the second sample. * 'greater': the mean of the distribution underlying the first sample is greater than the mean of the distribution underlying the second sample. .. versionadded:: 1.7.0 Returns ------- statistic : float or array t-statistic pvalue : float or array two-tailed p-value Notes ----- For more details on `ttest_rel`, see `scipy.stats.ttest_rel`. zunequal length arraysr<rdrArrrN)rUrsrYrXrrfrrrJrKrXrrrrrm) rMrTrNrkrrirdmrr'rjrs rPr7r7.s Lq!T*JAq$ 1vQ011vv{affkrvvrvv..  A qu B 1 SA B 4a A GGAENE Hh 7 JB;/GAt 1d ## s D44D=MannwhitneyuResultcvtj|jjt}tj|jjt}t t j||g}t|t|}}||z}|d|j||dzzdz z }t|||z|z }||z|z }||zdz } |dz|z dz } t|} | td| jDdz z} | ||zt||dz zz z} |r|dz | z tj| z } n|| z tj| z } tj t#| t jdz } t%|| S) a Computes the Mann-Whitney statistic Missing values in `x` and/or `y` are discarded. Parameters ---------- x : sequence Input y : sequence Input use_continuity : {True, False}, optional Whether a continuity correction (1/2.) should be taken into account. Returns ------- statistic : float The minimum of the Mann-Whitney statistics pvalue : float Approximate two-sided p-value assuming a normal distribution. NrArr(@c38K|]\}}||dz|z zywrNrbr7s rPr4zmannwhitneyu.. 61AqDF6r8rra)rJrurrr=rrf concatenatersrrvrrryrrcr>rgr)rruse_continuityranksnxnyntUumusigsqrr,rs rPrrls. 1   "''0A 1   "''0A R^^QqE* +EAAR bB cr 2r!t9R<'A Ar"uqyA 2 A R%B URZ E U #D S66 6s ::E RU5RT# ##E X]bggen , Vrwwu~ % <<Arwwqz) *D a &&rR KruskalResultc,t|}tjt|dd}|j d}|j d}|j }d||dzzz |dz|z j zd|dzzz }t |}d t d |jDt|dz|z z z }|dk(r td ||z}t|dz } tjj|| } t|| S) a Compute the Kruskal-Wallis H-test for independent samples Parameters ---------- sample1, sample2, ... : array_like Two or more arrays with the sample measurements can be given as arguments. Returns ------- statistic : float The Kruskal-Wallis H statistic, corrected for ties pvalue : float The p-value for the test using the assumption that H has a chi square distribution Notes ----- For more details on `kruskal`, see `scipy.stats.kruskal`. Examples -------- >>> from scipy.stats.mstats import kruskal Random samples from three different brands of batteries were tested to see how long the charge lasted. Results were as follows: >>> a = [6.3, 5.4, 5.7, 5.2, 5.0] >>> b = [6.9, 7.0, 6.1, 7.9] >>> c = [7.2, 6.9, 6.1, 6.5] Test the hypothesis that the distribution functions for all of the brands' durations are identical. Use 5% level of significance. >>> kruskal(a, b, c) KruskalResult(statistic=7.113812154696133, pvalue=0.028526948491942164) The null hypothesis is rejected at the 5% level of significance because the returned p-value is less than the critical value of 5%. Frr<rrrArarrc38K|]\}}||dz|z zywrrbr7s rPr4zkruskal..rr8z$All numbers are identical in kruskal)rrJrrrrrrryrYrsrBchi2sfr) r~rrsumrkngrpntotHrrrirs rPr r sV$ F OOHV? CE IIbME ;;r?D ;;=D T46]uax}1133aaj@A U #D S66 6uT1WT\7J JJAAv?@@FA VqB    B 'D D !!rRrrcddddj|jd|}tjjj |||||S)a Computes the Kolmogorov-Smirnov test on one sample of masked values. Missing values in `x` are discarded. Parameters ---------- x : array_like a 1-D array of observations of random variables. cdf : str or callable If a string, it should be the name of a distribution in `scipy.stats`. If a callable, that callable is used to calculate the cdf. args : tuple, sequence, optional Distribution parameters, used if `cdf` is a string. alternative : {'two-sided', 'less', 'greater'}, optional Indicates the alternative hypothesis. Default is 'two-sided'. method : {'auto', 'exact', 'asymp'}, optional Defines the method used for calculating the p-value. The following options are available (default is 'auto'): * 'auto' : use 'exact' for small size arrays, 'asymp' for large * 'exact' : use approximation to exact distribution of test statistic * 'asymp' : use asymptotic distribution of test statistic Returns ------- d : float Value of the Kolmogorov Smirnov test p : float Corresponding p-value. r`r_r^rjglr<)r~rkr)getlowerrrrr)rcdfr~rkrs rPrrs^D$)&AEE1{,K ;; ) ) 3T{6 * CCrRcddddj|jd|}tjjj ||||S)a Computes the Kolmogorov-Smirnov test on two samples. Missing values in `x` and/or `y` are discarded. Parameters ---------- data1 : array_like First data set data2 : array_like Second data set alternative : {'two-sided', 'less', 'greater'}, optional Indicates the alternative hypothesis. Default is 'two-sided'. method : {'auto', 'exact', 'asymp'}, optional Defines the method used for calculating the p-value. The following options are available (default is 'auto'): * 'auto' : use 'exact' for small size arrays, 'asymp' for large * 'exact' : use approximation to exact distribution of test statistic * 'asymp' : use asymptotic distribution of test statistic Returns ------- d : float Value of the Kolmogorov Smirnov test p : float Corresponding p-value. r`r_r^rr<rkr)rrrrrr )data1data2rkrs rPr r s[D$)&AEE1{,K ;; ) )%6A17 * 99rRc^tjjj|||||S)az Parameters ---------- data1 : array_like data2 : str, callable or array_like args : tuple, sequence, optional Distribution parameters, used if `data1` or `data2` are strings. alternative : str, as documented in stats.kstest method : str, as documented in stats.kstest Returns ------- tuple of (K-S statistic, probability) r)rrrr)rrr~rkrs rPrr2s3$ ;; ' 'ud4? ( PPrRctj|}|j||dk(r|S|\}}|\}}d}||r |||kz}n|||kz}||r |||kDz}n|||k\z}t||j d<|S)ak Trims an array by masking the data outside some given limits. Returns a masked version of the input array. Parameters ---------- a : array_like Input array. limits : {None, tuple}, optional Tuple of (lower limit, upper limit) in absolute values. Values of the input array lower (greater) than the lower (upper) limit will be masked. A limit is None indicates an open interval. inclusive : (bool, bool) tuple, optional Tuple of (lower flag, upper flag), indicating whether values exactly equal to the lower (upper) limit are allowed. Examples -------- >>> from scipy.stats.mstats import trima >>> import numpy as np >>> a = np.arange(10) The interval is left-closed and right-open, i.e., `[2, 8)`. Trim the array by keeping only values in the interval. >>> trima(a, limits=(2, 8), inclusive=(True, False)) masked_array(data=[--, --, 2, 3, 4, 5, 6, 7, --, --], mask=[ True, True, False, False, False, False, False, False, True, True], fill_value=999999) )NNFT)rJru unshare_maskr>r)rMlimits inclusive lower_lim upper_limlower_inupper_inrs rPr-r-HsF 1 ANNFl2#Y $XxI  !i- (I !y. )I  !i- (I !y. )I &Ait HrRc d}tj|}|j||S|\}}d}||dkDs|dkrt|dzd|dz||dkDs|dkrt|dzd|dz|\}} |5|j} ||j |||| j | Stj||||||| S) a) Trims an array by masking some proportion of the data on each end. Returns a masked version of the input array. Parameters ---------- a : sequence Input array. limits : {None, tuple}, optional Tuple of the percentages to cut on each side of the array, with respect to the number of unmasked data, as floats between 0. and 1. Noting n the number of unmasked data before trimming, the (n*limits[0])th smallest data and the (n*limits[1])th largest data are masked, and the total number of unmasked data after trimming is n*(1.-sum(limits)). The value of one limit can be set to None to indicate an open interval. inclusive : {(True,True) tuple}, optional Tuple of flags indicating whether the number of data being masked on the left (right) end should be truncated (True) or rounded (False) to integers. axis : {None,int}, optional Axis along which to trim. If None, the whole array is trimmed, but its shape is maintained. cR|j}|j}|r>|rt||z}n!ttj||z}t ||d|<|D|r|t||zz }n$|ttj||zz }t |||d<|Sr;)rrrrfroundr>) rM low_limitup_limit low_inclusive up_inclusiverrlowidxupidxs rP_trimr1Dztrimr.._trimr1Ds GGIiik Yq[)RXXik23$Ac'6lO  C( O+C8 455#Ac%&kNrR=The proportion to cut from the %s should be between 0. and 1.rr< beginning(got rWend)rJrurrYrrLrr) rMrrrNrlolimuplimerrmsgloincupincshps rPr.r.s4" 1 ANN ~NUE LF  2:Vk1eE7!4DDE E  2:Ve^eWA.>>? ?NUE |gg %eE:BB3GG""8T1eE%NNrRaZ Parameters ---------- a : sequence Input array limits : {None, tuple}, optional If `relative` is False, tuple (lower limit, upper limit) in absolute values. Values of the input array lower (greater) than the lower (upper) limit are masked. If `relative` is True, tuple (lower percentage, upper percentage) to cut on each side of the array, with respect to the number of unmasked data. Noting n the number of unmasked data before trimming, the (n*limits[0])th smallest data and the (n*limits[1])th largest data are masked, and the total number of unmasked data after trimming is n*(1.-sum(limits)) In each case, the value of one limit can be set to None to indicate an open interval. If limits is None, no trimming is performed inclusive : {(bool, bool) tuple}, optional If `relative` is False, tuple indicating whether values exactly equal to the absolute limits are allowed. If `relative` is True, tuple indicating whether the number of data being masked on each side should be rounded (True) or truncated (False). relative : bool, optional Whether to consider the limits as absolute values (False) or proportions to cut (True). axis : int, optional Axis along which to trim. c@|rt||||St|||S)a| Trims an array by masking the data outside some given limits. Returns a masked version of the input array. %s Examples -------- >>> from scipy.stats.mstats import trim >>> z = [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10] >>> print(trim(z,(3,8))) [-- -- 3 4 5 6 7 8 -- --] >>> print(trim(z,(0.1,0.2),relative=True)) [-- 2 3 4 5 6 7 8 -- --] rrrNrr)r.r-rMrrrelativerNs rPr*r*s'$QvFFQv;;rRc$t|||f||S)a Trims the smallest and largest data values. Trims the `data` by masking the ``int(proportiontocut * n)`` smallest and ``int(proportiontocut * n)`` largest values of data along the given axis, where n is the number of unmasked values before trimming. Parameters ---------- data : ndarray Data to trim. proportiontocut : float, optional Percentage of trimming (as a float between 0 and 1). If n is the number of unmasked values before trimming, the number of values after trimming is ``(1 - 2*proportiontocut) * n``. Default is 0.2. inclusive : {(bool, bool) tuple}, optional Tuple indicating whether the number of data being masked on each side should be rounded (True) or truncated (False). axis : int, optional Axis along which to perform the trimming. If None, the input array is first flattened. r)r.)rproportiontocutrrNs rPr+r+s2 ?$4 11rRct|jd}|dk(r|df}n|dk(rd|f}n tdt||||S)a Trims the data by masking values from one tail. Parameters ---------- data : array_like Data to trim. proportiontocut : float, optional Percentage of trimming. If n is the number of unmasked values before trimming, the number of values after trimming is ``(1 - proportiontocut) * n``. Default is 0.2. tail : {'left','right'}, optional If 'left' the `proportiontocut` lowest values will be masked. If 'right' the `proportiontocut` highest values will be masked. Default is 'left'. inclusive : {(bool, bool) tuple}, optional Tuple indicating whether the number of data being masked on each side should be rounded (True) or truncated (False). Default is (True, True). axis : int, optional Axis along which to perform the trimming. If None, the input array is first flattened. Default is None. Returns ------- trimtail : ndarray Returned array of same shape as `data` with masked tail values. r<rNrz/The tail argument should be in ('left','right'))rrNr)rr TypeErrorr.)rrtailrrNrs rPr,r,!sX> t9?? Q D s{!$' (IJJ f49 EErRct|tst|tr||f}|rt||||j |St |||j |S)zHReturns the trimmed mean of the data along the given axis. %s rrr)rtrryr.rr-rs rPr/r/Ns` ve $*VE*B&!QfydCHHdHSSQfy9>>D>IIrRct|tst|tr||f}|rt||||}nt |||}|j ||S)a6Returns the trimmed variance of the data along the given axis. %s ddof : {0,integer}, optional Means Delta Degrees of Freedom. The denominator used during computations is (n-ddof). DDOF=0 corresponds to a biased estimate, DDOF=1 to an un- biased estimate of the variance. rrr)rtrryr.r-rrMrrrrNrouts rPr2r2asU ve $*VE*B&!AVydCAVi8 7747 ((rRct|tst|tr||f}|rt||||}nt |||}|j ||S)a@Returns the trimmed standard deviation of the data along the given axis. %s ddof : {0,integer}, optional Means Delta Degrees of Freedom. The denominator used during computations is (n-ddof). DDOF=0 corresponds to a biased estimate, DDOF=1 to an un- biased estimate of the variance. rrr)rtrryr.r-rZrs rPr0r0zsU ve $*VE*B&!AViTBAVi8 77$7 ''rRc ld}tj|dd}|j|8|j|dtj|j |z St |tst |tr||f}|\}}d}||dkDs|dkrt|d zd |d z||dkDs|dkrt|d zd |d z|\}} |||j|||| S|jd kDrtd|jtj||||||| S)a Returns the standard error of the trimmed mean along the given axis. Parameters ---------- a : sequence Input array limits : {(0.1,0.1), tuple of float}, optional tuple (lower percentage, upper percentage) to cut on each side of the array, with respect to the number of unmasked data. If n is the number of unmasked data before trimming, the values smaller than ``n * limits[0]`` and the values larger than ``n * `limits[1]`` are masked, and the total number of unmasked data after trimming is ``n * (1.-sum(limits))``. In each case, the value of one limit can be set to None to indicate an open interval. If `limits` is None, no trimming is performed. inclusive : {(bool, bool) tuple} optional Tuple indicating whether the number of data being masked on each side should be rounded (True) or truncated (False). axis : int, optional Axis along which to trim. Returns ------- trimmed_stde : scalar or ndarray c|j}|j}|r5|rt||z}ntj||z}t ||d|<|;|r|t||zz }n|tj||zz }t |||d<||||d|<||dz |||d<|j d} | d|z |z tjt|zz S)zCReturns the standard error of the trimmed mean for a 1D input data.NrAr) rrrrfrr>rZrrs) rMrrrrrrrrwinstds rP_trimmed_stde_1Dz&trimmed_stde.._trimmed_stde_1Ds GGIiik Yq[))A+.$Ac'6lO  C( O+BHHQxZ00#Ac%&kNCK.#gv,3uQw<#ef+A!I+h.A?@@rRTrr/rArrrr<rrrWrraz>? ?NUE  %eEBB 66A: 112:; ;""#3T1#(uU< ?? IrRc>t|||j|S)a Compute the trimmed mean. Parameters ---------- a : array_like Array of values. limits : None or (lower limit, upper limit), optional Values in the input array less than the lower limit or greater than the upper limit will be ignored. When limits is None (default), then all values are used. Either of the limit values in the tuple can also be None representing a half-open interval. inclusive : (bool, bool), optional A tuple consisting of the (lower flag, upper flag). These flags determine whether values exactly equal to the lower or upper limits are included. The default value is (True, True). axis : int or None, optional Axis along which to operate. If None, compute over the whole array. Default is None. Returns ------- tmean : float Notes ----- For more details on `tmean`, see `scipy.stats.tmean`. Examples -------- >>> import numpy as np >>> from scipy.stats import mstats >>> a = np.array([[6, 8, 3, 0], ... [3, 9, 1, 2], ... [8, 7, 8, 2], ... [5, 6, 0, 2], ... [4, 5, 5, 2]]) ... ... >>> mstats.tmean(a, (2,5)) 3.3 >>> mstats.tmean(a, (2,5), axis=0) masked_array(data=[4.0, 5.0, 4.0, 2.0], mask=[False, False, False, False], fill_value=1e+20) rr)r-r)rMrrrNs rPr(r( s"` 6Y 7 < <$ < GGrRc2|jtj}|C|jj }t j j||z|dz z St|||}t j j|||S)a Compute the trimmed variance This function computes the sample variance of an array of values, while ignoring values which are outside of given `limits`. Parameters ---------- a : array_like Array of values. limits : None or (lower limit, upper limit), optional Values in the input array less than the lower limit or greater than the upper limit will be ignored. When limits is None, then all values are used. Either of the limit values in the tuple can also be None representing a half-open interval. The default value is None. inclusive : (bool, bool), optional A tuple consisting of the (lower flag, upper flag). These flags determine whether values exactly equal to the lower or upper limits are included. The default value is (True, True). axis : int or None, optional Axis along which to operate. If None, compute over the whole array. Default is zero. ddof : int, optional Delta degrees of freedom. Default is 1. Returns ------- tvar : float Trimmed variance. Notes ----- For more details on `tvar`, see `scipy.stats.tvar`. rrr) rXryrLrrrrfrJrr)rMrrrNrrrs rPr8r8@ sxH A ~ffWMMOuuyy|a2&& 6Y ?B 5599Rd9 ..rRct||\}}t||df|df}tjj ||S)a Compute the trimmed minimum Parameters ---------- a : array_like array of values lowerlimit : None or float, optional Values in the input array less than the given limit will be ignored. When lowerlimit is None, then all values are used. The default value is None. axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. inclusive : {True, False}, optional This flag determines whether values exactly equal to the lower limit are included. The default value is True. Returns ------- tmin : float, int or ndarray Notes ----- For more details on `tmin`, see `scipy.stats.tmin`. Examples -------- >>> import numpy as np >>> from scipy.stats import mstats >>> a = np.array([[6, 8, 3, 0], ... [3, 2, 1, 2], ... [8, 1, 8, 2], ... [5, 3, 0, 2], ... [4, 7, 5, 2]]) ... >>> mstats.tmin(a, 5) masked_array(data=[5, 7, 5, --], mask=[False, False, False, True], fill_value=999999) NF)rQr-rJminimumreduce)rM lowerlimitrNrrs rPr)r)m sDV1d#GAt q:t$y%&8 9B ::  R &&rRct||\}}t|d|fd|f}tjj ||S)a< Compute the trimmed maximum This function computes the maximum value of an array along a given axis, while ignoring values larger than a specified upper limit. Parameters ---------- a : array_like array of values upperlimit : None or float, optional Values in the input array greater than the given limit will be ignored. When upperlimit is None, then all values are used. The default value is None. axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. inclusive : {True, False}, optional This flag determines whether values exactly equal to the upper limit are included. The default value is True. Returns ------- tmax : float, int or ndarray Notes ----- For more details on `tmax`, see `scipy.stats.tmax`. Examples -------- >>> import numpy as np >>> from scipy.stats import mstats >>> a = np.array([[6, 8, 3, 0], ... [3, 9, 1, 2], ... [8, 7, 8, 2], ... [5, 6, 0, 2], ... [4, 5, 5, 2]]) ... ... >>> mstats.tmax(a, 4) masked_array(data=[4, --, 3, 2], mask=[False, True, False, False], fill_value=999999) NF)rQr-rJmaximumr)rM upperlimitrNrrs rPr'r' sD^1d#GAt q4$ui&8 9B ::  R &&rRctj|j}|Bt|j }|j ||tj |z St|j||}tj |j||}|tj |j z S)a Compute the trimmed standard error of the mean. This function finds the standard error of the mean for given values, ignoring values outside the given `limits`. Parameters ---------- a : array_like array of values limits : None or (lower limit, upper limit), optional Values in the input array less than the lower limit or greater than the upper limit will be ignored. When limits is None, then all values are used. Either of the limit values in the tuple can also be None representing a half-open interval. The default value is None. inclusive : (bool, bool), optional A tuple consisting of the (lower flag, upper flag). These flags determine whether values exactly equal to the lower or upper limits are included. The default value is (True, True). axis : int or None, optional Axis along which to operate. If None, compute over the whole array. Default is zero. ddof : int, optional Delta degrees of freedom. Default is 1. Returns ------- tsem : float Notes ----- For more details on `tsem`, see `scipy.stats.tsem`. r) rJrurLryrrZrr-rfr)rMrrrNrrrsds rPr3r3 sF 1 A ~ !'') uu$Tu*2771:55 qwwy&) ,B T- .B  # ##rRc  d}t||}tj|tj|}||St |t st |tr||f}|\}} d} ||dkDs|dkrt| dzd|dz| | dkDs| dkrt| d zd| dz|\} } |7|j} ||j|| | | ||j| Stj||||| | | || S) aReturns a Winsorized version of the input array. The (limits[0])th lowest values are set to the (limits[0])th percentile, and the (limits[1])th highest values are set to the (1 - limits[1])th percentile. Masked values are skipped. Parameters ---------- a : sequence Input array. limits : {None, tuple of float}, optional Tuple of the percentages to cut on each side of the array, with respect to the number of unmasked data, as floats between 0. and 1. Noting n the number of unmasked data before trimming, the (n*limits[0])th smallest data and the (n*limits[1])th largest data are masked, and the total number of unmasked data after trimming is n*(1.-sum(limits)) The value of one limit can be set to None to indicate an open interval. inclusive : {(True, True) tuple}, optional Tuple indicating whether the number of data being masked on each side should be truncated (True) or rounded (False). inplace : {False, True}, optional Whether to winsorize in place (True) or to use a copy (False) axis : {None, int}, optional Axis along which to trim. If None, the whole array is trimmed, but its shape is maintained. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. The following options are available (default is 'propagate'): * 'propagate': allows nan values and may overwrite or propagate them * 'raise': throws an error * 'omit': performs the calculations ignoring nan values Notes ----- This function is applied to reduce the effect of possibly spurious outliers by limiting the extreme values. Examples -------- >>> import numpy as np >>> from scipy.stats.mstats import winsorize A shuffled array contains integers from 1 to 10. >>> a = np.array([10, 4, 9, 8, 5, 3, 7, 2, 1, 6]) The 10% of the lowest value (i.e., ``1``) and the 20% of the highest values (i.e., ``9`` and ``10``) are replaced. >>> winsorize(a, limits=[0.1, 0.2]) masked_array(data=[8, 4, 8, 8, 5, 3, 7, 2, 2, 6], mask=False, fill_value=999999) cD|j}|j}|r(tjtj|} |rc|rt ||z} n+tj ||zjt } |r|dk(rt| | z dz } ||| ||d| <|n|r|t ||zz } n.|tj ||zjt z } |r|dk(r||| dz |||  <|S||| dz ||| d<|S)NrrA) rrrf count_nonzerorrrrXr) rMrr low_include up_include contains_nanrrr nan_countrrs rP _winsorize1Dzwinsorize.._winsorize1D; s+ GGIiik ((!5I Y]+)a-077< f 4VQy[]3F nAc'6lO  CH --BHHQ\299#>> f 4+,S^+<#eYJ'("#3uqy>!2#ef+rRrrrr<rrrWr) rDrJrwrfr{rtrryrYrrLrr)rMrrinplacerNrrrrrrrrrs rPr:r: s4z2!J/L 01A ~ vu %:fe+D&!NUE LF  2:Vk1eE7!4DDE E  2:Ve^eWA.>>? ?NUE |ggAGGIueUE(*66=gcl C""<q%#(, D DrRc t||\}}|jdk(rt|j}||=|jj dvr|jj ntj}tj|r|nt|g|z}t|dk(r|tjStjtj|tj|Stj|sD|j|d}|Dcgc]}t!||||}}tj|St!|||Scc}w)a Calculates the nth moment about the mean for a sample. Parameters ---------- a : array_like data moment : int, optional order of central moment that is returned axis : int or None, optional Axis along which the central moment is computed. Default is 0. If None, compute over the whole array `a`. Returns ------- n-th central moment : ndarray or float The appropriate moment along the given axis or over all values if axis is None. The denominator for the moment calculation is the number of observations, no degrees of freedom correction is done. Notes ----- For more details about `moment`, see `scipy.stats.moment`. r<fcroTrr)rQrXrrrpkindtyperfrisscalarrsrrJrwfullr_moment) rMrrN moment_shaperp out_shaperr mmnts rPrrr s41d#GAtvv{AGG}   !  4 "**%'[[%8\v;-,6  y>Q = 88BGGIrvvUCD D ;;v vvdTv*8>?11d.??xx~q&$''@s$Er ctj|tj|z dkDr td|dk(s|dk(rt |j }||=|j jdvr|j jntj}t|dk(r||dk(rdSdS|dk(rtj||Stj||S|g}|}|dkDr*|dzr |dz dz }n|dz}|j||dkDr*||j|d n|}||z }|d dk(r|j!} n|dz} |d dd D]} | dz} | dzs| |z} | j|S) Nr<z&All moment parameters must be integersrAr rrroraTr r)rfrgrrYrrrprrrrsrJrrappendrr) rMrrNrrrpn_list current_n a_zero_meansrs rPrr s vvfrxx''(1,ABB {fkQWW  $K !  4 "** u:?! 5 55 539Q;BGGE/ 7%u5 7 !m1}&q[!O Q MM) $ !m/3lqvvdTv*$h ":?  "AQAB !A1A1u[  !vvd|rRcjt||\}}|j|||j|z S)a Compute the coefficient of variation. The coefficient of variation is the standard deviation divided by the mean. This function is equivalent to:: np.std(x, axis=axis, ddof=ddof) / np.mean(x) The default for ``ddof`` is 0, but many definitions of the coefficient of variation use the square root of the unbiased sample variance for the sample standard deviation, which corresponds to ``ddof=1``. Parameters ---------- a : array_like Input array. axis : int or None, optional Axis along which to calculate the coefficient of variation. Default is 0. If None, compute over the whole array `a`. ddof : int, optional Delta degrees of freedom. Default is 0. Returns ------- variation : ndarray The calculated variation along the requested axis. Notes ----- For more details about `variation`, see `scipy.stats.variation`. Examples -------- >>> import numpy as np >>> from scipy.stats.mstats import variation >>> a = np.array([2,8,4]) >>> variation(a) 0.5345224838248487 >>> b = np.array([2,8,3,4]) >>> c = np.ma.masked_array(b, mask=[0,0,1,0]) >>> variation(c) 0.5345224838248487 In the example above, it can be seen that this works the same as `scipy.stats.variation` except 'stats.mstats.variation' ignores masked array elements. r)rQrZr)rMrNrs rPr9r9 s5b1d#GAt 55D5 !!&&, ..rRc>t||\}}|j|d}t|d||}t|d||}|tj|j j |j|zdzk}tjd5tj|d||d zz }d d d |s|tjur|tjur|j|}||dkDz} | jrtj| |}tj| |}tj| |}tj|d z |z|d z z |z|d zz } tj | | S#1swYxYw) aB Computes the skewness of a data set. Parameters ---------- a : ndarray data axis : int or None, optional Axis along which skewness is calculated. Default is 0. If None, compute over the whole array `a`. bias : bool, optional If False, then the calculations are corrected for statistical bias. Returns ------- skewness : ndarray The skewness of values along an axis, returning 0 where all values are equal. Notes ----- For more details about `skew`, see `scipy.stats.skew`. Tr rar rrallr<?Nrr)rQrrrffinforp resolutionsqueezerrJrr>rrextractrplace) rMrNbiasrm2m3zerovalsr can_correctnvals rPr"r" sd21T"GAt 66$6 &D At$ 'B At$ 'B 288BHH%004<<3EEI ID  "/xxab#g./ D )b .A GGDMeq1uo ??  ;*AK,BK,B77AcE19%qu-b0S8D HHT; - K//s FFcVt||\}}|j|d}t|d||}t|d||}|tj|j j |j|zdzk}tjd5tj|d||d zz }d d d |s|tjur|tjur|j|} || d kDz} | jrtj| | } tj| |}tj| |}d | dz z | d z z | | zd z |z|d zz d | d z d zzz z} tj| | dz|rd z SS#1swYxYw)a Computes the kurtosis (Fisher or Pearson) of a dataset. Kurtosis is the fourth central moment divided by the square of the variance. If Fisher's definition is used, then 3.0 is subtracted from the result to give 0.0 for a normal distribution. If bias is False then the kurtosis is calculated using k statistics to eliminate bias coming from biased moment estimators Use `kurtosistest` to see if result is close enough to normal. Parameters ---------- a : array data for which the kurtosis is calculated axis : int or None, optional Axis along which the kurtosis is calculated. Default is 0. If None, compute over the whole array `a`. fisher : bool, optional If True, Fisher's definition is used (normal ==> 0.0). If False, Pearson's definition is used (normal ==> 3.0). bias : bool, optional If False, then the calculations are corrected for statistical bias. Returns ------- kurtosis : array The kurtosis of values along an axis. If all values are equal, return -3 for Fisher's definition and 0 for Pearson's definition. Notes ----- For more details about `kurtosis`, see `scipy.stats.kurtosis`. Tr rar rrrr<rNrrrAr<)rQrrrfr"rpr#r$rrJrr>rrr%r&) rMrNfisherr'rr(m4r*r+rr,r-s rPrr0 sJ1d#GAt 66$6 &D At$ 'B At$ 'B 288BHH%004<<3EEI ID  "/xxab#g./ D )b .A GGDMeq1uo ??  ;*AK,BK,B!9ac?QqSWbLS$8AaC#:$EFD HHT;S 1 ax //s FF(DescribeResult)nobsminmaxrvarianceskewnessrcft||\}}|j|}tjj ||tj j ||f}|j |}|j||}t|||}t|||} t|||||| S)a Computes several descriptive statistics of the passed array. Parameters ---------- a : array_like Data array axis : int or None, optional Axis along which to calculate statistics. Default 0. If None, compute over the whole array `a`. ddof : int, optional degree of freedom (default 0); note that default ddof is different from the same routine in stats.describe bias : bool, optional If False, then the skewness and kurtosis calculations are corrected for statistical bias. Returns ------- nobs : int (size of the data (discarding missing values) minmax : (int, int) min, max mean : float arithmetic mean variance : float unbiased variance skewness : float biased skewness kurtosis : float biased kurtosis Examples -------- >>> import numpy as np >>> from scipy.stats.mstats import describe >>> ma = np.ma.array(range(6), mask=[0, 0, 0, 1, 1, 1]) >>> describe(ma) DescribeResult(nobs=np.int64(3), minmax=(masked_array(data=0, mask=False, fill_value=999999), masked_array(data=2, mask=False, fill_value=999999)), mean=np.float64(1.0), variance=np.float64(0.6666666666666666), skewness=masked_array(data=0., mask=False, fill_value=1e+20), kurtosis=np.float64(-1.5)) rr)r') rQrrJrrrrrr"rr1) rMrNrr'rmmrrskkurts rPrrq sl1d#GAt  A **  AD  )2::+<+._stdemed_1D s|wwt() I  !A#rA" $55a8 9acT!A#Y&A./rRFTrrazBArray 'data' must be at most two dimensional, but got data.ndim = )rJrwrhrYr)rrNr>s rP stde_medianr? sn0 88DuD 1D 4  99q= 448II;@A A"";d;;rRSkewtestResultct||\}}||j}d}t||}|j|}t j |dkr"t dt j |d|tj|dz|dzzd|dz zz z}d ||zd |zzd z z|dzz|dzz|d z |d zz|dzz|dzzz }dtjd|dz zz}dtjdtj|zz }tjd |dz z } tj|dk(d|}|tj|| z tj|| z dzdzzz} tjjj| tj |} t#| d| dS)a Tests whether the skew is different from the normal distribution. Parameters ---------- a : array_like The data to be tested axis : int or None, optional Axis along which statistics are calculated. Default is 0. If None, compute over the whole array `a`. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. Default is 'two-sided'. The following options are available: * 'two-sided': the skewness of the distribution underlying the sample is different from that of the normal distribution (i.e. 0) * 'less': the skewness of the distribution underlying the sample is less than that of the normal distribution * 'greater': the skewness of the distribution underlying the sample is greater than that of the normal distribution .. versionadded:: 1.7.0 Returns ------- statistic : array_like The computed z-score for this test. pvalue : array_like A p-value for the hypothesis test Notes ----- For more details about `skewtest`, see `scipy.stats.skewtest`. r<z0skewtest is not valid with less than 8 samples; z samples were given.rAr@rar<Frr rrrb)rQrLr"rrfrrYrJrlogrrrrrrBrr@) rMrNrkb2rrbeta2W2deltaroZrs rPr#r# sH1d#GAt | GGI aB  A vvay1}KFF1I;&:<= = RWWqsQqSkc1Q3i0 11A !A#bd(2+ ! $ac *#!}ac/BAaC/H IE bggaqk" "B bggc"&&*n% %E GGCAJ E aAA bffQuWrww%!|A~6677A [[ " " . .q-2D2Dk RF !B% ,,rRKurtosistestResultc Vt||\}}|j|}tj|dkr"t dtj|dtj|dkr-t j dtj|dt||d }d |d z z|d zz }d |z|dz z|dz z|d z|dzz|dzz|dzzz }||z tj|z }d||zd|zz dzz|dz|dzzz tjd|dzz|dzz||dz z|dz zz z}dd|z d|z tjd d|dzz zzzz} d dd| zz z } d |tjd| dz z zz} tjj| r t| | dk(<n | dk(rt} tjj| dkDtjd d| z z | z dtjd d| z z | z d } | | z tjdd| zz z } tjj j#| t$j&|}t)| d|dS)ax Tests whether a dataset has normal kurtosis Parameters ---------- a : array_like array of the sample data axis : int or None, optional Axis along which to compute test. Default is 0. If None, compute over the whole array `a`. alternative : {'two-sided', 'less', 'greater'}, optional Defines the alternative hypothesis. The following options are available (default is 'two-sided'): * 'two-sided': the kurtosis of the distribution underlying the sample is different from that of the normal distribution * 'less': the kurtosis of the distribution underlying the sample is less than that of the normal distribution * 'greater': the kurtosis of the distribution underlying the sample is greater than that of the normal distribution .. versionadded:: 1.7.0 Returns ------- statistic : array_like The computed z-score for this test. pvalue : array_like The p-value for the hypothesis test Notes ----- For more details about `kurtosistest`, see `scipy.stats.kurtosistest`. rrz/kurtosistest requires at least 5 observations; z observations were given.z;kurtosistest only valid for n>=20 ... continuing anyway, n=ra) stacklevelF)r/r<rAg8@rrrrCrFrGg @r<rrr<gUUUUUU?rb)rQrrfrrYwarningswarnrrJr isMaskedArrayr>rpowerrrrrrBrrN)rMrNrkrrIEvarb2r sqrtbeta1Aterm1r'term2rMrs rPrr sH1d#GAt TA vvay1}JFF1I;&?AB B vvay2~ ##%66!9+/;< > !T% (B QqS QqSA FAbDM1Q3 AaC!B$<1#5qs#; >> import numpy as np >>> from scipy.stats.mstats import mquantiles >>> a = np.array([6., 47., 49., 15., 42., 41., 7., 39., 43., 40., 36.]) >>> mquantiles(a) array([ 19.2, 40. , 42.8]) Using a 2D array, specifying axis and limit. >>> data = np.array([[ 6., 7., 1.], ... [ 47., 15., 2.], ... [ 49., 36., 3.], ... [ 15., 39., 4.], ... [ 42., 40., -999.], ... [ 41., 41., -999.], ... [ 7., -999., -999.], ... [ 39., -999., -999.], ... [ 43., -999., -999.], ... [ 40., -999., -999.], ... [ 36., -999., -999.]]) >>> print(mquantiles(data, axis=0, limit=(0, 50))) [[19.2 14.6 1.45] [40. 37.5 2.5 ] [42.8 40.05 3.55]] >>> data[:, 2] = -999. >>> print(mquantiles(data, axis=0, limit=(0, 50))) [[19.200000000000003 14.6 --] [40.0 37.5 --] [42.800000000000004 40.05 --]] cltj|j}t|}|dk(r9t j tj t|tdS|dk(r9t j tj||jtS||z|z}tj|jd|dz jt}||z jdd}d|z ||dz jz|||jzzS)Nr<roTrqrAr)rfr=rrsrJrwrxryresizerr?floorrrXrtolist)rrprralephrgammas rP _quantiles1Dz mquantiles.._quantiles1D s GGDOO% & F 688BHHSV59E E !V88BIIa1? ?1q HHUZZ1Q3' ( / / 4qq#5!QqSLLN++eAahhjM.AAArRFrrazArray should be 2D at most !r<rATr) rJrwrhrr>rrf atleast_1drur) rMralphapbetaprNlimitrgrrrdrs rPrrx sH B 88AE "D yy1}677 1X_a9 (.it$ $% bjj&'ABvIeO$$A D!Q''  |T4A >>rRcz|dks|dkDrtd|dt||dz g|||djS)zCalculate the score at the given 'per' percentile of the sequence a. For example, the score at per=50 is the median. This function is a shortcut to mquantile r<gY@z4The percentile should be between 0. and 100. ! (got rW)rrirjrkrN)rYrr$)rperrkrirjs rPrr sO aS4ZOPSuTUVWW d#d(F%! ++2795rRctj|djdd}|j}t j |j t}d||dt jd|dz|z |dz|z |z z ||jd d|<tj||j S) ay Returns plotting positions (or empirical percentile points) for the data. Plotting positions are defined as ``(i-alpha)/(n+1-alpha-beta)``, where: - i is the rank order statistics - n is the number of unmasked values along the given axis - `alpha` and `beta` are two parameters. Typical values for `alpha` and `beta` are: - (0,1) : ``p(k) = k/n``, linear interpolation of cdf (R, type 4) - (.5,.5) : ``p(k) = (k-1/2.)/n``, piecewise linear function (R, type 5) - (0,0) : ``p(k) = k/(n+1)``, Weibull (R type 6) - (1,1) : ``p(k) = (k-1)/(n-1)``, in this case, ``p(k) = mode[F(x[k])]``. That's R default (R type 7) - (1/3,1/3): ``p(k) = (k-1/3)/(n+1/3)``, then ``p(k) ~ median[F(x[k])]``. The resulting quantile estimates are approximately median-unbiased regardless of the distribution of x. (R type 8) - (3/8,3/8): ``p(k) = (k-3/8)/(n+1/4)``, Blom. The resulting quantile estimates are approximately unbiased if x is normally distributed (R type 9) - (.4,.4) : approximately quantile unbiased (Cunnane) - (.35,.35): APL, used with PWM - (.3175, .3175): used in scipy.stats.probplot Parameters ---------- data : array_like Input data, as a sequence or array of dimension at most 2. alpha : float, optional Plotting positions parameter. Default is 0.4. beta : float, optional Plotting positions parameter. Default is 0.4. Returns ------- positions : MaskedArray The calculated plotting positions. FrrArror<Nrrrq) rJrwrrrfrxrXryrrrp)rrobetarplposs rPrr sT 88Du % - -a 3D A HHTYYe ,EE!"I+-99Q!+>> import numpy as np >>> from scipy import stats >>> a = np.arange(20).reshape(5,4) >>> print(stats.mstats.sem(a)) [2.8284271247461903 2.8284271247461903 2.8284271247461903 2.8284271247461903] Find standard error across the whole array, using n degrees of freedom: >>> print(stats.mstats.sem(a, axis=None, ddof=0)) 1.2893796958227628 rr)rQrrZrJr)rMrNrrrs rPr r W sI^1d#GAt TA 4d#bggaj0A HrRF_onewayResultct|}t|}|j}|dzj|jdzt |z z }|jd|j d|j z dzzj}||z }|dz }||z }|t |z } |t |z } | | z } t j||| } t| | S)a Performs a 1-way ANOVA, returning an F-value and probability given any number of groups. From Heiman, pp.394-7. Usage: ``f_oneway(*args)``, where ``*args`` is 2 or more arrays, one per treatment group. Returns ------- statistic : float The computed F-value of the test. pvalue : float The associated p-value from the F-distribution. rarrA) rrsrrryrrcfdtrcrt) r~rngroupsrsstotssbgsswgdfbgdfwgmsbmswfrs rPrr s"  D$iG ::D uT{ C uT{ C CA ==tQ 'D !T ""rRFriedmanchisquareResultct|jt}t|}|dkrt d|dt j t|dd}|jturIt j|}|jj|djt}n |j}|j \}}|j"Dcgc] }t%|}}t'j(|Dcgc]\}}|j*dkDs|c}}} d| dz| z j-t||dz|z zz z } t'j,|j-d||dzzdz z d z} | d z||z|dzzz d z| z } t/| t0j2j5| |dz Scc}wcc}}w) aDFriedman Chi-Square is a non-parametric, one-way within-subjects ANOVA. This function calculates the Friedman Chi-square test for repeated measures and returns the result, along with the associated probability value. Each input is considered a given group. Ideally, the number of treatments among each group should be equal. If this is not the case, only the first n treatments are taken into account, where n is the number of treatments of the smallest group. If a group has some missing values, the corresponding treatments are masked in the other groups. The test statistic is corrected for ties. Masked values in one group are propagated to the other groups. Returns ------- statistic : float the test statistic. pvalue : float the associated p-value. rzLess than 3 groups (z(): the Friedman test is NOT appropriate.r<rrrArrarr)rrXryrsrYrJ masked_valuesrrpr? mask_colsrrrr=r}rrrrfrwrXrrrBrr) r~rrrankedrrowrrrrtie_correctionrychisqs rPrr s.   $ $U +D D A1u/s3/01 1  ht!4a 8F ||6!f%""$,,Qr277@ LLEQq,2HH5S|C 5G5 887941aaffqjQ9 :D$'$,++-eAq!tAvJ.???N 666::b>AqsGBJ.2 3D 3J!QqS "R ' 6E "5#0#5#5#8#8!#D FF69s GG G BrunnerMunzelResultctj|jjt}tj|jjt}t |}t |}|dk(s|dk(r(t tjtjSttj||f}|d|}||||z}tj|} tj|} t|} t|} tj| } tj| }tjtj|| z | z | zd}||dz z}tjtj|| z | z |zd}||dz z}||z| | z z}|||ztj||z||zzzz}|dk(rtj||z||zzd}tj||zd|dz z }|tj||zd|dz z z }||z }tj j#||}n0|dk(r tj$j#|}n t'd|dk(rn9|dk(rd|z }n.|d k(rd tj(|d|z gz}n t'd t ||S) aV Compute the Brunner-Munzel test on samples x and y. Any missing values in `x` and/or `y` are discarded. The Brunner-Munzel test is a nonparametric test of the null hypothesis that when values are taken one by one from each group, the probabilities of getting large values in both groups are equal. Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the assumption of equivariance of two groups. Note that this does not assume the distributions are same. This test works on two independent samples, which may have different sizes. Parameters ---------- x, y : array_like Array of samples, should be one-dimensional. alternative : 'less', 'two-sided', or 'greater', optional Whether to get the p-value for the one-sided hypothesis ('less' or 'greater') or for the two-sided hypothesis ('two-sided'). Defaults value is 'two-sided' . distribution : 't' or 'normal', optional Whether to get the p-value by t-distribution or by standard normal distribution. Defaults value is 't' . Returns ------- statistic : float The Brunner-Munzer W statistic. pvalue : float p-value assuming an t distribution. One-sided or two-sided, depending on the choice of `alternative` and `distribution`. See Also -------- mannwhitneyu : Mann-Whitney rank test on two samples. Notes ----- For more details on `brunnermunzel`, see `scipy.stats.brunnermunzel`. Examples -------- >>> from scipy.stats.mstats import brunnermunzel >>> import numpy as np >>> x1 = [1, 2, np.nan, np.nan, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1] >>> x2 = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4] >>> brunnermunzel(x1, x2) BrunnerMunzelResult(statistic=1.4723186918922935, pvalue=0.15479415300426624) # may vary r<rrArjnormalz&distribution should be 't' or 'normal'r_r^r`raz6alternative should be 'less', 'greater' or 'two-sided')rJrurrr=rsrrfrrrrrrUrrBrjrrrYr)rrrk distributionrrrankcrankcxrankcy rankcx_mean rankcy_meanrankxranky rankx_mean ranky_meanSxSywbfndf_numerdf_denomrirds rPr;r; sj 1   "''0A 1   "''0A QB QB Qw"'"26626622 R^^QqE* +E 1R[F 2be_F''&/K''&/K QKE QKEJJ %+5 BCH IB"q&LB %+5 BCH IB"q&LB 7kK/ 0DR"WR"r' 12 22Ds88BGb2g-s388BGS)R!V4BHHR"Wc*b1f55   OO  b )  !    " "4 ( 46 6i   E  # 1Q3x  DF F tQ ''rRr)NF)r<)r<T)NTN propagater`)r`)TFrr`r;)Ngffffff?separate)N hierarchical)r<r`)r<Tr`)T)rbr`r)r`r)NTT)NrN)NrFN)皙?rN)rleftrN)皙?rrArATN)rrTNr<)rrN)Nrr<rA)Nr<T)NrFNrrr)r<TT)r<r<T))g?rg?皙?rNrb)rbrr)rr)r<rA)r`rj)t__doc____all__numpyrfr=numpy.marJr>r?rrrR collectionsr@rBscipy._lib._utilrCrDscipy._lib._bunchrE scipy.specialrcscipy.stats._stats_pyrrr_stats_mstats_commonrFr&rqr%rsrQrUr\rmrrrrrrrrrrr$rrr rUrrrtr!r|r4r5rr6rr7rrrr r rr r rr-r.trimdocr*r+r,trim1r/r2r0r1rr(r8r)r'r3r:rrr9r"rr1rr?r@r#rNrr\rrrrrrr rtrrrrr;rbrRrPrs 2# "=/))   ,<~* Z1h-P` &7 8 !.HB$ $ i9X?J%Xv@F?E&|~=@""8;EF0+fOdC?L63r,,E-:M,JLq1B<<,.EF7-t 46MNA1H02IJ>BBF~?B 50,f 42 j,.EF#B%%>%<>-F`!!68OPc(rR