
    (phK                         S SK r S SKrS SKJr  S SKJr  S SKJr  S SKJ	r	  SSK
Jr  S r " S	 S
5      r\ R                  " 5       rSS jrS rS r\" SS5      r\" \SS9  SS j5       rg)    N)
namedtuple)special)stats)	_rankdata   )_axis_nan_policy_factoryc                    [         R                  " XS5      n [         R                  " XS5      n[         R                  " U S   US   5      n[         R                  " XR                  U R                  S   4-   5      n [         R                  " XR                  UR                  S   4-   5      n[         R
                  " X4SS9nXU4$ )zBBroadcast then concatenate arrays, leaving concatenation axis last).r   axis)npmoveaxis	broadcastbroadcast_toshapeconcatenate)xyr   zs       L/var/www/html/venv/lib/python3.13/site-packages/scipy/stats/_mannwhitneyu.py_broadcast_concatenater   
   s    
AR A
AR A
QvY&	*A
77aggbk^34A
77aggbk^34A
vB'A7N    c                   N    \ rS rSrSrS rS rS rS rS r	S r
S	 rS
 rS rSrg)_MWU   z7Distribution of MWU statistic under the null hypothesisc                 &    U R                  X5        g N)_resetselfn1n2s      r   __init___MWU.__init__   s    Br   c                    [        X5      [        X5      p!X4U R                  U R                  4:X  a  g Xl        X l        [        R
                  " S[        S9U l        [        R
                  " S[        R                  S9U l	        g )Nr   dtype)
minmaxr!   r"   r   zerosints_arrayuint64configurationsr   s      r   
set_shapes_MWU.set_shapes   s^    Rc"kB8))xx- hhq		:r   c                 P    U R                  U R                  U R                  5        g r   )r   r!   r"   )r    s    r   reset
_MWU.reset%   s    DGGTWW%r   c                 B    S U l         S U l        U R                  X5        g r   )r!   r"   r/   r   s      r   r   _MWU._reset(   s    r   c                 T    U R                  [        R                  " U5      5      nX!   $ r   )build_u_freqs_arrayr   r)   )r    kpmfss      r   pmf_MWU.pmf-   s#     ''q	2wr   c                     U R                  [        R                  " U5      5      n[        R                  " U5      nX1   $ )z Cumulative distribution function)r7   r   r)   cumsum)r    r8   r9   cdfss       r   cdf_MWU.cdf9   s0    
 ''q	2yywr   c                    [         R                  " U R                  U R                  -  U-
  5      nX:  n[         R                  " U5      (       aM  X   X#'   [         R                  " U R                  U5      5      nSXC   -
  U R                  X#   5      -   XC'   US   $ [         R                  " U R                  U5      5      nUS   $ )zSurvival functiong      ? )r   asarrayr!   r"   anyr?   r:   )r    r8   kcir>   s        r   sf_MWU.sfB   s     ZZ!+,F66!99DBE::dhhrl+D47lTXXbe_4DG Bx ::dhhrl+DBxr   c                    U R                   U R                  p2US-   U R                  R                  ::  a  U R                  SUS-    $ [        R
                  " US-   [        S9n[        R                  " SUS-   5       H)  n[        R                  " XQS-   U5      nXF==   U-  ss'   M+     [        R                  " US-   X2-   S-   5       H)  n[        R                  " XQS-   U5      nXF==   U-  ss'   M+     X@l        USS  $ )Nr   r&   )r!   r"   r,   sizer   r*   r+   arange)r    ar!   r"   r,   dindicess          r   build_sigma_array_MWU.build_sigma_arrayV   s    $''Bq5DLL%%%<<!A#&&((1q5,1b1f%Aiiq5!,G!	 & 2627Q;/Aiiq5!,G!	 0 qr{r   c                    U R                   U R                  p2[        R                  " X#-   U5      nUS-   U R                  R
                  ::  a  U R                  SUS-    U-  $ U R                  U5      n[        R                  " US-   [        R                  S9nSn[        R                  " [        R                  5      R                  nSUS'   [        R                  " SUS-   5       HQ  n	XYS-
  SS2   n
[        R                  " USU	 U
5      U	-  nX:  a  U(       a  UR                  [        5      nSnXU	'   MS     X`l        Xd-  $ )zh
Build all the array of frequencies for u from 0 to maxu.
Assumptions:
  n1 <= n2
  maxu <= n1 * n2 / 2
r   Nr&   Tr   r
   F)r!   r"   r   binomr.   rJ   rO   r   r*   r-   iinfor)   rK   dotastypefloat)r    maxur!   r"   totalr,   r.   configurations_is_uintuint_maxucoeffsnew_vals               r   r7   _MWU.build_u_freqs_arraym   s,    $''Bbgr*!8t**///&&yq1E99((. $("))<!%88BII&**q1dQh'AUYBY'Fff^BQ/81<G!&<
 "0!6!6u!=).& '1 ( -%%r   )r.   r!   r"   r,   N)__name__
__module____qualname____firstlineno____doc__r#   r/   r2   r   r:   r?   rG   rO   r7   __static_attributes__rB   r   r   r   r      s2    A;& 

(.#&r   r   c                 &   X-  S-  nX-   nUS-  U-
  R                  SS9n[        R                  " X-  S-  US-   XUS-
  -  -  -
  -  5      n	X-
  n
U(       a  U
S-  n
[        R                  " SSS	9   X-  nS
S
S
5        U$ ! , (       d  f       W$ = f)zStandardized MWU statistic      r
   r      r   g      ?ignore)divideinvalidN)sumr   sqrterrstate)Ur!   r"   tr   
continuitymuntie_terms	numeratorr   s               r   
_get_mwu_zrw      s     
1B
A 1q~~2~&H
bQUh1Q3&889:AI S	 
Hh	7M 
8H 
8	7Hs   2B
Bc                    [         R                  " U 5      [         R                  " U5      p[         R                  " U 5      R                  5       (       d)  [         R                  " U5      R                  5       (       a  [	        S5      e[         R
                  " U 5      S:X  d  [         R
                  " U5      S:X  a  [	        S5      eSS1nX&;  a  [	        SU S35      e1 SknUR                  5       nX7;  a  [	        S	U S35      e[        U5      nXH:w  a  [	        S
5      e[        U[        R                  5      (       d(  1 Skn	UR                  5       nXY;  a  [	        SU	 S35      eXX#X4$ )z6Input validation and standardization for mannwhitneyu z"`x` and `y` must not contain NaNs.r   z$`x` and `y` must be of nonzero size.TFz `use_continuity` must be one of .>   lessgreater	two-sidedz`alternative` must be one of z`axis` must be an integer.>   autoexact
asymptoticz`method` must be one of )r   
atleast_1disnanrD   
ValueErrorrJ   lowerr+   
isinstancer   PermutationMethod)
r   r   use_continuityalternativer   methodboolsalternativesaxis_intmethodss
             r   _mwu_input_validationr      s3    ==R]]1-q	xx{BHHQKOO--=>>	wwqzQ"''!*/?@@5ME";E7!DEE3L##%K&8aHII4yH566fe55661 7yBCCh>>r   c                 .    U S:  a  US:  a  gU(       a  gg)zCChoose method 'asymptotic' or 'exact' depending on input size, ties   r   r~   rB   )r!   r"   tiess      r   _mwu_choose_methodr      s     
Av"q& r   MannwhitneyuResult)	statisticpvaluerf   )	n_samplesc                   ^^ [        XTTXE5      u  pmmpe[        XU5      u  pnU R                  S   UR                  S   p[        USSS9u  pU
SSU24   R	                  SS9nXUS-   -  S	-  -
  nX-  U-
  nTS
:X  a  USnnO#TS:X  a  USnnO[
        R                  " X5      S	nnUS:X  a#  [        X[
        R                  " US:  5      5      nUS:X  a|  [        [        S5      (       d  [        SS5      [        l        [        R                  R                  X5        [        R                  R                  UR                  [         5      5      nOsUS:X  a+  [#        XXTS9n[$        R&                  R                  U5      nOBUU4S jn[$        R(                  " X4U4SU0UR+                  5       DST0D6nUR,                  nSnUU-  n[
        R.                  " USS5      n[1        UU5      $ )u7#  Perform the Mann-Whitney U rank test on two independent samples.

The Mann-Whitney U test is a nonparametric test of the null hypothesis
that the distribution underlying sample `x` is the same as the
distribution underlying sample `y`. It is often used as a test of
difference in location between distributions.

Parameters
----------
x, y : array-like
    N-d arrays of samples. The arrays must be broadcastable except along
    the dimension given by `axis`.
use_continuity : bool, optional
        Whether a continuity correction (1/2) should be applied.
        Default is True when `method` is ``'asymptotic'``; has no effect
        otherwise.
alternative : {'two-sided', 'less', 'greater'}, optional
    Defines the alternative hypothesis. Default is 'two-sided'.
    Let *SX(u)* and *SY(u)* be the survival functions of the
    distributions underlying `x` and `y`, respectively. Then the following
    alternative hypotheses are available:

    * 'two-sided': the distributions are not equal, i.e. *SX(u) ≠ SY(u)* for
      at least one *u*.
    * 'less': the distribution underlying `x` is stochastically less
      than the distribution underlying `y`, i.e. *SX(u) < SY(u)* for all *u*.
    * 'greater': the distribution underlying `x` is stochastically greater
      than the distribution underlying `y`, i.e. *SX(u) > SY(u)* for all *u*.

    Under a more restrictive set of assumptions, the alternative hypotheses
    can be expressed in terms of the locations of the distributions;
    see [5]_ section 5.1.
axis : int, optional
    Axis along which to perform the test. Default is 0.
method : {'auto', 'asymptotic', 'exact'} or `PermutationMethod` instance, optional
    Selects the method used to calculate the *p*-value.
    Default is 'auto'. The following options are available.

    * ``'asymptotic'``: compares the standardized test statistic
      against the normal distribution, correcting for ties.
    * ``'exact'``: computes the exact *p*-value by comparing the observed
      :math:`U` statistic against the exact distribution of the :math:`U`
      statistic under the null hypothesis. No correction is made for ties.
    * ``'auto'``: chooses ``'exact'`` when the size of one of the samples
      is less than or equal to 8 and there are no ties;
      chooses ``'asymptotic'`` otherwise.
    * `PermutationMethod` instance. In this case, the p-value
      is computed using `permutation_test` with the provided
      configuration options and other appropriate settings.

Returns
-------
res : MannwhitneyuResult
    An object containing attributes:

    statistic : float
        The Mann-Whitney U statistic corresponding with sample `x`. See
        Notes for the test statistic corresponding with sample `y`.
    pvalue : float
        The associated *p*-value for the chosen `alternative`.

Notes
-----
If ``U1`` is the statistic corresponding with sample `x`, then the
statistic corresponding with sample `y` is
``U2 = x.shape[axis] * y.shape[axis] - U1``.

`mannwhitneyu` is for independent samples. For related / paired samples,
consider `scipy.stats.wilcoxon`.

`method` ``'exact'`` is recommended when there are no ties and when either
sample size is less than 8 [1]_. The implementation follows the algorithm
reported in [3]_.
Note that the exact method is *not* corrected for ties, but
`mannwhitneyu` will not raise errors or warnings if there are ties in the
data. If there are ties and either samples is small (fewer than ~10
observations), consider passing an instance of `PermutationMethod`
as the `method` to perform a permutation test.

The Mann-Whitney U test is a non-parametric version of the t-test for
independent samples. When the means of samples from the populations
are normally distributed, consider `scipy.stats.ttest_ind`.

See Also
--------
scipy.stats.wilcoxon, scipy.stats.ranksums, scipy.stats.ttest_ind

References
----------
.. [1] H.B. Mann and D.R. Whitney, "On a test of whether one of two random
       variables is stochastically larger than the other", The Annals of
       Mathematical Statistics, Vol. 18, pp. 50-60, 1947.
.. [2] Mann-Whitney U Test, Wikipedia,
       http://en.wikipedia.org/wiki/Mann-Whitney_U_test
.. [3] Andreas Löffler,
       "Über eine Partition der nat. Zahlen und ihr Anwendung beim U-Test",
       Wiss. Z. Univ. Halle, XXXII'83 pp. 87-89.
.. [4] Rosie Shier, "Statistics: 2.3 The Mann-Whitney U Test", Mathematics
       Learning Support Centre, 2004.
.. [5] Michael P. Fay and Michael A. Proschan. "Wilcoxon-Mann-Whitney
       or t-test? On assumptions for hypothesis tests and multiple \
       interpretations of decision rules." Statistics surveys, Vol. 4, pp.
       1-39, 2010. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2857732/

Examples
--------
We follow the example from [4]_: nine randomly sampled young adults were
diagnosed with type II diabetes at the ages below.

>>> males = [19, 22, 16, 29, 24]
>>> females = [20, 11, 17, 12]

We use the Mann-Whitney U test to assess whether there is a statistically
significant difference in the diagnosis age of males and females.
The null hypothesis is that the distribution of male diagnosis ages is
the same as the distribution of female diagnosis ages. We decide
that a confidence level of 95% is required to reject the null hypothesis
in favor of the alternative that the distributions are different.
Since the number of samples is very small and there are no ties in the
data, we can compare the observed test statistic against the *exact*
distribution of the test statistic under the null hypothesis.

>>> from scipy.stats import mannwhitneyu
>>> U1, p = mannwhitneyu(males, females, method="exact")
>>> print(U1)
17.0

`mannwhitneyu` always reports the statistic associated with the first
sample, which, in this case, is males. This agrees with :math:`U_M = 17`
reported in [4]_. The statistic associated with the second statistic
can be calculated:

>>> nx, ny = len(males), len(females)
>>> U2 = nx*ny - U1
>>> print(U2)
3.0

This agrees with :math:`U_F = 3` reported in [4]_. The two-sided
*p*-value can be calculated from either statistic, and the value produced
by `mannwhitneyu` agrees with :math:`p = 0.11` reported in [4]_.

>>> print(p)
0.1111111111111111

The exact distribution of the test statistic is asymptotically normal, so
the example continues by comparing the exact *p*-value against the
*p*-value produced using the normal approximation.

>>> _, pnorm = mannwhitneyu(males, females, method="asymptotic")
>>> print(pnorm)
0.11134688653314041

Here `mannwhitneyu`'s reported *p*-value appears to conflict with the
value :math:`p = 0.09` given in [4]_. The reason is that [4]_
does not apply the continuity correction performed by `mannwhitneyu`;
`mannwhitneyu` reduces the distance between the test statistic and the
mean :math:`\mu = n_x n_y / 2` by 0.5 to correct for the fact that the
discrete statistic is being compared against a continuous distribution.
Here, the :math:`U` statistic used is less than the mean, so we reduce
the distance by adding 0.5 in the numerator.

>>> import numpy as np
>>> from scipy.stats import norm
>>> U = min(U1, U2)
>>> N = nx + ny
>>> z = (U - nx*ny/2 + 0.5) / np.sqrt(nx*ny * (N + 1)/ 12)
>>> p = 2 * norm.cdf(z)  # use CDF to get p-value from smaller statistic
>>> print(p)
0.11134688653314041

If desired, we can disable the continuity correction to get a result
that agrees with that reported in [4]_.

>>> _, pnorm = mannwhitneyu(males, females, use_continuity=False,
...                         method="asymptotic")
>>> print(pnorm)
0.0864107329737

Regardless of whether we perform an exact or asymptotic test, the
probability of the test statistic being as extreme or more extreme by
chance exceeds 5%, so we do not consider the results statistically
significant.

Suppose that, before seeing the data, we had hypothesized that females
would tend to be diagnosed at a younger age than males.
In that case, it would be natural to provide the female ages as the
first input, and we would have performed a one-sided test using
``alternative = 'less'``: females are diagnosed at an age that is
stochastically less than that of males.

>>> res = mannwhitneyu(females, males, alternative="less", method="exact")
>>> print(res)
MannwhitneyuResult(statistic=3.0, pvalue=0.05555555555555555)

Again, the probability of getting a sufficiently low value of the
test statistic by chance under the null hypothesis is greater than 5%,
so we do not reject the null hypothesis in favor of our alternative.

If it is reasonable to assume that the means of samples from the
populations are normally distributed, we could have used a t-test to
perform the analysis.

>>> from scipy.stats import ttest_ind
>>> res = ttest_ind(females, males, alternative="less")
>>> print(res)
TtestResult(statistic=-2.239334696520584,
            pvalue=0.030068441095757924,
            df=7.0)

Under this assumption, the *p*-value would be low enough to reject the
null hypothesis in favor of the alternative.

r
   averageT)return_ties.Nr   r   rf   r{   rz   r}   r~   ru   r   r   )rq   c           	      2   > [        XTTUSS9R                  $ )Nr   )r   r   r   r   )mannwhitneyur   )r   r   r   r   r   s      r   r   mannwhitneyu.<locals>.statistic  s!    ^,7d'355>Y?r   r   r   )r   r   r   r   rl   r   maximumr   rD   hasattr
_mwu_stater   ru   r/   rG   rU   r+   rw   r   normpermutation_test_asdictr   clipr   )r   r   r   r   r   r   r   xyr!   r"   ranksrp   R1U1U2ro   fpr   r   ress     ``                 r   r   r      s   t 	aNKN 8A.+x &aD1HA"WWR[!''"+ YD9HE	sCRCx		"		%B	"Q$ik	B	2Bi111		111zz"!11#BBFF1q5M:z3''1:JL'LLOOAHHSM*	<	qb?JJMM!	?
 $$aVY RT R'-~~'7REPRJJFA 	1aAb!$$r   )r   T)Tr|   r   r}   )	threadingnumpyr   collectionsr   scipyr   r   scipy.stats._stats_pyr   _axis_nan_policyr   r   r   localr   rw   r   r   r   r   rB   r   r   <module>r      s~      "   + 6{& {&B __
4?>   46MN  ,:8C &H% ;H%r   